[ { "task_id": "ClassEval_0", "skeleton": "\nimport logging\nimport datetime\n\nclass AccessGatewayFilter:\n \"\"\"\n This class is a filter used for accessing gateway filtering, primarily for authentication and access log recording.\n \"\"\"\n\n def __init__(self):\n pass\n\n def filter(self, request):\n \"\"\"\n Filter the incoming request based on certain rules and conditions.\n :param request: dict, the incoming request details\n :return: bool, True if the request is allowed, False otherwise\n >>> filter = AccessGatewayFilter()\n >>> filter.filter({'path': '/login', 'method': 'POST'})\n True\n\n \"\"\"\n\n\n def is_start_with(self, request_uri):\n \"\"\"\n Check if the request URI starts with certain prefixes.\n :param request_uri: str, the URI of the request\n :return: bool, True if the URI starts with certain prefixes, False otherwise\n >>> filter = AccessGatewayFilter()\n >>> filter.is_start_with('/api/data')\n True\n\n \"\"\"\n\n\n def get_jwt_user(self, request):\n \"\"\"\n Get the user information from the JWT token in the request.\n :param request: dict, the incoming request details\n :return: dict or None, the user information if the token is valid, None otherwise\n >>> filter = AccessGatewayFilter()\n >>> filter.get_jwt_user({'headers': {'Authorization': {'user': {'name': 'user1'}, 'jwt': 'user1'+str(datetime.date.today())}}})\n {'user': {'name': 'user1'}\n\n \"\"\"\n\n def set_current_user_info_and_log(self, user):\n \"\"\"\n Set the current user information and log the access.\n :param user: dict, the user information\n :return: None\n >>> filter = AccessGatewayFilter()\n >>> user = {'name': 'user1', 'address': '127.0.0.1'}\n >>> filter.set_current_user_info_and_log(user)\n\n \"\"\"", "test": "import unittest\n\nclass AccessGatewayFilterTestFilter(unittest.TestCase):\n def test_filter_1(self):\n agf = AccessGatewayFilter()\n request = {'path': '/api/data', 'method': 'GET'}\n res = agf.filter(request)\n self.assertTrue(res)\n\n def test_filter_2(self):\n agf = AccessGatewayFilter()\n request = {'path': '/api/data', 'method': 'POST'}\n res = agf.filter(request)\n self.assertTrue(res)\n\n def test_filter_3(self):\n agf = AccessGatewayFilter()\n request = {'path': '/login/data', 'method': 'GET'}\n res = agf.filter(request)\n self.assertTrue(res)\n\n def test_filter_4(self):\n agf = AccessGatewayFilter()\n request = {'path': '/login/data', 'method': 'POST'}\n res = agf.filter(request)\n self.assertTrue(res)\n\n def test_filter_5(self):\n agf = AccessGatewayFilter()\n request = {'path': '/abc', 'method': 'POST',\n 'headers': {\n 'Authorization': {'user': {'name': 'user1', 'level': 5, 'address': 'address1'},\n 'jwt': 'user1' + str(datetime.date.today())}}}\n res = agf.filter(request)\n self.assertTrue(res)\n\n def test_filter_6(self):\n agf = AccessGatewayFilter()\n request = {'path': '/abc', 'method': 'POST',\n 'headers': {\n 'Authorization': {'user': {'name': 'user1', 'level': 3, 'address': 'address1'},\n 'jwt': 'user1' + str(datetime.date.today() - datetime.timedelta(days=365))}}}\n res = agf.filter(request)\n self.assertFalse(res)\n\n def test_filter_7(self):\n agf = AccessGatewayFilter()\n request = {'path': '/abc', 'method': 'POST',\n 'headers': {\n 'Authorization': {'user': {'name': 'user1', 'level': 1, 'address': 'address1'},\n 'jwt': 'user1' + str(datetime.date.today())}}}\n res = agf.filter(request)\n self.assertIsNone(res)\n\n def test_filter_8(self):\n agf = AccessGatewayFilter()\n request = {'path': '/abc', 'method': 'POST',\n 'headers': {\n 'Authorization': {'user': {'name': 'user1', 'level': 3, 'address': 'address1'},\n 'jwt': 'user2' + str(datetime.date.today() - datetime.timedelta(days=365))}}}\n res = agf.filter(request)\n self.assertTrue(res)\n\n\nclass AccessGatewayFilterTestIsStartWith(unittest.TestCase):\n def test_is_start_with_1(self):\n agf = AccessGatewayFilter()\n request_uri = '/api/data'\n res = agf.is_start_with(request_uri)\n self.assertTrue(res)\n\n def test_is_start_with_2(self):\n agf = AccessGatewayFilter()\n request_uri = '/admin/settings'\n res = agf.is_start_with(request_uri)\n self.assertFalse(res)\n\n def test_is_start_with_3(self):\n agf = AccessGatewayFilter()\n request_uri = '/login/data'\n res = agf.is_start_with(request_uri)\n self.assertTrue(res)\n\n def test_is_start_with_4(self):\n agf = AccessGatewayFilter()\n request_uri = '/abc/data'\n res = agf.is_start_with(request_uri)\n self.assertFalse(res)\n\n def test_is_start_with_5(self):\n agf = AccessGatewayFilter()\n request_uri = '/def/data'\n res = agf.is_start_with(request_uri)\n self.assertFalse(res)\n\n\nclass AccessGatewayFilterTestGetJwtUser(unittest.TestCase):\n def test_get_jwt_user_1(self):\n agf = AccessGatewayFilter()\n request = {\n 'headers': {'Authorization': {'user': {'name': 'user1'}, 'jwt': 'user1' + str(datetime.date.today())}}}\n res = agf.get_jwt_user(request)\n self.assertIsNotNone(res)\n\n def test_get_jwt_user_2(self):\n agf = AccessGatewayFilter()\n request = {\n 'headers': {'Authorization': {'user': {'name': 'user2'}, 'jwt': 'user2' + str(datetime.date.today())}}}\n res = agf.get_jwt_user(request)\n self.assertIsNotNone(res)\n\n def test_get_jwt_user_3(self):\n agf = AccessGatewayFilter()\n request = {\n 'headers': {'Authorization': {'user': {'name': 'user3'}, 'jwt': 'user3' + str(datetime.date.today())}}}\n res = agf.get_jwt_user(request)\n self.assertIsNotNone(res)\n\n def test_get_jwt_user_4(self):\n agf = AccessGatewayFilter()\n request = {\n 'headers': {'Authorization': {'user': {'name': 'user4'}, 'jwt': 'user4' + str(datetime.date.today())}}}\n res = agf.get_jwt_user(request)\n self.assertIsNotNone(res)\n\n def test_get_jwt_user_5(self):\n agf = AccessGatewayFilter()\n request = {'headers': {'Authorization': {'user': {'name': 'user1'}, 'jwt': 'user1' + str(\n datetime.date.today() - datetime.timedelta(days=5))}}}\n res = agf.get_jwt_user(request)\n self.assertIsNone(res)\n\n\nclass AccessGatewayFilterTest(unittest.TestCase):\n def test_AccessGatewayFilter(self):\n agf = AccessGatewayFilter()\n request = {'path': '/api/data', 'method': 'GET'}\n res = agf.filter(request)\n self.assertTrue(res)\n\n request_uri = '/api/data'\n res = agf.is_start_with(request_uri)\n self.assertTrue(res)\n\n request = {\n 'headers': {'Authorization': {'user': {'name': 'user1'}, 'jwt': 'user1' + str(datetime.date.today())}}}\n res = agf.get_jwt_user(request)\n self.assertIsNotNone(res)", "solution_code": "import logging\nimport datetime\n\n\nclass AccessGatewayFilter:\n\n def __init__(self):\n pass\n\n def filter(self, request):\n request_uri = request['path']\n method = request['method']\n\n if self.is_start_with(request_uri):\n return True\n\n try:\n token = self.get_jwt_user(request)\n user = token['user']\n if user['level'] > 2:\n self.set_current_user_info_and_log(user)\n return True\n except:\n return False\n\n def is_start_with(self, request_uri):\n start_with = [\"/api\", '/login']\n for s in start_with:\n if request_uri.startswith(s):\n return True\n return False\n\n def get_jwt_user(self, request):\n token = request['headers']['Authorization']\n user = token['user']\n if token['jwt'].startswith(user['name']):\n jwt_str_date = token['jwt'].split(user['name'])[1]\n jwt_date = datetime.datetime.strptime(jwt_str_date, \"%Y-%m-%d\")\n if datetime.datetime.today() - jwt_date >= datetime.timedelta(days=3):\n return None\n return token\n\n def set_current_user_info_and_log(self, user):\n host = user['address']\n logging.log(msg=user['name'] + host + str(datetime.datetime.now()), level=1)", "import_statement": [ "import logging", "import datetime" ], "class_description": " \"\"\"\n This class is a filter used for accessing gateway filtering, primarily for authentication and access log recording.\n \"\"\"\n", "class_name": "AccessGatewayFilter", "test_classes": [ "AccessGatewayFilterTestFilter", "AccessGatewayFilterTestIsStartWith", "AccessGatewayFilterTestGetJwtUser", "AccessGatewayFilterTest" ], "class_constructor": "class AccessGatewayFilter: \n def __init__(self):\n pass\n\n", "fields": [], "methods_info": [ { "method_name": "filter", "method_description": "def filter(self, request):\n \"\"\"\n Filter the incoming request based on certain rules and conditions.\n :param request: dict, the incoming request details\n :return: bool, True if the request is allowed, False otherwise\n >>> filter = AccessGatewayFilter()\n >>> filter.filter({'path': '/login', 'method': 'POST'})\n True\n\n \"\"\"", "test_class": "AccessGatewayFilterTestFilter", "test_code": "class AccessGatewayFilterTestFilter(unittest.TestCase):\n def test_filter_1(self):\n agf = AccessGatewayFilter()\n request = {'path': '/api/data', 'method': 'GET'}\n res = agf.filter(request)\n self.assertTrue(res)\n\n def test_filter_2(self):\n agf = AccessGatewayFilter()\n request = {'path': '/api/data', 'method': 'POST'}\n res = agf.filter(request)\n self.assertTrue(res)\n\n def test_filter_3(self):\n agf = AccessGatewayFilter()\n request = {'path': '/login/data', 'method': 'GET'}\n res = agf.filter(request)\n self.assertTrue(res)\n\n def test_filter_4(self):\n agf = AccessGatewayFilter()\n request = {'path': '/login/data', 'method': 'POST'}\n res = agf.filter(request)\n self.assertTrue(res)\n\n def test_filter_5(self):\n agf = AccessGatewayFilter()\n request = {'path': '/abc', 'method': 'POST',\n 'headers': {\n 'Authorization': {'user': {'name': 'user1', 'level': 5, 'address': 'address1'},\n 'jwt': 'user1' + str(datetime.date.today())}}}\n res = agf.filter(request)\n self.assertTrue(res)\n\n def test_filter_6(self):\n agf = AccessGatewayFilter()\n request = {'path': '/abc', 'method': 'POST',\n 'headers': {\n 'Authorization': {'user': {'name': 'user1', 'level': 3, 'address': 'address1'},\n 'jwt': 'user1' + str(datetime.date.today() - datetime.timedelta(days=365))}}}\n res = agf.filter(request)\n self.assertFalse(res)\n\n def test_filter_7(self):\n agf = AccessGatewayFilter()\n request = {'path': '/abc', 'method': 'POST',\n 'headers': {\n 'Authorization': {'user': {'name': 'user1', 'level': 1, 'address': 'address1'},\n 'jwt': 'user1' + str(datetime.date.today())}}}\n res = agf.filter(request)\n self.assertIsNone(res)\n\n def test_filter_8(self):\n agf = AccessGatewayFilter()\n request = {'path': '/abc', 'method': 'POST',\n 'headers': {\n 'Authorization': {'user': {'name': 'user1', 'level': 3, 'address': 'address1'},\n 'jwt': 'user2' + str(datetime.date.today() - datetime.timedelta(days=365))}}}\n res = agf.filter(request)\n self.assertTrue(res)", "solution_code": "def filter(self, request):\n request_uri = request['path']\n method = request['method']\n\n if self.is_start_with(request_uri):\n return True\n\n try:\n token = self.get_jwt_user(request)\n user = token['user']\n if user['level'] > 2:\n self.set_current_user_info_and_log(user)\n return True\n except:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "is_start_with", "get_jwt_user", "set_current_user_info_and_log" ] } }, { "method_name": "is_start_with", "method_description": "def is_start_with(self, request_uri):\n \"\"\"\n Check if the request URI starts with certain prefixes.\n :param request_uri: str, the URI of the request\n :return: bool, True if the URI starts with certain prefixes, False otherwise\n >>> filter = AccessGatewayFilter()\n >>> filter.is_start_with('/api/data')\n True\n\n \"\"\"", "test_class": "AccessGatewayFilterTestIsStartWith", "test_code": "class AccessGatewayFilterTestIsStartWith(unittest.TestCase):\n def test_is_start_with_1(self):\n agf = AccessGatewayFilter()\n request_uri = '/api/data'\n res = agf.is_start_with(request_uri)\n self.assertTrue(res)\n\n def test_is_start_with_2(self):\n agf = AccessGatewayFilter()\n request_uri = '/admin/settings'\n res = agf.is_start_with(request_uri)\n self.assertFalse(res)\n\n def test_is_start_with_3(self):\n agf = AccessGatewayFilter()\n request_uri = '/login/data'\n res = agf.is_start_with(request_uri)\n self.assertTrue(res)\n\n def test_is_start_with_4(self):\n agf = AccessGatewayFilter()\n request_uri = '/abc/data'\n res = agf.is_start_with(request_uri)\n self.assertFalse(res)\n\n def test_is_start_with_5(self):\n agf = AccessGatewayFilter()\n request_uri = '/def/data'\n res = agf.is_start_with(request_uri)\n self.assertFalse(res)", "solution_code": "def is_start_with(self, request_uri):\n start_with = [\"/api\", '/login']\n for s in start_with:\n if request_uri.startswith(s):\n return True\n return False", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "get_jwt_user", "method_description": "def get_jwt_user(self, request):\n \"\"\"\n Get the user information from the JWT token in the request.\n :param request: dict, the incoming request details\n :return: dict or None, the user information if the token is valid, None otherwise\n >>> filter = AccessGatewayFilter()\n >>> filter.get_jwt_user({'headers': {'Authorization': {'user': {'name': 'user1'}, 'jwt': 'user1'+str(datetime.date.today())}}})\n {'user': {'name': 'user1'}\n\n \"\"\"", "test_class": "AccessGatewayFilterTestGetJwtUser", "test_code": "class AccessGatewayFilterTestGetJwtUser(unittest.TestCase):\n def test_get_jwt_user_1(self):\n agf = AccessGatewayFilter()\n request = {\n 'headers': {'Authorization': {'user': {'name': 'user1'}, 'jwt': 'user1' + str(datetime.date.today())}}}\n res = agf.get_jwt_user(request)\n self.assertIsNotNone(res)\n\n def test_get_jwt_user_2(self):\n agf = AccessGatewayFilter()\n request = {\n 'headers': {'Authorization': {'user': {'name': 'user2'}, 'jwt': 'user2' + str(datetime.date.today())}}}\n res = agf.get_jwt_user(request)\n self.assertIsNotNone(res)\n\n def test_get_jwt_user_3(self):\n agf = AccessGatewayFilter()\n request = {\n 'headers': {'Authorization': {'user': {'name': 'user3'}, 'jwt': 'user3' + str(datetime.date.today())}}}\n res = agf.get_jwt_user(request)\n self.assertIsNotNone(res)\n\n def test_get_jwt_user_4(self):\n agf = AccessGatewayFilter()\n request = {\n 'headers': {'Authorization': {'user': {'name': 'user4'}, 'jwt': 'user4' + str(datetime.date.today())}}}\n res = agf.get_jwt_user(request)\n self.assertIsNotNone(res)\n\n def test_get_jwt_user_5(self):\n agf = AccessGatewayFilter()\n request = {'headers': {'Authorization': {'user': {'name': 'user1'}, 'jwt': 'user1' + str(\n datetime.date.today() - datetime.timedelta(days=5))}}}\n res = agf.get_jwt_user(request)\n self.assertIsNone(res)", "solution_code": "def get_jwt_user(self, request):\n token = request['headers']['Authorization']\n user = token['user']\n if token['jwt'].startswith(user['name']):\n jwt_str_date = token['jwt'].split(user['name'])[1]\n jwt_date = datetime.datetime.strptime(jwt_str_date, \"%Y-%m-%d\")\n if datetime.datetime.today() - jwt_date >= datetime.timedelta(days=3):\n return None\n return token", "dependencies": { "Standalone": false, "lib_dependencies": [ "datetime" ], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "set_current_user_info_and_log", "method_description": "def set_current_user_info_and_log(self, user):\n \"\"\"\n Set the current user information and log the access.\n :param user: dict, the user information\n :return: None\n >>> filter = AccessGatewayFilter()\n >>> user = {'name': 'user1', 'address': '127.0.0.1'}\n >>> filter.set_current_user_info_and_log(user)\n\n \"\"\"", "test_class": "AccessGatewayFilterTest", "test_code": "class AccessGatewayFilterTest(unittest.TestCase):\n def test_AccessGatewayFilter(self):\n agf = AccessGatewayFilter()\n request = {'path': '/api/data', 'method': 'GET'}\n res = agf.filter(request)\n self.assertTrue(res)\n\n request_uri = '/api/data'\n res = agf.is_start_with(request_uri)\n self.assertTrue(res)\n\n request = {\n 'headers': {'Authorization': {'user': {'name': 'user1'}, 'jwt': 'user1' + str(datetime.date.today())}}}\n res = agf.get_jwt_user(request)\n self.assertIsNotNone(res)", "solution_code": "def set_current_user_info_and_log(self, user):\n host = user['address']\n logging.log(msg=user['name'] + host + str(datetime.datetime.now()), level=1)", "dependencies": { "Standalone": false, "lib_dependencies": [ "logging", "datetime" ], "field_dependencies": [], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_1", "skeleton": "\nimport math\nclass AreaCalculator:\n \"\"\"\n This is a class for calculating the area of different shapes, including circle, sphere, cylinder, sector and annulus.\n \"\"\"\n\n\n def __init__(self, radius):\n \"\"\"\n Initialize the radius for shapes.\n :param radius: float\n \"\"\"\n self.radius = radius\n\n def calculate_circle_area(self):\n \"\"\"\n calculate the area of circle based on self.radius\n :return: area of circle, float\n >>> areaCalculator = AreaCalculator(2)\n >>> areaCalculator.calculate_circle_area()\n 12.566370614359172\n \"\"\"\n\n def calculate_sphere_area(self):\n \"\"\"\n calculate the area of sphere based on self.radius\n :return: area of sphere, float\n >>> areaCalculator = AreaCalculator(2)\n >>> areaCalculator.calculate_sphere_area()\n 50.26548245743669\n \"\"\"\n\n def calculate_cylinder_area(self, height):\n \"\"\"\n calculate the area of cylinder based on self.radius and height\n :param height: height of cylinder, float\n :return: area of cylinder, float\n >>> areaCalculator = AreaCalculator(2)\n >>> areaCalculator.calculate_cylinder_area(3)\n 62.83185307179586\n \"\"\"\n\n def calculate_sector_area(self, angle):\n \"\"\"\n calculate the area of sector based on self.radius and angle\n :param angle: angle of sector, float\n :return: area of sector, float\n >>> areaCalculator = AreaCalculator(2)\n >>> areaCalculator.calculate_sector_area(math.pi)\n 6.283185307179586\n \"\"\"\n\n def calculate_annulus_area(self, inner_radius, outer_radius):\n \"\"\"\n calculate the area of annulus based on inner_radius and out_radius\n :param inner_radius: inner radius of sector, float\n :param outer_radius: outer radius of sector, float\n :return: area of annulus, float\n >>> areaCalculator.calculate_annulus_area(2, 3)\n 15.707963267948966\n \"\"\"", "test": "import unittest\n\nclass AreaCalculatorTestCalculateCircleArea(unittest.TestCase):\n def test_calculate_circle_area(self):\n areaCalculator = AreaCalculator(2)\n self.assertAlmostEqual(12.56, areaCalculator.calculate_circle_area(), delta=0.01)\n def test_calculate_circle_area_2(self):\n areaCalculator = AreaCalculator(2.5)\n self.assertAlmostEqual(19.63, areaCalculator.calculate_circle_area(), delta=0.01)\n\n def test_calculate_circle_area_3(self):\n areaCalculator = AreaCalculator(2000)\n self.assertAlmostEqual(12566370.61, areaCalculator.calculate_circle_area(), delta=0.01)\n\n def test_calculate_circle_area_4(self):\n areaCalculator = AreaCalculator(0)\n self.assertAlmostEqual(0, areaCalculator.calculate_circle_area(), delta=0.01)\n\n def test_calculate_circle_area_5(self):\n areaCalculator = AreaCalculator(0.1)\n self.assertAlmostEqual(0.031, areaCalculator.calculate_circle_area(), delta=0.01)\n\n\nclass AreaCalculatorTestCalculateSphereArea(unittest.TestCase):\n def test_calculate_sphere_area(self):\n areaCalculator = AreaCalculator(2)\n self.assertAlmostEqual(50.27, areaCalculator.calculate_sphere_area(), delta=0.01)\n\n def test_calculate_sphere_area_2(self):\n areaCalculator = AreaCalculator(2.5)\n self.assertAlmostEqual(19.63, areaCalculator.calculate_circle_area(), delta=0.01)\n\n def test_calculate_sphere_area_3(self):\n areaCalculator = AreaCalculator(2000)\n self.assertAlmostEqual(12566370.61, areaCalculator.calculate_circle_area(), delta=0.01)\n\n def test_calculate_sphere_area_4(self):\n areaCalculator = AreaCalculator(0)\n self.assertAlmostEqual(0, areaCalculator.calculate_circle_area(), delta=0.01)\n\n def test_calculate_sphere_area_5(self):\n areaCalculator = AreaCalculator(0.1)\n self.assertAlmostEqual(0.031, areaCalculator.calculate_circle_area(), delta=0.01)\n\n\nclass AreaCalculatorTestCalculateCylinderArea(unittest.TestCase):\n def test_calculate_cylinder_area(self):\n areaCalculator = AreaCalculator(2)\n self.assertAlmostEqual(50.27, areaCalculator.calculate_cylinder_area(2), delta=0.01)\n\n def test_calculate_cylinder_area_2(self):\n areaCalculator = AreaCalculator(2)\n self.assertAlmostEqual(25.13, areaCalculator.calculate_cylinder_area(0), delta=0.01)\n\n def test_calculate_cylinder_area_3(self):\n areaCalculator = AreaCalculator(0)\n self.assertAlmostEqual(0, areaCalculator.calculate_cylinder_area(2000), delta=0.01)\n\n def test_calculate_cylinder_area_4(self):\n areaCalculator = AreaCalculator(2.5)\n self.assertAlmostEqual(70.68, areaCalculator.calculate_cylinder_area(2), delta=0.01)\n\n def test_calculate_cylinder_area_5(self):\n areaCalculator = AreaCalculator(2.5)\n self.assertAlmostEqual(62.83, areaCalculator.calculate_cylinder_area(1.5), delta=0.01)\n\nclass AreaCalculatorTestCalculateSectorArea(unittest.TestCase):\n def test_calculate_sector_area(self):\n areaCalculator = AreaCalculator(1.5)\n self.assertAlmostEqual(3.53, areaCalculator.calculate_sector_area(math.pi), delta=0.01)\n\n def test_calculate_sector_area_2(self):\n areaCalculator = AreaCalculator(2)\n self.assertAlmostEqual(3.14, areaCalculator.calculate_sector_area(math.pi/2), delta=0.01)\n\n def test_calculate_sector_area_3(self):\n areaCalculator = AreaCalculator(2)\n self.assertAlmostEqual(0, areaCalculator.calculate_sector_area(0), delta=0.01)\n\n def test_calculate_sector_area_4(self):\n areaCalculator = AreaCalculator(2)\n self.assertAlmostEqual(12.56, areaCalculator.calculate_sector_area(2*math.pi), delta=0.01)\n\n def test5_calculate_sector_area_5(self):\n areaCalculator = AreaCalculator(0)\n self.assertAlmostEqual(0, areaCalculator.calculate_sector_area(math.pi), delta=0.01)\n\nclass AreaCalculatorTestCalculateAnnulusArea(unittest.TestCase):\n def test_calculate_annulus_area(self):\n areaCalculator = AreaCalculator(2)\n self.assertAlmostEqual(25.128, areaCalculator.calculate_annulus_area(1, 3), delta=0.01)\n\n def test_calculate_annulus_area_2(self):\n areaCalculator = AreaCalculator(2.5)\n self.assertAlmostEqual(0, areaCalculator.calculate_annulus_area(3, 3), delta=0.01)\n\n def test_calculate_annulus_area_3(self):\n areaCalculator = AreaCalculator(2000)\n self.assertAlmostEqual(3.14, areaCalculator.calculate_annulus_area(0, 1), delta=0.01)\n\n def test_calculate_annulus_area_4(self):\n areaCalculator = AreaCalculator(0)\n self.assertAlmostEqual(25.13, areaCalculator.calculate_annulus_area(1, 3), delta=0.01)\n\n def test_calculate_annulus_area_5(self):\n areaCalculator = AreaCalculator(2.5)\n self.assertAlmostEqual(25.13, areaCalculator.calculate_annulus_area(1, 3), delta=0.01)\n\nclass AreaCalculatorTestCalculateMain(unittest.TestCase):\n def test_main(self):\n areaCalculator = AreaCalculator(2)\n self.assertAlmostEqual(12.56, areaCalculator.calculate_circle_area(), delta=0.01)\n self.assertAlmostEqual(50.27, areaCalculator.calculate_sphere_area(), delta=0.01)\n self.assertAlmostEqual(50.27, areaCalculator.calculate_cylinder_area(2), delta=0.01)\n self.assertAlmostEqual(6.28, areaCalculator.calculate_sector_area(math.pi), delta=0.01)\n self.assertAlmostEqual(25.128, areaCalculator.calculate_annulus_area(1, 3), delta=0.01)", "solution_code": "import math\n\n\nclass AreaCalculator:\n\n def __init__(self, radius):\n self.radius = radius\n\n def calculate_circle_area(self):\n return math.pi * self.radius ** 2\n\n def calculate_sphere_area(self):\n return 4 * math.pi * self.radius ** 2\n\n def calculate_cylinder_area(self, height):\n return 2 * math.pi * self.radius * (self.radius + height)\n\n def calculate_sector_area(self, angle):\n return self.radius ** 2 * angle / 2\n\n def calculate_annulus_area(self, inner_radius, outer_radius):\n return math.pi * (outer_radius ** 2 - inner_radius ** 2)", "import_statement": [ "import math" ], "class_description": " \"\"\"\n This is a class for calculating the area of different shapes, including circle, sphere, cylinder, sector and annulus.\n \"\"\"\n", "class_name": "AreaCalculator", "test_classes": [ "AreaCalculatorTestCalculateCircleArea", "AreaCalculatorTestCalculateSphereArea", "AreaCalculatorTestCalculateCylinderArea", "AreaCalculatorTestCalculateSectorArea", "AreaCalculatorTestCalculateAnnulusArea", "AreaCalculatorTestCalculateMain" ], "class_constructor": "class AreaCalculator: \n def __init__(self, radius):\n \"\"\"\n Initialize the radius for shapes.\n :param radius: float\n \"\"\"\n self.radius = radius\n\n", "fields": [ "self.radius" ], "methods_info": [ { "method_name": "calculate_circle_area", "method_description": "def calculate_circle_area(self):\n \"\"\"\n calculate the area of circle based on self.radius\n :return: area of circle, float\n >>> areaCalculator = AreaCalculator(2)\n >>> areaCalculator.calculate_circle_area()\n 12.566370614359172\n \"\"\"", "test_class": "AreaCalculatorTestCalculateCircleArea", "test_code": "class AreaCalculatorTestCalculateCircleArea(unittest.TestCase):\n def test_calculate_circle_area(self):\n areaCalculator = AreaCalculator(2)\n self.assertAlmostEqual(12.56, areaCalculator.calculate_circle_area(), delta=0.01)\n def test_calculate_circle_area_2(self):\n areaCalculator = AreaCalculator(2.5)\n self.assertAlmostEqual(19.63, areaCalculator.calculate_circle_area(), delta=0.01)\n\n def test_calculate_circle_area_3(self):\n areaCalculator = AreaCalculator(2000)\n self.assertAlmostEqual(12566370.61, areaCalculator.calculate_circle_area(), delta=0.01)\n\n def test_calculate_circle_area_4(self):\n areaCalculator = AreaCalculator(0)\n self.assertAlmostEqual(0, areaCalculator.calculate_circle_area(), delta=0.01)\n\n def test_calculate_circle_area_5(self):\n areaCalculator = AreaCalculator(0.1)\n self.assertAlmostEqual(0.031, areaCalculator.calculate_circle_area(), delta=0.01)", "solution_code": "def calculate_circle_area(self):\n return math.pi * self.radius ** 2", "dependencies": { "Standalone": false, "lib_dependencies": [ "math" ], "field_dependencies": [ "self.radius" ], "method_dependencies": [] } }, { "method_name": "calculate_sphere_area", "method_description": "def calculate_sphere_area(self):\n \"\"\"\n calculate the area of sphere based on self.radius\n :return: area of sphere, float\n >>> areaCalculator = AreaCalculator(2)\n >>> areaCalculator.calculate_sphere_area()\n 50.26548245743669\n \"\"\"", "test_class": "AreaCalculatorTestCalculateSphereArea", "test_code": "class AreaCalculatorTestCalculateSphereArea(unittest.TestCase):\n def test_calculate_sphere_area(self):\n areaCalculator = AreaCalculator(2)\n self.assertAlmostEqual(50.27, areaCalculator.calculate_sphere_area(), delta=0.01)\n\n def test_calculate_sphere_area_2(self):\n areaCalculator = AreaCalculator(2.5)\n self.assertAlmostEqual(19.63, areaCalculator.calculate_circle_area(), delta=0.01)\n\n def test_calculate_sphere_area_3(self):\n areaCalculator = AreaCalculator(2000)\n self.assertAlmostEqual(12566370.61, areaCalculator.calculate_circle_area(), delta=0.01)\n\n def test_calculate_sphere_area_4(self):\n areaCalculator = AreaCalculator(0)\n self.assertAlmostEqual(0, areaCalculator.calculate_circle_area(), delta=0.01)\n\n def test_calculate_sphere_area_5(self):\n areaCalculator = AreaCalculator(0.1)\n self.assertAlmostEqual(0.031, areaCalculator.calculate_circle_area(), delta=0.01)", "solution_code": "def calculate_sphere_area(self):\n return 4 * math.pi * self.radius ** 2", "dependencies": { "Standalone": false, "lib_dependencies": [ "math" ], "field_dependencies": [ "self.radius" ], "method_dependencies": [] } }, { "method_name": "calculate_cylinder_area", "method_description": "def calculate_cylinder_area(self, height):\n \"\"\"\n calculate the area of cylinder based on self.radius and height\n :param height: height of cylinder, float\n :return: area of cylinder, float\n >>> areaCalculator = AreaCalculator(2)\n >>> areaCalculator.calculate_cylinder_area(3)\n 62.83185307179586\n \"\"\"", "test_class": "AreaCalculatorTestCalculateCylinderArea", "test_code": "class AreaCalculatorTestCalculateCylinderArea(unittest.TestCase):\n def test_calculate_cylinder_area(self):\n areaCalculator = AreaCalculator(2)\n self.assertAlmostEqual(50.27, areaCalculator.calculate_cylinder_area(2), delta=0.01)\n\n def test_calculate_cylinder_area_2(self):\n areaCalculator = AreaCalculator(2)\n self.assertAlmostEqual(25.13, areaCalculator.calculate_cylinder_area(0), delta=0.01)\n\n def test_calculate_cylinder_area_3(self):\n areaCalculator = AreaCalculator(0)\n self.assertAlmostEqual(0, areaCalculator.calculate_cylinder_area(2000), delta=0.01)\n\n def test_calculate_cylinder_area_4(self):\n areaCalculator = AreaCalculator(2.5)\n self.assertAlmostEqual(70.68, areaCalculator.calculate_cylinder_area(2), delta=0.01)\n\n def test_calculate_cylinder_area_5(self):\n areaCalculator = AreaCalculator(2.5)\n self.assertAlmostEqual(62.83, areaCalculator.calculate_cylinder_area(1.5), delta=0.01)", "solution_code": "def calculate_cylinder_area(self, height):\n return 2 * math.pi * self.radius * (self.radius + height)", "dependencies": { "Standalone": false, "lib_dependencies": [ "math" ], "field_dependencies": [ "self.radius" ], "method_dependencies": [] } }, { "method_name": "calculate_sector_area", "method_description": "def calculate_sector_area(self, angle):\n \"\"\"\n calculate the area of sector based on self.radius and angle\n :param angle: angle of sector, float\n :return: area of sector, float\n >>> areaCalculator = AreaCalculator(2)\n >>> areaCalculator.calculate_sector_area(math.pi)\n 6.283185307179586\n \"\"\"", "test_class": "AreaCalculatorTestCalculateSectorArea", "test_code": "class AreaCalculatorTestCalculateSectorArea(unittest.TestCase):\n def test_calculate_sector_area(self):\n areaCalculator = AreaCalculator(1.5)\n self.assertAlmostEqual(3.53, areaCalculator.calculate_sector_area(math.pi), delta=0.01)\n\n def test_calculate_sector_area_2(self):\n areaCalculator = AreaCalculator(2)\n self.assertAlmostEqual(3.14, areaCalculator.calculate_sector_area(math.pi/2), delta=0.01)\n\n def test_calculate_sector_area_3(self):\n areaCalculator = AreaCalculator(2)\n self.assertAlmostEqual(0, areaCalculator.calculate_sector_area(0), delta=0.01)\n\n def test_calculate_sector_area_4(self):\n areaCalculator = AreaCalculator(2)\n self.assertAlmostEqual(12.56, areaCalculator.calculate_sector_area(2*math.pi), delta=0.01)\n\n def test5_calculate_sector_area_5(self):\n areaCalculator = AreaCalculator(0)\n self.assertAlmostEqual(0, areaCalculator.calculate_sector_area(math.pi), delta=0.01)", "solution_code": "def calculate_sector_area(self, angle):\n return self.radius ** 2 * angle / 2", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.radius" ], "method_dependencies": [] } }, { "method_name": "calculate_annulus_area", "method_description": "def calculate_annulus_area(self, inner_radius, outer_radius):\n \"\"\"\n calculate the area of annulus based on inner_radius and out_radius\n :param inner_radius: inner radius of sector, float\n :param outer_radius: outer radius of sector, float\n :return: area of annulus, float\n >>> areaCalculator.calculate_annulus_area(2, 3)\n 15.707963267948966\n \"\"\"", "test_class": "AreaCalculatorTestCalculateAnnulusArea", "test_code": "class AreaCalculatorTestCalculateAnnulusArea(unittest.TestCase):\n def test_calculate_annulus_area(self):\n areaCalculator = AreaCalculator(2)\n self.assertAlmostEqual(25.128, areaCalculator.calculate_annulus_area(1, 3), delta=0.01)\n\n def test_calculate_annulus_area_2(self):\n areaCalculator = AreaCalculator(2.5)\n self.assertAlmostEqual(0, areaCalculator.calculate_annulus_area(3, 3), delta=0.01)\n\n def test_calculate_annulus_area_3(self):\n areaCalculator = AreaCalculator(2000)\n self.assertAlmostEqual(3.14, areaCalculator.calculate_annulus_area(0, 1), delta=0.01)\n\n def test_calculate_annulus_area_4(self):\n areaCalculator = AreaCalculator(0)\n self.assertAlmostEqual(25.13, areaCalculator.calculate_annulus_area(1, 3), delta=0.01)\n\n def test_calculate_annulus_area_5(self):\n areaCalculator = AreaCalculator(2.5)\n self.assertAlmostEqual(25.13, areaCalculator.calculate_annulus_area(1, 3), delta=0.01)", "solution_code": "def calculate_annulus_area(self, inner_radius, outer_radius):\n return math.pi * (outer_radius ** 2 - inner_radius ** 2)", "dependencies": { "Standalone": false, "lib_dependencies": [ "math" ], "field_dependencies": [], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_2", "skeleton": "\nclass ArgumentParser:\n \"\"\"\n This is a class for parsing command line arguments to a dictionary.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialize the fields.\n self.arguments is a dict that stores the args in a command line\n self.requried is a set that stores the required arguments\n self.types is a dict that stores type of every arguments.\n >>> parser.arguments\n {'key1': 'value1', 'option1': True}\n >>> parser.required\n {'arg1'}\n >>> parser.types\n {'arg1': 'type1'}\n \"\"\"\n self.arguments = {}\n self.required = set()\n self.types = {}\n\n def parse_arguments(self, command_string):\n \"\"\"\n Parses the given command line argument string and invoke _convert_type to stores the parsed result in specific type in the arguments dictionary.\n Checks for missing required arguments, if any, and returns False with the missing argument names, otherwise returns True.\n :param command_string: str, command line argument string, formatted like \"python script.py --arg1=value1 -arg2 value2 --option1 -option2\"\n :return tuple: (True, None) if parsing is successful, (False, missing_args) if parsing fails,\n where missing_args is a set of the missing argument names which are str.\n >>> parser.parse_arguments(\"python script.py --arg1=value1 -arg2 value2 --option1 -option2\")\n (True, None)\n >>> parser.arguments\n {'arg1': 'value1', 'arg2': 'value2', 'option1': True, 'option2': True}\n \"\"\"\n\n def get_argument(self, key):\n \"\"\"\n Retrieves the value of the specified argument from the arguments dictionary and returns it.\n :param key: str, argument name\n :return: The value of the argument, or None if the argument does not exist.\n >>> parser.arguments\n {'arg1': 'value1', 'arg2': 'value2', 'option1': True, 'option2': True}\n >>> parser.get_argument('arg2')\n 'value2'\n \"\"\"\n\n def add_argument(self, arg, required=False, arg_type=str):\n \"\"\"\n Adds an argument to self.types and self.required.\n Check if it is a required argument and store the argument type.\n If the argument is set as required, it wull be added to the required set.\n The argument type and name are stored in the types dictionary as key-value pairs.\n :param arg: str, argument name\n :param required: bool, whether the argument is required, default is False\n :param arg_type:str, Argument type, default is str\n >>> parser.add_argument('arg1', True, 'int')\n >>> parser.required\n {'arg1'}\n >>> parser.types\n {'arg1': 'int'}\n \"\"\"\n\n def _convert_type(self, arg, value):\n \"\"\"\n Try to convert the type of input value by searching in self.types.\n :param value: str, the input value in command line\n :return: return corresponding value in self.types if convert successfully, or the input value oherwise\n >>> parser.types\n {'arg1': int}\n >>> parser._convert_type('arg1', '21')\n 21\n \"\"\"", "test": "import unittest\n\nclass ArgumentParserTestParseArguments(unittest.TestCase):\n\n def setUp(self):\n self.parser = ArgumentParser()\n\n # key value arguments\n def test_parse_arguments_1(self):\n command_str = \"script --name=John --age=25\"\n self.parser.add_argument(\"name\")\n self.parser.add_argument(\"age\", arg_type=int)\n\n result, missing_args = self.parser.parse_arguments(command_str)\n\n self.assertTrue(result)\n self.assertIsNone(missing_args)\n self.assertEqual(self.parser.get_argument(\"name\"), \"John\")\n self.assertEqual(self.parser.get_argument(\"age\"), 25)\n\n # switches options\n def test_parse_arguments_2(self):\n command_str = \"script --verbose -d\"\n self.parser.add_argument(\"verbose\", arg_type=bool)\n self.parser.add_argument(\"d\")\n\n result, missing_args = self.parser.parse_arguments(command_str)\n\n self.assertTrue(result)\n self.assertIsNone(missing_args)\n self.assertEqual(self.parser.get_argument(\"verbose\"), True)\n self.assertEqual(self.parser.get_argument(\"d\"), True)\n\n # miss required\n def test_parse_arguments_3(self):\n command_str = \"script --name=John\"\n self.parser.add_argument(\"name\")\n self.parser.add_argument(\"age\", required=True, arg_type=int)\n\n result, missing_args = self.parser.parse_arguments(command_str)\n\n self.assertFalse(result)\n self.assertEqual(missing_args, {\"age\"})\n\n def test_parse_arguments_4(self):\n command_str = \"script --name=John\"\n self.parser.add_argument(\"name\")\n self.parser.add_argument(\"age\", required=False, arg_type=int)\n\n result, missing_args = self.parser.parse_arguments(command_str)\n\n self.assertTrue(result)\n self.assertEqual(missing_args, None)\n\n def test_parse_arguments_5(self):\n command_str = \"script --name=John\"\n self.parser.add_argument(\"name\")\n self.parser.add_argument(\"age\", arg_type=int)\n\n result, missing_args = self.parser.parse_arguments(command_str)\n\n self.assertTrue(result)\n self.assertEqual(missing_args, None)\n\nclass ArgumentParserTestGetArgument(unittest.TestCase):\n\n def setUp(self):\n self.parser = ArgumentParser()\n\n # key exists\n def test_get_argument_1(self):\n self.parser.arguments = {\"name\": \"John\"}\n result = self.parser.get_argument(\"name\")\n self.assertEqual(result, \"John\")\n\n # key not exists\n def test_get_argument_2(self):\n self.parser.arguments = {\"name\": \"John\", \"age\": 25}\n result = self.parser.get_argument(\"age\")\n self.assertEqual(result, 25)\n\n def test_get_argument_3(self):\n self.parser.arguments = {\"name\": \"John\", \"age\": \"25\", \"verbose\": True}\n result = self.parser.get_argument(\"verbose\")\n self.assertEqual(result, True)\n\n def test_get_argument_4(self):\n self.parser.arguments = {\"name\": \"Amy\", \"age\": 25, \"verbose\": True, \"d\": True}\n result = self.parser.get_argument(\"d\")\n self.assertEqual(result, True)\n\n def test_get_argument_5(self):\n self.parser.arguments = {\"name\": \"John\", \"age\": 25, \"verbose\": True, \"d\": True, \"option\": \"value\"}\n result = self.parser.get_argument(\"option\")\n self.assertEqual(result, \"value\")\n\n\nclass ArgumentParserTestAddArgument(unittest.TestCase):\n\n def setUp(self):\n self.parser = ArgumentParser()\n\n def test_add_argument(self):\n self.parser.add_argument(\"name\")\n self.parser.add_argument(\"age\", required=True, arg_type=int)\n\n self.assertEqual(self.parser.required, {\"age\"})\n self.assertEqual(self.parser.types, {\"name\": str, \"age\": int})\n\n def test_add_argument_2(self):\n self.parser.add_argument(\"name\")\n self.parser.add_argument(\"age\", required=False, arg_type=int)\n self.parser.add_argument(\"verbose\", arg_type=bool)\n\n self.assertEqual(self.parser.required, set())\n self.assertEqual(self.parser.types, {\"name\": str, \"age\": int, \"verbose\": bool})\n\n def test_add_argument_3(self):\n self.parser.add_argument(\"name\")\n self.parser.add_argument(\"age\", required=False, arg_type=int)\n self.parser.add_argument(\"verbose\", arg_type=bool)\n self.parser.add_argument(\"d\")\n\n self.assertEqual(self.parser.required, set())\n self.assertEqual(self.parser.types, {\"name\": str, \"age\": int, \"verbose\": bool, \"d\": str})\n\n def test_add_argument_4(self):\n self.parser.add_argument(\"name\")\n self.parser.add_argument(\"age\", required=False, arg_type=int)\n self.parser.add_argument(\"verbose\", arg_type=bool)\n self.parser.add_argument(\"d\")\n self.parser.add_argument(\"option\")\n\n self.assertEqual(self.parser.required, set())\n self.assertEqual(self.parser.types, {\"name\": str, \"age\": int, \"verbose\": bool, \"d\": str, \"option\": str})\n\n def test_add_argument_5(self):\n self.parser.add_argument(\"name\")\n self.parser.add_argument(\"age\", required=False, arg_type=int)\n self.parser.add_argument(\"verbose\", arg_type=bool)\n self.parser.add_argument(\"d\")\n self.parser.add_argument(\"option\")\n self.parser.add_argument(\"option2\", arg_type=bool)\n\n self.assertEqual(self.parser.required, set())\n self.assertEqual(self.parser.types, {\"name\": str, \"age\": int, \"verbose\": bool, \"d\": str, \"option\": str, \"option2\": bool})\n\n\nclass ArgumentParserTestConvertType(unittest.TestCase):\n\n def setUp(self):\n self.parser = ArgumentParser()\n\n def test_convert_type_1(self):\n self.parser.types = {\"age\": int}\n result = self.parser._convert_type(\"age\", \"25\")\n self.assertEqual(result, 25)\n\n # fail\n def test_convert_type_2(self):\n self.parser.types = {\"age\": int}\n result = self.parser._convert_type(\"age\", \"twenty-five\")\n self.assertEqual(result, \"twenty-five\")\n\n def test_convert_type_3(self):\n self.parser.types = {\"age\": int}\n result = self.parser._convert_type(\"age\", \"25\")\n self.assertEqual(result, 25)\n\n def test_convert_type_4(self):\n self.parser.types = {\"age\": int, \"verbose\": bool}\n result = self.parser._convert_type(\"verbose\", \"True\")\n self.assertEqual(result, True)\n \n def test_convert_type_5(self):\n self.parser.types = {\"age\": int, \"verbose\": bool}\n result = self.parser._convert_type(\"verbose\", \"False\")\n self.assertEqual(result, True)\n\n\nclass ArgumentParserTestMain(unittest.TestCase):\n def test_main(self):\n parser = ArgumentParser()\n command = \"script --arg1=21 --option1 -arg2 value -option2\"\n\n parser.add_argument('arg1', required=True, arg_type=int)\n parser.add_argument('arg2')\n\n self.assertEqual(parser.required, {'arg1'})\n self.assertEqual(parser.types, {'arg1': int, 'arg2': str})\n self.assertEqual(parser.arguments, {})\n\n parser.parse_arguments(command)\n arguments = {'arg1': 21, 'option1': True, 'arg2': 'value', 'option2': True}\n self.assertEqual(parser.arguments, arguments)", "solution_code": "class ArgumentParser:\n def __init__(self):\n self.arguments = {}\n self.required = set()\n self.types = {}\n\n def parse_arguments(self, command_string):\n args = command_string.split()[1:]\n for i in range(len(args)):\n arg = args[i]\n if arg.startswith('--'):\n key_value = arg[2:].split('=')\n if len(key_value) == 2:\n self.arguments[key_value[0]] = self._convert_type(key_value[0], key_value[1])\n else:\n self.arguments[key_value[0]] = True\n elif arg.startswith('-'):\n key = arg[1:]\n if i + 1 < len(args) and not args[i + 1].startswith('-'):\n self.arguments[key] = self._convert_type(key, args[i + 1])\n else:\n self.arguments[key] = True\n missing_args = self.required - set(self.arguments.keys())\n if missing_args:\n return False, missing_args\n\n return True, None\n\n def get_argument(self, key):\n return self.arguments.get(key)\n\n def add_argument(self, arg, required=False, arg_type=str):\n if required:\n self.required.add(arg)\n self.types[arg] = arg_type\n\n def _convert_type(self, arg, value):\n try:\n return self.types[arg](value)\n except (ValueError, KeyError):\n return value", "import_statement": [], "class_description": " \"\"\"\n This is a class for parsing command line arguments to a dictionary.\n \"\"\"\n", "class_name": "ArgumentParser", "test_classes": [ "ArgumentParserTestParseArguments", "ArgumentParserTestGetArgument", "ArgumentParserTestAddArgument", "ArgumentParserTestConvertType", "ArgumentParserTestMain" ], "class_constructor": "class ArgumentParser: \n def __init__(self):\n \"\"\"\n Initialize the fields.\n self.arguments is a dict that stores the args in a command line\n self.requried is a set that stores the required arguments\n self.types is a dict that stores type of every arguments.\n >>> parser.arguments\n {'key1': 'value1', 'option1': True}\n >>> parser.required\n {'arg1'}\n >>> parser.types\n {'arg1': 'type1'}\n \"\"\"\n self.arguments = {}\n self.required = set()\n self.types = {}\n\n", "fields": [ "self.arguments", "self.required", "self.types" ], "methods_info": [ { "method_name": "parse_arguments", "method_description": "def parse_arguments(self, command_string):\n \"\"\"\n Parses the given command line argument string and invoke _convert_type to stores the parsed result in specific type in the arguments dictionary.\n Checks for missing required arguments, if any, and returns False with the missing argument names, otherwise returns True.\n :param command_string: str, command line argument string, formatted like \"python script.py --arg1=value1 -arg2 value2 --option1 -option2\"\n :return tuple: (True, None) if parsing is successful, (False, missing_args) if parsing fails,\n where missing_args is a set of the missing argument names which are str.\n >>> parser.parse_arguments(\"python script.py --arg1=value1 -arg2 value2 --option1 -option2\")\n (True, None)\n >>> parser.arguments\n {'arg1': 'value1', 'arg2': 'value2', 'option1': True, 'option2': True}\n \"\"\"", "test_class": "ArgumentParserTestParseArguments", "test_code": "class ArgumentParserTestParseArguments(unittest.TestCase):\n\n def setUp(self):\n self.parser = ArgumentParser()\n\n # key value arguments\n def test_parse_arguments_1(self):\n command_str = \"script --name=John --age=25\"\n self.parser.add_argument(\"name\")\n self.parser.add_argument(\"age\", arg_type=int)\n\n result, missing_args = self.parser.parse_arguments(command_str)\n\n self.assertTrue(result)\n self.assertIsNone(missing_args)\n self.assertEqual(self.parser.get_argument(\"name\"), \"John\")\n self.assertEqual(self.parser.get_argument(\"age\"), 25)\n\n # switches options\n def test_parse_arguments_2(self):\n command_str = \"script --verbose -d\"\n self.parser.add_argument(\"verbose\", arg_type=bool)\n self.parser.add_argument(\"d\")\n\n result, missing_args = self.parser.parse_arguments(command_str)\n\n self.assertTrue(result)\n self.assertIsNone(missing_args)\n self.assertEqual(self.parser.get_argument(\"verbose\"), True)\n self.assertEqual(self.parser.get_argument(\"d\"), True)\n\n # miss required\n def test_parse_arguments_3(self):\n command_str = \"script --name=John\"\n self.parser.add_argument(\"name\")\n self.parser.add_argument(\"age\", required=True, arg_type=int)\n\n result, missing_args = self.parser.parse_arguments(command_str)\n\n self.assertFalse(result)\n self.assertEqual(missing_args, {\"age\"})\n\n def test_parse_arguments_4(self):\n command_str = \"script --name=John\"\n self.parser.add_argument(\"name\")\n self.parser.add_argument(\"age\", required=False, arg_type=int)\n\n result, missing_args = self.parser.parse_arguments(command_str)\n\n self.assertTrue(result)\n self.assertEqual(missing_args, None)\n\n def test_parse_arguments_5(self):\n command_str = \"script --name=John\"\n self.parser.add_argument(\"name\")\n self.parser.add_argument(\"age\", arg_type=int)\n\n result, missing_args = self.parser.parse_arguments(command_str)\n\n self.assertTrue(result)\n self.assertEqual(missing_args, None)", "solution_code": "def parse_arguments(self, command_string):\n args = command_string.split()[1:]\n for i in range(len(args)):\n arg = args[i]\n if arg.startswith('--'):\n key_value = arg[2:].split('=')\n if len(key_value) == 2:\n self.arguments[key_value[0]] = self._convert_type(key_value[0], key_value[1])\n else:\n self.arguments[key_value[0]] = True\n elif arg.startswith('-'):\n key = arg[1:]\n if i + 1 < len(args) and not args[i + 1].startswith('-'):\n self.arguments[key] = self._convert_type(key, args[i + 1])\n else:\n self.arguments[key] = True\n missing_args = self.required - set(self.arguments.keys())\n if missing_args:\n return False, missing_args\n\n return True, None", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.arguments", "self.required" ], "method_dependencies": [ "_convert_type" ] } }, { "method_name": "get_argument", "method_description": "def get_argument(self, key):\n \"\"\"\n Retrieves the value of the specified argument from the arguments dictionary and returns it.\n :param key: str, argument name\n :return: The value of the argument, or None if the argument does not exist.\n >>> parser.arguments\n {'arg1': 'value1', 'arg2': 'value2', 'option1': True, 'option2': True}\n >>> parser.get_argument('arg2')\n 'value2'\n \"\"\"", "test_class": "ArgumentParserTestGetArgument", "test_code": "class ArgumentParserTestGetArgument(unittest.TestCase):\n\n def setUp(self):\n self.parser = ArgumentParser()\n\n # key exists\n def test_get_argument_1(self):\n self.parser.arguments = {\"name\": \"John\"}\n result = self.parser.get_argument(\"name\")\n self.assertEqual(result, \"John\")\n\n # key not exists\n def test_get_argument_2(self):\n self.parser.arguments = {\"name\": \"John\", \"age\": 25}\n result = self.parser.get_argument(\"age\")\n self.assertEqual(result, 25)\n\n def test_get_argument_3(self):\n self.parser.arguments = {\"name\": \"John\", \"age\": \"25\", \"verbose\": True}\n result = self.parser.get_argument(\"verbose\")\n self.assertEqual(result, True)\n\n def test_get_argument_4(self):\n self.parser.arguments = {\"name\": \"Amy\", \"age\": 25, \"verbose\": True, \"d\": True}\n result = self.parser.get_argument(\"d\")\n self.assertEqual(result, True)\n\n def test_get_argument_5(self):\n self.parser.arguments = {\"name\": \"John\", \"age\": 25, \"verbose\": True, \"d\": True, \"option\": \"value\"}\n result = self.parser.get_argument(\"option\")\n self.assertEqual(result, \"value\")", "solution_code": "def get_argument(self, key):\n return self.arguments.get(key)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.arguments" ], "method_dependencies": [] } }, { "method_name": "add_argument", "method_description": "def add_argument(self, arg, required=False, arg_type=str):\n \"\"\"\n Adds an argument to self.types and self.required.\n Check if it is a required argument and store the argument type.\n If the argument is set as required, it wull be added to the required set.\n The argument type and name are stored in the types dictionary as key-value pairs.\n :param arg: str, argument name\n :param required: bool, whether the argument is required, default is False\n :param arg_type:str, Argument type, default is str\n >>> parser.add_argument('arg1', True, 'int')\n >>> parser.required\n {'arg1'}\n >>> parser.types\n {'arg1': 'int'}\n \"\"\"", "test_class": "ArgumentParserTestAddArgument", "test_code": "class ArgumentParserTestAddArgument(unittest.TestCase):\n\n def setUp(self):\n self.parser = ArgumentParser()\n\n def test_add_argument(self):\n self.parser.add_argument(\"name\")\n self.parser.add_argument(\"age\", required=True, arg_type=int)\n\n self.assertEqual(self.parser.required, {\"age\"})\n self.assertEqual(self.parser.types, {\"name\": str, \"age\": int})\n\n def test_add_argument_2(self):\n self.parser.add_argument(\"name\")\n self.parser.add_argument(\"age\", required=False, arg_type=int)\n self.parser.add_argument(\"verbose\", arg_type=bool)\n\n self.assertEqual(self.parser.required, set())\n self.assertEqual(self.parser.types, {\"name\": str, \"age\": int, \"verbose\": bool})\n\n def test_add_argument_3(self):\n self.parser.add_argument(\"name\")\n self.parser.add_argument(\"age\", required=False, arg_type=int)\n self.parser.add_argument(\"verbose\", arg_type=bool)\n self.parser.add_argument(\"d\")\n\n self.assertEqual(self.parser.required, set())\n self.assertEqual(self.parser.types, {\"name\": str, \"age\": int, \"verbose\": bool, \"d\": str})\n\n def test_add_argument_4(self):\n self.parser.add_argument(\"name\")\n self.parser.add_argument(\"age\", required=False, arg_type=int)\n self.parser.add_argument(\"verbose\", arg_type=bool)\n self.parser.add_argument(\"d\")\n self.parser.add_argument(\"option\")\n\n self.assertEqual(self.parser.required, set())\n self.assertEqual(self.parser.types, {\"name\": str, \"age\": int, \"verbose\": bool, \"d\": str, \"option\": str})\n\n def test_add_argument_5(self):\n self.parser.add_argument(\"name\")\n self.parser.add_argument(\"age\", required=False, arg_type=int)\n self.parser.add_argument(\"verbose\", arg_type=bool)\n self.parser.add_argument(\"d\")\n self.parser.add_argument(\"option\")\n self.parser.add_argument(\"option2\", arg_type=bool)\n\n self.assertEqual(self.parser.required, set())\n self.assertEqual(self.parser.types, {\"name\": str, \"age\": int, \"verbose\": bool, \"d\": str, \"option\": str, \"option2\": bool})", "solution_code": "def add_argument(self, arg, required=False, arg_type=str):\n if required:\n self.required.add(arg)\n self.types[arg] = arg_type", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.required", "self.types" ], "method_dependencies": [] } }, { "method_name": "_convert_type", "method_description": "def _convert_type(self, arg, value):\n \"\"\"\n Try to convert the type of input value by searching in self.types.\n :param value: str, the input value in command line\n :return: return corresponding value in self.types if convert successfully, or the input value oherwise\n >>> parser.types\n {'arg1': int}\n >>> parser._convert_type('arg1', '21')\n 21\n \"\"\"", "test_class": "ArgumentParserTestConvertType", "test_code": "class ArgumentParserTestConvertType(unittest.TestCase):\n\n def setUp(self):\n self.parser = ArgumentParser()\n\n def test_convert_type_1(self):\n self.parser.types = {\"age\": int}\n result = self.parser._convert_type(\"age\", \"25\")\n self.assertEqual(result, 25)\n\n # fail\n def test_convert_type_2(self):\n self.parser.types = {\"age\": int}\n result = self.parser._convert_type(\"age\", \"twenty-five\")\n self.assertEqual(result, \"twenty-five\")\n\n def test_convert_type_3(self):\n self.parser.types = {\"age\": int}\n result = self.parser._convert_type(\"age\", \"25\")\n self.assertEqual(result, 25)\n\n def test_convert_type_4(self):\n self.parser.types = {\"age\": int, \"verbose\": bool}\n result = self.parser._convert_type(\"verbose\", \"True\")\n self.assertEqual(result, True)\n \n def test_convert_type_5(self):\n self.parser.types = {\"age\": int, \"verbose\": bool}\n result = self.parser._convert_type(\"verbose\", \"False\")\n self.assertEqual(result, True)", "solution_code": "def _convert_type(self, arg, value):\n try:\n return self.types[arg](value)\n except (ValueError, KeyError):\n return value", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.types" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_3", "skeleton": "\nimport itertools\n\nclass ArrangementCalculator:\n \"\"\"\n The Arrangement class provides permutation calculations and selection operations for a given set of data elements.\n \"\"\"\n\n def __init__(self, datas):\n \"\"\"\n Initializes the ArrangementCalculator object with a list of datas.\n :param datas: List, the data elements to be used for arrangements.\n \"\"\"\n self.datas = datas\n\n @staticmethod\n def count(n, m=None):\n \"\"\"\n Counts the number of arrangements by choosing m items from n items (permutations).\n If m is not provided or n equals m, returns factorial(n).\n :param n: int, the total number of items.\n :param m: int, the number of items to be chosen (default=None).\n :return: int, the count of arrangements.\n >>> ArrangementCalculator.count(5, 3)\n 60\n\n \"\"\"\n\n @staticmethod\n def count_all(n):\n \"\"\"\n Counts the total number of all possible arrangements by choosing at least 1 item and at most n items from n items.\n :param n: int, the total number of items.\n :return: int, the count of all arrangements.\n >>> ArrangementCalculator.count_all(4)\n 64\n\n \"\"\"\n\n\n def select(self, m=None):\n \"\"\"\n Generates a list of arrangements by selecting m items from the internal datas.\n If m is not provided, selects all items.\n :param m: int, the number of items to be chosen (default=None).\n :return: List, a list of arrangements.\n >>> ac = ArrangementCalculator([1, 2, 3, 4])\n >>> ac.select(2)\n [[1, 2], [1, 3], [1, 4], [2, 1], [2, 3], [2, 4], [3, 1], [3, 2], [3, 4], [4, 1], [4, 2], [4, 3]]\n\n \"\"\"\n\n\n def select_all(self):\n \"\"\"\n Generates a list of all arrangements by selecting at least 1 item and at most the number of internal datas.\n :return: List, a list of all arrangements.\n >>> ac = ArrangementCalculator([1, 2, 3])\n >>> ac.select_all()\n [[1], [2], [3], [1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2], [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]\n\n \"\"\"\n\n\n @staticmethod\n def factorial(n):\n \"\"\"\n Calculates the factorial of a given number.\n :param n: int, the number to calculate the factorial.\n :return: int, the factorial of the given number.\n >>> ArrangementCalculator.factorial(4)\n 24\n\n \"\"\"", "test": "import unittest\n\n\nclass ArrangementCalculatorTestCount(unittest.TestCase):\n def test_count_1(self):\n res = ArrangementCalculator.count(5, 3)\n self.assertEqual(res, 60)\n\n def test_count_2(self):\n res = ArrangementCalculator.count(4, 3)\n self.assertEqual(res, 24)\n\n def test_count_3(self):\n res = ArrangementCalculator.count(6, 3)\n self.assertEqual(res, 120)\n\n def test_count_4(self):\n res = ArrangementCalculator.count(7, 3)\n self.assertEqual(res, 210)\n\n def test_count_5(self):\n res = ArrangementCalculator.count(4, 4)\n self.assertEqual(res, 24)\n\n\nclass ArrangementCalculatorTestCountAll(unittest.TestCase):\n def test_count_all_1(self):\n res = ArrangementCalculator.count_all(4)\n self.assertEqual(res, 64)\n\n def test_count_all_2(self):\n res = ArrangementCalculator.count_all(1)\n self.assertEqual(res, 1)\n\n def test_count_all_3(self):\n res = ArrangementCalculator.count_all(2)\n self.assertEqual(res, 4)\n\n def test_count_all_4(self):\n res = ArrangementCalculator.count_all(3)\n self.assertEqual(res, 15)\n\n def test_count_all_5(self):\n res = ArrangementCalculator.count_all(5)\n self.assertEqual(res, 325)\n\n\nclass ArrangementCalculatorTestSelect(unittest.TestCase):\n def test_select_1(self):\n ac = ArrangementCalculator([1, 2, 3, 4])\n res = ac.select(2)\n expected = [[1, 2], [1, 3], [1, 4], [2, 1], [2, 3], [2, 4], [3, 1], [3, 2], [3, 4], [4, 1], [4, 2], [4, 3]]\n self.assertEqual(res, expected)\n\n def test_select_2(self):\n ac = ArrangementCalculator([1, 2, 3])\n res = ac.select(2)\n expected = [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]]\n self.assertEqual(res, expected)\n\n def test_select_3(self):\n ac = ArrangementCalculator([2, 3, 4])\n res = ac.select(2)\n expected = [[2, 3], [2, 4], [3, 2], [3, 4], [4, 2], [4, 3]]\n self.assertEqual(res, expected)\n\n def test_select_4(self):\n ac = ArrangementCalculator([1, 2])\n res = ac.select(2)\n expected = [[1, 2], [2, 1]]\n self.assertEqual(res, expected)\n\n def test_select_5(self):\n ac = ArrangementCalculator([1, 2, 3, 4])\n res = ac.select(1)\n expected = [[1], [2], [3], [4]]\n self.assertEqual(res, expected)\n\n def test_select_6(self):\n ac = ArrangementCalculator([1, 2])\n res = ac.select()\n expected = [[1, 2], [2, 1]]\n self.assertEqual(res, expected)\n\n\nclass ArrangementCalculatorTestSelectAll(unittest.TestCase):\n def test_select_all_1(self):\n ac = ArrangementCalculator([1, 2, 3])\n res = ac.select_all()\n expected = [[1], [2], [3], [1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2], [1, 2, 3], [1, 3, 2], [2, 1, 3],\n [2, 3, 1], [3, 1, 2], [3, 2, 1]]\n self.assertEqual(res, expected)\n\n def test_select_all_2(self):\n ac = ArrangementCalculator([1, 2, 4])\n res = ac.select_all()\n expected = [[1], [2], [4], [1, 2], [1, 4], [2, 1], [2, 4], [4, 1], [4, 2], [1, 2, 4], [1, 4, 2], [2, 1, 4],\n [2, 4, 1], [4, 1, 2], [4, 2, 1]]\n self.assertEqual(res, expected)\n\n def test_select_all_3(self):\n ac = ArrangementCalculator([1, 2])\n res = ac.select_all()\n expected = [[1], [2], [1, 2], [2, 1]]\n self.assertEqual(res, expected)\n\n def test_select_all_4(self):\n ac = ArrangementCalculator([1, 3])\n res = ac.select_all()\n expected = [[1], [3], [1, 3], [3, 1]]\n self.assertEqual(res, expected)\n\n def test_select_all_5(self):\n ac = ArrangementCalculator([1])\n res = ac.select_all()\n expected = [[1]]\n self.assertEqual(res, expected)\n\n\nclass ArrangementCalculatorTestFactorial(unittest.TestCase):\n def test_factorial_1(self):\n res = ArrangementCalculator.factorial(4)\n self.assertEqual(res, 24)\n\n def test_factorial_2(self):\n res = ArrangementCalculator.factorial(5)\n self.assertEqual(res, 120)\n\n def test_factorial_3(self):\n res = ArrangementCalculator.factorial(3)\n self.assertEqual(res, 6)\n\n def test_factorial_4(self):\n res = ArrangementCalculator.factorial(2)\n self.assertEqual(res, 2)\n\n def test_factorial_5(self):\n res = ArrangementCalculator.factorial(1)\n self.assertEqual(res, 1)\n\n\nclass ArrangementCalculatorTest(unittest.TestCase):\n def test_arrangementcalculator(self):\n res = ArrangementCalculator.count(5, 3)\n self.assertEqual(res, 60)\n\n res = ArrangementCalculator.count_all(4)\n self.assertEqual(res, 64)\n\n ac = ArrangementCalculator([1, 2, 3, 4])\n res = ac.select(2)\n expected = [[1, 2], [1, 3], [1, 4], [2, 1], [2, 3], [2, 4], [3, 1], [3, 2], [3, 4], [4, 1], [4, 2], [4, 3]]\n self.assertEqual(res, expected)\n\n ac = ArrangementCalculator([1, 2, 3])\n res = ac.select_all()\n expected = [[1], [2], [3], [1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2], [1, 2, 3], [1, 3, 2], [2, 1, 3],\n [2, 3, 1], [3, 1, 2], [3, 2, 1]]\n self.assertEqual(res, expected)\n\n res = ArrangementCalculator.factorial(4)\n self.assertEqual(res, 24)", "solution_code": "import itertools\n\n\nclass ArrangementCalculator:\n def __init__(self, datas):\n self.datas = datas\n\n @staticmethod\n def count(n, m=None):\n if m is None or n == m:\n return ArrangementCalculator.factorial(n)\n else:\n return ArrangementCalculator.factorial(n) // ArrangementCalculator.factorial(n - m)\n\n @staticmethod\n def count_all(n):\n total = 0\n for i in range(1, n + 1):\n total += ArrangementCalculator.count(n, i)\n return total\n\n def select(self, m=None):\n if m is None:\n m = len(self.datas)\n result = []\n for permutation in itertools.permutations(self.datas, m):\n result.append(list(permutation))\n return result\n\n def select_all(self):\n result = []\n for i in range(1, len(self.datas) + 1):\n result.extend(self.select(i))\n return result\n\n @staticmethod\n def factorial(n):\n result = 1\n for i in range(2, n + 1):\n result *= i\n return result", "import_statement": [ "import itertools" ], "class_description": " \"\"\"\n The Arrangement class provides permutation calculations and selection operations for a given set of data elements.\n \"\"\"\n", "class_name": "ArrangementCalculator", "test_classes": [ "ArrangementCalculatorTestCount", "ArrangementCalculatorTestCountAll", "ArrangementCalculatorTestSelect", "ArrangementCalculatorTestSelectAll", "ArrangementCalculatorTestFactorial", "ArrangementCalculatorTest" ], "class_constructor": "class ArrangementCalculator: \n def __init__(self, datas):\n \"\"\"\n Initializes the ArrangementCalculator object with a list of datas.\n :param datas: List, the data elements to be used for arrangements.\n \"\"\"\n self.datas = datas\n\n @staticmethod\n", "fields": [ "self.datas" ], "methods_info": [ { "method_name": "count", "method_description": "def count(n, m=None):\n \"\"\"\n Counts the number of arrangements by choosing m items from n items (permutations).\n If m is not provided or n equals m, returns factorial(n).\n :param n: int, the total number of items.\n :param m: int, the number of items to be chosen (default=None).\n :return: int, the count of arrangements.\n >>> ArrangementCalculator.count(5, 3)\n 60\n\n \"\"\"", "test_class": "ArrangementCalculatorTestCount", "test_code": "class ArrangementCalculatorTestCount(unittest.TestCase):\n def test_count_1(self):\n res = ArrangementCalculator.count(5, 3)\n self.assertEqual(res, 60)\n\n def test_count_2(self):\n res = ArrangementCalculator.count(4, 3)\n self.assertEqual(res, 24)\n\n def test_count_3(self):\n res = ArrangementCalculator.count(6, 3)\n self.assertEqual(res, 120)\n\n def test_count_4(self):\n res = ArrangementCalculator.count(7, 3)\n self.assertEqual(res, 210)\n\n def test_count_5(self):\n res = ArrangementCalculator.count(4, 4)\n self.assertEqual(res, 24)", "solution_code": "def count(n, m=None):\n if m is None or n == m:\n return ArrangementCalculator.factorial(n)\n else:\n return ArrangementCalculator.factorial(n) // ArrangementCalculator.factorial(n - m)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "factorial" ] } }, { "method_name": "count_all", "method_description": "@staticmethod\n def count_all(n):\n \"\"\"\n Counts the total number of all possible arrangements by choosing at least 1 item and at most n items from n items.\n :param n: int, the total number of items.\n :return: int, the count of all arrangements.\n >>> ArrangementCalculator.count_all(4)\n 64\n\n \"\"\"", "test_class": "ArrangementCalculatorTestCountAll", "test_code": "class ArrangementCalculatorTestCountAll(unittest.TestCase):\n def test_count_all_1(self):\n res = ArrangementCalculator.count_all(4)\n self.assertEqual(res, 64)\n\n def test_count_all_2(self):\n res = ArrangementCalculator.count_all(1)\n self.assertEqual(res, 1)\n\n def test_count_all_3(self):\n res = ArrangementCalculator.count_all(2)\n self.assertEqual(res, 4)\n\n def test_count_all_4(self):\n res = ArrangementCalculator.count_all(3)\n self.assertEqual(res, 15)\n\n def test_count_all_5(self):\n res = ArrangementCalculator.count_all(5)\n self.assertEqual(res, 325)", "solution_code": "@staticmethod\n def count_all(n):\n total = 0\n for i in range(1, n + 1):\n total += ArrangementCalculator.count(n, i)\n return total", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "count" ] } }, { "method_name": "select", "method_description": "def select(self, m=None):\n \"\"\"\n Generates a list of arrangements by selecting m items from the internal datas.\n If m is not provided, selects all items.\n :param m: int, the number of items to be chosen (default=None).\n :return: List, a list of arrangements.\n >>> ac = ArrangementCalculator([1, 2, 3, 4])\n >>> ac.select(2)\n [[1, 2], [1, 3], [1, 4], [2, 1], [2, 3], [2, 4], [3, 1], [3, 2], [3, 4], [4, 1], [4, 2], [4, 3]]\n\n \"\"\"", "test_class": "ArrangementCalculatorTestSelect", "test_code": "class ArrangementCalculatorTestSelect(unittest.TestCase):\n def test_select_1(self):\n ac = ArrangementCalculator([1, 2, 3, 4])\n res = ac.select(2)\n expected = [[1, 2], [1, 3], [1, 4], [2, 1], [2, 3], [2, 4], [3, 1], [3, 2], [3, 4], [4, 1], [4, 2], [4, 3]]\n self.assertEqual(res, expected)\n\n def test_select_2(self):\n ac = ArrangementCalculator([1, 2, 3])\n res = ac.select(2)\n expected = [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]]\n self.assertEqual(res, expected)\n\n def test_select_3(self):\n ac = ArrangementCalculator([2, 3, 4])\n res = ac.select(2)\n expected = [[2, 3], [2, 4], [3, 2], [3, 4], [4, 2], [4, 3]]\n self.assertEqual(res, expected)\n\n def test_select_4(self):\n ac = ArrangementCalculator([1, 2])\n res = ac.select(2)\n expected = [[1, 2], [2, 1]]\n self.assertEqual(res, expected)\n\n def test_select_5(self):\n ac = ArrangementCalculator([1, 2, 3, 4])\n res = ac.select(1)\n expected = [[1], [2], [3], [4]]\n self.assertEqual(res, expected)\n\n def test_select_6(self):\n ac = ArrangementCalculator([1, 2])\n res = ac.select()\n expected = [[1, 2], [2, 1]]\n self.assertEqual(res, expected)", "solution_code": "def select(self, m=None):\n if m is None:\n m = len(self.datas)\n result = []\n for permutation in itertools.permutations(self.datas, m):\n result.append(list(permutation))\n return result", "dependencies": { "Standalone": false, "lib_dependencies": [ "itertools" ], "field_dependencies": [ "self.datas" ], "method_dependencies": [] } }, { "method_name": "select_all", "method_description": "def select_all(self):\n \"\"\"\n Generates a list of all arrangements by selecting at least 1 item and at most the number of internal datas.\n :return: List, a list of all arrangements.\n >>> ac = ArrangementCalculator([1, 2, 3])\n >>> ac.select_all()\n [[1], [2], [3], [1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2], [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]\n\n \"\"\"", "test_class": "ArrangementCalculatorTestSelectAll", "test_code": "class ArrangementCalculatorTestSelectAll(unittest.TestCase):\n def test_select_all_1(self):\n ac = ArrangementCalculator([1, 2, 3])\n res = ac.select_all()\n expected = [[1], [2], [3], [1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2], [1, 2, 3], [1, 3, 2], [2, 1, 3],\n [2, 3, 1], [3, 1, 2], [3, 2, 1]]\n self.assertEqual(res, expected)\n\n def test_select_all_2(self):\n ac = ArrangementCalculator([1, 2, 4])\n res = ac.select_all()\n expected = [[1], [2], [4], [1, 2], [1, 4], [2, 1], [2, 4], [4, 1], [4, 2], [1, 2, 4], [1, 4, 2], [2, 1, 4],\n [2, 4, 1], [4, 1, 2], [4, 2, 1]]\n self.assertEqual(res, expected)\n\n def test_select_all_3(self):\n ac = ArrangementCalculator([1, 2])\n res = ac.select_all()\n expected = [[1], [2], [1, 2], [2, 1]]\n self.assertEqual(res, expected)\n\n def test_select_all_4(self):\n ac = ArrangementCalculator([1, 3])\n res = ac.select_all()\n expected = [[1], [3], [1, 3], [3, 1]]\n self.assertEqual(res, expected)\n\n def test_select_all_5(self):\n ac = ArrangementCalculator([1])\n res = ac.select_all()\n expected = [[1]]\n self.assertEqual(res, expected)", "solution_code": "def select_all(self):\n result = []\n for i in range(1, len(self.datas) + 1):\n result.extend(self.select(i))\n return result", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.datas" ], "method_dependencies": [ "select" ] } }, { "method_name": "factorial", "method_description": "@staticmethod\n def factorial(n):\n \"\"\"\n Calculates the factorial of a given number.\n :param n: int, the number to calculate the factorial.\n :return: int, the factorial of the given number.\n >>> ArrangementCalculator.factorial(4)\n 24\n\n \"\"\"", "test_class": "ArrangementCalculatorTestFactorial", "test_code": "class ArrangementCalculatorTestFactorial(unittest.TestCase):\n def test_factorial_1(self):\n res = ArrangementCalculator.factorial(4)\n self.assertEqual(res, 24)\n\n def test_factorial_2(self):\n res = ArrangementCalculator.factorial(5)\n self.assertEqual(res, 120)\n\n def test_factorial_3(self):\n res = ArrangementCalculator.factorial(3)\n self.assertEqual(res, 6)\n\n def test_factorial_4(self):\n res = ArrangementCalculator.factorial(2)\n self.assertEqual(res, 2)\n\n def test_factorial_5(self):\n res = ArrangementCalculator.factorial(1)\n self.assertEqual(res, 1)", "solution_code": "@staticmethod\n def factorial(n):\n result = 1\n for i in range(2, n + 1):\n result *= i\n return result", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_4", "skeleton": "\nclass AssessmentSystem:\n \"\"\"\n This is a class as an student assessment system, which supports add student, add course score, calculate GPA, and other functions for students and courses.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialize the students dict in assessment system.\n \"\"\"\n self.students = {}\n\n def add_student(self, name, grade, major):\n \"\"\"\n Add a new student into self.students dict\n :param name: str, student name\n :param grade: int, student grade\n :param major: str, student major\n >>> system.add_student('student 1', 3, 'SE')\n >>> system.students\n {'student 1': {'name': 'student 1', 'grade': 3, 'major': 'SE', 'courses': {}}}\n \"\"\"\n\n def add_course_score(self, name, course, score):\n \"\"\"\n Add score of specific course for student in self.students\n :param name: str, student name\n :param cource: str, cource name\n :param score: int, cource score\n >>> system.add_student('student 1', 3, 'SE')\n >>> system.add_course_score('student 1', 'math', 94)\n >>> system.students\n {'student 1': {'name': 'student 1', 'grade': 3, 'major': 'SE', 'courses': {'math': 94}}}\n \"\"\"\n\n def get_gpa(self, name):\n \"\"\"\n Get average grade of one student.\n :param name: str, student name\n :return: if name is in students and this students have courses grade, return average grade(float)\n or None otherwise\n >>> system.add_student('student 1', 3, 'SE')\n >>> system.add_course_score('student 1', 'math', 94)\n >>> system.add_course_score('student 1', 'Computer Network', 92)\n >>> system.get_gpa('student 1')\n 93.0\n\n \"\"\"\n\n def get_all_students_with_fail_course(self):\n \"\"\"\n Get all students who have any score blow 60\n :return: list of str ,student name\n >>> system.add_course_score('student 1', 'Society', 59)\n >>> system.get_all_students_with_fail_course()\n ['student 1']\n \"\"\"\n\n def get_course_average(self, course):\n \"\"\"\n Get the average score of a specific course.\n :param course: str, course name\n :return: float, average scores of this course if anyone have score of this course, or None if nobody have records.\n \"\"\"\n\n def get_top_student(self):\n \"\"\"\n Calculate every student's gpa with get_gpa method, and find the student with highest gpa\n :return: str, name of student whose gpa is highest\n >>> system.add_student('student 1', 3, 'SE')\n >>> system.add_student('student 2', 2, 'SE')\n >>> system.add_course_score('student 1', 'Computer Network', 92)\n >>> system.add_course_score('student 2', 'Computer Network', 97)\n >>> system.get_top_student()\n 'student 2'\n \"\"\"", "test": "import unittest\n\nclass AssessmentSystemTestAddStudent(unittest.TestCase):\n def test_add_student(self):\n assessment_system = AssessmentSystem()\n assessment_system.add_student(\"Alice\", 3, \"Mathematics\")\n self.assertEqual(assessment_system.students[\"Alice\"],\n {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}})\n\n def test_add_student_2(self):\n assessment_system = AssessmentSystem()\n assessment_system.add_student(\"Alice\", 3, \"Mathematics\")\n assessment_system.add_student(\"Bob\", 2, \"Science\")\n self.assertEqual(assessment_system.students,\n {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}},\n 'Bob': {'name': 'Bob', 'grade': 2, 'major': 'Science', 'courses': {}}})\n\n def test_add_student_3(self):\n assessment_system = AssessmentSystem()\n assessment_system.add_student(\"Alice\", 3, \"Mathematics\")\n assessment_system.add_student(\"Bob\", 2, \"Science\")\n assessment_system.add_student(\"Charlie\", 4, \"Chemistry\")\n self.assertEqual(assessment_system.students,\n {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}},\n 'Bob': {'name': 'Bob', 'grade': 2, 'major': 'Science', 'courses': {}},\n 'Charlie': {'name': 'Charlie', 'grade': 4, 'major': 'Chemistry', 'courses': {}}})\n\n def test_add_student_4(self):\n assessment_system = AssessmentSystem()\n assessment_system.add_student(\"Alice\", 3, \"Mathematics\")\n assessment_system.add_student(\"Bob\", 2, \"Science\")\n assessment_system.add_student(\"Charlie\", 4, \"Chemistry\")\n assessment_system.add_student(\"David\", 1, \"Physics\")\n self.assertEqual(assessment_system.students,\n {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}},\n 'Bob': {'name': 'Bob', 'grade': 2, 'major': 'Science', 'courses': {}},\n 'Charlie': {'name': 'Charlie', 'grade': 4, 'major': 'Chemistry', 'courses': {}},\n 'David': {'name': 'David', 'grade': 1, 'major': 'Physics', 'courses': {}}})\n\n def test_add_student_5(self):\n assessment_system = AssessmentSystem()\n assessment_system.add_student(\"Alice\", 3, \"Mathematics\")\n assessment_system.add_student(\"Bob\", 2, \"Science\")\n assessment_system.add_student(\"Charlie\", 4, \"Chemistry\")\n assessment_system.add_student(\"David\", 1, \"Physics\")\n assessment_system.add_student(\"Eve\", 3, \"Mathematics\")\n self.assertEqual(assessment_system.students,\n {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}},\n 'Bob': {'name': 'Bob', 'grade': 2, 'major': 'Science', 'courses': {}},\n 'Charlie': {'name': 'Charlie', 'grade': 4, 'major': 'Chemistry', 'courses': {}},\n 'David': {'name': 'David', 'grade': 1, 'major': 'Physics', 'courses': {}},\n 'Eve': {'name': 'Eve', 'grade': 3, 'major': 'Mathematics', 'courses': {}}})\n\nclass AssessmentSystemTestAddCourseScore(unittest.TestCase):\n def test_add_course_score(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {\"Alice\": {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}}\n assessment_system.add_course_score(\"Alice\", \"Math\", 90)\n self.assertEqual(assessment_system.students[\"Alice\"][\"courses\"][\"Math\"], 90)\n\n def test_add_course_score_2(self):\n assessment_system = AssessmentSystem()\n assessment_system.students[\"Alice\"] = {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}\n assessment_system.add_course_score(\"Alice\", \"Math\", 90)\n self.assertEqual(assessment_system.students[\"Alice\"][\"courses\"][\"Math\"], 90)\n\n def test_add_course_score_3(self):\n assessment_system = AssessmentSystem()\n assessment_system.students[\"Alice\"] = {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}\n assessment_system.add_course_score(\"Alice\", \"Math\", 90)\n assessment_system.add_course_score(\"Alice\", \"Science\", 80)\n assessment_system.add_course_score(\"Alice\", \"Math\", 95)\n self.assertEqual(assessment_system.students[\"Alice\"][\"courses\"][\"Math\"], 95)\n self.assertEqual(assessment_system.students[\"Alice\"][\"courses\"][\"Science\"], 80)\n\n def test_add_course_score_4(self):\n assessment_system = AssessmentSystem()\n assessment_system.students[\"Alice\"] = {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}\n assessment_system.add_course_score(\"Alice\", \"Math\", 90)\n assessment_system.add_course_score(\"Alice\", \"Science\", 80)\n assessment_system.add_course_score(\"Alice\", \"Math\", 95)\n assessment_system.add_course_score(\"Alice\", \"Science\", 85)\n self.assertEqual(assessment_system.students[\"Alice\"][\"courses\"][\"Math\"], 95)\n self.assertEqual(assessment_system.students[\"Alice\"][\"courses\"][\"Science\"], 85)\n\n def test_add_course_score_5(self):\n assessment_system = AssessmentSystem()\n assessment_system.students[\"Alice\"] = {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}\n assessment_system.add_course_score(\"Bob\", \"Math\", 90)\n self.assertEqual(assessment_system.students[\"Alice\"][\"courses\"], {})\n\nclass AssessmentSystemTestGetGPA(unittest.TestCase):\n def test_get_gpa_1(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 80}}}\n self.assertEqual(assessment_system.get_gpa(\"Alice\"), 85.0)\n\n\n # No such student\n def test_get_gpa_2(self):\n assessment_system = AssessmentSystem()\n self.assertEqual(assessment_system.get_gpa('Alice'), None)\n\n # student don't have any scores\n def test_get_gpa_3(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}}\n self.assertEqual(assessment_system.get_gpa('Alice'), None)\n\n def test_get_gpa_4(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90}}}\n self.assertEqual(assessment_system.get_gpa('Bob'), None)\n\n def test_get_gpa_5(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90}}}\n self.assertEqual(assessment_system.get_gpa('Alice'), 90.0)\n\n\n\nclass AssessmentSystemTestGetAllStudentsWithFailCourse(unittest.TestCase):\n def test_get_all_students_with_fail_course(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 80}},\n 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 50}},\n 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70}},\n 'David': {'name': 'David', 'grade': 1, 'major': 'Physics', 'courses': {'Physics': 60}},\n 'Eve': {'name': 'Eve', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90}}}\n self.assertEqual(assessment_system.get_all_students_with_fail_course(), ['Bob'])\n\n def test_get_all_students_with_fail_course_2(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 80}},\n 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 70}},\n 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70}},\n 'David': {'name': 'David', 'grade': 1, 'major': 'Physics', 'courses': {'Physics': 70}},\n 'Eve': {'name': 'Eve', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90}}}\n self.assertEqual(assessment_system.get_all_students_with_fail_course(), [])\n\n def test_get_all_students_with_fail_course_3(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {}\n self.assertEqual(assessment_system.get_all_students_with_fail_course(), [])\n\n def test_get_all_students_with_fail_course_4(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}}\n self.assertEqual(assessment_system.get_all_students_with_fail_course(), [])\n\n def test_get_all_students_with_fail_course_5(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 50}},\n 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 50}},\n 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70}},\n 'David': {'name': 'David', 'grade': 1, 'major': 'Physics', 'courses': {'Physics': 70}},\n 'Eve': {'name': 'Eve', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90}}}\n self.assertEqual(assessment_system.get_all_students_with_fail_course(), ['Alice', 'Bob'])\n\nclass AssessmentSystemTestGetCourseAverage(unittest.TestCase):\n\n def test_get_course_average_1(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 80}},\n 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 90}},\n 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70,'Physics': 80}}\n }\n self.assertEqual(assessment_system.get_course_average(\"Physics\"), 85.0)\n\n def test_get_course_average_2(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics',\n 'courses': {'Mathematics': 90, 'Science': 80}},\n 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics',\n 'courses': {'Physics': 85}},\n 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry',\n 'courses': {'Chemistry': 70,'Physics': None }}\n }\n self.assertEqual(assessment_system.get_course_average('Physics'), 85)\n\n def test_get_course_average_3(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics',\n 'courses': {'Mathematics': 90, 'Science': 80}},\n 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics',\n 'courses': {'Physics': 85}},\n 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry',\n 'courses': {'Chemistry': 70, 'Physics': 80}}\n }\n self.assertEqual(assessment_system.get_course_average('Computer'), None)\n\n def test_get_course_average_4(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {}\n self.assertEqual(assessment_system.get_course_average('Computer'), None)\n\n def test_get_course_average_5(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics',\n 'courses': {'Mathematics': 90, 'Science': 80}},\n 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics',\n 'courses': {'Physics': 85}},\n 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry',\n 'courses': {'Chemistry': 70, 'Physics': 80}}\n }\n self.assertEqual(assessment_system.get_course_average('Mathematics'), 90)\n\n\nclass AssessmentSystemTestGetTopStudent(unittest.TestCase):\n def test_get_top_student(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics',\n 'courses': {'Mathematics': 90}},\n 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics',\n 'courses': {'Physics': 85}}\n }\n self.assertEqual(assessment_system.get_top_student(), \"Alice\")\n\n def test_get_top_student_2(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics',\n 'courses': { }},\n 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics',\n 'courses': {'Physics': 85}},\n 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry',\n 'courses': {'Chemistry': 70, 'Physics': 80}}\n }\n self.assertEqual(assessment_system.get_top_student(), \"Bob\")\n\n def test_get_top_student_3(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {}\n self.assertEqual(assessment_system.get_top_student(), None)\n\n def test_get_top_student_4(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics',\n 'courses': {'Mathematics': 90, 'Science': 60}},\n 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics',\n 'courses': {'Physics': 85}},\n 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry',\n 'courses': {'Chemistry': 70, 'Physics': 80}}\n }\n self.assertEqual(assessment_system.get_top_student(), \"Bob\")\n\n def test_get_top_student_5(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics',\n 'courses': {'Mathematics': 90, 'Science': 60}},\n 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics',\n 'courses': {'Physics': 85}},\n 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry',\n 'courses': {'Chemistry': 70, 'Physics': 80}},\n 'David': {'name': 'David', 'grade': 2, 'major': 'Chemistry',\n 'courses': {'Chemistry': 70, 'Physics': 80}}\n }\n self.assertEqual(assessment_system.get_top_student(), \"Bob\")\n\n\nclass AssessmentSystemTestMain(unittest.TestCase):\n def test_main(self):\n system = AssessmentSystem()\n system.add_student('student 1', 3, 'SE')\n system.add_student('student 2', 2, 'SE')\n self.assertEqual({'student 1': {'name': 'student 1', 'grade': 3, 'major': 'SE', 'courses': {}},\n 'student 2': {'name': 'student 2', 'grade': 2, 'major': 'SE', 'courses': {}}},\n system.students)\n system.add_course_score('student 1', 'course 1', 86)\n system.add_course_score('student 2', 'course 1', 59)\n system.add_course_score('student 1', 'course 2', 78)\n system.add_course_score('student 2', 'course 2', 90)\n\n self.assertEqual(system.students['student 1']['courses']['course 1'], 86)\n self.assertEqual(system.students['student 1']['courses']['course 2'], 78)\n self.assertEqual(system.students['student 2']['courses']['course 1'], 59)\n self.assertEqual(system.students['student 2']['courses']['course 2'], 90)\n\n self.assertEqual(system.get_all_students_with_fail_course(), ['student 2'])\n self.assertEqual(system.get_course_average('course 1'), 72.5)\n self.assertEqual(system.get_course_average('course 2'), 84)\n\n self.assertEqual(system.get_gpa('student 1'), 82.0)\n self.assertEqual(system.get_gpa('student 2'), 74.5)\n\n self.assertEqual(system.get_top_student(), 'student 1')", "solution_code": "class AssessmentSystem:\n def __init__(self):\n self.students = {}\n\n def add_student(self, name, grade, major):\n self.students[name] = {'name': name, 'grade': grade, 'major': major, 'courses': {}}\n\n def add_course_score(self, name, course, score):\n if name in self.students:\n self.students[name]['courses'][course] = score\n\n def get_gpa(self, name):\n if name in self.students and self.students[name]['courses']:\n return sum(self.students[name]['courses'].values()) / len(self.students[name]['courses'])\n else:\n return None\n\n def get_all_students_with_fail_course(self):\n students = []\n for name, student in self.students.items():\n for course, score in student['courses'].items():\n if score < 60:\n students.append(name)\n break\n return students\n\n def get_course_average(self, course):\n total = 0\n count = 0\n for student in self.students.values():\n if course in student['courses']:\n score = student['courses'][course]\n if score is not None:\n total += score\n count += 1\n return total / count if count > 0 else None\n\n def get_top_student(self):\n top_student = None\n top_gpa = 0\n for name, student in self.students.items():\n gpa = self.get_gpa(name)\n if gpa is not None and gpa > top_gpa:\n top_gpa = gpa\n top_student = name\n return top_student", "import_statement": [], "class_description": " \"\"\"\n This is a class as an student assessment system, which supports add student, add course score, calculate GPA, and other functions for students and courses.\n \"\"\"\n", "class_name": "AssessmentSystem", "test_classes": [ "AssessmentSystemTestAddStudent", "AssessmentSystemTestAddCourseScore", "AssessmentSystemTestGetGPA", "AssessmentSystemTestGetAllStudentsWithFailCourse", "AssessmentSystemTestGetCourseAverage", "AssessmentSystemTestGetTopStudent", "AssessmentSystemTestMain" ], "class_constructor": "class AssessmentSystem: \n def __init__(self):\n \"\"\"\n Initialize the students dict in assessment system.\n \"\"\"\n self.students = {}\n\n", "fields": [ "self.students" ], "methods_info": [ { "method_name": "add_student", "method_description": "def add_student(self, name, grade, major):\n \"\"\"\n Add a new student into self.students dict\n :param name: str, student name\n :param grade: int, student grade\n :param major: str, student major\n >>> system.add_student('student 1', 3, 'SE')\n >>> system.students\n {'student 1': {'name': 'student 1', 'grade': 3, 'major': 'SE', 'courses': {}}}\n \"\"\"", "test_class": "AssessmentSystemTestAddStudent", "test_code": "class AssessmentSystemTestAddStudent(unittest.TestCase):\n def test_add_student(self):\n assessment_system = AssessmentSystem()\n assessment_system.add_student(\"Alice\", 3, \"Mathematics\")\n self.assertEqual(assessment_system.students[\"Alice\"],\n {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}})\n\n def test_add_student_2(self):\n assessment_system = AssessmentSystem()\n assessment_system.add_student(\"Alice\", 3, \"Mathematics\")\n assessment_system.add_student(\"Bob\", 2, \"Science\")\n self.assertEqual(assessment_system.students,\n {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}},\n 'Bob': {'name': 'Bob', 'grade': 2, 'major': 'Science', 'courses': {}}})\n\n def test_add_student_3(self):\n assessment_system = AssessmentSystem()\n assessment_system.add_student(\"Alice\", 3, \"Mathematics\")\n assessment_system.add_student(\"Bob\", 2, \"Science\")\n assessment_system.add_student(\"Charlie\", 4, \"Chemistry\")\n self.assertEqual(assessment_system.students,\n {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}},\n 'Bob': {'name': 'Bob', 'grade': 2, 'major': 'Science', 'courses': {}},\n 'Charlie': {'name': 'Charlie', 'grade': 4, 'major': 'Chemistry', 'courses': {}}})\n\n def test_add_student_4(self):\n assessment_system = AssessmentSystem()\n assessment_system.add_student(\"Alice\", 3, \"Mathematics\")\n assessment_system.add_student(\"Bob\", 2, \"Science\")\n assessment_system.add_student(\"Charlie\", 4, \"Chemistry\")\n assessment_system.add_student(\"David\", 1, \"Physics\")\n self.assertEqual(assessment_system.students,\n {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}},\n 'Bob': {'name': 'Bob', 'grade': 2, 'major': 'Science', 'courses': {}},\n 'Charlie': {'name': 'Charlie', 'grade': 4, 'major': 'Chemistry', 'courses': {}},\n 'David': {'name': 'David', 'grade': 1, 'major': 'Physics', 'courses': {}}})\n\n def test_add_student_5(self):\n assessment_system = AssessmentSystem()\n assessment_system.add_student(\"Alice\", 3, \"Mathematics\")\n assessment_system.add_student(\"Bob\", 2, \"Science\")\n assessment_system.add_student(\"Charlie\", 4, \"Chemistry\")\n assessment_system.add_student(\"David\", 1, \"Physics\")\n assessment_system.add_student(\"Eve\", 3, \"Mathematics\")\n self.assertEqual(assessment_system.students,\n {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}},\n 'Bob': {'name': 'Bob', 'grade': 2, 'major': 'Science', 'courses': {}},\n 'Charlie': {'name': 'Charlie', 'grade': 4, 'major': 'Chemistry', 'courses': {}},\n 'David': {'name': 'David', 'grade': 1, 'major': 'Physics', 'courses': {}},\n 'Eve': {'name': 'Eve', 'grade': 3, 'major': 'Mathematics', 'courses': {}}})", "solution_code": "def add_student(self, name, grade, major):\n self.students[name] = {'name': name, 'grade': grade, 'major': major, 'courses': {}}", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.students" ], "method_dependencies": [] } }, { "method_name": "add_course_score", "method_description": "def add_course_score(self, name, course, score):\n \"\"\"\n Add score of specific course for student in self.students\n :param name: str, student name\n :param cource: str, cource name\n :param score: int, cource score\n >>> system.add_student('student 1', 3, 'SE')\n >>> system.add_course_score('student 1', 'math', 94)\n >>> system.students\n {'student 1': {'name': 'student 1', 'grade': 3, 'major': 'SE', 'courses': {'math': 94}}}\n \"\"\"", "test_class": "AssessmentSystemTestAddCourseScore", "test_code": "class AssessmentSystemTestAddCourseScore(unittest.TestCase):\n def test_add_course_score(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {\"Alice\": {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}}\n assessment_system.add_course_score(\"Alice\", \"Math\", 90)\n self.assertEqual(assessment_system.students[\"Alice\"][\"courses\"][\"Math\"], 90)\n\n def test_add_course_score_2(self):\n assessment_system = AssessmentSystem()\n assessment_system.students[\"Alice\"] = {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}\n assessment_system.add_course_score(\"Alice\", \"Math\", 90)\n self.assertEqual(assessment_system.students[\"Alice\"][\"courses\"][\"Math\"], 90)\n\n def test_add_course_score_3(self):\n assessment_system = AssessmentSystem()\n assessment_system.students[\"Alice\"] = {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}\n assessment_system.add_course_score(\"Alice\", \"Math\", 90)\n assessment_system.add_course_score(\"Alice\", \"Science\", 80)\n assessment_system.add_course_score(\"Alice\", \"Math\", 95)\n self.assertEqual(assessment_system.students[\"Alice\"][\"courses\"][\"Math\"], 95)\n self.assertEqual(assessment_system.students[\"Alice\"][\"courses\"][\"Science\"], 80)\n\n def test_add_course_score_4(self):\n assessment_system = AssessmentSystem()\n assessment_system.students[\"Alice\"] = {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}\n assessment_system.add_course_score(\"Alice\", \"Math\", 90)\n assessment_system.add_course_score(\"Alice\", \"Science\", 80)\n assessment_system.add_course_score(\"Alice\", \"Math\", 95)\n assessment_system.add_course_score(\"Alice\", \"Science\", 85)\n self.assertEqual(assessment_system.students[\"Alice\"][\"courses\"][\"Math\"], 95)\n self.assertEqual(assessment_system.students[\"Alice\"][\"courses\"][\"Science\"], 85)\n\n def test_add_course_score_5(self):\n assessment_system = AssessmentSystem()\n assessment_system.students[\"Alice\"] = {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}\n assessment_system.add_course_score(\"Bob\", \"Math\", 90)\n self.assertEqual(assessment_system.students[\"Alice\"][\"courses\"], {})", "solution_code": "def add_course_score(self, name, course, score):\n if name in self.students:\n self.students[name]['courses'][course] = score", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.students" ], "method_dependencies": [] } }, { "method_name": "get_gpa", "method_description": "def get_gpa(self, name):\n \"\"\"\n Get average grade of one student.\n :param name: str, student name\n :return: if name is in students and this students have courses grade, return average grade(float)\n or None otherwise\n >>> system.add_student('student 1', 3, 'SE')\n >>> system.add_course_score('student 1', 'math', 94)\n >>> system.add_course_score('student 1', 'Computer Network', 92)\n >>> system.get_gpa('student 1')\n 93.0\n\n \"\"\"", "test_class": "AssessmentSystemTestGetGPA", "test_code": "class AssessmentSystemTestGetGPA(unittest.TestCase):\n def test_get_gpa_1(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 80}}}\n self.assertEqual(assessment_system.get_gpa(\"Alice\"), 85.0)\n\n\n # No such student\n def test_get_gpa_2(self):\n assessment_system = AssessmentSystem()\n self.assertEqual(assessment_system.get_gpa('Alice'), None)\n\n # student don't have any scores\n def test_get_gpa_3(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}}\n self.assertEqual(assessment_system.get_gpa('Alice'), None)\n\n def test_get_gpa_4(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90}}}\n self.assertEqual(assessment_system.get_gpa('Bob'), None)\n\n def test_get_gpa_5(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90}}}\n self.assertEqual(assessment_system.get_gpa('Alice'), 90.0)", "solution_code": "def get_gpa(self, name):\n if name in self.students and self.students[name]['courses']:\n return sum(self.students[name]['courses'].values()) / len(self.students[name]['courses'])\n else:\n return None", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.students" ], "method_dependencies": [] } }, { "method_name": "get_all_students_with_fail_course", "method_description": "def get_all_students_with_fail_course(self):\n \"\"\"\n Get all students who have any score blow 60\n :return: list of str ,student name\n >>> system.add_course_score('student 1', 'Society', 59)\n >>> system.get_all_students_with_fail_course()\n ['student 1']\n \"\"\"", "test_class": "AssessmentSystemTestGetAllStudentsWithFailCourse", "test_code": "class AssessmentSystemTestGetAllStudentsWithFailCourse(unittest.TestCase):\n def test_get_all_students_with_fail_course(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 80}},\n 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 50}},\n 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70}},\n 'David': {'name': 'David', 'grade': 1, 'major': 'Physics', 'courses': {'Physics': 60}},\n 'Eve': {'name': 'Eve', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90}}}\n self.assertEqual(assessment_system.get_all_students_with_fail_course(), ['Bob'])\n\n def test_get_all_students_with_fail_course_2(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 80}},\n 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 70}},\n 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70}},\n 'David': {'name': 'David', 'grade': 1, 'major': 'Physics', 'courses': {'Physics': 70}},\n 'Eve': {'name': 'Eve', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90}}}\n self.assertEqual(assessment_system.get_all_students_with_fail_course(), [])\n\n def test_get_all_students_with_fail_course_3(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {}\n self.assertEqual(assessment_system.get_all_students_with_fail_course(), [])\n\n def test_get_all_students_with_fail_course_4(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}}\n self.assertEqual(assessment_system.get_all_students_with_fail_course(), [])\n\n def test_get_all_students_with_fail_course_5(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 50}},\n 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 50}},\n 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70}},\n 'David': {'name': 'David', 'grade': 1, 'major': 'Physics', 'courses': {'Physics': 70}},\n 'Eve': {'name': 'Eve', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90}}}\n self.assertEqual(assessment_system.get_all_students_with_fail_course(), ['Alice', 'Bob'])", "solution_code": "def get_all_students_with_fail_course(self):\n students = []\n for name, student in self.students.items():\n for course, score in student['courses'].items():\n if score < 60:\n students.append(name)\n break\n return students", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.students" ], "method_dependencies": [] } }, { "method_name": "get_course_average", "method_description": "def get_course_average(self, course):\n \"\"\"\n Get the average score of a specific course.\n :param course: str, course name\n :return: float, average scores of this course if anyone have score of this course, or None if nobody have records.\n \"\"\"", "test_class": "AssessmentSystemTestGetCourseAverage", "test_code": "class AssessmentSystemTestGetCourseAverage(unittest.TestCase):\n\n def test_get_course_average_1(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 80}},\n 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 90}},\n 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70,'Physics': 80}}\n }\n self.assertEqual(assessment_system.get_course_average(\"Physics\"), 85.0)\n\n def test_get_course_average_2(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics',\n 'courses': {'Mathematics': 90, 'Science': 80}},\n 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics',\n 'courses': {'Physics': 85}},\n 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry',\n 'courses': {'Chemistry': 70,'Physics': None }}\n }\n self.assertEqual(assessment_system.get_course_average('Physics'), 85)\n\n def test_get_course_average_3(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics',\n 'courses': {'Mathematics': 90, 'Science': 80}},\n 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics',\n 'courses': {'Physics': 85}},\n 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry',\n 'courses': {'Chemistry': 70, 'Physics': 80}}\n }\n self.assertEqual(assessment_system.get_course_average('Computer'), None)\n\n def test_get_course_average_4(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {}\n self.assertEqual(assessment_system.get_course_average('Computer'), None)\n\n def test_get_course_average_5(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics',\n 'courses': {'Mathematics': 90, 'Science': 80}},\n 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics',\n 'courses': {'Physics': 85}},\n 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry',\n 'courses': {'Chemistry': 70, 'Physics': 80}}\n }\n self.assertEqual(assessment_system.get_course_average('Mathematics'), 90)", "solution_code": "def get_course_average(self, course):\n total = 0\n count = 0\n for student in self.students.values():\n if course in student['courses']:\n score = student['courses'][course]\n if score is not None:\n total += score\n count += 1\n return total / count if count > 0 else None", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.students" ], "method_dependencies": [] } }, { "method_name": "get_top_student", "method_description": "def get_top_student(self):\n \"\"\"\n Calculate every student's gpa with get_gpa method, and find the student with highest gpa\n :return: str, name of student whose gpa is highest\n >>> system.add_student('student 1', 3, 'SE')\n >>> system.add_student('student 2', 2, 'SE')\n >>> system.add_course_score('student 1', 'Computer Network', 92)\n >>> system.add_course_score('student 2', 'Computer Network', 97)\n >>> system.get_top_student()\n 'student 2'\n \"\"\"", "test_class": "AssessmentSystemTestGetTopStudent", "test_code": "class AssessmentSystemTestGetTopStudent(unittest.TestCase):\n def test_get_top_student(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics',\n 'courses': {'Mathematics': 90}},\n 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics',\n 'courses': {'Physics': 85}}\n }\n self.assertEqual(assessment_system.get_top_student(), \"Alice\")\n\n def test_get_top_student_2(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics',\n 'courses': { }},\n 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics',\n 'courses': {'Physics': 85}},\n 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry',\n 'courses': {'Chemistry': 70, 'Physics': 80}}\n }\n self.assertEqual(assessment_system.get_top_student(), \"Bob\")\n\n def test_get_top_student_3(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {}\n self.assertEqual(assessment_system.get_top_student(), None)\n\n def test_get_top_student_4(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics',\n 'courses': {'Mathematics': 90, 'Science': 60}},\n 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics',\n 'courses': {'Physics': 85}},\n 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry',\n 'courses': {'Chemistry': 70, 'Physics': 80}}\n }\n self.assertEqual(assessment_system.get_top_student(), \"Bob\")\n\n def test_get_top_student_5(self):\n assessment_system = AssessmentSystem()\n assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics',\n 'courses': {'Mathematics': 90, 'Science': 60}},\n 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics',\n 'courses': {'Physics': 85}},\n 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry',\n 'courses': {'Chemistry': 70, 'Physics': 80}},\n 'David': {'name': 'David', 'grade': 2, 'major': 'Chemistry',\n 'courses': {'Chemistry': 70, 'Physics': 80}}\n }\n self.assertEqual(assessment_system.get_top_student(), \"Bob\")", "solution_code": "def get_top_student(self):\n top_student = None\n top_gpa = 0\n for name, student in self.students.items():\n gpa = self.get_gpa(name)\n if gpa is not None and gpa > top_gpa:\n top_gpa = gpa\n top_student = name\n return top_student", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.students" ], "method_dependencies": [ "get_gpa" ] } } ] }, { "task_id": "ClassEval_5", "skeleton": "\nclass AutomaticGuitarSimulator:\n \"\"\"\n This class is an automatic guitar simulator that can interpret and play based on the input guitar sheet music.\n \"\"\"\n\n def __init__(self, text) -> None:\n \"\"\"\n Initialize the score to be played\n :param text:str, score to be played\n \"\"\"\n self.play_text = text\n\n def interpret(self, display=False):\n \"\"\"\n Interpret the music score to be played\n :param display:Bool, representing whether to print the interpreted score\n :return:list of dict, The dict includes two fields, Chore and Tune, which are letters and numbers, respectively\n >>> context = AutomaticGuitarSimulator(\"C53231323 Em43231323 F43231323 G63231323\")\n >>> play_list = context.interpret(display = False)\n [{'Chord': 'C', 'Tune': '53231323'}, {'Chord': 'Em', 'Tune': '43231323'}, {'Chord': 'F', 'Tune': '43231323'}, {'Chord': 'G', 'Tune': '63231323'}]\n\n \"\"\"\n\n\n def display(self, key, value):\n \"\"\"\n Print out chord and play tune with following format: Normal Guitar Playing -- Chord: %s, Play Tune: %s\n :param key:str, chord\n :param value:str, play tune\n :return:None\n >>> context = AutomaticGuitarSimulator(\"C53231323 Em43231323 F43231323 G63231323\")\n >>> context.display(\"C\", \"53231323\")\n Normal Guitar Playing -- Chord: C, Play Tune: 53231323\n\n \"\"\"", "test": "import unittest\n\n\nclass AutomaticGuitarSimulatorTestInterpret(unittest.TestCase):\n def test_interpret_1(self):\n context = AutomaticGuitarSimulator(\"C53231323\")\n play_list = context.interpret()\n self.assertEqual(play_list, [{'Chord': 'C', 'Tune': '53231323'}])\n\n def test_interpret_2(self):\n context = AutomaticGuitarSimulator(\"F43231323\")\n play_list = context.interpret()\n self.assertEqual(play_list, [{'Chord': 'F', 'Tune': '43231323'}])\n\n def test_interpret_3(self):\n context = AutomaticGuitarSimulator(\"Em43231323\")\n play_list = context.interpret()\n self.assertEqual(play_list, [{'Chord': 'Em', 'Tune': '43231323'}])\n\n def test_interpret_4(self):\n context = AutomaticGuitarSimulator(\"G63231323\")\n play_list = context.interpret()\n self.assertEqual(play_list, [{'Chord': 'G', 'Tune': '63231323'}])\n\n def test_interpret_5(self):\n context = AutomaticGuitarSimulator(\"F43231323 G63231323\")\n play_list = context.interpret()\n self.assertEqual(play_list, [{'Chord': 'F', 'Tune': '43231323'}, {'Chord': 'G', 'Tune': '63231323'}])\n\n def test_interpret_6(self):\n context = AutomaticGuitarSimulator(\" \")\n play_list = context.interpret()\n self.assertEqual(play_list, [{'Chord': '', 'Tune': ''}, {'Chord': '', 'Tune': ''}])\n\n def test_interpret_7(self):\n context = AutomaticGuitarSimulator(\"ABC43231323 DEF63231323\")\n play_list = context.interpret()\n self.assertEqual(play_list, [{'Chord': 'ABC', 'Tune': '43231323'}, {'Chord': 'DEF', 'Tune': '63231323'}])\n\n def test_interpret_8(self):\n context = AutomaticGuitarSimulator(\"C53231323\")\n play_list = context.interpret(display=True)\n self.assertEqual(play_list, [{'Chord': 'C', 'Tune': '53231323'}])\n\n def test_interpret_9(self):\n context = AutomaticGuitarSimulator(\"\")\n play_list = context.interpret()\n self.assertIsNone(play_list)\n\n\nclass AutomaticGuitarSimulatorTestDisplay(unittest.TestCase):\n def test_display_1(self):\n context = AutomaticGuitarSimulator(\"C53231323 Em43231323\")\n play_list = context.interpret()\n str = context.display(play_list[0]['Chord'], play_list[0]['Tune'])\n self.assertEqual(str, \"Normal Guitar Playing -- Chord: C, Play Tune: 53231323\")\n\n def test_display_2(self):\n context = AutomaticGuitarSimulator(\"C53231323 Em43231323\")\n play_list = context.interpret()\n str = context.display(play_list[1]['Chord'], play_list[1]['Tune'])\n self.assertEqual(str, \"Normal Guitar Playing -- Chord: Em, Play Tune: 43231323\")\n\n def test_display_3(self):\n context = AutomaticGuitarSimulator(\"F43231323 G63231323\")\n play_list = context.interpret()\n str = context.display(play_list[0]['Chord'], play_list[0]['Tune'])\n self.assertEqual(str, \"Normal Guitar Playing -- Chord: F, Play Tune: 43231323\")\n\n def test_display_4(self):\n context = AutomaticGuitarSimulator(\"F43231323 G63231323\")\n play_list = context.interpret()\n str = context.display(play_list[1]['Chord'], play_list[1]['Tune'])\n self.assertEqual(str, \"Normal Guitar Playing -- Chord: G, Play Tune: 63231323\")\n\n def test_display_5(self):\n context = AutomaticGuitarSimulator(\"\")\n str = context.display('', '')\n self.assertEqual(str, \"Normal Guitar Playing -- Chord: , Play Tune: \")\n\n\nclass AutomaticGuitarSimulatorTest(unittest.TestCase):\n def test_AutomaticGuitarSimulator(self):\n context = AutomaticGuitarSimulator(\"C53231323\")\n play_list = context.interpret()\n self.assertEqual(play_list, [{'Chord': 'C', 'Tune': '53231323'}])\n\n context = AutomaticGuitarSimulator(\"C53231323 Em43231323\")\n play_list = context.interpret()\n str = context.display(play_list[0]['Chord'], play_list[0]['Tune'])\n self.assertEqual(str, \"Normal Guitar Playing -- Chord: C, Play Tune: 53231323\")", "solution_code": "class AutomaticGuitarSimulator:\n def __init__(self, text) -> None:\n self.play_text = text\n\n def interpret(self, display=False):\n if len(self.play_text) == 0:\n return\n else:\n play_list = []\n play_segs = self.play_text.split(\" \")\n for play_seg in play_segs:\n pos = 0\n for ele in play_seg:\n if ele.isalpha():\n pos += 1\n continue\n break\n play_chord = play_seg[0:pos]\n play_value = play_seg[pos:]\n play_list.append({'Chord': play_chord, 'Tune': play_value})\n if display:\n self.display(play_chord, play_value)\n return play_list\n\n def display(self, key, value):\n return \"Normal Guitar Playing -- Chord: %s, Play Tune: %s\" % (key, value)", "import_statement": [], "class_description": " \"\"\"\n This class is an automatic guitar simulator that can interpret and play based on the input guitar sheet music.\n \"\"\"\n", "class_name": "AutomaticGuitarSimulator", "test_classes": [ "AutomaticGuitarSimulatorTestInterpret", "AutomaticGuitarSimulatorTestDisplay", "AutomaticGuitarSimulatorTest" ], "class_constructor": "class AutomaticGuitarSimulator: \n def __init__(self, text) -> None:\n \"\"\"\n Initialize the score to be played\n :param text:str, score to be played\n \"\"\"\n self.play_text = text\n\n", "fields": [ "self.play_text" ], "methods_info": [ { "method_name": "interpret", "method_description": "def interpret(self, display=False):\n \"\"\"\n Interpret the music score to be played\n :param display:Bool, representing whether to print the interpreted score\n :return:list of dict, The dict includes two fields, Chore and Tune, which are letters and numbers, respectively\n >>> context = AutomaticGuitarSimulator(\"C53231323 Em43231323 F43231323 G63231323\")\n >>> play_list = context.interpret(display = False)\n [{'Chord': 'C', 'Tune': '53231323'}, {'Chord': 'Em', 'Tune': '43231323'}, {'Chord': 'F', 'Tune': '43231323'}, {'Chord': 'G', 'Tune': '63231323'}]\n\n \"\"\"", "test_class": "AutomaticGuitarSimulatorTestInterpret", "test_code": "class AutomaticGuitarSimulatorTestInterpret(unittest.TestCase):\n def test_interpret_1(self):\n context = AutomaticGuitarSimulator(\"C53231323\")\n play_list = context.interpret()\n self.assertEqual(play_list, [{'Chord': 'C', 'Tune': '53231323'}])\n\n def test_interpret_2(self):\n context = AutomaticGuitarSimulator(\"F43231323\")\n play_list = context.interpret()\n self.assertEqual(play_list, [{'Chord': 'F', 'Tune': '43231323'}])\n\n def test_interpret_3(self):\n context = AutomaticGuitarSimulator(\"Em43231323\")\n play_list = context.interpret()\n self.assertEqual(play_list, [{'Chord': 'Em', 'Tune': '43231323'}])\n\n def test_interpret_4(self):\n context = AutomaticGuitarSimulator(\"G63231323\")\n play_list = context.interpret()\n self.assertEqual(play_list, [{'Chord': 'G', 'Tune': '63231323'}])\n\n def test_interpret_5(self):\n context = AutomaticGuitarSimulator(\"F43231323 G63231323\")\n play_list = context.interpret()\n self.assertEqual(play_list, [{'Chord': 'F', 'Tune': '43231323'}, {'Chord': 'G', 'Tune': '63231323'}])\n\n def test_interpret_6(self):\n context = AutomaticGuitarSimulator(\" \")\n play_list = context.interpret()\n self.assertEqual(play_list, [{'Chord': '', 'Tune': ''}, {'Chord': '', 'Tune': ''}])\n\n def test_interpret_7(self):\n context = AutomaticGuitarSimulator(\"ABC43231323 DEF63231323\")\n play_list = context.interpret()\n self.assertEqual(play_list, [{'Chord': 'ABC', 'Tune': '43231323'}, {'Chord': 'DEF', 'Tune': '63231323'}])\n\n def test_interpret_8(self):\n context = AutomaticGuitarSimulator(\"C53231323\")\n play_list = context.interpret(display=True)\n self.assertEqual(play_list, [{'Chord': 'C', 'Tune': '53231323'}])\n\n def test_interpret_9(self):\n context = AutomaticGuitarSimulator(\"\")\n play_list = context.interpret()\n self.assertIsNone(play_list)", "solution_code": "def interpret(self, display=False):\n if len(self.play_text) == 0:\n return\n else:\n play_list = []\n play_segs = self.play_text.split(\" \")\n for play_seg in play_segs:\n pos = 0\n for ele in play_seg:\n if ele.isalpha():\n pos += 1\n continue\n break\n play_chord = play_seg[0:pos]\n play_value = play_seg[pos:]\n play_list.append({'Chord': play_chord, 'Tune': play_value})\n if display:\n self.display(play_chord, play_value)\n return play_list", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.play_text" ], "method_dependencies": [ "display" ] } }, { "method_name": "display", "method_description": "def display(self, key, value):\n \"\"\"\n Print out chord and play tune with following format: Normal Guitar Playing -- Chord: %s, Play Tune: %s\n :param key:str, chord\n :param value:str, play tune\n :return:None\n >>> context = AutomaticGuitarSimulator(\"C53231323 Em43231323 F43231323 G63231323\")\n >>> context.display(\"C\", \"53231323\")\n Normal Guitar Playing -- Chord: C, Play Tune: 53231323\n\n \"\"\"", "test_class": "AutomaticGuitarSimulatorTestDisplay", "test_code": "class AutomaticGuitarSimulatorTestDisplay(unittest.TestCase):\n def test_display_1(self):\n context = AutomaticGuitarSimulator(\"C53231323 Em43231323\")\n play_list = context.interpret()\n str = context.display(play_list[0]['Chord'], play_list[0]['Tune'])\n self.assertEqual(str, \"Normal Guitar Playing -- Chord: C, Play Tune: 53231323\")\n\n def test_display_2(self):\n context = AutomaticGuitarSimulator(\"C53231323 Em43231323\")\n play_list = context.interpret()\n str = context.display(play_list[1]['Chord'], play_list[1]['Tune'])\n self.assertEqual(str, \"Normal Guitar Playing -- Chord: Em, Play Tune: 43231323\")\n\n def test_display_3(self):\n context = AutomaticGuitarSimulator(\"F43231323 G63231323\")\n play_list = context.interpret()\n str = context.display(play_list[0]['Chord'], play_list[0]['Tune'])\n self.assertEqual(str, \"Normal Guitar Playing -- Chord: F, Play Tune: 43231323\")\n\n def test_display_4(self):\n context = AutomaticGuitarSimulator(\"F43231323 G63231323\")\n play_list = context.interpret()\n str = context.display(play_list[1]['Chord'], play_list[1]['Tune'])\n self.assertEqual(str, \"Normal Guitar Playing -- Chord: G, Play Tune: 63231323\")\n\n def test_display_5(self):\n context = AutomaticGuitarSimulator(\"\")\n str = context.display('', '')\n self.assertEqual(str, \"Normal Guitar Playing -- Chord: , Play Tune: \")", "solution_code": "def display(self, key, value):\n return \"Normal Guitar Playing -- Chord: %s, Play Tune: %s\" % (key, value)", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_6", "skeleton": "\nclass AvgPartition:\n \"\"\"\n This is a class that partitions the given list into different blocks by specifying the number of partitions, with each block having a uniformly distributed length.\n \"\"\"\n\n def __init__(self, lst, limit):\n \"\"\"\n Initialize the class with the given list and the number of partitions, and check if the number of partitions is greater than 0.\n \"\"\"\n self.lst = lst\n self.limit = limit\n\n def setNum(self):\n \"\"\"\n Calculate the size of each block and the remainder of the division.\n :return: the size of each block and the remainder of the division, tuple.\n >>> a = AvgPartition([1, 2, 3, 4], 2)\n >>> a.setNum()\n (2, 0)\n\n \"\"\"\n\n\n def get(self, index):\n \"\"\"\n calculate the size of each block and the remainder of the division, and calculate the corresponding start and end positions based on the index of the partition.\n :param index: the index of the partition,int.\n :return: the corresponding block, list.\n >>> a = AvgPartition([1, 2, 3, 4], 2)\n >>> a.get(0)\n [1, 2]\n\n \"\"\"", "test": "import unittest\n\nclass AvgPartitionTestSetNum(unittest.TestCase):\n def test_setNum(self):\n a = AvgPartition([1, 2, 3, 4], 2)\n self.assertEqual(a.setNum(), (2, 0))\n\n def test_setNum_2(self):\n a = AvgPartition([1, 2, 3, 4, 5], 2)\n self.assertEqual(a.setNum(), (2, 1))\n\n def test_setNum_3(self):\n a = AvgPartition([1, 2, 3, 4, 5], 3)\n self.assertEqual(a.setNum(), (1, 2))\n\n def test_setNum_4(self):\n a = AvgPartition([1, 2, 3, 4, 5], 4)\n self.assertEqual(a.setNum(), (1, 1))\n\n def test_setNum_5(self):\n a = AvgPartition([1, 2, 3, 4, 5], 5)\n self.assertEqual(a.setNum(), (1, 0))\n\nclass AvgPartitionTestGet(unittest.TestCase):\n\n def test_get(self):\n a = AvgPartition([1, 2, 3, 4], 2)\n self.assertEqual(a.get(0), [1, 2])\n\n def test_get_2(self):\n a = AvgPartition([1, 2, 3, 4], 2)\n self.assertEqual(a.get(1), [3, 4])\n\n def test_get_3(self):\n a = AvgPartition([1, 2, 3, 4, 5], 2)\n self.assertEqual(a.get(0), [1, 2, 3])\n\n def test_get_4(self):\n a = AvgPartition([1, 2, 3, 4, 5], 2)\n self.assertEqual(a.get(1), [4, 5])\n\n def test_get_5(self):\n a = AvgPartition([1, 2, 3, 4, 5], 3)\n self.assertEqual(a.get(0), [1, 2])\n\nclass AvgPartitionTestMain(unittest.TestCase):\n def test_main(self):\n a = AvgPartition([1, 2, 3, 4], 2)\n self.assertEqual(a.setNum(), (2, 0))\n self.assertEqual(a.get(0), [1, 2])", "solution_code": "class AvgPartition:\n def __init__(self, lst, limit):\n self.lst = lst\n self.limit = limit\n\n def setNum(self):\n size = len(self.lst) // self.limit\n remainder = len(self.lst) % self.limit\n return size, remainder\n\n \n def get(self, index):\n size, remainder = self.setNum()\n start = index * size + min(index, remainder)\n end = start + size\n if index + 1 <= remainder:\n end += 1\n return self.lst[start:end]", "import_statement": [], "class_description": " \"\"\"\n This is a class that partitions the given list into different blocks by specifying the number of partitions, with each block having a uniformly distributed length.\n \"\"\"\n", "class_name": "AvgPartition", "test_classes": [ "AvgPartitionTestSetNum", "AvgPartitionTestGet", "AvgPartitionTestMain" ], "class_constructor": "class AvgPartition: \n def __init__(self, lst, limit):\n \"\"\"\n Initialize the class with the given list and the number of partitions, and check if the number of partitions is greater than 0.\n \"\"\"\n self.lst = lst\n self.limit = limit\n\n", "fields": [ "self.limit", "self.lst" ], "methods_info": [ { "method_name": "setNum", "method_description": "def setNum(self):\n \"\"\"\n Calculate the size of each block and the remainder of the division.\n :return: the size of each block and the remainder of the division, tuple.\n >>> a = AvgPartition([1, 2, 3, 4], 2)\n >>> a.setNum()\n (2, 0)\n\n \"\"\"", "test_class": "AvgPartitionTestSetNum", "test_code": "class AvgPartitionTestSetNum(unittest.TestCase):\n def test_setNum(self):\n a = AvgPartition([1, 2, 3, 4], 2)\n self.assertEqual(a.setNum(), (2, 0))\n\n def test_setNum_2(self):\n a = AvgPartition([1, 2, 3, 4, 5], 2)\n self.assertEqual(a.setNum(), (2, 1))\n\n def test_setNum_3(self):\n a = AvgPartition([1, 2, 3, 4, 5], 3)\n self.assertEqual(a.setNum(), (1, 2))\n\n def test_setNum_4(self):\n a = AvgPartition([1, 2, 3, 4, 5], 4)\n self.assertEqual(a.setNum(), (1, 1))\n\n def test_setNum_5(self):\n a = AvgPartition([1, 2, 3, 4, 5], 5)\n self.assertEqual(a.setNum(), (1, 0))", "solution_code": "def setNum(self):\n size = len(self.lst) // self.limit\n remainder = len(self.lst) % self.limit\n return size, remainder", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.limit", "self.lst" ], "method_dependencies": [] } }, { "method_name": "get", "method_description": "def get(self, index):\n \"\"\"\n calculate the size of each block and the remainder of the division, and calculate the corresponding start and end positions based on the index of the partition.\n :param index: the index of the partition,int.\n :return: the corresponding block, list.\n >>> a = AvgPartition([1, 2, 3, 4], 2)\n >>> a.get(0)\n [1, 2]\n\n \"\"\"", "test_class": "AvgPartitionTestGet", "test_code": "class AvgPartitionTestGet(unittest.TestCase):\n\n def test_get(self):\n a = AvgPartition([1, 2, 3, 4], 2)\n self.assertEqual(a.get(0), [1, 2])\n\n def test_get_2(self):\n a = AvgPartition([1, 2, 3, 4], 2)\n self.assertEqual(a.get(1), [3, 4])\n\n def test_get_3(self):\n a = AvgPartition([1, 2, 3, 4, 5], 2)\n self.assertEqual(a.get(0), [1, 2, 3])\n\n def test_get_4(self):\n a = AvgPartition([1, 2, 3, 4, 5], 2)\n self.assertEqual(a.get(1), [4, 5])\n\n def test_get_5(self):\n a = AvgPartition([1, 2, 3, 4, 5], 3)\n self.assertEqual(a.get(0), [1, 2])", "solution_code": "def get(self, index):\n size, remainder = self.setNum()\n start = index * size + min(index, remainder)\n end = start + size\n if index + 1 <= remainder:\n end += 1\n return self.lst[start:end]", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.lst" ], "method_dependencies": [ "setNum" ] } } ] }, { "task_id": "ClassEval_7", "skeleton": "\nclass BalancedBrackets:\n \"\"\"\n This is a class that checks for bracket matching\n \"\"\"\n\n def __init__(self, expr):\n \"\"\"\n Initializes the class with an expression.\n :param expr: The expression to check for balanced brackets,str.\n \"\"\"\n self.stack = []\n self.left_brackets = [\"(\", \"{\", \"[\"]\n self.right_brackets = [\")\", \"}\", \"]\"]\n self.expr = expr\n\n def clear_expr(self):\n \"\"\"\n Clears the expression of all characters that are not brackets.\n >>> b = BalancedBrackets(\"a(b)c\")\n >>> b.clear_expr()\n >>> b.expr\n '()'\n\n \"\"\"\n\n def check_balanced_brackets(self):\n \"\"\"\n Checks if the expression has balanced brackets.\n :return: True if the expression has balanced brackets, False otherwise.\n >>> b = BalancedBrackets(\"a(b)c\")\n >>> b.check_balanced_brackets()\n True\n\n \"\"\"", "test": "import unittest\n\n\nclass BalancedBracketsTestClearExpr(unittest.TestCase):\n def test_clear_expr(self):\n b = BalancedBrackets(\"a(b)c\")\n b.clear_expr()\n self.assertEqual(b.expr, \"()\")\n\n def test_clear_expr_2(self):\n b = BalancedBrackets(\"a(b){c}\")\n b.clear_expr()\n self.assertEqual(b.expr, \"(){}\")\n\n def test_clear_expr_3(self):\n b = BalancedBrackets(\"[a](b){c}\")\n b.clear_expr()\n self.assertEqual(b.expr, \"[](){}\")\n\n def test_clear_expr_4(self):\n b = BalancedBrackets(\"[a(b){c}\")\n b.clear_expr()\n self.assertEqual(b.expr, \"[(){}\")\n\n def test_clear_expr_5(self):\n b = BalancedBrackets(\"a(b){c}]\")\n b.clear_expr()\n self.assertEqual(b.expr, \"(){}]\")\n\n\nclass BalancedBracketsTestCheckBalancedBrackets(unittest.TestCase):\n def test_check_balanced_brackets(self):\n b = BalancedBrackets(\"a(b)c\")\n self.assertEqual(b.check_balanced_brackets(), True)\n\n def test_check_balanced_brackets_2(self):\n b = BalancedBrackets(\"a(b){c}\")\n self.assertEqual(b.check_balanced_brackets(), True)\n\n def test_check_balanced_brackets_3(self):\n b = BalancedBrackets(\"[a](b){c}\")\n self.assertEqual(b.check_balanced_brackets(), True)\n\n def test_check_balanced_brackets_4(self):\n b = BalancedBrackets(\"[a(b){c}\")\n self.assertEqual(b.check_balanced_brackets(), False)\n\n def test_check_balanced_brackets_5(self):\n b = BalancedBrackets(\"a(b{c}]\")\n self.assertEqual(b.check_balanced_brackets(), False)\n\n def test_check_balanced_brackets_6(self):\n b = BalancedBrackets(\"a(b{c]]\")\n self.assertEqual(b.check_balanced_brackets(), False)\n\n def test_check_balanced_brackets_7(self):\n b = BalancedBrackets(\"[a)(b){c}\")\n self.assertEqual(b.check_balanced_brackets(), False)\n\n\nclass BalancedBracketsTestMain(unittest.TestCase):\n def test_main(self):\n b = BalancedBrackets(\"a(b)c\")\n b.clear_expr()\n self.assertEqual(b.expr, \"()\")\n self.assertEqual(b.check_balanced_brackets(), True)\n\n def test_main_2(self):\n b = BalancedBrackets(\"[a(b){c}\")\n b.clear_expr()\n self.assertEqual(b.expr, \"[(){}\")\n self.assertEqual(b.check_balanced_brackets(), False)\n\n def test_main_3(self):\n b = BalancedBrackets(\"a(b{c}]\")\n b.clear_expr()\n self.assertEqual(b.expr, \"({}]\")\n self.assertEqual(b.check_balanced_brackets(), False)", "solution_code": "class BalancedBrackets:\n def __init__(self, expr):\n self.stack = []\n self.left_brackets = [\"(\", \"{\", \"[\"]\n self.right_brackets = [\")\", \"}\", \"]\"]\n self.expr = expr\n\n def clear_expr(self):\n self.expr = ''.join(c for c in self.expr if (c in self.left_brackets or c in self.right_brackets))\n\n def check_balanced_brackets(self):\n self.clear_expr()\n for Brkt in self.expr:\n if Brkt in self.left_brackets:\n self.stack.append(Brkt)\n else:\n Current_Brkt = self.stack.pop()\n if Current_Brkt == \"(\":\n if Brkt != \")\":\n return False\n if Current_Brkt == \"{\":\n if Brkt != \"}\":\n return False\n if Current_Brkt == \"[\":\n if Brkt != \"]\":\n return False\n if self.stack:\n return False\n return True", "import_statement": [], "class_description": " \"\"\"\n This is a class that checks for bracket matching\n \"\"\"\n", "class_name": "BalancedBrackets", "test_classes": [ "BalancedBracketsTestClearExpr", "BalancedBracketsTestCheckBalancedBrackets", "BalancedBracketsTestMain" ], "class_constructor": "class BalancedBrackets: \n def __init__(self, expr):\n \"\"\"\n Initializes the class with an expression.\n :param expr: The expression to check for balanced brackets,str.\n \"\"\"\n self.stack = []\n self.left_brackets = [\"(\", \"{\", \"[\"]\n self.right_brackets = [\")\", \"}\", \"]\"]\n self.expr = expr\n\n", "fields": [ "self.expr", "self.left_brackets", "self.right_brackets", "self.stack" ], "methods_info": [ { "method_name": "clear_expr", "method_description": "def clear_expr(self):\n \"\"\"\n Clears the expression of all characters that are not brackets.\n >>> b = BalancedBrackets(\"a(b)c\")\n >>> b.clear_expr()\n >>> b.expr\n '()'\n\n \"\"\"", "test_class": "BalancedBracketsTestClearExpr", "test_code": "class BalancedBracketsTestClearExpr(unittest.TestCase):\n def test_clear_expr(self):\n b = BalancedBrackets(\"a(b)c\")\n b.clear_expr()\n self.assertEqual(b.expr, \"()\")\n\n def test_clear_expr_2(self):\n b = BalancedBrackets(\"a(b){c}\")\n b.clear_expr()\n self.assertEqual(b.expr, \"(){}\")\n\n def test_clear_expr_3(self):\n b = BalancedBrackets(\"[a](b){c}\")\n b.clear_expr()\n self.assertEqual(b.expr, \"[](){}\")\n\n def test_clear_expr_4(self):\n b = BalancedBrackets(\"[a(b){c}\")\n b.clear_expr()\n self.assertEqual(b.expr, \"[(){}\")\n\n def test_clear_expr_5(self):\n b = BalancedBrackets(\"a(b){c}]\")\n b.clear_expr()\n self.assertEqual(b.expr, \"(){}]\")", "solution_code": "def clear_expr(self):\n self.expr = ''.join(c for c in self.expr if (c in self.left_brackets or c in self.right_brackets))", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.expr", "self.left_brackets", "self.right_brackets" ], "method_dependencies": [] } }, { "method_name": "check_balanced_brackets", "method_description": "def check_balanced_brackets(self):\n \"\"\"\n Checks if the expression has balanced brackets.\n :return: True if the expression has balanced brackets, False otherwise.\n >>> b = BalancedBrackets(\"a(b)c\")\n >>> b.check_balanced_brackets()\n True\n\n \"\"\"", "test_class": "BalancedBracketsTestCheckBalancedBrackets", "test_code": "class BalancedBracketsTestCheckBalancedBrackets(unittest.TestCase):\n def test_check_balanced_brackets(self):\n b = BalancedBrackets(\"a(b)c\")\n self.assertEqual(b.check_balanced_brackets(), True)\n\n def test_check_balanced_brackets_2(self):\n b = BalancedBrackets(\"a(b){c}\")\n self.assertEqual(b.check_balanced_brackets(), True)\n\n def test_check_balanced_brackets_3(self):\n b = BalancedBrackets(\"[a](b){c}\")\n self.assertEqual(b.check_balanced_brackets(), True)\n\n def test_check_balanced_brackets_4(self):\n b = BalancedBrackets(\"[a(b){c}\")\n self.assertEqual(b.check_balanced_brackets(), False)\n\n def test_check_balanced_brackets_5(self):\n b = BalancedBrackets(\"a(b{c}]\")\n self.assertEqual(b.check_balanced_brackets(), False)\n\n def test_check_balanced_brackets_6(self):\n b = BalancedBrackets(\"a(b{c]]\")\n self.assertEqual(b.check_balanced_brackets(), False)\n\n def test_check_balanced_brackets_7(self):\n b = BalancedBrackets(\"[a)(b){c}\")\n self.assertEqual(b.check_balanced_brackets(), False)", "solution_code": "def check_balanced_brackets(self):\n self.clear_expr()\n for Brkt in self.expr:\n if Brkt in self.left_brackets:\n self.stack.append(Brkt)\n else:\n Current_Brkt = self.stack.pop()\n if Current_Brkt == \"(\":\n if Brkt != \")\":\n return False\n if Current_Brkt == \"{\":\n if Brkt != \"}\":\n return False\n if Current_Brkt == \"[\":\n if Brkt != \"]\":\n return False\n if self.stack:\n return False\n return True", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.expr", "self.left_brackets", "self.stack" ], "method_dependencies": [ "clear_expr" ] } } ] }, { "task_id": "ClassEval_8", "skeleton": "\nclass BankAccount:\n \"\"\"\n This is a class as a bank account system, which supports deposit money, withdraw money, view balance, and transfer money.\n \"\"\"\n\n def __init__(self, balance=0):\n \"\"\"\n Initializes a bank account object with an attribute balance, default value is 0.\n \"\"\"\n self.balance = balance\n\n def deposit(self, amount):\n \"\"\"\n Deposits a certain amount into the account, increasing the account balance, return the current account balance.\n If amount is negative, raise a ValueError(\"Invalid amount\").\n :param amount: int\n \"\"\"\n\n def withdraw(self, amount):\n \"\"\"\n Withdraws a certain amount from the account, decreasing the account balance, return the current account balance.\n If amount is negative, raise a ValueError(\"Invalid amount\").\n If the withdrawal amount is greater than the account balance, raise a ValueError(\"Insufficient balance.\").\n :param amount: int\n \"\"\"\n\n def view_balance(self):\n \"\"\"\n Return the account balance.\n \"\"\"\n\n def transfer(self, other_account, amount):\n \"\"\"\n Transfers a certain amount from the current account to another account.\n :param other_account: BankAccount\n :param amount: int\n >>> account1 = BankAccount()\n >>> account2 = BankAccount()\n >>> account1.deposit(1000)\n >>> account1.transfer(account2, 300)\n account1.balance = 700 account2.balance = 300\n \"\"\"", "test": "import unittest\n\nclass BankAccountTestDeposit(unittest.TestCase):\n\n def test_deposit(self):\n account1 = BankAccount()\n ret = account1.deposit(1000)\n self.assertEqual(ret, 1000)\n\n def test_deposit_2(self):\n account1 = BankAccount()\n account1.deposit(1000)\n ret = account1.deposit(2000)\n self.assertEqual(ret, 3000)\n\n\n def test_deposit_3(self):\n account1 = BankAccount()\n with self.assertRaises(ValueError) as context:\n account1.deposit(-1000)\n self.assertEqual(str(context.exception), \"Invalid amount\")\n\n def test_deposit_4(self):\n account1 = BankAccount()\n ret = account1.deposit(0)\n self.assertEqual(ret, 0)\n\n def test_deposit_5(self):\n account1 = BankAccount()\n account1.deposit(1000)\n ret = account1.deposit(1000)\n self.assertEqual(ret, 2000)\n\nclass BankAccountTestWithdraw(unittest.TestCase):\n\n def test_withdraw(self):\n account1 = BankAccount()\n account1.balance = 1000\n ret = account1.withdraw(200)\n self.assertEqual(ret, 800)\n\n def test_withdraw_2(self):\n account1 = BankAccount()\n account1.balance = 500\n with self.assertRaises(ValueError) as context:\n account1.withdraw(1000)\n self.assertEqual(str(context.exception), \"Insufficient balance.\")\n\n def test_withdraw_3(self):\n account1 = BankAccount()\n with self.assertRaises(ValueError) as context:\n account1.withdraw(-1000)\n self.assertEqual(str(context.exception), \"Invalid amount\")\n\n def test_withdraw_4(self):\n account1 = BankAccount()\n account1.balance = 1000\n ret = account1.withdraw(500)\n self.assertEqual(ret, 500)\n\n def test_withdraw_5(self):\n account1 = BankAccount()\n account1.balance = 1000\n ret = account1.withdraw(1000)\n self.assertEqual(ret, 0)\n\nclass BankAccountTestViewBalance(unittest.TestCase):\n\n def test_view_balance(self):\n account1 = BankAccount()\n self.assertEqual(account1.view_balance(), 0)\n\n def test_view_balance_2(self):\n account1 = BankAccount()\n account1.balance = 1000\n self.assertEqual(account1.view_balance(), 1000)\n\n def test_view_balance_3(self):\n account1 = BankAccount()\n account1.balance = 500\n self.assertEqual(account1.view_balance(), 500)\n\n def test_view_balance_4(self):\n account1 = BankAccount()\n account1.balance = 1500\n self.assertEqual(account1.view_balance(), 1500)\n\n def test_view_balance_5(self):\n account1 = BankAccount()\n account1.balance = 2000\n self.assertEqual(account1.view_balance(), 2000)\n\nclass BankAccountTestTransfer(unittest.TestCase):\n\n def test_transfer(self):\n account1 = BankAccount()\n account2 = BankAccount()\n account1.balance = 800\n account2.balance = 1000\n account1.transfer(account2, 300)\n self.assertEqual(account1.view_balance(), 500)\n self.assertEqual(account2.view_balance(), 1300)\n\n def test_transfer_2(self):\n account1 = BankAccount()\n account2 = BankAccount()\n account1.balance = 500\n with self.assertRaises(ValueError) as context:\n account1.transfer(account2, 600)\n self.assertEqual(str(context.exception), \"Insufficient balance.\")\n\n def test_transfer_3(self):\n account1 = BankAccount()\n account2 = BankAccount()\n account1.balance = 500\n account2.balance = 1000\n with self.assertRaises(ValueError) as context:\n account1.transfer(account2, -600)\n self.assertEqual(str(context.exception), \"Invalid amount\")\n\n def test_transfer_4(self):\n account1 = BankAccount()\n account2 = BankAccount()\n account1.balance = 500\n account2.balance = 1000\n account1.transfer(account2, 500)\n self.assertEqual(account1.view_balance(), 0)\n self.assertEqual(account2.view_balance(), 1500)\n\n def test_transfer_5(self):\n account1 = BankAccount()\n account2 = BankAccount()\n account1.balance = 500\n account2.balance = 1000\n account1.transfer(account2, 200)\n self.assertEqual(account1.view_balance(), 300)\n self.assertEqual(account2.view_balance(), 1200)\n\nclass BankAccountTest(unittest.TestCase):\n\n def test_all(self):\n account1 = BankAccount()\n account2 = BankAccount()\n account1.deposit(1000)\n account1.withdraw(200)\n account1.transfer(account2, 300)\n self.assertEqual(account1.view_balance(), 500)\n self.assertEqual(account2.view_balance(), 300)\n\n def test_all2(self):\n account1 = BankAccount()\n account2 = BankAccount()\n account1.deposit(1000)\n account1.withdraw(200)\n account1.transfer(account2, 300)\n account2.withdraw(100)\n self.assertEqual(account1.view_balance(), 500)\n self.assertEqual(account2.view_balance(), 200)", "solution_code": "class BankAccount:\n def __init__(self, balance=0):\n self.balance = balance\n\n def deposit(self, amount):\n if amount < 0:\n raise ValueError(\"Invalid amount\")\n self.balance += amount\n return self.balance\n\n def withdraw(self, amount):\n if amount < 0:\n raise ValueError(\"Invalid amount\")\n if amount > self.balance:\n raise ValueError(\"Insufficient balance.\")\n self.balance -= amount\n return self.balance\n\n def view_balance(self):\n return self.balance\n\n def transfer(self, other_account, amount):\n self.withdraw(amount)\n other_account.deposit(amount)", "import_statement": [], "class_description": " \"\"\"\n This is a class as a bank account system, which supports deposit money, withdraw money, view balance, and transfer money.\n \"\"\"\n", "class_name": "BankAccount", "test_classes": [ "BankAccountTestDeposit", "BankAccountTestWithdraw", "BankAccountTestViewBalance", "BankAccountTestTransfer", "BankAccountTest" ], "class_constructor": "class BankAccount: \n def __init__(self, balance=0):\n \"\"\"\n Initializes a bank account object with an attribute balance, default value is 0.\n \"\"\"\n self.balance = balance\n\n", "fields": [ "self.balance" ], "methods_info": [ { "method_name": "deposit", "method_description": "def deposit(self, amount):\n \"\"\"\n Deposits a certain amount into the account, increasing the account balance, return the current account balance.\n If amount is negative, raise a ValueError(\"Invalid amount\").\n :param amount: int\n \"\"\"", "test_class": "BankAccountTestDeposit", "test_code": "class BankAccountTestDeposit(unittest.TestCase):\n\n def test_deposit(self):\n account1 = BankAccount()\n ret = account1.deposit(1000)\n self.assertEqual(ret, 1000)\n\n def test_deposit_2(self):\n account1 = BankAccount()\n account1.deposit(1000)\n ret = account1.deposit(2000)\n self.assertEqual(ret, 3000)\n\n\n def test_deposit_3(self):\n account1 = BankAccount()\n with self.assertRaises(ValueError) as context:\n account1.deposit(-1000)\n self.assertEqual(str(context.exception), \"Invalid amount\")\n\n def test_deposit_4(self):\n account1 = BankAccount()\n ret = account1.deposit(0)\n self.assertEqual(ret, 0)\n\n def test_deposit_5(self):\n account1 = BankAccount()\n account1.deposit(1000)\n ret = account1.deposit(1000)\n self.assertEqual(ret, 2000)", "solution_code": "def deposit(self, amount):\n if amount < 0:\n raise ValueError(\"Invalid amount\")\n self.balance += amount\n return self.balance", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.balance" ], "method_dependencies": [] } }, { "method_name": "withdraw", "method_description": "def withdraw(self, amount):\n \"\"\"\n Withdraws a certain amount from the account, decreasing the account balance, return the current account balance.\n If amount is negative, raise a ValueError(\"Invalid amount\").\n If the withdrawal amount is greater than the account balance, raise a ValueError(\"Insufficient balance.\").\n :param amount: int\n \"\"\"", "test_class": "BankAccountTestWithdraw", "test_code": "class BankAccountTestWithdraw(unittest.TestCase):\n\n def test_withdraw(self):\n account1 = BankAccount()\n account1.balance = 1000\n ret = account1.withdraw(200)\n self.assertEqual(ret, 800)\n\n def test_withdraw_2(self):\n account1 = BankAccount()\n account1.balance = 500\n with self.assertRaises(ValueError) as context:\n account1.withdraw(1000)\n self.assertEqual(str(context.exception), \"Insufficient balance.\")\n\n def test_withdraw_3(self):\n account1 = BankAccount()\n with self.assertRaises(ValueError) as context:\n account1.withdraw(-1000)\n self.assertEqual(str(context.exception), \"Invalid amount\")\n\n def test_withdraw_4(self):\n account1 = BankAccount()\n account1.balance = 1000\n ret = account1.withdraw(500)\n self.assertEqual(ret, 500)\n\n def test_withdraw_5(self):\n account1 = BankAccount()\n account1.balance = 1000\n ret = account1.withdraw(1000)\n self.assertEqual(ret, 0)", "solution_code": "def withdraw(self, amount):\n if amount < 0:\n raise ValueError(\"Invalid amount\")\n if amount > self.balance:\n raise ValueError(\"Insufficient balance.\")\n self.balance -= amount\n return self.balance", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.balance" ], "method_dependencies": [] } }, { "method_name": "view_balance", "method_description": "def view_balance(self):\n \"\"\"\n Return the account balance.\n \"\"\"", "test_class": "BankAccountTestViewBalance", "test_code": "class BankAccountTestViewBalance(unittest.TestCase):\n\n def test_view_balance(self):\n account1 = BankAccount()\n self.assertEqual(account1.view_balance(), 0)\n\n def test_view_balance_2(self):\n account1 = BankAccount()\n account1.balance = 1000\n self.assertEqual(account1.view_balance(), 1000)\n\n def test_view_balance_3(self):\n account1 = BankAccount()\n account1.balance = 500\n self.assertEqual(account1.view_balance(), 500)\n\n def test_view_balance_4(self):\n account1 = BankAccount()\n account1.balance = 1500\n self.assertEqual(account1.view_balance(), 1500)\n\n def test_view_balance_5(self):\n account1 = BankAccount()\n account1.balance = 2000\n self.assertEqual(account1.view_balance(), 2000)", "solution_code": "def view_balance(self):\n return self.balance", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.balance" ], "method_dependencies": [] } }, { "method_name": "transfer", "method_description": "def transfer(self, other_account, amount):\n \"\"\"\n Transfers a certain amount from the current account to another account.\n :param other_account: BankAccount\n :param amount: int\n >>> account1 = BankAccount()\n >>> account2 = BankAccount()\n >>> account1.deposit(1000)\n >>> account1.transfer(account2, 300)\n account1.balance = 700 account2.balance = 300\n \"\"\"", "test_class": "BankAccountTestTransfer", "test_code": "class BankAccountTestTransfer(unittest.TestCase):\n\n def test_transfer(self):\n account1 = BankAccount()\n account2 = BankAccount()\n account1.balance = 800\n account2.balance = 1000\n account1.transfer(account2, 300)\n self.assertEqual(account1.view_balance(), 500)\n self.assertEqual(account2.view_balance(), 1300)\n\n def test_transfer_2(self):\n account1 = BankAccount()\n account2 = BankAccount()\n account1.balance = 500\n with self.assertRaises(ValueError) as context:\n account1.transfer(account2, 600)\n self.assertEqual(str(context.exception), \"Insufficient balance.\")\n\n def test_transfer_3(self):\n account1 = BankAccount()\n account2 = BankAccount()\n account1.balance = 500\n account2.balance = 1000\n with self.assertRaises(ValueError) as context:\n account1.transfer(account2, -600)\n self.assertEqual(str(context.exception), \"Invalid amount\")\n\n def test_transfer_4(self):\n account1 = BankAccount()\n account2 = BankAccount()\n account1.balance = 500\n account2.balance = 1000\n account1.transfer(account2, 500)\n self.assertEqual(account1.view_balance(), 0)\n self.assertEqual(account2.view_balance(), 1500)\n\n def test_transfer_5(self):\n account1 = BankAccount()\n account2 = BankAccount()\n account1.balance = 500\n account2.balance = 1000\n account1.transfer(account2, 200)\n self.assertEqual(account1.view_balance(), 300)\n self.assertEqual(account2.view_balance(), 1200)", "solution_code": "def transfer(self, other_account, amount):\n self.withdraw(amount)\n other_account.deposit(amount)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "deposit", "withdraw" ] } } ] }, { "task_id": "ClassEval_9", "skeleton": "\nclass BigNumCalculator:\n \"\"\"\n This is a class that implements big number calculations, including adding, subtracting and multiplying.\n \"\"\"\n\n @staticmethod\n def add(num1, num2):\n \"\"\"\n Adds two big numbers.\n :param num1: The first number to add,str.\n :param num2: The second number to add,str.\n :return: The sum of the two numbers,str.\n >>> bigNum = BigNumCalculator()\n >>> bigNum.add(\"12345678901234567890\", \"98765432109876543210\")\n '111111111011111111100'\n\n \"\"\"\n\n @staticmethod\n def subtract(num1, num2):\n \"\"\"\n Subtracts two big numbers.\n :param num1: The first number to subtract,str.\n :param num2: The second number to subtract,str.\n :return: The difference of the two numbers,str.\n >>> bigNum = BigNumCalculator()\n >>> bigNum.subtract(\"12345678901234567890\", \"98765432109876543210\")\n '-86419753208641975320'\n\n \"\"\"\n\n @staticmethod\n def multiply(num1, num2):\n \"\"\"\n Multiplies two big numbers.\n :param num1: The first number to multiply,str.\n :param num2: The second number to multiply,str.\n :return: The product of the two numbers,str.\n >>> bigNum = BigNumCalculator()\n >>> bigNum.multiply(\"12345678901234567890\", \"98765432109876543210\")\n '1219326311370217952237463801111263526900'\n\n \"\"\"", "test": "import unittest\n\nclass BigNumCalculatorTestAdd(unittest.TestCase):\n def test_add(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.add(\"12345678901234567890\", \"98765432109876543210\"), \"111111111011111111100\")\n\n def test_add_2(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.add(\"123456789012345678922\", \"98765432109876543210\"), \"222222221122222222132\")\n\n def test_add_3(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.add(\"123456789012345678934\", \"98765432109876543210\"), \"222222221122222222144\")\n\n def test_add_4(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.add(\"123456789012345678946\", \"98765432109876543210\"), \"222222221122222222156\")\n\n def test_add_5(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.add(\"123456789012345678958\", \"98765432109876543210\"), \"222222221122222222168\")\n\nclass BigNumCalculatorTestSubtract(unittest.TestCase):\n def test_subtract(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.subtract(\"12345678901234567890\", \"98765432109876543210\"), \"-86419753208641975320\")\n\n def test_subtract_2(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.subtract(\"123456789012345678922\", \"98765432109876543210\"), \"24691356902469135712\")\n\n def test_subtract_3(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.subtract(\"123456789012345678934\", \"98765432109876543\"), \"123358023580235802391\")\n\n def test_subtract_4(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.subtract(\"12345678901234567\", \"98765432109876543210\"), \"-98753086430975308643\")\n\n def test_subtract_5(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.subtract(\"923456789\", \"187654321\"), \"735802468\")\n\nclass BigNumCalculatorTestMultiply(unittest.TestCase):\n def test_multiply(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.multiply(\"12345678901234567890\", \"98765432109876543210\"), \"1219326311370217952237463801111263526900\")\n\n def test_multiply_2(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.multiply(\"123456789012345678922\", \"98765432109876543210\"), \"12193263113702179524547477517529919219620\")\n\n def test_multiply_3(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.multiply(\"123456789012345678934\", \"98765432109876543\"), \"12193263113702179499806737010255845162\")\n\n def test_multiply_4(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.multiply(\"12345678901234567\", \"98765432109876543210\"), \"1219326311370217864336229223321140070\")\n\n def test_multiply_5(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.multiply(\"923456789\", \"187654321\"), \"173290656712635269\")\n\n def test_multiply_6(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.multiply(\"000000001\", \"000000001\"), \"1\")\n\nclass BigNumCalculatorTestMain(unittest.TestCase):\n def test_main(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.add(\"12345678901234567890\", \"98765432109876543210\"), \"111111111011111111100\")\n self.assertEqual(bigNum.subtract(\"12345678901234567890\", \"98765432109876543210\"), \"-86419753208641975320\")\n self.assertEqual(bigNum.multiply(\"12345678901234567890\", \"98765432109876543210\"), \"1219326311370217952237463801111263526900\")", "solution_code": "class BigNumCalculator:\n @staticmethod\n def add(num1, num2):\n max_length = max(len(num1), len(num2))\n num1 = num1.zfill(max_length)\n num2 = num2.zfill(max_length)\n\n carry = 0\n result = []\n for i in range(max_length - 1, -1, -1):\n digit_sum = int(num1[i]) + int(num2[i]) + carry\n carry = digit_sum // 10\n digit = digit_sum % 10\n result.insert(0, str(digit))\n\n if carry > 0:\n result.insert(0, str(carry))\n\n return ''.join(result)\n\n @staticmethod\n def subtract(num1, num2):\n\n if len(num1) < len(num2):\n num1, num2 = num2, num1\n negative = True\n elif len(num1) > len(num2):\n negative = False\n else:\n if num1 < num2:\n num1, num2 = num2, num1\n negative = True\n else:\n negative = False\n\n max_length = max(len(num1), len(num2))\n num1 = num1.zfill(max_length)\n num2 = num2.zfill(max_length)\n\n borrow = 0\n result = []\n for i in range(max_length - 1, -1, -1):\n digit_diff = int(num1[i]) - int(num2[i]) - borrow\n\n if digit_diff < 0:\n digit_diff += 10\n borrow = 1\n else:\n borrow = 0\n\n result.insert(0, str(digit_diff))\n\n while len(result) > 1 and result[0] == '0':\n result.pop(0)\n\n if negative:\n result.insert(0, '-')\n\n return ''.join(result)\n\n @staticmethod\n def multiply(num1, num2):\n len1, len2 = len(num1), len(num2)\n result = [0] * (len1 + len2)\n\n for i in range(len1 - 1, -1, -1):\n for j in range(len2 - 1, -1, -1):\n mul = int(num1[i]) * int(num2[j])\n p1, p2 = i + j, i + j + 1\n total = mul + result[p2]\n\n result[p1] += total // 10\n result[p2] = total % 10\n\n start = 0\n while start < len(result) - 1 and result[start] == 0:\n start += 1\n\n return ''.join(map(str, result[start:]))", "import_statement": [], "class_description": " \"\"\"\n This is a class that implements big number calculations, including adding, subtracting and multiplying.\n \"\"\"\n", "class_name": "BigNumCalculator", "test_classes": [ "BigNumCalculatorTestAdd", "BigNumCalculatorTestSubtract", "BigNumCalculatorTestMultiply", "BigNumCalculatorTestMain" ], "class_constructor": "class BigNumCalculator: \n", "fields": [], "methods_info": [ { "method_name": "add", "method_description": "def add(num1, num2):\n \"\"\"\n Adds two big numbers.\n :param num1: The first number to add,str.\n :param num2: The second number to add,str.\n :return: The sum of the two numbers,str.\n >>> bigNum = BigNumCalculator()\n >>> bigNum.add(\"12345678901234567890\", \"98765432109876543210\")\n '111111111011111111100'\n\n \"\"\"", "test_class": "BigNumCalculatorTestAdd", "test_code": "class BigNumCalculatorTestAdd(unittest.TestCase):\n def test_add(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.add(\"12345678901234567890\", \"98765432109876543210\"), \"111111111011111111100\")\n\n def test_add_2(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.add(\"123456789012345678922\", \"98765432109876543210\"), \"222222221122222222132\")\n\n def test_add_3(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.add(\"123456789012345678934\", \"98765432109876543210\"), \"222222221122222222144\")\n\n def test_add_4(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.add(\"123456789012345678946\", \"98765432109876543210\"), \"222222221122222222156\")\n\n def test_add_5(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.add(\"123456789012345678958\", \"98765432109876543210\"), \"222222221122222222168\")", "solution_code": "def add(num1, num2):\n max_length = max(len(num1), len(num2))\n num1 = num1.zfill(max_length)\n num2 = num2.zfill(max_length)\n\n carry = 0\n result = []\n for i in range(max_length - 1, -1, -1):\n digit_sum = int(num1[i]) + int(num2[i]) + carry\n carry = digit_sum // 10\n digit = digit_sum % 10\n result.insert(0, str(digit))\n\n if carry > 0:\n result.insert(0, str(carry))\n\n return ''.join(result)", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "subtract", "method_description": "@staticmethod\n def subtract(num1, num2):\n \"\"\"\n Subtracts two big numbers.\n :param num1: The first number to subtract,str.\n :param num2: The second number to subtract,str.\n :return: The difference of the two numbers,str.\n >>> bigNum = BigNumCalculator()\n >>> bigNum.subtract(\"12345678901234567890\", \"98765432109876543210\")\n '-86419753208641975320'\n\n \"\"\"", "test_class": "BigNumCalculatorTestSubtract", "test_code": "class BigNumCalculatorTestSubtract(unittest.TestCase):\n def test_subtract(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.subtract(\"12345678901234567890\", \"98765432109876543210\"), \"-86419753208641975320\")\n\n def test_subtract_2(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.subtract(\"123456789012345678922\", \"98765432109876543210\"), \"24691356902469135712\")\n\n def test_subtract_3(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.subtract(\"123456789012345678934\", \"98765432109876543\"), \"123358023580235802391\")\n\n def test_subtract_4(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.subtract(\"12345678901234567\", \"98765432109876543210\"), \"-98753086430975308643\")\n\n def test_subtract_5(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.subtract(\"923456789\", \"187654321\"), \"735802468\")", "solution_code": "@staticmethod\n def subtract(num1, num2):\n\n if len(num1) < len(num2):\n num1, num2 = num2, num1\n negative = True\n elif len(num1) > len(num2):\n negative = False\n else:\n if num1 < num2:\n num1, num2 = num2, num1\n negative = True\n else:\n negative = False\n\n max_length = max(len(num1), len(num2))\n num1 = num1.zfill(max_length)\n num2 = num2.zfill(max_length)\n\n borrow = 0\n result = []\n for i in range(max_length - 1, -1, -1):\n digit_diff = int(num1[i]) - int(num2[i]) - borrow\n\n if digit_diff < 0:\n digit_diff += 10\n borrow = 1\n else:\n borrow = 0\n\n result.insert(0, str(digit_diff))\n\n while len(result) > 1 and result[0] == '0':\n result.pop(0)\n\n if negative:\n result.insert(0, '-')\n\n return ''.join(result)", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "multiply", "method_description": "@staticmethod\n def multiply(num1, num2):\n \"\"\"\n Multiplies two big numbers.\n :param num1: The first number to multiply,str.\n :param num2: The second number to multiply,str.\n :return: The product of the two numbers,str.\n >>> bigNum = BigNumCalculator()\n >>> bigNum.multiply(\"12345678901234567890\", \"98765432109876543210\")\n '1219326311370217952237463801111263526900'\n\n \"\"\"", "test_class": "BigNumCalculatorTestMultiply", "test_code": "class BigNumCalculatorTestMultiply(unittest.TestCase):\n def test_multiply(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.multiply(\"12345678901234567890\", \"98765432109876543210\"), \"1219326311370217952237463801111263526900\")\n\n def test_multiply_2(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.multiply(\"123456789012345678922\", \"98765432109876543210\"), \"12193263113702179524547477517529919219620\")\n\n def test_multiply_3(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.multiply(\"123456789012345678934\", \"98765432109876543\"), \"12193263113702179499806737010255845162\")\n\n def test_multiply_4(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.multiply(\"12345678901234567\", \"98765432109876543210\"), \"1219326311370217864336229223321140070\")\n\n def test_multiply_5(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.multiply(\"923456789\", \"187654321\"), \"173290656712635269\")\n\n def test_multiply_6(self):\n bigNum = BigNumCalculator()\n self.assertEqual(bigNum.multiply(\"000000001\", \"000000001\"), \"1\")", "solution_code": "@staticmethod\n def multiply(num1, num2):\n len1, len2 = len(num1), len(num2)\n result = [0] * (len1 + len2)\n\n for i in range(len1 - 1, -1, -1):\n for j in range(len2 - 1, -1, -1):\n mul = int(num1[i]) * int(num2[j])\n p1, p2 = i + j, i + j + 1\n total = mul + result[p2]\n\n result[p1] += total // 10\n result[p2] = total % 10\n\n start = 0\n while start < len(result) - 1 and result[start] == 0:\n start += 1\n\n return ''.join(map(str, result[start:]))", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_10", "skeleton": "\nclass BinaryDataProcessor:\n \"\"\"\n This is a class used to process binary data, which includes functions such as clearing non 0 or 1 characters, counting binary string information, and converting to corresponding strings based on different encoding methods.\n \"\"\"\n\n def __init__(self, binary_string):\n \"\"\"\n Initialize the class with a binary string and clean it by removing all non 0 or 1 characters.\n \"\"\"\n self.binary_string = binary_string\n self.clean_non_binary_chars()\n\n def clean_non_binary_chars(self):\n \"\"\"\n Clean the binary string by removing all non 0 or 1 characters.\n >>> bdp = BinaryDataProcessor(\"01101000daf3e4r01100101011011000110110001101111\")\n >>> bdp.clean_non_binary_chars()\n >>> bdp.binary_string\n '0110100001100101011011000110110001101111'\n\n \"\"\"\n\n def calculate_binary_info(self):\n \"\"\"\n Calculate the binary string information, including the percentage of 0 and 1, and the total length of the binary string.\n >>> bdp = BinaryDataProcessor(\"0110100001100101011011000110110001101111\")\n >>> bdp.calculate_binary_info()\n {'Zeroes': 0.475, 'Ones': 0.525, 'Bit length': 40}\n\n \"\"\"\n\n def convert_to_ascii(self):\n \"\"\"\n Convert the binary string to ascii string.\n >>> bdp = BinaryDataProcessor(\"0110100001100101011011000110110001101111\")\n >>> bdp.convert_to_ascii()\n 'hello'\n\n \"\"\"\n\n def convert_to_utf8(self):\n \"\"\"\n Convert the binary string to utf-8 string.\n >>> bdp = BinaryDataProcessor(\"0110100001100101011011000110110001101111\")\n >>> bdp.convert_to_utf8()\n 'hello'\n\n \"\"\"", "test": "import unittest\n\nclass BinaryDataProcessorTestCleanNonBinaryChars(unittest.TestCase):\n def test_clean_non_binary_chars(self):\n bdp = BinaryDataProcessor(\"01101000daf3e4r01100101011011000110110001101111\")\n self.assertEqual(bdp.binary_string, \"0110100001100101011011000110110001101111\")\n\n def test_clean_non_binary_chars_2(self):\n bdp = BinaryDataProcessor(\"01101000daf3e4r01100101011011addf0110001d1111\")\n self.assertEqual(bdp.binary_string, \"011010000110010101101101100011111\")\n\n def test_clean_non_binary_chars_3(self):\n bdp = BinaryDataProcessor(\"0sd1000daf3e4r01100101011011addf0110001d1111\")\n self.assertEqual(bdp.binary_string, \"010000110010101101101100011111\")\n\n def test_clean_non_binary_chars_4(self):\n bdp = BinaryDataProcessor(\"sdsdf\")\n self.assertEqual(bdp.binary_string, \"\")\n\n def test_clean_non_binary_chars_5(self):\n bdp = BinaryDataProcessor(\"0\")\n self.assertEqual(bdp.binary_string, \"0\")\n\nclass BinaryDataProcessorTestCalculateBinaryInfo(unittest.TestCase):\n def test_calculate_binary_info(self):\n bdp = BinaryDataProcessor(\"0110100001100101011011000110110001101111\")\n self.assertEqual(bdp.calculate_binary_info(), {'Zeroes': 0.475, 'Ones': 0.525, 'Bit length': 40})\n\n def test_calculate_binary_info_2(self):\n bdp = BinaryDataProcessor(\"0110100001100101011010011111\")\n self.assertEqual(bdp.calculate_binary_info(), {'Bit length': 28, 'Ones': 0.5357142857142857, 'Zeroes': 0.4642857142857143})\n\n def test_calculate_binary_info_3(self):\n bdp = BinaryDataProcessor(\"01101001111100101011010011111\")\n self.assertEqual(bdp.calculate_binary_info(), {'Bit length': 29, 'Ones': 0.6206896551724138, 'Zeroes': 0.3793103448275862})\n\n def test_calculate_binary_info_4(self):\n bdp = BinaryDataProcessor(\"011010011111001\")\n self.assertEqual(bdp.calculate_binary_info(), {'Bit length': 15, 'Ones': 0.6, 'Zeroes': 0.4})\n\n def test_calculate_binary_info_5(self):\n bdp = BinaryDataProcessor(\"0110100111110010\")\n self.assertEqual(bdp.calculate_binary_info(), {'Bit length': 16, 'Ones': 0.5625, 'Zeroes': 0.4375})\n\nclass BinaryDataProcessorTestConvertToAscii(unittest.TestCase):\n def test_convert_to_ascii(self):\n bdp = BinaryDataProcessor(\"0110100001100101011011000110110001101111\")\n self.assertEqual(bdp.convert_to_ascii(), \"hello\")\n\n def test_convert_to_ascii_2(self):\n bdp = BinaryDataProcessor(\"0110100000100101011011000110110001101111\")\n self.assertEqual(bdp.convert_to_ascii(), \"h%llo\")\n\n def test_convert_to_ascii_3(self):\n bdp = BinaryDataProcessor(\"01101000011011010110001001101111\")\n self.assertEqual(bdp.convert_to_ascii(), \"hmbo\")\n\n def test_convert_to_ascii_4(self):\n bdp = BinaryDataProcessor(\"01101000011001010110001001101111\")\n self.assertEqual(bdp.convert_to_ascii(), \"hebo\")\n\n def test_convert_to_ascii_5(self):\n bdp = BinaryDataProcessor(\"0110100001100101011011000110110001101111\")\n self.assertEqual(bdp.convert_to_ascii(), \"hello\")\n\nclass BinaryDataProcessorTestConvertToUtf8(unittest.TestCase):\n def test_convert_to_utf8(self):\n bdp = BinaryDataProcessor(\"0110100001100101011011000110110001101111\")\n self.assertEqual(bdp.convert_to_utf8(), \"hello\")\n\n def test_convert_to_utf8_2(self):\n bdp = BinaryDataProcessor(\"0110100001100101011011000110110001101001\")\n self.assertEqual(bdp.convert_to_utf8(), \"helli\")\n\n def test_convert_to_utf8_3(self):\n bdp = BinaryDataProcessor(\"0110000001100101011011000110110001101111\")\n self.assertEqual(bdp.convert_to_utf8(), \"`ello\")\n\n def test_convert_to_utf8_4(self):\n bdp = BinaryDataProcessor(\"0110101101100101011011000110110001101111\")\n self.assertEqual(bdp.convert_to_utf8(), \"kello\")\n\n def test_convert_to_utf8_5(self):\n bdp = BinaryDataProcessor(\"0110101101100100011011000110110001101111\")\n self.assertEqual(bdp.convert_to_utf8(), \"kdllo\")\n\nclass BinaryDataProcessorTestMain(unittest.TestCase):\n def test_main(self):\n bdp = BinaryDataProcessor(\"01101000daf3e4r01100101011011000110110001101111\")\n self.assertEqual(bdp.binary_string, \"0110100001100101011011000110110001101111\")\n self.assertEqual(bdp.calculate_binary_info(), {'Zeroes': 0.475, 'Ones': 0.525, 'Bit length': 40})\n self.assertEqual(bdp.convert_to_ascii(), \"hello\")\n self.assertEqual(bdp.convert_to_utf8(), \"hello\")", "solution_code": "class BinaryDataProcessor:\n def __init__(self, binary_string):\n self.binary_string = binary_string\n self.clean_non_binary_chars()\n\n def clean_non_binary_chars(self):\n self.binary_string = ''.join(filter(lambda x: x in '01', self.binary_string))\n\n def calculate_binary_info(self):\n zeroes_count = self.binary_string.count('0')\n ones_count = self.binary_string.count('1')\n total_length = len(self.binary_string)\n\n zeroes_percentage = (zeroes_count / total_length)\n ones_percentage = (ones_count / total_length)\n\n return {\n 'Zeroes': zeroes_percentage,\n 'Ones': ones_percentage,\n 'Bit length': total_length\n }\n\n def convert_to_ascii(self):\n byte_array = bytearray()\n for i in range(0, len(self.binary_string), 8):\n byte = self.binary_string[i:i+8]\n decimal = int(byte, 2)\n byte_array.append(decimal)\n\n return byte_array.decode('ascii')\n\n def convert_to_utf8(self):\n byte_array = bytearray()\n for i in range(0, len(self.binary_string), 8):\n byte = self.binary_string[i:i+8]\n decimal = int(byte, 2)\n byte_array.append(decimal)\n\n return byte_array.decode('utf-8')", "import_statement": [], "class_description": " \"\"\"\n This is a class used to process binary data, which includes functions such as clearing non 0 or 1 characters, counting binary string information, and converting to corresponding strings based on different encoding methods.\n \"\"\"\n", "class_name": "BinaryDataProcessor", "test_classes": [ "BinaryDataProcessorTestCleanNonBinaryChars", "BinaryDataProcessorTestCalculateBinaryInfo", "BinaryDataProcessorTestConvertToAscii", "BinaryDataProcessorTestConvertToUtf8", "BinaryDataProcessorTestMain" ], "class_constructor": "class BinaryDataProcessor: \n def __init__(self, binary_string):\n \"\"\"\n Initialize the class with a binary string and clean it by removing all non 0 or 1 characters.\n \"\"\"\n self.binary_string = binary_string\n self.clean_non_binary_chars()\n\n", "fields": [ "self.binary_string" ], "methods_info": [ { "method_name": "clean_non_binary_chars", "method_description": "def clean_non_binary_chars(self):\n \"\"\"\n Clean the binary string by removing all non 0 or 1 characters.\n >>> bdp = BinaryDataProcessor(\"01101000daf3e4r01100101011011000110110001101111\")\n >>> bdp.clean_non_binary_chars()\n >>> bdp.binary_string\n '0110100001100101011011000110110001101111'\n\n \"\"\"", "test_class": "BinaryDataProcessorTestCleanNonBinaryChars", "test_code": "class BinaryDataProcessorTestCleanNonBinaryChars(unittest.TestCase):\n def test_clean_non_binary_chars(self):\n bdp = BinaryDataProcessor(\"01101000daf3e4r01100101011011000110110001101111\")\n self.assertEqual(bdp.binary_string, \"0110100001100101011011000110110001101111\")\n\n def test_clean_non_binary_chars_2(self):\n bdp = BinaryDataProcessor(\"01101000daf3e4r01100101011011addf0110001d1111\")\n self.assertEqual(bdp.binary_string, \"011010000110010101101101100011111\")\n\n def test_clean_non_binary_chars_3(self):\n bdp = BinaryDataProcessor(\"0sd1000daf3e4r01100101011011addf0110001d1111\")\n self.assertEqual(bdp.binary_string, \"010000110010101101101100011111\")\n\n def test_clean_non_binary_chars_4(self):\n bdp = BinaryDataProcessor(\"sdsdf\")\n self.assertEqual(bdp.binary_string, \"\")\n\n def test_clean_non_binary_chars_5(self):\n bdp = BinaryDataProcessor(\"0\")\n self.assertEqual(bdp.binary_string, \"0\")", "solution_code": "def clean_non_binary_chars(self):\n self.binary_string = ''.join(filter(lambda x: x in '01', self.binary_string))", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.binary_string" ], "method_dependencies": [] } }, { "method_name": "calculate_binary_info", "method_description": "def calculate_binary_info(self):\n \"\"\"\n Calculate the binary string information, including the percentage of 0 and 1, and the total length of the binary string.\n >>> bdp = BinaryDataProcessor(\"0110100001100101011011000110110001101111\")\n >>> bdp.calculate_binary_info()\n {'Zeroes': 0.475, 'Ones': 0.525, 'Bit length': 40}\n\n \"\"\"", "test_class": "BinaryDataProcessorTestCalculateBinaryInfo", "test_code": "class BinaryDataProcessorTestCalculateBinaryInfo(unittest.TestCase):\n def test_calculate_binary_info(self):\n bdp = BinaryDataProcessor(\"0110100001100101011011000110110001101111\")\n self.assertEqual(bdp.calculate_binary_info(), {'Zeroes': 0.475, 'Ones': 0.525, 'Bit length': 40})\n\n def test_calculate_binary_info_2(self):\n bdp = BinaryDataProcessor(\"0110100001100101011010011111\")\n self.assertEqual(bdp.calculate_binary_info(), {'Bit length': 28, 'Ones': 0.5357142857142857, 'Zeroes': 0.4642857142857143})\n\n def test_calculate_binary_info_3(self):\n bdp = BinaryDataProcessor(\"01101001111100101011010011111\")\n self.assertEqual(bdp.calculate_binary_info(), {'Bit length': 29, 'Ones': 0.6206896551724138, 'Zeroes': 0.3793103448275862})\n\n def test_calculate_binary_info_4(self):\n bdp = BinaryDataProcessor(\"011010011111001\")\n self.assertEqual(bdp.calculate_binary_info(), {'Bit length': 15, 'Ones': 0.6, 'Zeroes': 0.4})\n\n def test_calculate_binary_info_5(self):\n bdp = BinaryDataProcessor(\"0110100111110010\")\n self.assertEqual(bdp.calculate_binary_info(), {'Bit length': 16, 'Ones': 0.5625, 'Zeroes': 0.4375})", "solution_code": "def calculate_binary_info(self):\n zeroes_count = self.binary_string.count('0')\n ones_count = self.binary_string.count('1')\n total_length = len(self.binary_string)\n\n zeroes_percentage = (zeroes_count / total_length)\n ones_percentage = (ones_count / total_length)\n\n return {\n 'Zeroes': zeroes_percentage,\n 'Ones': ones_percentage,\n 'Bit length': total_length\n }", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.binary_string" ], "method_dependencies": [] } }, { "method_name": "convert_to_ascii", "method_description": "def convert_to_ascii(self):\n \"\"\"\n Convert the binary string to ascii string.\n >>> bdp = BinaryDataProcessor(\"0110100001100101011011000110110001101111\")\n >>> bdp.convert_to_ascii()\n 'hello'\n\n \"\"\"", "test_class": "BinaryDataProcessorTestConvertToAscii", "test_code": "class BinaryDataProcessorTestConvertToAscii(unittest.TestCase):\n def test_convert_to_ascii(self):\n bdp = BinaryDataProcessor(\"0110100001100101011011000110110001101111\")\n self.assertEqual(bdp.convert_to_ascii(), \"hello\")\n\n def test_convert_to_ascii_2(self):\n bdp = BinaryDataProcessor(\"0110100000100101011011000110110001101111\")\n self.assertEqual(bdp.convert_to_ascii(), \"h%llo\")\n\n def test_convert_to_ascii_3(self):\n bdp = BinaryDataProcessor(\"01101000011011010110001001101111\")\n self.assertEqual(bdp.convert_to_ascii(), \"hmbo\")\n\n def test_convert_to_ascii_4(self):\n bdp = BinaryDataProcessor(\"01101000011001010110001001101111\")\n self.assertEqual(bdp.convert_to_ascii(), \"hebo\")\n\n def test_convert_to_ascii_5(self):\n bdp = BinaryDataProcessor(\"0110100001100101011011000110110001101111\")\n self.assertEqual(bdp.convert_to_ascii(), \"hello\")", "solution_code": "def convert_to_ascii(self):\n byte_array = bytearray()\n for i in range(0, len(self.binary_string), 8):\n byte = self.binary_string[i:i+8]\n decimal = int(byte, 2)\n byte_array.append(decimal)\n\n return byte_array.decode('ascii')", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.binary_string" ], "method_dependencies": [] } }, { "method_name": "convert_to_utf8", "method_description": "def convert_to_utf8(self):\n \"\"\"\n Convert the binary string to utf-8 string.\n >>> bdp = BinaryDataProcessor(\"0110100001100101011011000110110001101111\")\n >>> bdp.convert_to_utf8()\n 'hello'\n\n \"\"\"", "test_class": "BinaryDataProcessorTestConvertToUtf8", "test_code": "class BinaryDataProcessorTestConvertToUtf8(unittest.TestCase):\n def test_convert_to_utf8(self):\n bdp = BinaryDataProcessor(\"0110100001100101011011000110110001101111\")\n self.assertEqual(bdp.convert_to_utf8(), \"hello\")\n\n def test_convert_to_utf8_2(self):\n bdp = BinaryDataProcessor(\"0110100001100101011011000110110001101001\")\n self.assertEqual(bdp.convert_to_utf8(), \"helli\")\n\n def test_convert_to_utf8_3(self):\n bdp = BinaryDataProcessor(\"0110000001100101011011000110110001101111\")\n self.assertEqual(bdp.convert_to_utf8(), \"`ello\")\n\n def test_convert_to_utf8_4(self):\n bdp = BinaryDataProcessor(\"0110101101100101011011000110110001101111\")\n self.assertEqual(bdp.convert_to_utf8(), \"kello\")\n\n def test_convert_to_utf8_5(self):\n bdp = BinaryDataProcessor(\"0110101101100100011011000110110001101111\")\n self.assertEqual(bdp.convert_to_utf8(), \"kdllo\")", "solution_code": "def convert_to_utf8(self):\n byte_array = bytearray()\n for i in range(0, len(self.binary_string), 8):\n byte = self.binary_string[i:i+8]\n decimal = int(byte, 2)\n byte_array.append(decimal)\n\n return byte_array.decode('utf-8')", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.binary_string" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_11", "skeleton": "\nclass BitStatusUtil:\n \"\"\"\n This is a utility class that provides methods for manipulating and checking status using bitwise operations.\n \"\"\"\n\n @staticmethod\n def add(states, stat):\n \"\"\"\n Add a status to the current status,and check the parameters wheather they are legal.\n :param states: Current status,int.\n :param stat: Status to be added,int.\n :return: The status after adding the status,int.\n >>> bit_status_util = BitStatusUtil()\n >>> bit_status_util.add(2,4)\n 6\n\n \"\"\"\n\n @staticmethod\n def has(states, stat):\n \"\"\"\n Check if the current status contains the specified status,and check the parameters wheather they are legal.\n :param states: Current status,int.\n :param stat: Specified status,int.\n :return: True if the current status contains the specified status,otherwise False,bool.\n >>> bit_status_util = BitStatusUtil()\n >>> bit_status_util.has(6,2)\n True\n\n \"\"\"\n\n @staticmethod\n def remove(states, stat):\n \"\"\"\n Remove the specified status from the current status,and check the parameters wheather they are legal.\n :param states: Current status,int.\n :param stat: Specified status,int.\n :return: The status after removing the specified status,int.\n >>> bit_status_util = BitStatusUtil()\n >>> bit_status_util.remove(6,2)\n 4\n\n \"\"\"\n\n @staticmethod\n def check(args):\n \"\"\"\n Check if the parameters are legal, args must be greater than or equal to 0 and must be even,if not,raise ValueError.\n :param args: Parameters to be checked,list.\n :return: None.\n >>> bit_status_util = BitStatusUtil()\n >>> bit_status_util.check([2,3,4])\n Traceback (most recent call last):\n ...\n ValueError: 3 not even\n \"\"\"", "test": "import unittest\n\n\nclass BitStatusUtilTestAdd(unittest.TestCase):\n def test_add(self):\n bit_status_util = BitStatusUtil()\n self.assertEqual(bit_status_util.add(2, 4), 6)\n\n def test_add_2(self):\n bit_status_util = BitStatusUtil()\n self.assertEqual(bit_status_util.add(2, 0), 2)\n\n def test_add_3(self):\n bit_status_util = BitStatusUtil()\n self.assertEqual(bit_status_util.add(0, 0), 0)\n\n def test_add_4(self):\n bit_status_util = BitStatusUtil()\n self.assertEqual(bit_status_util.add(0, 2), 2)\n\n def test_add_5(self):\n bit_status_util = BitStatusUtil()\n self.assertEqual(bit_status_util.add(2, 2), 2)\n\n\nclass BitStatusUtilTestHas(unittest.TestCase):\n def test_has(self):\n bit_status_util = BitStatusUtil()\n self.assertTrue(bit_status_util.has(6, 2))\n\n def test_has_2(self):\n bit_status_util = BitStatusUtil()\n self.assertFalse(bit_status_util.has(8, 2))\n\n def test_has_3(self):\n bit_status_util = BitStatusUtil()\n self.assertTrue(bit_status_util.has(6, 4))\n\n def test_has_4(self):\n bit_status_util = BitStatusUtil()\n self.assertFalse(bit_status_util.has(8, 6))\n\n def test_has_5(self):\n bit_status_util = BitStatusUtil()\n self.assertTrue(bit_status_util.has(6, 6))\n\n\nclass BitStatusUtilTestRemove(unittest.TestCase):\n def test_remove(self):\n bit_status_util = BitStatusUtil()\n self.assertEqual(bit_status_util.remove(6, 2), 4)\n\n def test_remove_2(self):\n bit_status_util = BitStatusUtil()\n self.assertEqual(bit_status_util.remove(8, 2), 8)\n\n def test_remove_3(self):\n bit_status_util = BitStatusUtil()\n self.assertEqual(bit_status_util.remove(6, 4), 2)\n\n def test_remove_4(self):\n bit_status_util = BitStatusUtil()\n self.assertEqual(bit_status_util.remove(8, 6), 8)\n\n def test_remove_5(self):\n bit_status_util = BitStatusUtil()\n self.assertEqual(bit_status_util.remove(6, 6), 0)\n\n\nclass BitStatusUtilTestCheck(unittest.TestCase):\n def test_check(self):\n bit_status_util = BitStatusUtil()\n bit_status_util.check([2])\n\n def test_check_2(self):\n bit_status_util = BitStatusUtil()\n with self.assertRaises(ValueError):\n bit_status_util.check([3])\n\n def test_check_3(self):\n bit_status_util = BitStatusUtil()\n with self.assertRaises(ValueError):\n bit_status_util.check([-1])\n\n def test_check_4(self):\n bit_status_util = BitStatusUtil()\n with self.assertRaises(ValueError):\n bit_status_util.check([2, 3, 4])\n\n def test_check_5(self):\n bit_status_util = BitStatusUtil()\n with self.assertRaises(ValueError):\n bit_status_util.check([2, 3, 4, 5])\n\n\nclass BitStatusUtilTestMain(unittest.TestCase):\n def test_main(self):\n bit_status_util = BitStatusUtil()\n self.assertEqual(bit_status_util.add(2, 4), 6)\n self.assertTrue(bit_status_util.has(6, 2))\n self.assertEqual(bit_status_util.remove(6, 2), 4)\n with self.assertRaises(ValueError):\n bit_status_util.check([2, 3, 4])", "solution_code": "class BitStatusUtil:\n @staticmethod\n def add(states, stat):\n BitStatusUtil.check([states, stat])\n return states | stat\n\n @staticmethod\n def has(states, stat):\n BitStatusUtil.check([states, stat])\n return (states & stat) == stat\n\n @staticmethod\n def remove(states, stat):\n BitStatusUtil.check([states, stat])\n if BitStatusUtil.has(states, stat):\n return states ^ stat\n return states\n\n @staticmethod\n def check(args):\n for arg in args:\n if arg < 0:\n raise ValueError(f\"{arg} must be greater than or equal to 0\")\n if arg % 2 != 0:\n raise ValueError(f\"{arg} not even\")", "import_statement": [], "class_description": " \"\"\"\n This is a utility class that provides methods for manipulating and checking status using bitwise operations.\n \"\"\"\n", "class_name": "BitStatusUtil", "test_classes": [ "BitStatusUtilTestAdd", "BitStatusUtilTestHas", "BitStatusUtilTestRemove", "BitStatusUtilTestCheck", "BitStatusUtilTestMain" ], "class_constructor": "class BitStatusUtil: \n", "fields": [], "methods_info": [ { "method_name": "add", "method_description": "def add(states, stat):\n \"\"\"\n Add a status to the current status,and check the parameters wheather they are legal.\n :param states: Current status,int.\n :param stat: Status to be added,int.\n :return: The status after adding the status,int.\n >>> bit_status_util = BitStatusUtil()\n >>> bit_status_util.add(2,4)\n 6\n\n \"\"\"", "test_class": "BitStatusUtilTestAdd", "test_code": "class BitStatusUtilTestAdd(unittest.TestCase):\n def test_add(self):\n bit_status_util = BitStatusUtil()\n self.assertEqual(bit_status_util.add(2, 4), 6)\n\n def test_add_2(self):\n bit_status_util = BitStatusUtil()\n self.assertEqual(bit_status_util.add(2, 0), 2)\n\n def test_add_3(self):\n bit_status_util = BitStatusUtil()\n self.assertEqual(bit_status_util.add(0, 0), 0)\n\n def test_add_4(self):\n bit_status_util = BitStatusUtil()\n self.assertEqual(bit_status_util.add(0, 2), 2)\n\n def test_add_5(self):\n bit_status_util = BitStatusUtil()\n self.assertEqual(bit_status_util.add(2, 2), 2)", "solution_code": "def add(states, stat):\n BitStatusUtil.check([states, stat])\n return states | stat", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "check" ] } }, { "method_name": "has", "method_description": "@staticmethod\n def has(states, stat):\n \"\"\"\n Check if the current status contains the specified status,and check the parameters wheather they are legal.\n :param states: Current status,int.\n :param stat: Specified status,int.\n :return: True if the current status contains the specified status,otherwise False,bool.\n >>> bit_status_util = BitStatusUtil()\n >>> bit_status_util.has(6,2)\n True\n\n \"\"\"", "test_class": "BitStatusUtilTestHas", "test_code": "class BitStatusUtilTestHas(unittest.TestCase):\n def test_has(self):\n bit_status_util = BitStatusUtil()\n self.assertTrue(bit_status_util.has(6, 2))\n\n def test_has_2(self):\n bit_status_util = BitStatusUtil()\n self.assertFalse(bit_status_util.has(8, 2))\n\n def test_has_3(self):\n bit_status_util = BitStatusUtil()\n self.assertTrue(bit_status_util.has(6, 4))\n\n def test_has_4(self):\n bit_status_util = BitStatusUtil()\n self.assertFalse(bit_status_util.has(8, 6))\n\n def test_has_5(self):\n bit_status_util = BitStatusUtil()\n self.assertTrue(bit_status_util.has(6, 6))", "solution_code": "@staticmethod\n def has(states, stat):\n BitStatusUtil.check([states, stat])\n return (states & stat) == stat", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "check" ] } }, { "method_name": "remove", "method_description": "@staticmethod\n def remove(states, stat):\n \"\"\"\n Remove the specified status from the current status,and check the parameters wheather they are legal.\n :param states: Current status,int.\n :param stat: Specified status,int.\n :return: The status after removing the specified status,int.\n >>> bit_status_util = BitStatusUtil()\n >>> bit_status_util.remove(6,2)\n 4\n\n \"\"\"", "test_class": "BitStatusUtilTestRemove", "test_code": "class BitStatusUtilTestRemove(unittest.TestCase):\n def test_remove(self):\n bit_status_util = BitStatusUtil()\n self.assertEqual(bit_status_util.remove(6, 2), 4)\n\n def test_remove_2(self):\n bit_status_util = BitStatusUtil()\n self.assertEqual(bit_status_util.remove(8, 2), 8)\n\n def test_remove_3(self):\n bit_status_util = BitStatusUtil()\n self.assertEqual(bit_status_util.remove(6, 4), 2)\n\n def test_remove_4(self):\n bit_status_util = BitStatusUtil()\n self.assertEqual(bit_status_util.remove(8, 6), 8)\n\n def test_remove_5(self):\n bit_status_util = BitStatusUtil()\n self.assertEqual(bit_status_util.remove(6, 6), 0)", "solution_code": "@staticmethod\n def remove(states, stat):\n BitStatusUtil.check([states, stat])\n if BitStatusUtil.has(states, stat):\n return states ^ stat\n return states", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "has", "check" ] } }, { "method_name": "check", "method_description": "@staticmethod\n def check(args):\n \"\"\"\n Check if the parameters are legal, args must be greater than or equal to 0 and must be even,if not,raise ValueError.\n :param args: Parameters to be checked,list.\n :return: None.\n >>> bit_status_util = BitStatusUtil()\n >>> bit_status_util.check([2,3,4])\n Traceback (most recent call last):\n ...\n ValueError: 3 not even\n \"\"\"", "test_class": "BitStatusUtilTestCheck", "test_code": "class BitStatusUtilTestCheck(unittest.TestCase):\n def test_check(self):\n bit_status_util = BitStatusUtil()\n bit_status_util.check([2])\n\n def test_check_2(self):\n bit_status_util = BitStatusUtil()\n with self.assertRaises(ValueError):\n bit_status_util.check([3])\n\n def test_check_3(self):\n bit_status_util = BitStatusUtil()\n with self.assertRaises(ValueError):\n bit_status_util.check([-1])\n\n def test_check_4(self):\n bit_status_util = BitStatusUtil()\n with self.assertRaises(ValueError):\n bit_status_util.check([2, 3, 4])\n\n def test_check_5(self):\n bit_status_util = BitStatusUtil()\n with self.assertRaises(ValueError):\n bit_status_util.check([2, 3, 4, 5])", "solution_code": "@staticmethod\n def check(args):\n for arg in args:\n if arg < 0:\n raise ValueError(f\"{arg} must be greater than or equal to 0\")\n if arg % 2 != 0:\n raise ValueError(f\"{arg} not even\")", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_12", "skeleton": "\nimport random\nclass BlackjackGame:\n \"\"\"\n This is a class representing a game of blackjack, which includes creating a deck, calculating the value of a hand, and determine the winner based on the hand values of the player and dealer.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialize the Blackjack Game with the attribute deck, player_hand and dealer_hand.\n While initializing deck attribute, call the create_deck method to generate.\n The deck stores 52 rondom order poker with the Jokers removed, format is ['AS', '2S', ...].\n player_hand is a list which stores player's hand cards.\n dealer_hand is is a list which stores dealer's hand cards.\n \"\"\"\n self.deck = self.create_deck()\n self.player_hand = []\n self.dealer_hand = []\n\n def create_deck(self):\n \"\"\"\n Create a deck of 52 cards, which stores 52 rondom order poker with the Jokers removed.\n :return: a list of 52 rondom order poker with the Jokers removed, format is ['AS', '2S', ...].\n >>> black_jack_game = BlackjackGame()\n >>> black_jack_game.create_deck()\n ['QD', '9D', 'JC', 'QH', '2S', 'JH', '7D', '6H', '9S', '5C', '7H', 'QS', '5H',\n '6C', '7C', '3D', '10C', 'AD', '4C', '5D', 'AH', '2D', 'QC', 'KH', '9C', '9H',\n '4H', 'JS', '6S', '8H', '8C', '4S', '3H', '10H', '7S', '6D', '3C', 'KC', '3S',\n '2H', '10D', 'KS', '4D', 'AC', '10S', '2C', 'KD', '5S', 'JD', '8S', 'AS', '8D']\n \"\"\"\n\n def calculate_hand_value(self, hand):\n \"\"\"\n Calculate the value of the poker cards stored in hand list according to the rules of the Blackjack Game.\n If the card is a digit, its value is added to the total hand value.\n Value of J, Q, or K is 10, while Aces are worth 11.\n If the total hand value exceeds 21 and there are Aces present, one Ace is treated as having a value of 1 instead of 11,\n until the hand value is less than or equal to 21, or all Aces have been counted as value of 1.\n :param hand: list\n :return: the value of the poker cards stored in hand list, a number.\n >>> black_jack_game.calculate_hand_value(['QD', '9D', 'JC', 'QH', 'AS'])\n 40\n \"\"\"\n\n def check_winner(self, player_hand, dealer_hand):\n \"\"\"\n Determines the winner of a game by comparing the hand values of the player and dealer.\n rule:\n If both players have hand values that are equal to or less than 21, the winner is the one whose hand value is closer to 21.\n Otherwise, the winner is the one with the lower hand value.\n :param player_hand: list\n :param dealer_hand: list\n :return: the result of the game, only two certain str: 'Dealer wins' or 'Player wins'\n >>> black_jack_game.check_winner(['QD', '9D', 'JC', 'QH', 'AS'], ['QD', '9D', 'JC', 'QH', '2S'])\n 'Player wins'\n \"\"\"", "test": "import unittest\n\nclass BlackjackGameTestCreateDeck(unittest.TestCase):\n def setUp(self):\n self.blackjackGame = BlackjackGame()\n self.deck = self.blackjackGame.deck\n\n def test_create_deck_1(self):\n self.assertEqual(len(self.deck), 52)\n\n def test_create_deck_2(self):\n suits = ['S', 'C', 'D', 'H']\n ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']\n for suit in suits:\n for rank in ranks:\n self.assertIn(rank + suit, self.deck)\n\n def test_create_deck_3(self):\n suits = ['S', 'C', 'D', 'H']\n ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9']\n for suit in suits:\n for rank in ranks:\n self.assertIn(rank + suit, self.deck)\n\n def test_create_deck_4(self):\n suits = ['S', 'C', 'D', 'H']\n ranks = ['10', 'J', 'Q', 'K']\n for suit in suits:\n for rank in ranks:\n self.assertIn(rank + suit, self.deck)\n\n def test_create_deck_5(self):\n suits = ['S', 'C', 'D', 'H']\n ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9']\n for suit in suits:\n for rank in ranks:\n self.assertIn(rank + suit, self.deck)\n\nclass BlackjackGameTestCalculateHandValue(unittest.TestCase):\n def test_calculate_hand_value_1(self):\n blackjackGame = BlackjackGame()\n hand = ['2S', '3S', '4S', '5S']\n self.assertEqual(blackjackGame.calculate_hand_value(hand), 14)\n\n def test_calculate_hand_value_2(self):\n blackjackGame = BlackjackGame()\n hand = ['2S', '3S', 'JS', 'QS']\n self.assertEqual(blackjackGame.calculate_hand_value(hand), 25)\n\n def test_calculate_hand_value_3(self):\n blackjackGame = BlackjackGame()\n hand = ['2S', '3S', '4S', 'AS']\n self.assertEqual(blackjackGame.calculate_hand_value(hand), 20)\n\n def test_calculate_hand_value_4(self):\n blackjackGame = BlackjackGame()\n hand = ['JS', 'QS', '4S', 'AS']\n self.assertEqual(blackjackGame.calculate_hand_value(hand), 25)\n\n def test_calculate_hand_value_5(self):\n blackjackGame = BlackjackGame()\n hand = ['JS', 'QS', 'AS', 'AS', 'AS']\n self.assertEqual(blackjackGame.calculate_hand_value(hand), 23)\n\n def test_calculate_hand_value_6(self):\n blackjackGame = BlackjackGame()\n hand = ['JS', 'QS', 'BS', 'CS']\n self.assertEqual(blackjackGame.calculate_hand_value(hand), 20)\n\n\nclass BlackjackGameTestCheckWinner(unittest.TestCase):\n def setUp(self):\n self.blackjackGame = BlackjackGame()\n\n # player > 21 but dealer not, dealer wins.\n def test_check_winner_1(self):\n player_hand = ['2S', 'JS', 'QS']\n dealer_hand = ['7S', '9S']\n self.assertEqual(self.blackjackGame.check_winner(player_hand, dealer_hand), 'Dealer wins')\n\n # dealer > 21 but player not, player wins.\n def test_check_winner_2(self):\n player_hand = ['2S', '4S', '5S']\n dealer_hand = ['2S', 'JS', 'QS']\n self.assertEqual(self.blackjackGame.check_winner(player_hand, dealer_hand), 'Player wins')\n\n # both > 21 but dealer smaller, dealer wins.\n def test_check_winner_3(self):\n player_hand = ['3S', 'JS', 'QS']\n dealer_hand = ['2S', 'JS', 'QS']\n self.assertEqual(self.blackjackGame.check_winner(player_hand, dealer_hand), 'Dealer wins')\n\n # both > 21 but player smaller, player wins.\n def test_check_winner_4(self):\n player_hand = ['2S', 'JS', 'QS']\n dealer_hand = ['3S', 'JS', 'QS']\n self.assertEqual(self.blackjackGame.check_winner(player_hand, dealer_hand), 'Player wins')\n\n # both < 21 but dealer is bigger, dealer wins.\n def test_check_winner_5(self):\n player_hand = ['2S', '3S', '5S']\n dealer_hand = ['AS', 'JS']\n self.assertEqual(self.blackjackGame.check_winner(player_hand, dealer_hand), 'Dealer wins')\n\n # both < 21 but player is bigger, player wins.\n def test_check_winner_6(self):\n player_hand = ['AS', 'JS']\n dealer_hand = ['2S', '3S', '5S']\n self.assertEqual(self.blackjackGame.check_winner(player_hand, dealer_hand), 'Player wins')\n\n\nclass BlackjackGameTestMain(unittest.TestCase):\n # calculate_hand_value method will be invoked in check_winner\n def test_main_1(self):\n blackjackGame = BlackjackGame()\n deck = blackjackGame.deck\n suits = ['S', 'C', 'D', 'H']\n ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']\n for suit in suits:\n for rank in ranks:\n self.assertIn(rank + suit, deck)\n player_hand = ['2S', 'JS', 'QS']\n dealer_hand = ['7S', '9S']\n self.assertEqual(blackjackGame.check_winner(player_hand, dealer_hand), 'Dealer wins')", "solution_code": "import random\n\n\nclass BlackjackGame:\n def __init__(self):\n self.deck = self.create_deck()\n self.player_hand = []\n self.dealer_hand = []\n\n def create_deck(self):\n deck = []\n suits = ['S', 'C', 'D', 'H']\n ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']\n for suit in suits:\n for rank in ranks:\n deck.append(rank + suit)\n random.shuffle(deck)\n return deck\n\n def calculate_hand_value(self, hand):\n value = 0\n num_aces = 0\n for card in hand:\n rank = card[:-1]\n if rank.isdigit():\n value += int(rank)\n elif rank in ['J', 'Q', 'K']:\n value += 10\n elif rank == 'A':\n value += 11\n num_aces += 1\n while value > 21 and num_aces > 0:\n value -= 10\n num_aces -= 1\n return value\n\n def check_winner(self, player_hand, dealer_hand):\n player_value = self.calculate_hand_value(player_hand)\n dealer_value = self.calculate_hand_value(dealer_hand)\n if player_value > 21 and dealer_value > 21:\n if player_value <= dealer_value:\n return 'Player wins'\n else:\n return 'Dealer wins'\n elif player_value > 21:\n return 'Dealer wins'\n elif dealer_value > 21:\n return 'Player wins'\n else:\n if player_value <= dealer_value:\n return 'Dealer wins'\n else:\n return 'Player wins'", "import_statement": [ "import random" ], "class_description": " \"\"\"\n This is a class representing a game of blackjack, which includes creating a deck, calculating the value of a hand, and determine the winner based on the hand values of the player and dealer.\n \"\"\"\n", "class_name": "BlackjackGame", "test_classes": [ "BlackjackGameTestCreateDeck", "BlackjackGameTestCalculateHandValue", "BlackjackGameTestCheckWinner", "BlackjackGameTestMain" ], "class_constructor": "class BlackjackGame: \n def __init__(self):\n \"\"\"\n Initialize the Blackjack Game with the attribute deck, player_hand and dealer_hand.\n While initializing deck attribute, call the create_deck method to generate.\n The deck stores 52 rondom order poker with the Jokers removed, format is ['AS', '2S', ...].\n player_hand is a list which stores player's hand cards.\n dealer_hand is is a list which stores dealer's hand cards.\n \"\"\"\n self.deck = self.create_deck()\n self.player_hand = []\n self.dealer_hand = []\n\n", "fields": [ "self.dealer_hand", "self.deck", "self.player_hand" ], "methods_info": [ { "method_name": "create_deck", "method_description": "def create_deck(self):\n \"\"\"\n Create a deck of 52 cards, which stores 52 rondom order poker with the Jokers removed.\n :return: a list of 52 rondom order poker with the Jokers removed, format is ['AS', '2S', ...].\n >>> black_jack_game = BlackjackGame()\n >>> black_jack_game.create_deck()\n ['QD', '9D', 'JC', 'QH', '2S', 'JH', '7D', '6H', '9S', '5C', '7H', 'QS', '5H',\n '6C', '7C', '3D', '10C', 'AD', '4C', '5D', 'AH', '2D', 'QC', 'KH', '9C', '9H',\n '4H', 'JS', '6S', '8H', '8C', '4S', '3H', '10H', '7S', '6D', '3C', 'KC', '3S',\n '2H', '10D', 'KS', '4D', 'AC', '10S', '2C', 'KD', '5S', 'JD', '8S', 'AS', '8D']\n \"\"\"", "test_class": "BlackjackGameTestCreateDeck", "test_code": "class BlackjackGameTestCreateDeck(unittest.TestCase):\n def setUp(self):\n self.blackjackGame = BlackjackGame()\n self.deck = self.blackjackGame.deck\n\n def test_create_deck_1(self):\n self.assertEqual(len(self.deck), 52)\n\n def test_create_deck_2(self):\n suits = ['S', 'C', 'D', 'H']\n ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']\n for suit in suits:\n for rank in ranks:\n self.assertIn(rank + suit, self.deck)\n\n def test_create_deck_3(self):\n suits = ['S', 'C', 'D', 'H']\n ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9']\n for suit in suits:\n for rank in ranks:\n self.assertIn(rank + suit, self.deck)\n\n def test_create_deck_4(self):\n suits = ['S', 'C', 'D', 'H']\n ranks = ['10', 'J', 'Q', 'K']\n for suit in suits:\n for rank in ranks:\n self.assertIn(rank + suit, self.deck)\n\n def test_create_deck_5(self):\n suits = ['S', 'C', 'D', 'H']\n ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9']\n for suit in suits:\n for rank in ranks:\n self.assertIn(rank + suit, self.deck)", "solution_code": "def create_deck(self):\n deck = []\n suits = ['S', 'C', 'D', 'H']\n ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']\n for suit in suits:\n for rank in ranks:\n deck.append(rank + suit)\n random.shuffle(deck)\n return deck", "dependencies": { "Standalone": false, "lib_dependencies": [ "random" ], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "calculate_hand_value", "method_description": "def calculate_hand_value(self, hand):\n \"\"\"\n Calculate the value of the poker cards stored in hand list according to the rules of the Blackjack Game.\n If the card is a digit, its value is added to the total hand value.\n Value of J, Q, or K is 10, while Aces are worth 11.\n If the total hand value exceeds 21 and there are Aces present, one Ace is treated as having a value of 1 instead of 11,\n until the hand value is less than or equal to 21, or all Aces have been counted as value of 1.\n :param hand: list\n :return: the value of the poker cards stored in hand list, a number.\n >>> black_jack_game.calculate_hand_value(['QD', '9D', 'JC', 'QH', 'AS'])\n 40\n \"\"\"", "test_class": "BlackjackGameTestCalculateHandValue", "test_code": "class BlackjackGameTestCalculateHandValue(unittest.TestCase):\n def test_calculate_hand_value_1(self):\n blackjackGame = BlackjackGame()\n hand = ['2S', '3S', '4S', '5S']\n self.assertEqual(blackjackGame.calculate_hand_value(hand), 14)\n\n def test_calculate_hand_value_2(self):\n blackjackGame = BlackjackGame()\n hand = ['2S', '3S', 'JS', 'QS']\n self.assertEqual(blackjackGame.calculate_hand_value(hand), 25)\n\n def test_calculate_hand_value_3(self):\n blackjackGame = BlackjackGame()\n hand = ['2S', '3S', '4S', 'AS']\n self.assertEqual(blackjackGame.calculate_hand_value(hand), 20)\n\n def test_calculate_hand_value_4(self):\n blackjackGame = BlackjackGame()\n hand = ['JS', 'QS', '4S', 'AS']\n self.assertEqual(blackjackGame.calculate_hand_value(hand), 25)\n\n def test_calculate_hand_value_5(self):\n blackjackGame = BlackjackGame()\n hand = ['JS', 'QS', 'AS', 'AS', 'AS']\n self.assertEqual(blackjackGame.calculate_hand_value(hand), 23)\n\n def test_calculate_hand_value_6(self):\n blackjackGame = BlackjackGame()\n hand = ['JS', 'QS', 'BS', 'CS']\n self.assertEqual(blackjackGame.calculate_hand_value(hand), 20)", "solution_code": "def calculate_hand_value(self, hand):\n value = 0\n num_aces = 0\n for card in hand:\n rank = card[:-1]\n if rank.isdigit():\n value += int(rank)\n elif rank in ['J', 'Q', 'K']:\n value += 10\n elif rank == 'A':\n value += 11\n num_aces += 1\n while value > 21 and num_aces > 0:\n value -= 10\n num_aces -= 1\n return value", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "check_winner", "method_description": "def check_winner(self, player_hand, dealer_hand):\n \"\"\"\n Determines the winner of a game by comparing the hand values of the player and dealer.\n rule:\n If both players have hand values that are equal to or less than 21, the winner is the one whose hand value is closer to 21.\n Otherwise, the winner is the one with the lower hand value.\n :param player_hand: list\n :param dealer_hand: list\n :return: the result of the game, only two certain str: 'Dealer wins' or 'Player wins'\n >>> black_jack_game.check_winner(['QD', '9D', 'JC', 'QH', 'AS'], ['QD', '9D', 'JC', 'QH', '2S'])\n 'Player wins'\n \"\"\"", "test_class": "BlackjackGameTestCheckWinner", "test_code": "class BlackjackGameTestCheckWinner(unittest.TestCase):\n def setUp(self):\n self.blackjackGame = BlackjackGame()\n\n # player > 21 but dealer not, dealer wins.\n def test_check_winner_1(self):\n player_hand = ['2S', 'JS', 'QS']\n dealer_hand = ['7S', '9S']\n self.assertEqual(self.blackjackGame.check_winner(player_hand, dealer_hand), 'Dealer wins')\n\n # dealer > 21 but player not, player wins.\n def test_check_winner_2(self):\n player_hand = ['2S', '4S', '5S']\n dealer_hand = ['2S', 'JS', 'QS']\n self.assertEqual(self.blackjackGame.check_winner(player_hand, dealer_hand), 'Player wins')\n\n # both > 21 but dealer smaller, dealer wins.\n def test_check_winner_3(self):\n player_hand = ['3S', 'JS', 'QS']\n dealer_hand = ['2S', 'JS', 'QS']\n self.assertEqual(self.blackjackGame.check_winner(player_hand, dealer_hand), 'Dealer wins')\n\n # both > 21 but player smaller, player wins.\n def test_check_winner_4(self):\n player_hand = ['2S', 'JS', 'QS']\n dealer_hand = ['3S', 'JS', 'QS']\n self.assertEqual(self.blackjackGame.check_winner(player_hand, dealer_hand), 'Player wins')\n\n # both < 21 but dealer is bigger, dealer wins.\n def test_check_winner_5(self):\n player_hand = ['2S', '3S', '5S']\n dealer_hand = ['AS', 'JS']\n self.assertEqual(self.blackjackGame.check_winner(player_hand, dealer_hand), 'Dealer wins')\n\n # both < 21 but player is bigger, player wins.\n def test_check_winner_6(self):\n player_hand = ['AS', 'JS']\n dealer_hand = ['2S', '3S', '5S']\n self.assertEqual(self.blackjackGame.check_winner(player_hand, dealer_hand), 'Player wins')", "solution_code": "def check_winner(self, player_hand, dealer_hand):\n player_value = self.calculate_hand_value(player_hand)\n dealer_value = self.calculate_hand_value(dealer_hand)\n if player_value > 21 and dealer_value > 21:\n if player_value <= dealer_value:\n return 'Player wins'\n else:\n return 'Dealer wins'\n elif player_value > 21:\n return 'Dealer wins'\n elif dealer_value > 21:\n return 'Player wins'\n else:\n if player_value <= dealer_value:\n return 'Dealer wins'\n else:\n return 'Player wins'", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "calculate_hand_value" ] } } ] }, { "task_id": "ClassEval_13", "skeleton": "\nclass BookManagement:\n \"\"\"\n This is a class as managing books system, which supports to add and remove books from the inventory dict, view the inventory, and check the quantity of a specific book.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialize the inventory of Book Manager.\n \"\"\"\n self.inventory = {}\n\n def add_book(self, title, quantity=1):\n \"\"\"\n Add one or several books to inventory which is sorted by book title.\n :param title: str, the book title\n :param quantity: int, default value is 1.\n \"\"\"\n\n def remove_book(self, title, quantity):\n \"\"\"\n Remove one or several books from inventory which is sorted by book title.\n Raise false while get invalid input.\n :param title: str, the book title\n :param quantity: int\n \"\"\"\n\n def view_inventory(self):\n \"\"\"\n Get the inventory of the Book Management.\n :return self.inventory: dictionary, {title(str): quantity(int), ...}\n >>> bookManagement = BookManagement()\n >>> bookManagement.add_book(\"book1\", 1)\n >>> bookManagement.add_book(\"book2\", 1)\n >>> bookManagement.view_inventory()\n {'book1': 1, 'book2': 1}\n \"\"\"\n\n def view_book_quantity(self, title):\n \"\"\"\n Get the quantity of a book.\n :param title: str, the title of the book.\n :return quantity: the quantity of this book title. return 0 when the title does not exist in self.invenroty\n >>> bookManagement = BookManagement()\n >>> bookManagement.add_book(\"book1\", 1)\n >>> bookManagement.view_book_quantity(\"book3\")\n 0\n \"\"\"", "test": "import unittest\n\n\nclass BookManagementTestAddBook(unittest.TestCase):\n def test_add_book_1(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\")\n self.assertEqual({\"book1\": 1}, bookManagement.inventory)\n\n def test_add_book_2(self):\n bookManagement = BookManagement()\n self.assertEqual({}, bookManagement.inventory)\n\n def test_add_book_3(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\")\n bookManagement.add_book(\"book1\", 2)\n self.assertEqual({\"book1\": 3}, bookManagement.inventory)\n\n def test_add_book_4(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\", 2)\n self.assertEqual({\"book1\": 2}, bookManagement.inventory)\n\n def test_add_book_5(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\", 2)\n bookManagement.add_book(\"book1\")\n self.assertEqual({\"book1\": 3}, bookManagement.inventory)\n\n\nclass BookManagementTestRemoveBook(unittest.TestCase):\n def setUp(self) -> None:\n self.bookManagement = BookManagement()\n self.bookManagement.add_book(\"book1\", 2)\n self.bookManagement.add_book(\"book2\")\n\n # remove all this title books\n def test_remove_book_1(self):\n self.bookManagement.remove_book(\"book1\", 2)\n self.assertEqual(self.bookManagement.inventory, {\"book2\": 1})\n\n # remove part\n def test_remove_book_2(self):\n self.bookManagement.remove_book(\"book1\", 1)\n self.assertEqual(self.bookManagement.inventory, {\"book1\": 1, \"book2\": 1})\n\n # remove the title that doesn't exist\n def test_remove_book_3(self):\n with self.assertRaises(Exception):\n self.bookManagement.remove_book(\"book3\", 1)\n\n # invalid quantity\n def test_remove_book_4(self):\n with self.assertRaises(Exception):\n self.bookManagement.remove_book(\"book2\", 2)\n\n def test_remove_book_5(self):\n with self.assertRaises(Exception):\n self.bookManagement.remove_book(\"book2\", 5)\n\n\nclass BookManagementTestViewInventory(unittest.TestCase):\n def test_view_inventory_1(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\", 2)\n bookManagement.add_book(\"book2\")\n expected = {\"book1\": 2, \"book2\": 1}\n self.assertEqual(expected, bookManagement.inventory)\n\n def test_view_inventory_2(self):\n bookManagement = BookManagement()\n expected = {}\n self.assertEqual(expected, bookManagement.inventory)\n\n def test_view_inventory_3(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\", 2)\n bookManagement.add_book(\"book2\")\n expected = {\"book1\": 2, \"book2\": 1}\n self.assertEqual(expected, bookManagement.inventory)\n\n def test_view_inventory_4(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\", 2)\n bookManagement.add_book(\"book2\")\n bookManagement.remove_book(\"book1\", 2)\n expected = {\"book2\": 1}\n self.assertEqual(expected, bookManagement.inventory)\n\n def test_view_inventory_5(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\", 2)\n bookManagement.add_book(\"book2\", 1)\n bookManagement.remove_book(\"book1\", 2)\n bookManagement.remove_book(\"book2\",1)\n expected = {}\n self.assertEqual(expected, bookManagement.inventory)\n\n\nclass BookManagementTestViewBookQuantity(unittest.TestCase):\n def test_view_book_quantity_1(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\", 2)\n self.assertEqual(2, bookManagement.view_book_quantity(\"book1\"))\n\n def test_view_book_quantity_2(self):\n bookManagement = BookManagement()\n self.assertEqual(0, bookManagement.view_book_quantity(\"book1\"))\n\n def test_view_book_quantity_3(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\", 2)\n self.assertEqual(2, bookManagement.view_book_quantity(\"book1\"))\n\n def test_view_book_quantity_4(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\", 2)\n bookManagement.remove_book(\"book1\", 2)\n self.assertEqual(0, bookManagement.view_book_quantity(\"book1\"))\n\n def test_view_book_quantity_5(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\", 3)\n bookManagement.remove_book(\"book1\", 2)\n self.assertEqual(1, bookManagement.view_book_quantity(\"book1\"))\n\n\nclass BookManagementTestMain(unittest.TestCase):\n def test_main(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\", 2)\n bookManagement.add_book(\"book2\")\n self.assertEqual(bookManagement.view_inventory(), {\"book1\": 2, \"book2\": 1})\n\n bookManagement.remove_book(\"book2\", 1)\n self.assertEqual(bookManagement.view_inventory(), {\"book1\": 2})\n self.assertEqual(0, bookManagement.view_book_quantity(\"book2\"))", "solution_code": "class BookManagement:\n def __init__(self):\n self.inventory = {}\n\n def add_book(self, title, quantity=1):\n if title in self.inventory:\n self.inventory[title] += quantity\n else:\n self.inventory[title] = quantity\n\n def remove_book(self, title, quantity):\n if title not in self.inventory or self.inventory[title] < quantity:\n raise False\n self.inventory[title] -= quantity\n if self.inventory[title] == 0:\n del (self.inventory[title])\n\n def view_inventory(self):\n return self.inventory\n\n def view_book_quantity(self, title):\n if title not in self.inventory:\n return 0\n return self.inventory[title]", "import_statement": [], "class_description": " \"\"\"\n This is a class as managing books system, which supports to add and remove books from the inventory dict, view the inventory, and check the quantity of a specific book.\n \"\"\"\n", "class_name": "BookManagement", "test_classes": [ "BookManagementTestAddBook", "BookManagementTestRemoveBook", "BookManagementTestViewInventory", "BookManagementTestViewBookQuantity", "BookManagementTestMain" ], "class_constructor": "class BookManagement: \n def __init__(self):\n \"\"\"\n Initialize the inventory of Book Manager.\n \"\"\"\n self.inventory = {}\n\n", "fields": [ "self.inventory" ], "methods_info": [ { "method_name": "add_book", "method_description": "def add_book(self, title, quantity=1):\n \"\"\"\n Add one or several books to inventory which is sorted by book title.\n :param title: str, the book title\n :param quantity: int, default value is 1.\n \"\"\"", "test_class": "BookManagementTestAddBook", "test_code": "class BookManagementTestAddBook(unittest.TestCase):\n def test_add_book_1(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\")\n self.assertEqual({\"book1\": 1}, bookManagement.inventory)\n\n def test_add_book_2(self):\n bookManagement = BookManagement()\n self.assertEqual({}, bookManagement.inventory)\n\n def test_add_book_3(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\")\n bookManagement.add_book(\"book1\", 2)\n self.assertEqual({\"book1\": 3}, bookManagement.inventory)\n\n def test_add_book_4(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\", 2)\n self.assertEqual({\"book1\": 2}, bookManagement.inventory)\n\n def test_add_book_5(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\", 2)\n bookManagement.add_book(\"book1\")\n self.assertEqual({\"book1\": 3}, bookManagement.inventory)", "solution_code": "def add_book(self, title, quantity=1):\n if title in self.inventory:\n self.inventory[title] += quantity\n else:\n self.inventory[title] = quantity", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.inventory" ], "method_dependencies": [] } }, { "method_name": "remove_book", "method_description": "def remove_book(self, title, quantity):\n \"\"\"\n Remove one or several books from inventory which is sorted by book title.\n Raise false while get invalid input.\n :param title: str, the book title\n :param quantity: int\n \"\"\"", "test_class": "BookManagementTestRemoveBook", "test_code": "class BookManagementTestRemoveBook(unittest.TestCase):\n def setUp(self) -> None:\n self.bookManagement = BookManagement()\n self.bookManagement.add_book(\"book1\", 2)\n self.bookManagement.add_book(\"book2\")\n\n # remove all this title books\n def test_remove_book_1(self):\n self.bookManagement.remove_book(\"book1\", 2)\n self.assertEqual(self.bookManagement.inventory, {\"book2\": 1})\n\n # remove part\n def test_remove_book_2(self):\n self.bookManagement.remove_book(\"book1\", 1)\n self.assertEqual(self.bookManagement.inventory, {\"book1\": 1, \"book2\": 1})\n\n # remove the title that doesn't exist\n def test_remove_book_3(self):\n with self.assertRaises(Exception):\n self.bookManagement.remove_book(\"book3\", 1)\n\n # invalid quantity\n def test_remove_book_4(self):\n with self.assertRaises(Exception):\n self.bookManagement.remove_book(\"book2\", 2)\n\n def test_remove_book_5(self):\n with self.assertRaises(Exception):\n self.bookManagement.remove_book(\"book2\", 5)", "solution_code": "def remove_book(self, title, quantity):\n if title not in self.inventory or self.inventory[title] < quantity:\n raise False\n self.inventory[title] -= quantity\n if self.inventory[title] == 0:\n del (self.inventory[title])", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.inventory" ], "method_dependencies": [] } }, { "method_name": "view_inventory", "method_description": "def view_inventory(self):\n \"\"\"\n Get the inventory of the Book Management.\n :return self.inventory: dictionary, {title(str): quantity(int), ...}\n >>> bookManagement = BookManagement()\n >>> bookManagement.add_book(\"book1\", 1)\n >>> bookManagement.add_book(\"book2\", 1)\n >>> bookManagement.view_inventory()\n {'book1': 1, 'book2': 1}\n \"\"\"", "test_class": "BookManagementTestViewInventory", "test_code": "class BookManagementTestViewInventory(unittest.TestCase):\n def test_view_inventory_1(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\", 2)\n bookManagement.add_book(\"book2\")\n expected = {\"book1\": 2, \"book2\": 1}\n self.assertEqual(expected, bookManagement.inventory)\n\n def test_view_inventory_2(self):\n bookManagement = BookManagement()\n expected = {}\n self.assertEqual(expected, bookManagement.inventory)\n\n def test_view_inventory_3(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\", 2)\n bookManagement.add_book(\"book2\")\n expected = {\"book1\": 2, \"book2\": 1}\n self.assertEqual(expected, bookManagement.inventory)\n\n def test_view_inventory_4(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\", 2)\n bookManagement.add_book(\"book2\")\n bookManagement.remove_book(\"book1\", 2)\n expected = {\"book2\": 1}\n self.assertEqual(expected, bookManagement.inventory)\n\n def test_view_inventory_5(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\", 2)\n bookManagement.add_book(\"book2\", 1)\n bookManagement.remove_book(\"book1\", 2)\n bookManagement.remove_book(\"book2\",1)\n expected = {}\n self.assertEqual(expected, bookManagement.inventory)", "solution_code": "def view_inventory(self):\n return self.inventory", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.inventory" ], "method_dependencies": [] } }, { "method_name": "view_book_quantity", "method_description": "def view_book_quantity(self, title):\n \"\"\"\n Get the quantity of a book.\n :param title: str, the title of the book.\n :return quantity: the quantity of this book title. return 0 when the title does not exist in self.invenroty\n >>> bookManagement = BookManagement()\n >>> bookManagement.add_book(\"book1\", 1)\n >>> bookManagement.view_book_quantity(\"book3\")\n 0\n \"\"\"", "test_class": "BookManagementTestViewBookQuantity", "test_code": "class BookManagementTestViewBookQuantity(unittest.TestCase):\n def test_view_book_quantity_1(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\", 2)\n self.assertEqual(2, bookManagement.view_book_quantity(\"book1\"))\n\n def test_view_book_quantity_2(self):\n bookManagement = BookManagement()\n self.assertEqual(0, bookManagement.view_book_quantity(\"book1\"))\n\n def test_view_book_quantity_3(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\", 2)\n self.assertEqual(2, bookManagement.view_book_quantity(\"book1\"))\n\n def test_view_book_quantity_4(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\", 2)\n bookManagement.remove_book(\"book1\", 2)\n self.assertEqual(0, bookManagement.view_book_quantity(\"book1\"))\n\n def test_view_book_quantity_5(self):\n bookManagement = BookManagement()\n bookManagement.add_book(\"book1\", 3)\n bookManagement.remove_book(\"book1\", 2)\n self.assertEqual(1, bookManagement.view_book_quantity(\"book1\"))", "solution_code": "def view_book_quantity(self, title):\n if title not in self.inventory:\n return 0\n return self.inventory[title]", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.inventory" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_14", "skeleton": "\nimport sqlite3\n\nclass BookManagementDB:\n \"\"\"\n This is a database class as a book management system, used to handle the operations of adding, removing, updating, and searching books.\n \"\"\"\n\n\n def __init__(self, db_name):\n \"\"\"\n Initializes the class by creating a database connection and cursor, \n and creates the book table if it does not already exist\n :param db_name: str, the name of db file\n \"\"\"\n self.connection = sqlite3.connect(db_name)\n self.cursor = self.connection.cursor()\n self.create_table()\n\n def create_table(self):\n \"\"\"\n Creates the book table in the database if it does not already exist.\n >>> book_db = BookManagementDB(\"test.db\")\n >>> book_db.create_table()\n \"\"\"\n \n\n def add_book(self, title, author):\n \"\"\"\n Adds a book to the database with the specified title and author, \n setting its availability to 1 as free to borrow.\n :param title: str, book title\n :param author: str, author name\n >>> book_db = BookManagementDB(\"test.db\")\n >>> book_db.create_table()\n >>> book_db.add_book('book1', 'author')\n \"\"\"\n\n def remove_book(self, book_id):\n \"\"\"\n Removes a book from the database based on the given book ID.\n :param book_id: int\n >>> book_db = BookManagementDB(\"test.db\")\n >>> book_db.remove_book(1)\n \"\"\"\n\n def borrow_book(self, book_id):\n \"\"\"\n Marks a book as borrowed in the database based on the given book ID.\n :param book_id: int\n >>> book_db = BookManagementDB(\"test.db\")\n >>> book_db.borrow_book(1)\n \"\"\"\n\n def return_book(self, book_id):\n \"\"\"\n Marks a book as returned in the database based on the given book ID.\n :param book_id: int\n >>> book_db = BookManagementDB(\"test.db\")\n >>> book_db.return_book(1)\n \"\"\"\n\n def search_books(self):\n \"\"\"\n Retrieves all books from the database and returns their information.\n :return books: list[tuple], the information of all books in database\n >>> book_db.search_books()\n [(1, 'book1', 'author', 1)]\n \"\"\"", "test": "import unittest\nimport os\n\n\nclass BookManagementDBTestCreateTable(unittest.TestCase):\n def setUp(self):\n self.db_name = \"test.db\"\n self.db = BookManagementDB(self.db_name)\n self.connection = sqlite3.connect(self.db_name)\n self.cursor = self.connection.cursor()\n\n def test_create_table_1(self):\n # Check if the table exists\n self.cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name='books'\")\n result = self.cursor.fetchone()\n self.assertIsNotNone(result)\n\n def test_create_table_2(self):\n self.db.create_table()\n # Check if the table has the correct columns\n self.cursor.execute(\"PRAGMA table_info(books)\")\n columns = self.cursor.fetchall()\n column_names = [column[1] for column in columns]\n expected_column_names = ['id', 'title', 'author', 'available']\n self.assertEqual(column_names, expected_column_names)\n\n def tearDown(self):\n self.db.connection.close()\n self.connection.close()\n # remove the test database file\n os.remove(self.db_name)\n\n\nclass BookManagementDBTestAddBook(unittest.TestCase):\n def setUp(self):\n self.db_name = \"test.db\"\n self.db = BookManagementDB(self.db_name)\n self.connection = sqlite3.connect(self.db_name)\n self.cursor = self.connection.cursor()\n\n def test_add_book(self):\n title = \"Introduction to Python\"\n author = \"John Smith\"\n self.db.add_book(title, author)\n\n # Check if the book was added correctly\n self.cursor.execute(\"SELECT title, author, available FROM books WHERE id=1\")\n result = self.cursor.fetchone()\n self.assertIsNotNone(result)\n self.assertEqual(result[0], title)\n self.assertEqual(result[1], author)\n self.assertEqual(result[2], 1)\n\n def tearDown(self):\n self.db.connection.close()\n self.connection.close()\n # remove the test database file\n os.remove(self.db_name)\n\n\nclass BookManagementDBTestRemoveBook(unittest.TestCase):\n def setUp(self):\n self.db_name = \"test.db\"\n self.db = BookManagementDB(self.db_name)\n self.connection = sqlite3.connect(self.db_name)\n self.cursor = self.connection.cursor()\n # Add a book for testing removal\n self.db.add_book(\"Book to Remove\", \"John Doe\")\n\n def test_remove_book(self):\n self.db.remove_book(1)\n\n # Check if the book was removed correctly\n self.cursor.execute(\"SELECT * FROM books WHERE id=1\")\n result = self.cursor.fetchone()\n self.assertIsNone(result)\n\n def tearDown(self):\n self.db.connection.close()\n self.connection.close()\n # remove the test database file\n os.remove(self.db_name)\n\n\nclass BookManagementDBTestBorrowBook(unittest.TestCase):\n def setUp(self):\n self.db_name = \"test.db\"\n self.db = BookManagementDB(self.db_name)\n self.connection = sqlite3.connect(self.db_name)\n self.cursor = self.connection.cursor()\n # Add a book for testing borrowing\n self.db.add_book(\"Book to Borrow\", \"Jane Smith\")\n\n def test_borrow_book(self):\n self.db.borrow_book(1)\n\n # Check if the book was marked as unavailable\n self.cursor.execute(\"SELECT available FROM books WHERE id=1\")\n result = self.cursor.fetchone()\n self.assertEqual(result[0], 0)\n\n def tearDown(self):\n self.db.connection.close()\n self.connection.close()\n # remove the test database file\n os.remove(self.db_name)\n\n\nclass BookManagementDBTestReturnBook(unittest.TestCase):\n def setUp(self):\n self.db_name = \"test.db\"\n self.db = BookManagementDB(self.db_name)\n self.connection = sqlite3.connect(self.db_name)\n self.cursor = self.connection.cursor()\n # Add a book for testing returning\n self.db.add_book(\"Book to Return\", \"James Smith\")\n self.db.borrow_book(1) # Mark the book as borrowed\n\n def test_return_book(self):\n self.db.return_book(1)\n\n # Check if the book was marked as available again\n self.cursor.execute(\"SELECT available FROM books WHERE id=1\")\n result = self.cursor.fetchone()\n self.assertEqual(result[0], 1)\n\n def tearDown(self):\n self.db.connection.close()\n self.connection.close()\n # remove the test database file\n os.remove(self.db_name)\n\n\nclass BookManagementDBTestSearchBooks(unittest.TestCase):\n def setUp(self):\n self.db_name = \"test.db\"\n self.db = BookManagementDB(self.db_name)\n self.connection = sqlite3.connect(self.db_name)\n self.cursor = self.connection.cursor()\n # Add some books for testing search\n self.db.add_book(\"Book 1\", \"Author 1\")\n self.db.add_book(\"Book 2\", \"Author 2\")\n self.db.add_book(\"Book 3\", \"Author 3\")\n\n def test_search_books(self):\n books = self.db.search_books()\n\n # Ensure that all books were retrieved\n self.assertEqual(len(books), 3)\n\n # Ensure that the correct book information is retrieved\n self.assertEqual(books[0][1], \"Book 1\")\n self.assertEqual(books[1][2], \"Author 2\")\n self.assertEqual(books[2][3], 1)\n\n def tearDown(self):\n self.db.connection.close()\n self.connection.close()\n # remove the test database file\n os.remove(self.db_name)", "solution_code": "import sqlite3\n\nclass BookManagementDB:\n def __init__(self, db_name):\n self.connection = sqlite3.connect(db_name)\n self.cursor = self.connection.cursor()\n self.create_table()\n\n def create_table(self):\n self.cursor.execute('''\n CREATE TABLE IF NOT EXISTS books (\n id INTEGER PRIMARY KEY,\n title TEXT,\n author TEXT,\n available INTEGER\n )\n ''')\n self.connection.commit()\n\n def add_book(self, title, author):\n self.cursor.execute('''\n INSERT INTO books (title, author, available)\n VALUES (?, ?, 1)\n ''', (title, author))\n self.connection.commit()\n\n def remove_book(self, book_id):\n self.cursor.execute('''\n DELETE FROM books WHERE id = ?\n ''', (book_id,))\n self.connection.commit()\n\n def borrow_book(self, book_id):\n self.cursor.execute('''\n UPDATE books SET available = 0 WHERE id = ?\n ''', (book_id,))\n self.connection.commit()\n\n def return_book(self, book_id):\n self.cursor.execute('''\n UPDATE books SET available = 1 WHERE id = ?\n ''', (book_id,))\n self.connection.commit()\n\n def search_books(self):\n self.cursor.execute('''\n SELECT * FROM books\n ''')\n books = self.cursor.fetchall()\n return books", "import_statement": [ "import sqlite3" ], "class_description": " \"\"\"\n This is a database class as a book management system, used to handle the operations of adding, removing, updating, and searching books.\n \"\"\"\n", "class_name": "BookManagementDB", "test_classes": [ "BookManagementDBTestCreateTable", "BookManagementDBTestAddBook", "BookManagementDBTestRemoveBook", "BookManagementDBTestBorrowBook", "BookManagementDBTestReturnBook", "BookManagementDBTestSearchBooks" ], "class_constructor": "class BookManagementDB: \n def __init__(self, db_name):\n \"\"\"\n Initializes the class by creating a database connection and cursor, \n and creates the book table if it does not already exist\n :param db_name: str, the name of db file\n \"\"\"\n self.connection = sqlite3.connect(db_name)\n self.cursor = self.connection.cursor()\n self.create_table()\n\n", "fields": [ "self.connection", "self.cursor" ], "methods_info": [ { "method_name": "create_table", "method_description": "def create_table(self):\n \"\"\"\n Creates the book table in the database if it does not already exist.\n >>> book_db = BookManagementDB(\"test.db\")\n >>> book_db.create_table()\n \"\"\"", "test_class": "BookManagementDBTestCreateTable", "test_code": "class BookManagementDBTestCreateTable(unittest.TestCase):\n def setUp(self):\n self.db_name = \"test.db\"\n self.db = BookManagementDB(self.db_name)\n self.connection = sqlite3.connect(self.db_name)\n self.cursor = self.connection.cursor()\n\n def test_create_table_1(self):\n # Check if the table exists\n self.cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name='books'\")\n result = self.cursor.fetchone()\n self.assertIsNotNone(result)\n\n def test_create_table_2(self):\n self.db.create_table()\n # Check if the table has the correct columns\n self.cursor.execute(\"PRAGMA table_info(books)\")\n columns = self.cursor.fetchall()\n column_names = [column[1] for column in columns]\n expected_column_names = ['id', 'title', 'author', 'available']\n self.assertEqual(column_names, expected_column_names)\n\n def tearDown(self):\n self.db.connection.close()\n self.connection.close()\n # remove the test database file\n os.remove(self.db_name)", "solution_code": "def create_table(self):\n self.cursor.execute('''\n CREATE TABLE IF NOT EXISTS books (\n id INTEGER PRIMARY KEY,\n title TEXT,\n author TEXT,\n available INTEGER\n )\n ''')\n self.connection.commit()", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.connection", "self.cursor" ], "method_dependencies": [] } }, { "method_name": "add_book", "method_description": "def add_book(self, title, author):\n \"\"\"\n Adds a book to the database with the specified title and author, \n setting its availability to 1 as free to borrow.\n :param title: str, book title\n :param author: str, author name\n >>> book_db = BookManagementDB(\"test.db\")\n >>> book_db.create_table()\n >>> book_db.add_book('book1', 'author')\n \"\"\"", "test_class": "BookManagementDBTestAddBook", "test_code": "class BookManagementDBTestAddBook(unittest.TestCase):\n def setUp(self):\n self.db_name = \"test.db\"\n self.db = BookManagementDB(self.db_name)\n self.connection = sqlite3.connect(self.db_name)\n self.cursor = self.connection.cursor()\n\n def test_add_book(self):\n title = \"Introduction to Python\"\n author = \"John Smith\"\n self.db.add_book(title, author)\n\n # Check if the book was added correctly\n self.cursor.execute(\"SELECT title, author, available FROM books WHERE id=1\")\n result = self.cursor.fetchone()\n self.assertIsNotNone(result)\n self.assertEqual(result[0], title)\n self.assertEqual(result[1], author)\n self.assertEqual(result[2], 1)\n\n def tearDown(self):\n self.db.connection.close()\n self.connection.close()\n # remove the test database file\n os.remove(self.db_name)", "solution_code": "def add_book(self, title, author):\n self.cursor.execute('''\n INSERT INTO books (title, author, available)\n VALUES (?, ?, 1)\n ''', (title, author))\n self.connection.commit()", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.connection", "self.cursor" ], "method_dependencies": [] } }, { "method_name": "remove_book", "method_description": "def remove_book(self, book_id):\n \"\"\"\n Removes a book from the database based on the given book ID.\n :param book_id: int\n >>> book_db = BookManagementDB(\"test.db\")\n >>> book_db.remove_book(1)\n \"\"\"", "test_class": "BookManagementDBTestRemoveBook", "test_code": "class BookManagementDBTestRemoveBook(unittest.TestCase):\n def setUp(self):\n self.db_name = \"test.db\"\n self.db = BookManagementDB(self.db_name)\n self.connection = sqlite3.connect(self.db_name)\n self.cursor = self.connection.cursor()\n # Add a book for testing removal\n self.db.add_book(\"Book to Remove\", \"John Doe\")\n\n def test_remove_book(self):\n self.db.remove_book(1)\n\n # Check if the book was removed correctly\n self.cursor.execute(\"SELECT * FROM books WHERE id=1\")\n result = self.cursor.fetchone()\n self.assertIsNone(result)\n\n def tearDown(self):\n self.db.connection.close()\n self.connection.close()\n # remove the test database file\n os.remove(self.db_name)", "solution_code": "def remove_book(self, book_id):\n self.cursor.execute('''\n DELETE FROM books WHERE id = ?\n ''', (book_id,))\n self.connection.commit()", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.connection", "self.cursor" ], "method_dependencies": [] } }, { "method_name": "borrow_book", "method_description": "def borrow_book(self, book_id):\n \"\"\"\n Marks a book as borrowed in the database based on the given book ID.\n :param book_id: int\n >>> book_db = BookManagementDB(\"test.db\")\n >>> book_db.borrow_book(1)\n \"\"\"", "test_class": "BookManagementDBTestBorrowBook", "test_code": "class BookManagementDBTestBorrowBook(unittest.TestCase):\n def setUp(self):\n self.db_name = \"test.db\"\n self.db = BookManagementDB(self.db_name)\n self.connection = sqlite3.connect(self.db_name)\n self.cursor = self.connection.cursor()\n # Add a book for testing borrowing\n self.db.add_book(\"Book to Borrow\", \"Jane Smith\")\n\n def test_borrow_book(self):\n self.db.borrow_book(1)\n\n # Check if the book was marked as unavailable\n self.cursor.execute(\"SELECT available FROM books WHERE id=1\")\n result = self.cursor.fetchone()\n self.assertEqual(result[0], 0)\n\n def tearDown(self):\n self.db.connection.close()\n self.connection.close()\n # remove the test database file\n os.remove(self.db_name)", "solution_code": "def borrow_book(self, book_id):\n self.cursor.execute('''\n UPDATE books SET available = 0 WHERE id = ?\n ''', (book_id,))\n self.connection.commit()", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.connection", "self.cursor" ], "method_dependencies": [] } }, { "method_name": "return_book", "method_description": "def return_book(self, book_id):\n \"\"\"\n Marks a book as returned in the database based on the given book ID.\n :param book_id: int\n >>> book_db = BookManagementDB(\"test.db\")\n >>> book_db.return_book(1)\n \"\"\"", "test_class": "BookManagementDBTestReturnBook", "test_code": "class BookManagementDBTestReturnBook(unittest.TestCase):\n def setUp(self):\n self.db_name = \"test.db\"\n self.db = BookManagementDB(self.db_name)\n self.connection = sqlite3.connect(self.db_name)\n self.cursor = self.connection.cursor()\n # Add a book for testing returning\n self.db.add_book(\"Book to Return\", \"James Smith\")\n self.db.borrow_book(1) # Mark the book as borrowed\n\n def test_return_book(self):\n self.db.return_book(1)\n\n # Check if the book was marked as available again\n self.cursor.execute(\"SELECT available FROM books WHERE id=1\")\n result = self.cursor.fetchone()\n self.assertEqual(result[0], 1)\n\n def tearDown(self):\n self.db.connection.close()\n self.connection.close()\n # remove the test database file\n os.remove(self.db_name)", "solution_code": "def return_book(self, book_id):\n self.cursor.execute('''\n UPDATE books SET available = 1 WHERE id = ?\n ''', (book_id,))\n self.connection.commit()", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.connection", "self.cursor" ], "method_dependencies": [] } }, { "method_name": "search_books", "method_description": "def search_books(self):\n \"\"\"\n Retrieves all books from the database and returns their information.\n :return books: list[tuple], the information of all books in database\n >>> book_db.search_books()\n [(1, 'book1', 'author', 1)]\n \"\"\"", "test_class": "BookManagementDBTestSearchBooks", "test_code": "class BookManagementDBTestSearchBooks(unittest.TestCase):\n def setUp(self):\n self.db_name = \"test.db\"\n self.db = BookManagementDB(self.db_name)\n self.connection = sqlite3.connect(self.db_name)\n self.cursor = self.connection.cursor()\n # Add some books for testing search\n self.db.add_book(\"Book 1\", \"Author 1\")\n self.db.add_book(\"Book 2\", \"Author 2\")\n self.db.add_book(\"Book 3\", \"Author 3\")\n\n def test_search_books(self):\n books = self.db.search_books()\n\n # Ensure that all books were retrieved\n self.assertEqual(len(books), 3)\n\n # Ensure that the correct book information is retrieved\n self.assertEqual(books[0][1], \"Book 1\")\n self.assertEqual(books[1][2], \"Author 2\")\n self.assertEqual(books[2][3], 1)\n\n def tearDown(self):\n self.db.connection.close()\n self.connection.close()\n # remove the test database file\n os.remove(self.db_name)", "solution_code": "def search_books(self):\n self.cursor.execute('''\n SELECT * FROM books\n ''')\n books = self.cursor.fetchall()\n return books", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.cursor" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_15", "skeleton": "\nclass BoyerMooreSearch:\n \"\"\"\n his is a class that implements the Boyer-Moore algorithm for string searching, which is used to find occurrences of a pattern within a given text.\n \"\"\"\n\n def __init__(self, text, pattern):\n \"\"\"\n Initializes the BoyerMooreSearch class with the given text and pattern.\n :param text: The text to be searched, str.\n :param pattern: The pattern to be searched for, str.\n \"\"\"\n self.text, self.pattern = text, pattern\n self.textLen, self.patLen = len(text), len(pattern)\n\n def match_in_pattern(self, char):\n \"\"\"\n Finds the rightmost occurrence of a character in the pattern.\n :param char: The character to be searched for, str.\n :return: The index of the rightmost occurrence of the character in the pattern, int.\n >>> boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"AB\")\n >>> boyerMooreSearch.match_in_pattern(\"A\")\n 0\n\n \"\"\"\n\n def mismatch_in_text(self, currentPos):\n \"\"\"\n Determines the position of the first dismatch between the pattern and the text.\n :param currentPos: The current position in the text, int.\n :return: The position of the first dismatch between the pattern and the text, int,otherwise -1.\n >>> boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"ABC\")\n >>> boyerMooreSearch.mismatch_in_text(0)\n 2\n\n \"\"\"\n\n def bad_character_heuristic(self):\n \"\"\"\n Finds all occurrences of the pattern in the text.\n :return: A list of all positions of the pattern in the text, list.\n >>> boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"AB\")\n >>> boyerMooreSearch.bad_character_heuristic()\n [0, 3]\n\n \"\"\"", "test": "import unittest\n\nclass BoyerMooreSearchTestMatchInPattern(unittest.TestCase):\n def test_match_in_pattern(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"AB\")\n self.assertEqual(boyerMooreSearch.match_in_pattern(\"A\"), 0)\n\n def test_match_in_pattern_2(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"ABAB\")\n self.assertEqual(boyerMooreSearch.match_in_pattern(\"B\"), 3)\n\n def test_match_in_pattern_3(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"ABCABC\")\n self.assertEqual(boyerMooreSearch.match_in_pattern(\"C\"), 5)\n\n def test_match_in_pattern_4(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"ABCABC\")\n self.assertEqual(boyerMooreSearch.match_in_pattern(\"D\"), -1)\n\n def test_match_in_pattern_5(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"ABCABC\")\n self.assertEqual(boyerMooreSearch.match_in_pattern(\"E\"), -1)\n\n\nclass BoyerMooreSearchTestMismatchInText(unittest.TestCase):\n def test_mismatch_in_text(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"AB\")\n self.assertEqual(boyerMooreSearch.mismatch_in_text(0), -1)\n\n def test_mismatch_in_text_2(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"ABC\")\n self.assertEqual(boyerMooreSearch.mismatch_in_text(0), 2)\n\n def test_mismatch_in_text_3(self):\n boyerMooreSearch = BoyerMooreSearch(\"AAAA\", \"ABC\")\n self.assertEqual(boyerMooreSearch.mismatch_in_text(0), 2)\n\n def test_mismatch_in_text_4(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"\")\n self.assertEqual(boyerMooreSearch.mismatch_in_text(0), -1)\n\n def test_mismatch_in_text_5(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"ABC\")\n self.assertEqual(boyerMooreSearch.mismatch_in_text(3), 5)\n\n\nclass BoyerMooreSearchTestBadCharacterHeuristic(unittest.TestCase):\n def test_bad_character_heuristic(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"AB\")\n self.assertEqual(boyerMooreSearch.bad_character_heuristic(), [0, 3])\n\n def test_bad_character_heuristic_2(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"ABC\")\n self.assertEqual(boyerMooreSearch.bad_character_heuristic(), [])\n\n def test_bad_character_heuristic_3(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"\")\n self.assertEqual(boyerMooreSearch.bad_character_heuristic(), [0, 1, 2, 3, 4, 5, 6])\n\n def test_bad_character_heuristic_4(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABACABA\", \"ABA\")\n self.assertEqual(boyerMooreSearch.bad_character_heuristic(), [0, 4])\n\n def test_bad_character_heuristic_5(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABACABA\", \"ABAC\")\n self.assertEqual(boyerMooreSearch.bad_character_heuristic(), [0])\n\nclass BoyerMooreSearchTestMain(unittest.TestCase):\n def test_main(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"AB\")\n self.assertEqual(boyerMooreSearch.match_in_pattern(\"A\"), 0)\n self.assertEqual(boyerMooreSearch.mismatch_in_text(0), -1)\n self.assertEqual(boyerMooreSearch.bad_character_heuristic(), [0, 3])", "solution_code": "class BoyerMooreSearch:\n def __init__(self, text, pattern):\n self.text, self.pattern = text, pattern\n self.textLen, self.patLen = len(text), len(pattern)\n\n def match_in_pattern(self, char):\n for i in range(self.patLen - 1, -1, -1):\n if char == self.pattern[i]:\n return i\n return -1\n\n def mismatch_in_text(self, currentPos):\n for i in range(self.patLen - 1, -1, -1):\n if self.pattern[i] != self.text[currentPos + i]:\n return currentPos + i\n return -1\n\n def bad_character_heuristic(self):\n positions = []\n for i in range(self.textLen - self.patLen + 1):\n mismatch_index = self.mismatch_in_text(i)\n if mismatch_index == -1:\n positions.append(i)\n else:\n match_index = self.match_in_pattern(self.text[mismatch_index])\n i = (mismatch_index - match_index)\n return positions", "import_statement": [], "class_description": " \"\"\"\n his is a class that implements the Boyer-Moore algorithm for string searching, which is used to find occurrences of a pattern within a given text.\n \"\"\"\n", "class_name": "BoyerMooreSearch", "test_classes": [ "BoyerMooreSearchTestMatchInPattern", "BoyerMooreSearchTestMismatchInText", "BoyerMooreSearchTestBadCharacterHeuristic", "BoyerMooreSearchTestMain" ], "class_constructor": "class BoyerMooreSearch: \n def __init__(self, text, pattern):\n \"\"\"\n Initializes the BoyerMooreSearch class with the given text and pattern.\n :param text: The text to be searched, str.\n :param pattern: The pattern to be searched for, str.\n \"\"\"\n self.text, self.pattern = text, pattern\n self.textLen, self.patLen = len(text), len(pattern)\n\n", "fields": [ "self.patLen", "self.pattern", "self.text", "self.textLen" ], "methods_info": [ { "method_name": "match_in_pattern", "method_description": "def match_in_pattern(self, char):\n \"\"\"\n Finds the rightmost occurrence of a character in the pattern.\n :param char: The character to be searched for, str.\n :return: The index of the rightmost occurrence of the character in the pattern, int.\n >>> boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"AB\")\n >>> boyerMooreSearch.match_in_pattern(\"A\")\n 0\n\n \"\"\"", "test_class": "BoyerMooreSearchTestMatchInPattern", "test_code": "class BoyerMooreSearchTestMatchInPattern(unittest.TestCase):\n def test_match_in_pattern(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"AB\")\n self.assertEqual(boyerMooreSearch.match_in_pattern(\"A\"), 0)\n\n def test_match_in_pattern_2(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"ABAB\")\n self.assertEqual(boyerMooreSearch.match_in_pattern(\"B\"), 3)\n\n def test_match_in_pattern_3(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"ABCABC\")\n self.assertEqual(boyerMooreSearch.match_in_pattern(\"C\"), 5)\n\n def test_match_in_pattern_4(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"ABCABC\")\n self.assertEqual(boyerMooreSearch.match_in_pattern(\"D\"), -1)\n\n def test_match_in_pattern_5(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"ABCABC\")\n self.assertEqual(boyerMooreSearch.match_in_pattern(\"E\"), -1)", "solution_code": "def match_in_pattern(self, char):\n for i in range(self.patLen - 1, -1, -1):\n if char == self.pattern[i]:\n return i\n return -1", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.patLen", "self.pattern" ], "method_dependencies": [] } }, { "method_name": "mismatch_in_text", "method_description": "def mismatch_in_text(self, currentPos):\n \"\"\"\n Determines the position of the first dismatch between the pattern and the text.\n :param currentPos: The current position in the text, int.\n :return: The position of the first dismatch between the pattern and the text, int,otherwise -1.\n >>> boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"ABC\")\n >>> boyerMooreSearch.mismatch_in_text(0)\n 2\n\n \"\"\"", "test_class": "BoyerMooreSearchTestMismatchInText", "test_code": "class BoyerMooreSearchTestMismatchInText(unittest.TestCase):\n def test_mismatch_in_text(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"AB\")\n self.assertEqual(boyerMooreSearch.mismatch_in_text(0), -1)\n\n def test_mismatch_in_text_2(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"ABC\")\n self.assertEqual(boyerMooreSearch.mismatch_in_text(0), 2)\n\n def test_mismatch_in_text_3(self):\n boyerMooreSearch = BoyerMooreSearch(\"AAAA\", \"ABC\")\n self.assertEqual(boyerMooreSearch.mismatch_in_text(0), 2)\n\n def test_mismatch_in_text_4(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"\")\n self.assertEqual(boyerMooreSearch.mismatch_in_text(0), -1)\n\n def test_mismatch_in_text_5(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"ABC\")\n self.assertEqual(boyerMooreSearch.mismatch_in_text(3), 5)", "solution_code": "def mismatch_in_text(self, currentPos):\n for i in range(self.patLen - 1, -1, -1):\n if self.pattern[i] != self.text[currentPos + i]:\n return currentPos + i\n return -1", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.patLen", "self.pattern", "self.text" ], "method_dependencies": [] } }, { "method_name": "bad_character_heuristic", "method_description": "def bad_character_heuristic(self):\n \"\"\"\n Finds all occurrences of the pattern in the text.\n :return: A list of all positions of the pattern in the text, list.\n >>> boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"AB\")\n >>> boyerMooreSearch.bad_character_heuristic()\n [0, 3]\n\n \"\"\"", "test_class": "BoyerMooreSearchTestBadCharacterHeuristic", "test_code": "class BoyerMooreSearchTestBadCharacterHeuristic(unittest.TestCase):\n def test_bad_character_heuristic(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"AB\")\n self.assertEqual(boyerMooreSearch.bad_character_heuristic(), [0, 3])\n\n def test_bad_character_heuristic_2(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"ABC\")\n self.assertEqual(boyerMooreSearch.bad_character_heuristic(), [])\n\n def test_bad_character_heuristic_3(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"\")\n self.assertEqual(boyerMooreSearch.bad_character_heuristic(), [0, 1, 2, 3, 4, 5, 6])\n\n def test_bad_character_heuristic_4(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABACABA\", \"ABA\")\n self.assertEqual(boyerMooreSearch.bad_character_heuristic(), [0, 4])\n\n def test_bad_character_heuristic_5(self):\n boyerMooreSearch = BoyerMooreSearch(\"ABACABA\", \"ABAC\")\n self.assertEqual(boyerMooreSearch.bad_character_heuristic(), [0])", "solution_code": "def bad_character_heuristic(self):\n positions = []\n for i in range(self.textLen - self.patLen + 1):\n mismatch_index = self.mismatch_in_text(i)\n if mismatch_index == -1:\n positions.append(i)\n else:\n match_index = self.match_in_pattern(self.text[mismatch_index])\n i = (mismatch_index - match_index)\n return positions", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.patLen", "self.text", "self.textLen" ], "method_dependencies": [ "match_in_pattern", "mismatch_in_text" ] } } ] }, { "task_id": "ClassEval_16", "skeleton": "\nclass Calculator:\n \"\"\"\n This is a class for a calculator, capable of performing basic arithmetic calculations on numerical expressions using the operators +, -, *, /, and ^ (exponentiation).\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialize the operations performed by the five operators'+','-','*','/','^'\n \"\"\"\n self.operators = {\n '+': lambda x, y: x + y,\n '-': lambda x, y: x - y,\n '*': lambda x, y: x * y,\n '/': lambda x, y: x / y,\n '^': lambda x, y: x ** y\n }\n\n def calculate(self, expression):\n \"\"\"\n Calculate the value of a given expression\n :param expression: string, given expression\n :return:If successful, returns the value of the expression; otherwise, returns None\n >>> calculator = Calculator()\n >>> calculator.calculate('1+2-3')\n 0.0\n \"\"\"\n\n\n def precedence(self, operator):\n \"\"\"\n Returns the priority of the specified operator, where the higher the priority, the greater the assignment. The priority of '^' is greater than '/' and '*', and the priority of '/' and '*' is greater than '+' and '-'\n :param operator: string, given operator\n :return: int, the priority of the given operator, otherwise return 0\n >>> calculator = Calculator()\n >>> calculator.precedence('+')\n 1\n >>> calculator.precedence('^')\n 3\n \"\"\"\n\n\n def apply_operator(self, operand_stack, operator_stack):\n \"\"\"\n Use the operator at the top of the operator stack to perform the operation on the two numbers at the top of the operator stack, and store the results at the top of the operator stack\n :param operand_stack:list\n :param operator_stack:list\n :return: the updated operand_stack and operator_stack\n >>> calculator = Calculator()\n >>> calculator.apply_operator([1, 2, 3], ['+', '-'])\n ([1, -1], ['-'])\n \"\"\"", "test": "import unittest\n\nclass CalculatorTestCalculate(unittest.TestCase):\n def test_calculate_1(self):\n calculator = Calculator()\n res = calculator.calculate('1+2')\n self.assertEqual(res, 3)\n\n def test_calculate_2(self):\n calculator = Calculator()\n res = calculator.calculate('1+2*3')\n self.assertEqual(res, 7)\n\n def test_calculate_3(self):\n calculator = Calculator()\n res = calculator.calculate('1+2*3+4')\n self.assertEqual(res, 11)\n\n def test_calculate_4(self):\n calculator = Calculator()\n res = calculator.calculate('1+2^3*2+4*5')\n self.assertEqual(res, 37)\n\n def test_calculate_5(self):\n calculator = Calculator()\n res = calculator.calculate('1+2+3')\n self.assertEqual(res, 6)\n\n def test_calculate_6(self):\n calculator = Calculator()\n res = calculator.calculate('(1+2)+3')\n self.assertEqual(res, 6)\n\n def test_calculate_7(self):\n calculator = Calculator()\n res = calculator.calculate('')\n self.assertEqual(res, None)\n\n def test_calculate_8(self):\n calculator = Calculator()\n res = calculator.calculate('1+2?')\n self.assertEqual(res, 3)\n\n\nclass CalculatorTestPrecedence(unittest.TestCase):\n def test_precedence_1(self):\n calculator = Calculator()\n res1 = calculator.precedence('+')\n res2 = calculator.precedence('-')\n self.assertEqual(res1, res2)\n\n def test_precedence_2(self):\n calculator = Calculator()\n res1 = calculator.precedence('*')\n res2 = calculator.precedence('/')\n self.assertEqual(res1, res2)\n\n def test_precedence_3(self):\n calculator = Calculator()\n res1 = calculator.precedence('+')\n res2 = calculator.precedence('/')\n self.assertNotEqual(res1, res2)\n\n def test_precedence_4(self):\n calculator = Calculator()\n res1 = calculator.precedence('+')\n res2 = calculator.precedence('/')\n self.assertNotEqual(res1, res2)\n\n def test_precedence_5(self):\n calculator = Calculator()\n res1 = calculator.precedence('*')\n res2 = calculator.precedence('-')\n self.assertNotEqual(res1, res2)\n\n\nclass CalculatorTestApplyOperator(unittest.TestCase):\n def test_apply_operator_1(self):\n calculator = Calculator()\n operand_stack = [1, 2, 3]\n operator_stack = ['+', '-']\n calculator.apply_operator(operand_stack, operator_stack)\n self.assertEqual(operand_stack, [1, -1])\n self.assertEqual(operator_stack, ['+'])\n\n def test_apply_operator_2(self):\n calculator = Calculator()\n operand_stack = [1, 2, 3]\n operator_stack = ['+', '*']\n calculator.apply_operator(operand_stack, operator_stack)\n self.assertEqual(operand_stack, [1, 6])\n self.assertEqual(operator_stack, ['+'])\n\n def test_apply_operator_3(self):\n calculator = Calculator()\n operand_stack = [6, 3, 3]\n operator_stack = ['+', '/']\n calculator.apply_operator(operand_stack, operator_stack)\n self.assertEqual(operand_stack, [6, 1])\n self.assertEqual(operator_stack, ['+'])\n\n def test_apply_operator_4(self):\n calculator = Calculator()\n operand_stack = [1, 2, 3]\n operator_stack = ['+', '^']\n calculator.apply_operator(operand_stack, operator_stack)\n self.assertEqual(operand_stack, [1, 8])\n self.assertEqual(operator_stack, ['+'])\n\n def test_apply_operator_5(self):\n calculator = Calculator()\n operand_stack = [1, 2, 3]\n operator_stack = ['+', '+']\n calculator.apply_operator(operand_stack, operator_stack)\n self.assertEqual(operand_stack, [1, 5])\n self.assertEqual(operator_stack, ['+'])\n\n\nclass CalculatorTest(unittest.TestCase):\n def test_calculator(self):\n calculator = Calculator()\n res = calculator.calculate('1+2')\n self.assertEqual(res, 3)\n res1 = calculator.precedence('+')\n res2 = calculator.precedence('-')\n res3 = calculator.precedence('*')\n res4 = calculator.precedence('/')\n res5 = calculator.precedence('^')\n self.assertEqual(res1, res2)\n self.assertEqual(res3, res4)\n self.assertGreater(res3, res1)\n self.assertGreater(res5, res3)\n operand_stack = [1, 2, 3]\n operator_stack = ['+', '-']\n calculator.apply_operator(operand_stack, operator_stack)\n self.assertEqual(operand_stack, [1, -1])\n self.assertEqual(operator_stack, ['+'])", "solution_code": "class Calculator:\n def __init__(self):\n self.operators = {\n '+': lambda x, y: x + y,\n '-': lambda x, y: x - y,\n '*': lambda x, y: x * y,\n '/': lambda x, y: x / y,\n '^': lambda x, y: x ** y\n }\n\n def calculate(self, expression):\n operand_stack = []\n operator_stack = []\n num_buffer = ''\n\n for char in expression:\n if char.isdigit() or char == '.':\n num_buffer += char\n else:\n if num_buffer:\n operand_stack.append(float(num_buffer))\n num_buffer = ''\n\n if char in '+-*/^':\n while (\n operator_stack and\n operator_stack[-1] != '(' and\n self.precedence(operator_stack[-1]) >= self.precedence(char)\n ):\n operand_stack, operator_stack = self.apply_operator(operand_stack, operator_stack)\n\n operator_stack.append(char)\n elif char == '(':\n operator_stack.append(char)\n elif char == ')':\n while operator_stack and operator_stack[-1] != '(':\n operand_stack, operator_stack = self.apply_operator(operand_stack, operator_stack)\n\n operator_stack.pop()\n\n if num_buffer:\n operand_stack.append(float(num_buffer))\n\n while operator_stack:\n operand_stack, operator_stack = self.apply_operator(operand_stack, operator_stack)\n\n return operand_stack[-1] if operand_stack else None\n\n def precedence(self, operator):\n precedences = {\n '+': 1,\n '-': 1,\n '*': 2,\n '/': 2,\n '^': 3\n }\n return precedences.get(operator, 0)\n\n def apply_operator(self, operand_stack, operator_stack):\n operator = operator_stack.pop()\n if operator == '^':\n operand2 = operand_stack.pop()\n operand1 = operand_stack.pop()\n result = self.operators[operator](operand1, operand2)\n operand_stack.append(result)\n else:\n operand2 = operand_stack.pop()\n operand1 = operand_stack.pop()\n result = self.operators[operator](operand1, operand2)\n operand_stack.append(result)\n return operand_stack, operator_stack", "import_statement": [], "class_description": " \"\"\"\n This is a class for a calculator, capable of performing basic arithmetic calculations on numerical expressions using the operators +, -, *, /, and ^ (exponentiation).\n \"\"\"\n", "class_name": "Calculator", "test_classes": [ "CalculatorTestCalculate", "CalculatorTestPrecedence", "CalculatorTestApplyOperator", "CalculatorTest" ], "class_constructor": "class Calculator: \n def __init__(self):\n \"\"\"\n Initialize the operations performed by the five operators'+','-','*','/','^'\n \"\"\"\n self.operators = {\n '+': lambda x, y: x + y,\n '-': lambda x, y: x - y,\n '*': lambda x, y: x * y,\n '/': lambda x, y: x / y,\n '^': lambda x, y: x ** y\n }\n\n", "fields": [ "self.operators" ], "methods_info": [ { "method_name": "calculate", "method_description": "def calculate(self, expression):\n \"\"\"\n Calculate the value of a given expression\n :param expression: string, given expression\n :return:If successful, returns the value of the expression; otherwise, returns None\n >>> calculator = Calculator()\n >>> calculator.calculate('1+2-3')\n 0.0\n \"\"\"", "test_class": "CalculatorTestCalculate", "test_code": "class CalculatorTestCalculate(unittest.TestCase):\n def test_calculate_1(self):\n calculator = Calculator()\n res = calculator.calculate('1+2')\n self.assertEqual(res, 3)\n\n def test_calculate_2(self):\n calculator = Calculator()\n res = calculator.calculate('1+2*3')\n self.assertEqual(res, 7)\n\n def test_calculate_3(self):\n calculator = Calculator()\n res = calculator.calculate('1+2*3+4')\n self.assertEqual(res, 11)\n\n def test_calculate_4(self):\n calculator = Calculator()\n res = calculator.calculate('1+2^3*2+4*5')\n self.assertEqual(res, 37)\n\n def test_calculate_5(self):\n calculator = Calculator()\n res = calculator.calculate('1+2+3')\n self.assertEqual(res, 6)\n\n def test_calculate_6(self):\n calculator = Calculator()\n res = calculator.calculate('(1+2)+3')\n self.assertEqual(res, 6)\n\n def test_calculate_7(self):\n calculator = Calculator()\n res = calculator.calculate('')\n self.assertEqual(res, None)\n\n def test_calculate_8(self):\n calculator = Calculator()\n res = calculator.calculate('1+2?')\n self.assertEqual(res, 3)", "solution_code": "def calculate(self, expression):\n operand_stack = []\n operator_stack = []\n num_buffer = ''\n\n for char in expression:\n if char.isdigit() or char == '.':\n num_buffer += char\n else:\n if num_buffer:\n operand_stack.append(float(num_buffer))\n num_buffer = ''\n\n if char in '+-*/^':\n while (\n operator_stack and\n operator_stack[-1] != '(' and\n self.precedence(operator_stack[-1]) >= self.precedence(char)\n ):\n operand_stack, operator_stack = self.apply_operator(operand_stack, operator_stack)\n\n operator_stack.append(char)\n elif char == '(':\n operator_stack.append(char)\n elif char == ')':\n while operator_stack and operator_stack[-1] != '(':\n operand_stack, operator_stack = self.apply_operator(operand_stack, operator_stack)\n\n operator_stack.pop()\n\n if num_buffer:\n operand_stack.append(float(num_buffer))\n\n while operator_stack:\n operand_stack, operator_stack = self.apply_operator(operand_stack, operator_stack)\n\n return operand_stack[-1] if operand_stack else None", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "precedence", "apply_operator" ] } }, { "method_name": "precedence", "method_description": "def precedence(self, operator):\n \"\"\"\n Returns the priority of the specified operator, where the higher the priority, the greater the assignment. The priority of '^' is greater than '/' and '*', and the priority of '/' and '*' is greater than '+' and '-'\n :param operator: string, given operator\n :return: int, the priority of the given operator, otherwise return 0\n >>> calculator = Calculator()\n >>> calculator.precedence('+')\n 1\n >>> calculator.precedence('^')\n 3\n \"\"\"", "test_class": "CalculatorTestPrecedence", "test_code": "class CalculatorTestPrecedence(unittest.TestCase):\n def test_precedence_1(self):\n calculator = Calculator()\n res1 = calculator.precedence('+')\n res2 = calculator.precedence('-')\n self.assertEqual(res1, res2)\n\n def test_precedence_2(self):\n calculator = Calculator()\n res1 = calculator.precedence('*')\n res2 = calculator.precedence('/')\n self.assertEqual(res1, res2)\n\n def test_precedence_3(self):\n calculator = Calculator()\n res1 = calculator.precedence('+')\n res2 = calculator.precedence('/')\n self.assertNotEqual(res1, res2)\n\n def test_precedence_4(self):\n calculator = Calculator()\n res1 = calculator.precedence('+')\n res2 = calculator.precedence('/')\n self.assertNotEqual(res1, res2)\n\n def test_precedence_5(self):\n calculator = Calculator()\n res1 = calculator.precedence('*')\n res2 = calculator.precedence('-')\n self.assertNotEqual(res1, res2)", "solution_code": "def precedence(self, operator):\n precedences = {\n '+': 1,\n '-': 1,\n '*': 2,\n '/': 2,\n '^': 3\n }\n return precedences.get(operator, 0)", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "apply_operator", "method_description": "def apply_operator(self, operand_stack, operator_stack):\n \"\"\"\n Use the operator at the top of the operator stack to perform the operation on the two numbers at the top of the operator stack, and store the results at the top of the operator stack\n :param operand_stack:list\n :param operator_stack:list\n :return: the updated operand_stack and operator_stack\n >>> calculator = Calculator()\n >>> calculator.apply_operator([1, 2, 3], ['+', '-'])\n ([1, -1], ['-'])\n \"\"\"", "test_class": "CalculatorTestApplyOperator", "test_code": "class CalculatorTestApplyOperator(unittest.TestCase):\n def test_apply_operator_1(self):\n calculator = Calculator()\n operand_stack = [1, 2, 3]\n operator_stack = ['+', '-']\n calculator.apply_operator(operand_stack, operator_stack)\n self.assertEqual(operand_stack, [1, -1])\n self.assertEqual(operator_stack, ['+'])\n\n def test_apply_operator_2(self):\n calculator = Calculator()\n operand_stack = [1, 2, 3]\n operator_stack = ['+', '*']\n calculator.apply_operator(operand_stack, operator_stack)\n self.assertEqual(operand_stack, [1, 6])\n self.assertEqual(operator_stack, ['+'])\n\n def test_apply_operator_3(self):\n calculator = Calculator()\n operand_stack = [6, 3, 3]\n operator_stack = ['+', '/']\n calculator.apply_operator(operand_stack, operator_stack)\n self.assertEqual(operand_stack, [6, 1])\n self.assertEqual(operator_stack, ['+'])\n\n def test_apply_operator_4(self):\n calculator = Calculator()\n operand_stack = [1, 2, 3]\n operator_stack = ['+', '^']\n calculator.apply_operator(operand_stack, operator_stack)\n self.assertEqual(operand_stack, [1, 8])\n self.assertEqual(operator_stack, ['+'])\n\n def test_apply_operator_5(self):\n calculator = Calculator()\n operand_stack = [1, 2, 3]\n operator_stack = ['+', '+']\n calculator.apply_operator(operand_stack, operator_stack)\n self.assertEqual(operand_stack, [1, 5])\n self.assertEqual(operator_stack, ['+'])", "solution_code": "def apply_operator(self, operand_stack, operator_stack):\n operator = operator_stack.pop()\n if operator == '^':\n operand2 = operand_stack.pop()\n operand1 = operand_stack.pop()\n result = self.operators[operator](operand1, operand2)\n operand_stack.append(result)\n else:\n operand2 = operand_stack.pop()\n operand1 = operand_stack.pop()\n result = self.operators[operator](operand1, operand2)\n operand_stack.append(result)\n return operand_stack, operator_stack", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.operators" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_17", "skeleton": "\nfrom datetime import datetime, timedelta\n\nclass CalendarUtil:\n \"\"\"\n This is a class as CalendarUtil that provides functionalities to manage calendar events, schedule appointments, and perform conflict checks.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialize the calendar with an empty list of events.\n self.events = []\n\n def add_event(self, event):\n \"\"\"\n Add an event to the calendar.\n :param event: The event to be added to the calendar,dict.\n >>> calendar = CalendarUtil()\n >>> calendar.add_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0), 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})\n >>> calendar.events\n [{'date': datetime.datetime(2023, 1, 1, 0, 0), 'start_time': datetime.datetime(2023, 1, 1, 0, 0), 'end_time': datetime.datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n\n \"\"\"\n\n def remove_event(self, event):\n \"\"\"\n Remove an event from the calendar.\n :param event: The event to be removed from the calendar,dict.\n >>> calendar = CalendarUtil()\n >>> calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0), 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n >>> calendar.remove_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0), 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})\n >>> calendar.events\n []\n\n \"\"\"\n\n def get_events(self, date):\n \"\"\"\n Get all events on a given date.\n :param date: The date to get events for,datetime.\n :return: A list of events on the given date,list.\n >>> calendar = CalendarUtil()\n >>> calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0), 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n >>> calendar.get_events(datetime(2023, 1, 1, 0, 0))\n [{'date': datetime.datetime(2023, 1, 1, 0, 0), 'start_time': datetime.datetime(2023, 1, 1, 0, 0), 'end_time': datetime.datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n\n \"\"\"\n\n def is_available(self, start_time, end_time):\n \"\"\"\n Check if the calendar is available for a given time slot.\n :param start_time: The start time of the time slot,datetime.\n :param end_time: The end time of the time slot,datetime.\n :return: True if the calendar is available for the given time slot, False otherwise,bool.\n >>> calendar = CalendarUtil()\n >>> calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0), 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n >>> calendar.is_available(datetime(2023, 1, 1, 0, 0), datetime(2023, 1, 1, 1, 0))\n False\n\n \"\"\"\n\n def get_available_slots(self, date):\n \"\"\"\n Get all available time slots on a given date.\n :param date: The date to get available time slots for,datetime.\n :return: A list of available time slots on the given date,list.\n >>> calendar = CalendarUtil()\n >>> calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0), 'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'}]\n >>> calendar.get_available_slots(datetime(2023, 1, 1))\n [(datetime.datetime(2023, 1, 1, 23, 0), datetime.datetime(2023, 1, 2, 0, 0))]\n\n \"\"\"\n\n def get_upcoming_events(self, num_events):\n \"\"\"\n Get the next n upcoming events from a given date.\n :param date: The date to get upcoming events from,datetime.\n :param n: The number of upcoming events to get,int.\n :return: A list of the next n upcoming events from the given date,list.\n >>> calendar = CalendarUtil()\n >>> calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0), 'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'},{'date': datetime(2023, 1, 2, 0, 0),'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year 2'}]\n >>> calendar.get_upcoming_events(1)\n [{'date': datetime.datetime(2023, 1, 1, 0, 0), 'start_time': datetime.datetime(2023, 1, 1, 0, 0), 'end_time': datetime.datetime(2023, 1, 1, 23, 0), 'description': 'New Year'}, {'date': datetime.datetime(2023, 1, 2, 0, 0), 'end_time': datetime.datetime(2023, 1, 2, 1, 0), 'description': 'New Year 2'}]\n\n \"\"\"", "test": "import unittest\nfrom datetime import datetime\n\n\nclass CalendarTestAddEvent(unittest.TestCase):\n def test_add_event(self):\n calendar = CalendarUtil()\n calendar.add_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [\n {'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}])\n\n def test_add_event_2(self):\n calendar = CalendarUtil()\n calendar.add_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})\n calendar.add_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [\n {'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'},\n {'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}])\n\n def test_add_event_3(self):\n calendar = CalendarUtil()\n calendar.add_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [\n {'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'}])\n\n def test_add_event_4(self):\n calendar = CalendarUtil()\n calendar.add_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 22, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [\n {'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 22, 0), 'description': 'New Year'}])\n\n def test_add_event_5(self):\n calendar = CalendarUtil()\n calendar.add_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 20, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [\n {'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 20, 0), 'description': 'New Year'}])\n\n\nclass CalendarTestRemoveEvent(unittest.TestCase):\n def test_remove_event(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n calendar.remove_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [])\n\n def test_remove_event_2(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'},\n {'date': datetime(2023, 1, 2, 0, 0), 'start_time': datetime(2023, 1, 2, 0, 0),\n 'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year'}]\n calendar.remove_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [\n {'date': datetime(2023, 1, 2, 0, 0), 'start_time': datetime(2023, 1, 2, 0, 0),\n 'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year'}])\n\n def test_remove_event_3(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'},\n {'date': datetime(2023, 1, 2, 0, 0), 'start_time': datetime(2023, 1, 2, 0, 0),\n 'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year'}]\n calendar.remove_event({'date': datetime(2023, 1, 2, 0, 0), 'start_time': datetime(2023, 1, 2, 0, 0),\n 'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [\n {'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}])\n\n def test_remove_event_4(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'},\n {'date': datetime(2023, 1, 2, 0, 0), 'start_time': datetime(2023, 1, 2, 0, 0),\n 'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year'}]\n calendar.remove_event({'date': datetime(2023, 1, 2, 0, 0), 'start_time': datetime(2023, 1, 2, 0, 0),\n 'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [\n {'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'}])\n\n def test_remove_event_5(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 22, 0), 'description': 'New Year'},\n {'date': datetime(2023, 1, 2, 0, 0), 'start_time': datetime(2023, 1, 2, 0, 0),\n 'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year'}]\n calendar.remove_event({'date': datetime(2023, 1, 2, 0, 0), 'start_time': datetime(2023, 1, 2, 0, 0),\n 'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [\n {'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 22, 0), 'description': 'New Year'}])\n\n def test_remove_event_6(self):\n calendar = CalendarUtil()\n calendar.events = []\n calendar.remove_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [])\n\n\nclass CalendarTestGetEvents(unittest.TestCase):\n def test_get_events(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.get_events(datetime(2023, 1, 1)), [\n {'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}])\n\n def test_get_events_2(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.get_events(datetime(2023, 1, 2)), [])\n\n\nclass CalendarTestIsAvailable(unittest.TestCase):\n def test_is_available(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.is_available(datetime(2023, 1, 1, 0, 0), datetime(2023, 1, 1, 1, 0)), False)\n\n def test_is_available_2(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.is_available(datetime(2023, 1, 1, 1, 0), datetime(2023, 1, 1, 2, 0)), True)\n\n def test_is_available_3(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.is_available(datetime(2023, 1, 1, 0, 0), datetime(2023, 1, 1, 0, 30)), False)\n\n def test_is_available_4(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.is_available(datetime(2023, 1, 1, 0, 30), datetime(2023, 1, 1, 1, 0)), False)\n\n def test_is_available_5(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.is_available(datetime(2023, 1, 1, 1, 0), datetime(2023, 1, 1, 1, 30)), True)\n\n\nclass CalendarTestGetAvailableSlots(unittest.TestCase):\n def test_get_available_slots(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.get_available_slots(datetime(2023, 1, 1)),\n [(datetime(2023, 1, 1, 23, 0), datetime(2023, 1, 2, 0, 0))])\n\n def test_get_available_slots_2(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 1, 0),\n 'end_time': datetime(2023, 1, 1, 2, 0), 'description': 'New Year'}]\n self.assertEqual(len(calendar.get_available_slots(datetime(2023, 1, 1))), 23)\n\n def test_get_available_slots_3(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 2, 1, 0),\n 'end_time': datetime(2023, 1, 2, 2, 0), 'description': 'New Year'}]\n self.assertEqual(len(calendar.get_available_slots(datetime(2023, 1, 1))), 24)\n\n def test_get_available_slots_4(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 2, 1, 0),\n 'end_time': datetime(2023, 1, 2, 2, 0), 'description': 'New Year'}]\n self.assertEqual(len(calendar.get_available_slots(datetime(2023, 1, 1))), 24)\n\n def test_get_available_slots_5(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 2, 1, 0),\n 'end_time': datetime(2023, 1, 2, 2, 0), 'description': 'New Year'}]\n self.assertEqual(len(calendar.get_available_slots(datetime(2023, 1, 1))), 24)\n\n\nclass CalendarTestGetUpcomingEvents(unittest.TestCase):\n def test_get_upcoming_events(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.get_upcoming_events(1), [])\n\n def test_get_upcoming_events_2(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 1, 0),\n 'end_time': datetime(2023, 1, 1, 2, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.get_upcoming_events(1), [])\n\n def test_get_upcoming_events_3(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 2, 1, 0),\n 'end_time': datetime(2023, 1, 2, 2, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.get_upcoming_events(1), [])\n\n def test_get_upcoming_events_4(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 2, 1, 0),\n 'end_time': datetime(2023, 1, 2, 2, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.get_upcoming_events(2), [])\n\n def test_get_upcoming_events_5(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'},\n {'date': datetime(2024, 1, 2, 0, 0), 'start_time': datetime(2024, 1, 2, 1, 0),\n 'end_time': datetime(2024, 1, 2, 2, 0),\n 'description': 'New Year 2'}]\n self.assertEqual(calendar.get_upcoming_events(1), [\n {'date': datetime(2024, 1, 2, 0, 0), 'start_time': datetime(2024, 1, 2, 1, 0),\n 'end_time': datetime(2024, 1, 2, 2, 0), 'description': 'New Year 2'}])\n\n\nclass CalendarTestMain(unittest.TestCase):\n def test_main(self):\n calendar = CalendarUtil()\n calendar.add_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [\n {'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}])\n calendar.remove_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [])\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.get_events(datetime(2023, 1, 1)), [\n {'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'}])\n self.assertEqual(calendar.is_available(datetime(2023, 1, 1, 0, 0), datetime(2023, 1, 1, 1, 0)), False)\n self.assertEqual(calendar.get_available_slots(datetime(2023, 1, 1)),\n [(datetime(2023, 1, 1, 23, 0), datetime(2023, 1, 2, 0, 0))])\n self.assertEqual(calendar.get_upcoming_events(1), [])", "solution_code": "from datetime import datetime, timedelta\n\nclass CalendarUtil:\n def __init__(self):\n self.events = []\n\n def add_event(self, event):\n self.events.append(event)\n\n def remove_event(self, event):\n if event in self.events:\n self.events.remove(event)\n\n def get_events(self, date):\n events_on_date = []\n for event in self.events:\n if event['date'].date() == date.date():\n events_on_date.append(event)\n return events_on_date\n\n def is_available(self, start_time, end_time):\n for event in self.events:\n if start_time < event['end_time'] and end_time > event['start_time']:\n return False\n return True\n\n def get_available_slots(self, date):\n available_slots = []\n start_time = datetime(date.year, date.month, date.day, 0, 0)\n end_time = datetime(date.year, date.month, date.day, 23, 59)\n\n while start_time < end_time:\n slot_end_time = start_time + timedelta(minutes=60)\n if self.is_available(start_time, slot_end_time):\n available_slots.append((start_time, slot_end_time))\n start_time += timedelta(minutes=60)\n\n\n return available_slots\n\n def get_upcoming_events(self, num_events):\n now = datetime.now()\n upcoming_events = []\n for event in self.events:\n if event['start_time'] >= now:\n upcoming_events.append(event)\n if len(upcoming_events) == num_events:\n break\n return upcoming_events", "import_statement": [ "from datetime import datetime, timedelta" ], "class_description": " \"\"\"\n This is a class as CalendarUtil that provides functionalities to manage calendar events, schedule appointments, and perform conflict checks.\n \"\"\"\n", "class_name": "CalendarUtil", "test_classes": [ "CalendarTestAddEvent", "CalendarTestRemoveEvent", "CalendarTestGetEvents", "CalendarTestIsAvailable", "CalendarTestGetAvailableSlots", "CalendarTestGetUpcomingEvents", "CalendarTestMain" ], "class_constructor": "class CalendarUtil: \n def __init__(self):\n \"\"\"\n Initialize the calendar with an empty list of events.\n self.events = []\n\n", "fields": [ "self.events" ], "methods_info": [ { "method_name": "add_event", "method_description": "def add_event(self, event):\n \"\"\"\n Add an event to the calendar.\n :param event: The event to be added to the calendar,dict.\n >>> calendar = CalendarUtil()\n >>> calendar.add_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0), 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})\n >>> calendar.events\n [{'date': datetime.datetime(2023, 1, 1, 0, 0), 'start_time': datetime.datetime(2023, 1, 1, 0, 0), 'end_time': datetime.datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n\n \"\"\"", "test_class": "CalendarTestAddEvent", "test_code": "class CalendarTestAddEvent(unittest.TestCase):\n def test_add_event(self):\n calendar = CalendarUtil()\n calendar.add_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [\n {'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}])\n\n def test_add_event_2(self):\n calendar = CalendarUtil()\n calendar.add_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})\n calendar.add_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [\n {'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'},\n {'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}])\n\n def test_add_event_3(self):\n calendar = CalendarUtil()\n calendar.add_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [\n {'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'}])\n\n def test_add_event_4(self):\n calendar = CalendarUtil()\n calendar.add_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 22, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [\n {'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 22, 0), 'description': 'New Year'}])\n\n def test_add_event_5(self):\n calendar = CalendarUtil()\n calendar.add_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 20, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [\n {'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 20, 0), 'description': 'New Year'}])", "solution_code": "def add_event(self, event):\n self.events.append(event)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.events" ], "method_dependencies": [] } }, { "method_name": "remove_event", "method_description": "def remove_event(self, event):\n \"\"\"\n Remove an event from the calendar.\n :param event: The event to be removed from the calendar,dict.\n >>> calendar = CalendarUtil()\n >>> calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0), 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n >>> calendar.remove_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0), 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})\n >>> calendar.events\n []\n\n \"\"\"", "test_class": "CalendarTestRemoveEvent", "test_code": "class CalendarTestRemoveEvent(unittest.TestCase):\n def test_remove_event(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n calendar.remove_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [])\n\n def test_remove_event_2(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'},\n {'date': datetime(2023, 1, 2, 0, 0), 'start_time': datetime(2023, 1, 2, 0, 0),\n 'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year'}]\n calendar.remove_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [\n {'date': datetime(2023, 1, 2, 0, 0), 'start_time': datetime(2023, 1, 2, 0, 0),\n 'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year'}])\n\n def test_remove_event_3(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'},\n {'date': datetime(2023, 1, 2, 0, 0), 'start_time': datetime(2023, 1, 2, 0, 0),\n 'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year'}]\n calendar.remove_event({'date': datetime(2023, 1, 2, 0, 0), 'start_time': datetime(2023, 1, 2, 0, 0),\n 'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [\n {'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}])\n\n def test_remove_event_4(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'},\n {'date': datetime(2023, 1, 2, 0, 0), 'start_time': datetime(2023, 1, 2, 0, 0),\n 'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year'}]\n calendar.remove_event({'date': datetime(2023, 1, 2, 0, 0), 'start_time': datetime(2023, 1, 2, 0, 0),\n 'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [\n {'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'}])\n\n def test_remove_event_5(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 22, 0), 'description': 'New Year'},\n {'date': datetime(2023, 1, 2, 0, 0), 'start_time': datetime(2023, 1, 2, 0, 0),\n 'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year'}]\n calendar.remove_event({'date': datetime(2023, 1, 2, 0, 0), 'start_time': datetime(2023, 1, 2, 0, 0),\n 'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [\n {'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 22, 0), 'description': 'New Year'}])\n\n def test_remove_event_6(self):\n calendar = CalendarUtil()\n calendar.events = []\n calendar.remove_event({'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'})\n self.assertEqual(calendar.events, [])", "solution_code": "def remove_event(self, event):\n if event in self.events:\n self.events.remove(event)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.events" ], "method_dependencies": [] } }, { "method_name": "get_events", "method_description": "def get_events(self, date):\n \"\"\"\n Get all events on a given date.\n :param date: The date to get events for,datetime.\n :return: A list of events on the given date,list.\n >>> calendar = CalendarUtil()\n >>> calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0), 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n >>> calendar.get_events(datetime(2023, 1, 1, 0, 0))\n [{'date': datetime.datetime(2023, 1, 1, 0, 0), 'start_time': datetime.datetime(2023, 1, 1, 0, 0), 'end_time': datetime.datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n\n \"\"\"", "test_class": "CalendarTestGetEvents", "test_code": "class CalendarTestGetEvents(unittest.TestCase):\n def test_get_events(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.get_events(datetime(2023, 1, 1)), [\n {'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}])\n\n def test_get_events_2(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.get_events(datetime(2023, 1, 2)), [])", "solution_code": "def get_events(self, date):\n events_on_date = []\n for event in self.events:\n if event['date'].date() == date.date():\n events_on_date.append(event)\n return events_on_date", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.events" ], "method_dependencies": [] } }, { "method_name": "is_available", "method_description": "def is_available(self, start_time, end_time):\n \"\"\"\n Check if the calendar is available for a given time slot.\n :param start_time: The start time of the time slot,datetime.\n :param end_time: The end time of the time slot,datetime.\n :return: True if the calendar is available for the given time slot, False otherwise,bool.\n >>> calendar = CalendarUtil()\n >>> calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0), 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n >>> calendar.is_available(datetime(2023, 1, 1, 0, 0), datetime(2023, 1, 1, 1, 0))\n False\n\n \"\"\"", "test_class": "CalendarTestIsAvailable", "test_code": "class CalendarTestIsAvailable(unittest.TestCase):\n def test_is_available(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.is_available(datetime(2023, 1, 1, 0, 0), datetime(2023, 1, 1, 1, 0)), False)\n\n def test_is_available_2(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.is_available(datetime(2023, 1, 1, 1, 0), datetime(2023, 1, 1, 2, 0)), True)\n\n def test_is_available_3(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.is_available(datetime(2023, 1, 1, 0, 0), datetime(2023, 1, 1, 0, 30)), False)\n\n def test_is_available_4(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.is_available(datetime(2023, 1, 1, 0, 30), datetime(2023, 1, 1, 1, 0)), False)\n\n def test_is_available_5(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 1, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.is_available(datetime(2023, 1, 1, 1, 0), datetime(2023, 1, 1, 1, 30)), True)", "solution_code": "def is_available(self, start_time, end_time):\n for event in self.events:\n if start_time < event['end_time'] and end_time > event['start_time']:\n return False\n return True", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.events" ], "method_dependencies": [] } }, { "method_name": "get_available_slots", "method_description": "def get_available_slots(self, date):\n \"\"\"\n Get all available time slots on a given date.\n :param date: The date to get available time slots for,datetime.\n :return: A list of available time slots on the given date,list.\n >>> calendar = CalendarUtil()\n >>> calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0), 'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'}]\n >>> calendar.get_available_slots(datetime(2023, 1, 1))\n [(datetime.datetime(2023, 1, 1, 23, 0), datetime.datetime(2023, 1, 2, 0, 0))]\n\n \"\"\"", "test_class": "CalendarTestGetAvailableSlots", "test_code": "class CalendarTestGetAvailableSlots(unittest.TestCase):\n def test_get_available_slots(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.get_available_slots(datetime(2023, 1, 1)),\n [(datetime(2023, 1, 1, 23, 0), datetime(2023, 1, 2, 0, 0))])\n\n def test_get_available_slots_2(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 1, 0),\n 'end_time': datetime(2023, 1, 1, 2, 0), 'description': 'New Year'}]\n self.assertEqual(len(calendar.get_available_slots(datetime(2023, 1, 1))), 23)\n\n def test_get_available_slots_3(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 2, 1, 0),\n 'end_time': datetime(2023, 1, 2, 2, 0), 'description': 'New Year'}]\n self.assertEqual(len(calendar.get_available_slots(datetime(2023, 1, 1))), 24)\n\n def test_get_available_slots_4(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 2, 1, 0),\n 'end_time': datetime(2023, 1, 2, 2, 0), 'description': 'New Year'}]\n self.assertEqual(len(calendar.get_available_slots(datetime(2023, 1, 1))), 24)\n\n def test_get_available_slots_5(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 2, 1, 0),\n 'end_time': datetime(2023, 1, 2, 2, 0), 'description': 'New Year'}]\n self.assertEqual(len(calendar.get_available_slots(datetime(2023, 1, 1))), 24)", "solution_code": "def get_available_slots(self, date):\n available_slots = []\n start_time = datetime(date.year, date.month, date.day, 0, 0)\n end_time = datetime(date.year, date.month, date.day, 23, 59)\n\n while start_time < end_time:\n slot_end_time = start_time + timedelta(minutes=60)\n if self.is_available(start_time, slot_end_time):\n available_slots.append((start_time, slot_end_time))\n start_time += timedelta(minutes=60)\n\n\n return available_slots", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "is_available" ] } }, { "method_name": "get_upcoming_events", "method_description": "def get_upcoming_events(self, num_events):\n \"\"\"\n Get the next n upcoming events from a given date.\n :param date: The date to get upcoming events from,datetime.\n :param n: The number of upcoming events to get,int.\n :return: A list of the next n upcoming events from the given date,list.\n >>> calendar = CalendarUtil()\n >>> calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0), 'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'},{'date': datetime(2023, 1, 2, 0, 0),'end_time': datetime(2023, 1, 2, 1, 0), 'description': 'New Year 2'}]\n >>> calendar.get_upcoming_events(1)\n [{'date': datetime.datetime(2023, 1, 1, 0, 0), 'start_time': datetime.datetime(2023, 1, 1, 0, 0), 'end_time': datetime.datetime(2023, 1, 1, 23, 0), 'description': 'New Year'}, {'date': datetime.datetime(2023, 1, 2, 0, 0), 'end_time': datetime.datetime(2023, 1, 2, 1, 0), 'description': 'New Year 2'}]\n\n \"\"\"", "test_class": "CalendarTestGetUpcomingEvents", "test_code": "class CalendarTestGetUpcomingEvents(unittest.TestCase):\n def test_get_upcoming_events(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.get_upcoming_events(1), [])\n\n def test_get_upcoming_events_2(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 1, 0),\n 'end_time': datetime(2023, 1, 1, 2, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.get_upcoming_events(1), [])\n\n def test_get_upcoming_events_3(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 2, 1, 0),\n 'end_time': datetime(2023, 1, 2, 2, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.get_upcoming_events(1), [])\n\n def test_get_upcoming_events_4(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 2, 1, 0),\n 'end_time': datetime(2023, 1, 2, 2, 0), 'description': 'New Year'}]\n self.assertEqual(calendar.get_upcoming_events(2), [])\n\n def test_get_upcoming_events_5(self):\n calendar = CalendarUtil()\n calendar.events = [{'date': datetime(2023, 1, 1, 0, 0), 'start_time': datetime(2023, 1, 1, 0, 0),\n 'end_time': datetime(2023, 1, 1, 23, 0), 'description': 'New Year'},\n {'date': datetime(2024, 1, 2, 0, 0), 'start_time': datetime(2024, 1, 2, 1, 0),\n 'end_time': datetime(2024, 1, 2, 2, 0),\n 'description': 'New Year 2'}]\n self.assertEqual(calendar.get_upcoming_events(1), [\n {'date': datetime(2024, 1, 2, 0, 0), 'start_time': datetime(2024, 1, 2, 1, 0),\n 'end_time': datetime(2024, 1, 2, 2, 0), 'description': 'New Year 2'}])", "solution_code": "def get_upcoming_events(self, num_events):\n now = datetime.now()\n upcoming_events = []\n for event in self.events:\n if event['start_time'] >= now:\n upcoming_events.append(event)\n if len(upcoming_events) == num_events:\n break\n return upcoming_events", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.events" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_18", "skeleton": "\nclass CamelCaseMap:\n \"\"\"\n This is a custom class that allows keys to be in camel case style by converting them from underscore style, which provides dictionary-like functionality.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialize data to an empty dictionary\n \"\"\"\n self._data = {}\n\n def __getitem__(self, key):\n \"\"\"\n Return the value corresponding to the key\n :param key:str\n :return:str,the value corresponding to the key\n >>> camelize_map = CamelCaseMap()\n >>> camelize_map['first_name'] = 'John'\n >>> camelize_map.__getitem__('first_name')\n 'John'\n \"\"\"\n\n\n def __setitem__(self, key, value):\n \"\"\"\n Set the value corresponding to the key to the specified value\n :param key:str\n :param value:str, the specified value\n :return:None\n >>> camelize_map = CamelCaseMap()\n >>> camelize_map['first_name'] = 'John'\n >>> camelize_map.__setitem__('first_name', 'new name')\n camelize_map['first_name'] = 'new name'\n \"\"\"\n\n\n def __delitem__(self, key):\n \"\"\"\n Delete the value corresponding to the key\n :param key:str\n :return:None\n >>> camelize_map = CamelCaseMap()\n >>> camelize_map['first_name'] = 'John'\n >>> camelize_map.__delitem__('first_name')\n >>> flag = 'first_name' in camelize_map\n flag = False\n \"\"\"\n\n\n def __iter__(self):\n \"\"\"\n Returning Iterateable Objects with Own Data\n :return:Iterator\n >>> camelize_map = CamelCaseMap()\n >>> camelize_map['first_name'] = 'John'\n >>> camelize_map['last_name'] = 'Doe'\n >>> camelize_map['age'] = 30\n >>> camelize_map.__iter__()\n \n \"\"\"\n\n\n def __len__(self):\n \"\"\"\n Returns the length of the own data\n :return:int, length of data\n >>> camelize_map = CamelCaseMap()\n >>> camelize_map['first_name'] = 'John'\n >>> camelize_map['last_name'] = 'Doe'\n >>> camelize_map['age'] = 30\n >>> camelize_map.__len__()\n 3\n \"\"\"\n\n def _convert_key(self, key):\n \"\"\"\n convert key string into camel case\n :param key:str\n :return:str, converted key string\n >>> camelize_map = CamelCaseMap()\n >>> camelize_map._convert_key('first_name')\n 'firstName'\n \"\"\"\n\n @staticmethod\n def _to_camel_case(key):\n \"\"\"\n convert key string into camel case\n :param key:str\n :return:str, converted key string\n >>> camelize_map = CamelCaseMap()\n >>> camelize_map._to_camel_case('first_name')\n 'firstName'\n \"\"\"", "test": "import unittest\n\n\nclass CamelCaseMapTestGetitem(unittest.TestCase):\n def test_getitem_1(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n self.assertEqual(camelize_map.__getitem__('first_name'), 'John')\n\n def test_getitem_2(self):\n camelize_map = CamelCaseMap()\n camelize_map['last_name'] = 'Doe'\n self.assertEqual(camelize_map.__getitem__('last_name'), 'Doe')\n\n def test_getitem_3(self):\n camelize_map = CamelCaseMap()\n camelize_map['age'] = 30\n self.assertEqual(camelize_map.__getitem__('age'), 30)\n\n def test_getitem_4(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n self.assertEqual(camelize_map.__getitem__('first_Name'), 'John')\n\n def test_getitem_5(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n self.assertEqual(camelize_map.__getitem__('firstName'), 'John')\n\n\nclass CamelCaseMapTestSetitem(unittest.TestCase):\n def test_setitem_1(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map.__setitem__('first_name', 'newname')\n self.assertEqual(camelize_map['first_name'], 'newname')\n\n def test_setitem_2(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map.__setitem__('first_name', 'John')\n self.assertEqual(camelize_map['first_name'], 'John')\n\n def test_setitem_3(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map.__setitem__('first_Name', 'newname')\n self.assertEqual(camelize_map['first_name'], 'newname')\n\n def test_setitem_4(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map.__setitem__('firstName', 'newname')\n self.assertEqual(camelize_map['first_name'], 'newname')\n\n def test_setitem_5(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map.__setitem__('first_name', '')\n self.assertEqual(camelize_map['first_name'], '')\n\n\nclass CamelCaseMapTestDelitem(unittest.TestCase):\n def test_delitem_1(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map['last_name'] = 'Doe'\n camelize_map.__delitem__('first_name')\n self.assertEqual(camelize_map['last_name'], 'Doe')\n\n def test_delitem_2(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map.__delitem__('first_name')\n self.assertEqual('first_name' in camelize_map, False)\n\n def test_delitem_3(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map.__delitem__('first_Name')\n self.assertEqual('first_name' in camelize_map, False)\n\n def test_delitem_4(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map.__delitem__('firstName')\n self.assertEqual('first_name' in camelize_map, False)\n\n def test_delitem_5(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = ''\n camelize_map.__delitem__('first_name')\n self.assertEqual('first_name' in camelize_map, False)\n\n\nclass CamelCaseMapTestIter(unittest.TestCase):\n def test_iter_1(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map['last_name'] = 'Doe'\n camelize_map['age'] = 30\n lst = ['firstName', 'lastName', 'age']\n iter = camelize_map.__iter__()\n i = 0\n for key in iter:\n self.assertEqual(key, lst[i])\n i += 1\n\n def test_iter_2(self):\n camelize_map = CamelCaseMap()\n camelize_map['firstname'] = 'John'\n camelize_map['lastname'] = 'Doe'\n camelize_map['age'] = 30\n lst = ['firstname', 'lastname', 'age']\n iter = camelize_map.__iter__()\n i = 0\n for key in iter:\n self.assertEqual(key, lst[i])\n i += 1\n\n def test_iter_3(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_Name'] = 'John'\n camelize_map['last_Name'] = 'Doe'\n camelize_map['age'] = 30\n lst = ['firstName', 'lastName', 'age']\n iter = camelize_map.__iter__()\n i = 0\n for key in iter:\n self.assertEqual(key, lst[i])\n i += 1\n\n def test_iter_4(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_Name'] = 'John'\n camelize_map['last_Name'] = 'Doe'\n lst = ['firstName', 'lastName']\n iter = camelize_map.__iter__()\n i = 0\n for key in iter:\n self.assertEqual(key, lst[i])\n i += 1\n\n def test_iter_5(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_Name'] = 'John'\n lst = ['firstName']\n iter = camelize_map.__iter__()\n i = 0\n for key in iter:\n self.assertEqual(key, lst[i])\n i += 1\n\n\nclass CamelCaseMapTestLen(unittest.TestCase):\n def test_len_1(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n self.assertEqual(camelize_map.__len__(), 1)\n\n def test_len_2(self):\n camelize_map = CamelCaseMap()\n camelize_map['last_name'] = 'Doe'\n self.assertEqual(camelize_map.__len__(), 1)\n\n def test_len_3(self):\n camelize_map = CamelCaseMap()\n camelize_map['age'] = 30\n self.assertEqual(camelize_map.__len__(), 1)\n\n def test_len_4(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map['last_Name'] = 'Doe'\n camelize_map['age'] = 30\n self.assertEqual(camelize_map.__len__(), 3)\n\n def test_len_5(self):\n camelize_map = CamelCaseMap()\n self.assertEqual(camelize_map.__len__(), 0)\n\n\nclass CamelCaseMapTestConvertKey(unittest.TestCase):\n def test_convert_key_1(self):\n camelize_map = CamelCaseMap()\n self.assertEqual(camelize_map._convert_key('aaa_bbb'), 'aaaBbb')\n\n def test_convert_key_2(self):\n camelize_map = CamelCaseMap()\n self.assertEqual(camelize_map._convert_key('first_name'), 'firstName')\n\n def test_convert_key_3(self):\n camelize_map = CamelCaseMap()\n self.assertEqual(camelize_map._convert_key('last_name'), 'lastName')\n\n def test_convert_key_4(self):\n camelize_map = CamelCaseMap()\n self.assertEqual(camelize_map._convert_key('ccc_ddd'), 'cccDdd')\n\n def test_convert_key_5(self):\n camelize_map = CamelCaseMap()\n self.assertEqual(camelize_map._convert_key('eee_fff'), 'eeeFff')\n\n def test_convert_key_6(self):\n camelize_map = CamelCaseMap()\n self.assertEqual(camelize_map._convert_key(1234), 1234)\n\n\nclass CamelCaseMapTestToCamelCase(unittest.TestCase):\n def test_to_camel_case_1(self):\n self.assertEqual(CamelCaseMap._to_camel_case('aaa_bbb'), 'aaaBbb')\n\n def test_to_camel_case_2(self):\n self.assertEqual(CamelCaseMap._to_camel_case('first_name'), 'firstName')\n\n def test_to_camel_case_3(self):\n self.assertEqual(CamelCaseMap._to_camel_case('last_name'), 'lastName')\n\n def test_to_camel_case_4(self):\n self.assertEqual(CamelCaseMap._to_camel_case('ccc_ddd'), 'cccDdd')\n\n def test_to_camel_case_5(self):\n self.assertEqual(CamelCaseMap._to_camel_case('eee_fff'), 'eeeFff')\n\n\nclass CamelCaseMapTest(unittest.TestCase):\n def test_CamelCaseMap(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n self.assertEqual(camelize_map.__getitem__('first_name'), 'John')\n\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map.__setitem__('first_name', 'newname')\n self.assertEqual(camelize_map['first_name'], 'newname')", "solution_code": "class CamelCaseMap:\n def __init__(self):\n self._data = {}\n\n def __getitem__(self, key):\n return self._data[self._convert_key(key)]\n\n def __setitem__(self, key, value):\n self._data[self._convert_key(key)] = value\n\n def __delitem__(self, key):\n del self._data[self._convert_key(key)]\n\n def __iter__(self):\n return iter(self._data)\n\n def __len__(self):\n return len(self._data)\n\n def _convert_key(self, key):\n if isinstance(key, str):\n return self._to_camel_case(key)\n return key\n\n @staticmethod\n def _to_camel_case(key):\n parts = key.split('_')\n return parts[0] + ''.join(part.title() for part in parts[1:])", "import_statement": [], "class_description": " \"\"\"\n This is a custom class that allows keys to be in camel case style by converting them from underscore style, which provides dictionary-like functionality.\n \"\"\"\n", "class_name": "CamelCaseMap", "test_classes": [ "CamelCaseMapTestGetitem", "CamelCaseMapTestSetitem", "CamelCaseMapTestDelitem", "CamelCaseMapTestIter", "CamelCaseMapTestLen", "CamelCaseMapTestConvertKey", "CamelCaseMapTestToCamelCase", "CamelCaseMapTest" ], "class_constructor": "class CamelCaseMap: \n def __init__(self):\n \"\"\"\n Initialize data to an empty dictionary\n \"\"\"\n self._data = {}\n\n", "fields": [ "self._data" ], "methods_info": [ { "method_name": "__getitem__", "method_description": "def __getitem__(self, key):\n \"\"\"\n Return the value corresponding to the key\n :param key:str\n :return:str,the value corresponding to the key\n >>> camelize_map = CamelCaseMap()\n >>> camelize_map['first_name'] = 'John'\n >>> camelize_map.__getitem__('first_name')\n 'John'\n \"\"\"", "test_class": "CamelCaseMapTestGetitem", "test_code": "class CamelCaseMapTestGetitem(unittest.TestCase):\n def test_getitem_1(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n self.assertEqual(camelize_map.__getitem__('first_name'), 'John')\n\n def test_getitem_2(self):\n camelize_map = CamelCaseMap()\n camelize_map['last_name'] = 'Doe'\n self.assertEqual(camelize_map.__getitem__('last_name'), 'Doe')\n\n def test_getitem_3(self):\n camelize_map = CamelCaseMap()\n camelize_map['age'] = 30\n self.assertEqual(camelize_map.__getitem__('age'), 30)\n\n def test_getitem_4(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n self.assertEqual(camelize_map.__getitem__('first_Name'), 'John')\n\n def test_getitem_5(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n self.assertEqual(camelize_map.__getitem__('firstName'), 'John')", "solution_code": "def __getitem__(self, key):\n return self._data[self._convert_key(key)]", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self._data" ], "method_dependencies": [ "_convert_key" ] } }, { "method_name": "__setitem__", "method_description": "def __setitem__(self, key, value):\n \"\"\"\n Set the value corresponding to the key to the specified value\n :param key:str\n :param value:str, the specified value\n :return:None\n >>> camelize_map = CamelCaseMap()\n >>> camelize_map['first_name'] = 'John'\n >>> camelize_map.__setitem__('first_name', 'new name')\n camelize_map['first_name'] = 'new name'\n \"\"\"", "test_class": "CamelCaseMapTestSetitem", "test_code": "class CamelCaseMapTestSetitem(unittest.TestCase):\n def test_setitem_1(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map.__setitem__('first_name', 'newname')\n self.assertEqual(camelize_map['first_name'], 'newname')\n\n def test_setitem_2(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map.__setitem__('first_name', 'John')\n self.assertEqual(camelize_map['first_name'], 'John')\n\n def test_setitem_3(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map.__setitem__('first_Name', 'newname')\n self.assertEqual(camelize_map['first_name'], 'newname')\n\n def test_setitem_4(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map.__setitem__('firstName', 'newname')\n self.assertEqual(camelize_map['first_name'], 'newname')\n\n def test_setitem_5(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map.__setitem__('first_name', '')\n self.assertEqual(camelize_map['first_name'], '')", "solution_code": "def __setitem__(self, key, value):\n self._data[self._convert_key(key)] = value", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self._data" ], "method_dependencies": [ "_convert_key" ] } }, { "method_name": "__delitem__", "method_description": "def __delitem__(self, key):\n \"\"\"\n Delete the value corresponding to the key\n :param key:str\n :return:None\n >>> camelize_map = CamelCaseMap()\n >>> camelize_map['first_name'] = 'John'\n >>> camelize_map.__delitem__('first_name')\n >>> flag = 'first_name' in camelize_map\n flag = False\n \"\"\"", "test_class": "CamelCaseMapTestDelitem", "test_code": "class CamelCaseMapTestDelitem(unittest.TestCase):\n def test_delitem_1(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map['last_name'] = 'Doe'\n camelize_map.__delitem__('first_name')\n self.assertEqual(camelize_map['last_name'], 'Doe')\n\n def test_delitem_2(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map.__delitem__('first_name')\n self.assertEqual('first_name' in camelize_map, False)\n\n def test_delitem_3(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map.__delitem__('first_Name')\n self.assertEqual('first_name' in camelize_map, False)\n\n def test_delitem_4(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map.__delitem__('firstName')\n self.assertEqual('first_name' in camelize_map, False)\n\n def test_delitem_5(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = ''\n camelize_map.__delitem__('first_name')\n self.assertEqual('first_name' in camelize_map, False)", "solution_code": "def __delitem__(self, key):\n del self._data[self._convert_key(key)]", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self._data" ], "method_dependencies": [ "_convert_key" ] } }, { "method_name": "__iter__", "method_description": "def __iter__(self):\n \"\"\"\n Returning Iterateable Objects with Own Data\n :return:Iterator\n >>> camelize_map = CamelCaseMap()\n >>> camelize_map['first_name'] = 'John'\n >>> camelize_map['last_name'] = 'Doe'\n >>> camelize_map['age'] = 30\n >>> camelize_map.__iter__()\n \n \"\"\"", "test_class": "CamelCaseMapTestIter", "test_code": "class CamelCaseMapTestIter(unittest.TestCase):\n def test_iter_1(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map['last_name'] = 'Doe'\n camelize_map['age'] = 30\n lst = ['firstName', 'lastName', 'age']\n iter = camelize_map.__iter__()\n i = 0\n for key in iter:\n self.assertEqual(key, lst[i])\n i += 1\n\n def test_iter_2(self):\n camelize_map = CamelCaseMap()\n camelize_map['firstname'] = 'John'\n camelize_map['lastname'] = 'Doe'\n camelize_map['age'] = 30\n lst = ['firstname', 'lastname', 'age']\n iter = camelize_map.__iter__()\n i = 0\n for key in iter:\n self.assertEqual(key, lst[i])\n i += 1\n\n def test_iter_3(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_Name'] = 'John'\n camelize_map['last_Name'] = 'Doe'\n camelize_map['age'] = 30\n lst = ['firstName', 'lastName', 'age']\n iter = camelize_map.__iter__()\n i = 0\n for key in iter:\n self.assertEqual(key, lst[i])\n i += 1\n\n def test_iter_4(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_Name'] = 'John'\n camelize_map['last_Name'] = 'Doe'\n lst = ['firstName', 'lastName']\n iter = camelize_map.__iter__()\n i = 0\n for key in iter:\n self.assertEqual(key, lst[i])\n i += 1\n\n def test_iter_5(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_Name'] = 'John'\n lst = ['firstName']\n iter = camelize_map.__iter__()\n i = 0\n for key in iter:\n self.assertEqual(key, lst[i])\n i += 1", "solution_code": "def __iter__(self):\n return iter(self._data)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self._data" ], "method_dependencies": [] } }, { "method_name": "__len__", "method_description": "def __len__(self):\n \"\"\"\n Returns the length of the own data\n :return:int, length of data\n >>> camelize_map = CamelCaseMap()\n >>> camelize_map['first_name'] = 'John'\n >>> camelize_map['last_name'] = 'Doe'\n >>> camelize_map['age'] = 30\n >>> camelize_map.__len__()\n 3\n \"\"\"", "test_class": "CamelCaseMapTestLen", "test_code": "class CamelCaseMapTestLen(unittest.TestCase):\n def test_len_1(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n self.assertEqual(camelize_map.__len__(), 1)\n\n def test_len_2(self):\n camelize_map = CamelCaseMap()\n camelize_map['last_name'] = 'Doe'\n self.assertEqual(camelize_map.__len__(), 1)\n\n def test_len_3(self):\n camelize_map = CamelCaseMap()\n camelize_map['age'] = 30\n self.assertEqual(camelize_map.__len__(), 1)\n\n def test_len_4(self):\n camelize_map = CamelCaseMap()\n camelize_map['first_name'] = 'John'\n camelize_map['last_Name'] = 'Doe'\n camelize_map['age'] = 30\n self.assertEqual(camelize_map.__len__(), 3)\n\n def test_len_5(self):\n camelize_map = CamelCaseMap()\n self.assertEqual(camelize_map.__len__(), 0)", "solution_code": "def __len__(self):\n return len(self._data)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self._data" ], "method_dependencies": [] } }, { "method_name": "_convert_key", "method_description": "def _convert_key(self, key):\n \"\"\"\n convert key string into camel case\n :param key:str\n :return:str, converted key string\n >>> camelize_map = CamelCaseMap()\n >>> camelize_map._convert_key('first_name')\n 'firstName'\n \"\"\"", "test_class": "CamelCaseMapTestConvertKey", "test_code": "class CamelCaseMapTestConvertKey(unittest.TestCase):\n def test_convert_key_1(self):\n camelize_map = CamelCaseMap()\n self.assertEqual(camelize_map._convert_key('aaa_bbb'), 'aaaBbb')\n\n def test_convert_key_2(self):\n camelize_map = CamelCaseMap()\n self.assertEqual(camelize_map._convert_key('first_name'), 'firstName')\n\n def test_convert_key_3(self):\n camelize_map = CamelCaseMap()\n self.assertEqual(camelize_map._convert_key('last_name'), 'lastName')\n\n def test_convert_key_4(self):\n camelize_map = CamelCaseMap()\n self.assertEqual(camelize_map._convert_key('ccc_ddd'), 'cccDdd')\n\n def test_convert_key_5(self):\n camelize_map = CamelCaseMap()\n self.assertEqual(camelize_map._convert_key('eee_fff'), 'eeeFff')\n\n def test_convert_key_6(self):\n camelize_map = CamelCaseMap()\n self.assertEqual(camelize_map._convert_key(1234), 1234)", "solution_code": "def _convert_key(self, key):\n if isinstance(key, str):\n return self._to_camel_case(key)\n return key", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "_to_camel_case" ] } }, { "method_name": "_to_camel_case", "method_description": "@staticmethod\n def _to_camel_case(key):\n \"\"\"\n convert key string into camel case\n :param key:str\n :return:str, converted key string\n >>> camelize_map = CamelCaseMap()\n >>> camelize_map._to_camel_case('first_name')\n 'firstName'\n \"\"\"", "test_class": "CamelCaseMapTestToCamelCase", "test_code": "class CamelCaseMapTestToCamelCase(unittest.TestCase):\n def test_to_camel_case_1(self):\n self.assertEqual(CamelCaseMap._to_camel_case('aaa_bbb'), 'aaaBbb')\n\n def test_to_camel_case_2(self):\n self.assertEqual(CamelCaseMap._to_camel_case('first_name'), 'firstName')\n\n def test_to_camel_case_3(self):\n self.assertEqual(CamelCaseMap._to_camel_case('last_name'), 'lastName')\n\n def test_to_camel_case_4(self):\n self.assertEqual(CamelCaseMap._to_camel_case('ccc_ddd'), 'cccDdd')\n\n def test_to_camel_case_5(self):\n self.assertEqual(CamelCaseMap._to_camel_case('eee_fff'), 'eeeFff')", "solution_code": "@staticmethod\n def _to_camel_case(key):\n parts = key.split('_')\n return parts[0] + ''.join(part.title() for part in parts[1:])", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_19", "skeleton": "\nclass ChandrasekharSieve:\n \"\"\"\n This is a class that uses the Chandrasekhar's Sieve method to find all prime numbers within the range\n \"\"\"\n\n def __init__(self, n):\n \"\"\"\n Initialize the ChandrasekharSieve class with the given limit.\n :param n: int, the upper limit for generating prime numbers\n \"\"\"\n self.n = n\n self.primes = self.generate_primes()\n\n def generate_primes(self):\n \"\"\"\n Generate prime numbers up to the specified limit using the Chandrasekhar sieve algorithm.\n :return: list, a list of prime numbers\n >>> cs = ChandrasekharSieve(20)\n >>> cs.generate_primes()\n [2, 3, 5, 7, 11, 13, 17, 19]\n\n \"\"\"\n\n def get_primes(self):\n \"\"\"\n Get the list of generated prime numbers.\n :return: list, a list of prime numbers\n >>> cs = ChandrasekharSieve(20)\n >>> cs.get_primes()\n [2, 3, 5, 7, 11, 13, 17, 19]\n\n \"\"\"", "test": "import unittest\n\n\nclass ChandrasekharSieveTestGeneratePrimes(unittest.TestCase):\n def test_generate_primes_1(self):\n cs = ChandrasekharSieve(20)\n res = cs.generate_primes()\n self.assertEqual(res, [2, 3, 5, 7, 11, 13, 17, 19])\n\n def test_generate_primes_2(self):\n cs = ChandrasekharSieve(18)\n res = cs.generate_primes()\n self.assertEqual(res, [2, 3, 5, 7, 11, 13, 17])\n\n def test_generate_primes_3(self):\n cs = ChandrasekharSieve(15)\n res = cs.generate_primes()\n self.assertEqual(res, [2, 3, 5, 7, 11, 13])\n\n def test_generate_primes_4(self):\n cs = ChandrasekharSieve(10)\n res = cs.generate_primes()\n self.assertEqual(res, [2, 3, 5, 7])\n\n def test_generate_primes_5(self):\n cs = ChandrasekharSieve(1)\n res = cs.generate_primes()\n self.assertEqual(res, [])\n\n\nclass ChandrasekharSieveTestGetPrimes(unittest.TestCase):\n def test_get_primes_1(self):\n cs = ChandrasekharSieve(20)\n cs.generate_primes()\n res = cs.get_primes()\n self.assertEqual(res, [2, 3, 5, 7, 11, 13, 17, 19])\n\n def test_get_primes_2(self):\n cs = ChandrasekharSieve(18)\n cs.generate_primes()\n res = cs.get_primes()\n self.assertEqual(res, [2, 3, 5, 7, 11, 13, 17])\n\n def test_get_primes_3(self):\n cs = ChandrasekharSieve(15)\n cs.generate_primes()\n res = cs.get_primes()\n self.assertEqual(res, [2, 3, 5, 7, 11, 13])\n\n def test_get_primes_4(self):\n cs = ChandrasekharSieve(10)\n cs.generate_primes()\n res = cs.get_primes()\n self.assertEqual(res, [2, 3, 5, 7])\n\n def test_get_primes_5(self):\n cs = ChandrasekharSieve(1)\n res = cs.get_primes()\n self.assertEqual(res, [])\n\n\nclass ChandrasekharSieveTest(unittest.TestCase):\n def test_chandrasekharsieve(self):\n cs = ChandrasekharSieve(20)\n res = cs.generate_primes()\n self.assertEqual(res, [2, 3, 5, 7, 11, 13, 17, 19])\n res = cs.get_primes()\n self.assertEqual(res, [2, 3, 5, 7, 11, 13, 17, 19])", "solution_code": "class ChandrasekharSieve:\n def __init__(self, n):\n self.n = n\n self.primes = self.generate_primes()\n\n def generate_primes(self):\n if self.n < 2:\n return []\n\n sieve = [True] * (self.n + 1)\n sieve[0] = sieve[1] = False\n\n p = 2\n while p * p <= self.n:\n if sieve[p]:\n for i in range(p * p, self.n + 1, p):\n sieve[i] = False\n p += 1\n\n primes = []\n for i in range(2, self.n + 1):\n if sieve[i]:\n primes.append(i)\n\n return primes\n\n def get_primes(self):\n return self.primes", "import_statement": [], "class_description": " \"\"\"\n This is a class that uses the Chandrasekhar's Sieve method to find all prime numbers within the range\n \"\"\"\n", "class_name": "ChandrasekharSieve", "test_classes": [ "ChandrasekharSieveTestGeneratePrimes", "ChandrasekharSieveTestGetPrimes", "ChandrasekharSieveTest" ], "class_constructor": "class ChandrasekharSieve: \n def __init__(self, n):\n \"\"\"\n Initialize the ChandrasekharSieve class with the given limit.\n :param n: int, the upper limit for generating prime numbers\n \"\"\"\n self.n = n\n self.primes = self.generate_primes()\n\n", "fields": [ "self.n", "self.primes" ], "methods_info": [ { "method_name": "generate_primes", "method_description": "def generate_primes(self):\n \"\"\"\n Generate prime numbers up to the specified limit using the Chandrasekhar sieve algorithm.\n :return: list, a list of prime numbers\n >>> cs = ChandrasekharSieve(20)\n >>> cs.generate_primes()\n [2, 3, 5, 7, 11, 13, 17, 19]\n\n \"\"\"", "test_class": "ChandrasekharSieveTestGeneratePrimes", "test_code": "class ChandrasekharSieveTestGeneratePrimes(unittest.TestCase):\n def test_generate_primes_1(self):\n cs = ChandrasekharSieve(20)\n res = cs.generate_primes()\n self.assertEqual(res, [2, 3, 5, 7, 11, 13, 17, 19])\n\n def test_generate_primes_2(self):\n cs = ChandrasekharSieve(18)\n res = cs.generate_primes()\n self.assertEqual(res, [2, 3, 5, 7, 11, 13, 17])\n\n def test_generate_primes_3(self):\n cs = ChandrasekharSieve(15)\n res = cs.generate_primes()\n self.assertEqual(res, [2, 3, 5, 7, 11, 13])\n\n def test_generate_primes_4(self):\n cs = ChandrasekharSieve(10)\n res = cs.generate_primes()\n self.assertEqual(res, [2, 3, 5, 7])\n\n def test_generate_primes_5(self):\n cs = ChandrasekharSieve(1)\n res = cs.generate_primes()\n self.assertEqual(res, [])", "solution_code": "def generate_primes(self):\n if self.n < 2:\n return []\n\n sieve = [True] * (self.n + 1)\n sieve[0] = sieve[1] = False\n\n p = 2\n while p * p <= self.n:\n if sieve[p]:\n for i in range(p * p, self.n + 1, p):\n sieve[i] = False\n p += 1\n\n primes = []\n for i in range(2, self.n + 1):\n if sieve[i]:\n primes.append(i)\n\n return primes", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.n" ], "method_dependencies": [] } }, { "method_name": "get_primes", "method_description": "def get_primes(self):\n \"\"\"\n Get the list of generated prime numbers.\n :return: list, a list of prime numbers\n >>> cs = ChandrasekharSieve(20)\n >>> cs.get_primes()\n [2, 3, 5, 7, 11, 13, 17, 19]\n\n \"\"\"", "test_class": "ChandrasekharSieveTestGetPrimes", "test_code": "class ChandrasekharSieveTestGetPrimes(unittest.TestCase):\n def test_get_primes_1(self):\n cs = ChandrasekharSieve(20)\n cs.generate_primes()\n res = cs.get_primes()\n self.assertEqual(res, [2, 3, 5, 7, 11, 13, 17, 19])\n\n def test_get_primes_2(self):\n cs = ChandrasekharSieve(18)\n cs.generate_primes()\n res = cs.get_primes()\n self.assertEqual(res, [2, 3, 5, 7, 11, 13, 17])\n\n def test_get_primes_3(self):\n cs = ChandrasekharSieve(15)\n cs.generate_primes()\n res = cs.get_primes()\n self.assertEqual(res, [2, 3, 5, 7, 11, 13])\n\n def test_get_primes_4(self):\n cs = ChandrasekharSieve(10)\n cs.generate_primes()\n res = cs.get_primes()\n self.assertEqual(res, [2, 3, 5, 7])\n\n def test_get_primes_5(self):\n cs = ChandrasekharSieve(1)\n res = cs.get_primes()\n self.assertEqual(res, [])", "solution_code": "def get_primes(self):\n return self.primes", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.primes" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_20", "skeleton": "\nfrom datetime import datetime\n\nclass Chat:\n \"\"\"\n This is a chat class with the functions of adding users, removing users, sending messages, and obtaining messages.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialize the Chat with an attribute users, which is an empty dictionary.\n \"\"\"\n self.users = {}\n\n def add_user(self, username):\n \"\"\"\n Add a new user to the Chat.\n :param username: The user's name, str.\n :return: If the user is already in the Chat, returns False, otherwise, returns True.\n >>> chat = Chat()\n >>> chat.add_user('John')\n True\n self.users = {'John': []}\n >>> chat.add_user('John')\n False\n\n \"\"\"\n\n def remove_user(self, username):\n \"\"\"\n Remove a user from the Chat.\n :param username: The user's name, str.\n :return: If the user is already in the Chat, returns True, otherwise, returns False.\n >>> chat = Chat()\n >>> chat.users = {'John': []}\n >>> chat.remove_user('John')\n True\n >>> chat.remove_user('John')\n False\n\n \"\"\"\n\n def send_message(self, sender, receiver, message):\n \"\"\"\n Send a message from a user to another user.\n :param sender: The sender's name, str.\n :param receiver: The receiver's name, str.\n :param message: The message, str.\n :return: If the sender or the receiver is not in the Chat, returns False, otherwise, returns True.\n >>> chat = Chat()\n >>> chat.users = {'John': [], 'Mary': []}\n >>> chat.send_message('John', 'Mary', 'Hello')\n True\n >>> chat.send_message('John', 'Tom', 'Hello')\n False\n\n \"\"\"\n\n def get_messages(self, username):\n \"\"\"\n Get all the messages of a user from the Chat.\n :param username: The user's name, str.\n :return: A list of messages, each message is a dictionary with keys 'sender', 'receiver', 'message', 'timestamp'.\n >>> chat = Chat()\n >>> chat.users = {'John': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': '2023-01-01 00:00:00'}]}\n >>> chat.get_messages('John')\n [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': '2023-01-01 00:00:00'}]\n >>> chat.get_messages('Mary')\n []\n\n \"\"\"", "test": "import unittest\n\nclass ChatTestAddUser(unittest.TestCase):\n def test_add_user(self):\n chat = Chat()\n self.assertEqual(chat.add_user('John'), True)\n self.assertEqual(chat.users, {'John': []})\n def test_add_user_2(self):\n chat = Chat()\n chat.users = {'John': []}\n self.assertEqual(chat.add_user('John'), False)\n self.assertEqual(chat.users, {'John': []})\n\n def test_add_user_3(self):\n chat = Chat()\n chat.users = {'John': []}\n self.assertEqual(chat.add_user('Mary'), True)\n self.assertEqual(chat.users, {'John': [], 'Mary': []})\n\n def test_add_user_4(self):\n chat = Chat()\n chat.users = {'John': []}\n self.assertEqual(chat.add_user('Mary'), True)\n self.assertEqual(chat.users, {'John': [], 'Mary': []})\n\n def test_add_user_5(self):\n chat = Chat()\n self.assertEqual(chat.add_user('John'), True)\n self.assertEqual(chat.add_user('Mary'), True)\n self.assertEqual(chat.users, {'John': [], 'Mary': []})\n\nclass ChatTestRemoveUser(unittest.TestCase):\n def test_remove_user(self):\n chat = Chat()\n chat.users = {'John': []}\n self.assertEqual(chat.remove_user('John'), True)\n self.assertEqual(chat.users, {})\n def test_remove_user_2(self):\n chat = Chat()\n self.assertEqual(chat.remove_user('John'), False)\n self.assertEqual(chat.users, {})\n\n def test_remove_user_3(self):\n chat = Chat()\n chat.users = {'John': [], 'Mary': []}\n self.assertEqual(chat.remove_user('John'), True)\n self.assertEqual(chat.users, {'Mary': []})\n\n def test_remove_user_4(self):\n chat = Chat()\n chat.users = {'John': [], 'Mary': []}\n self.assertEqual(chat.remove_user('Mary'), True)\n self.assertEqual(chat.remove_user('John'), True)\n self.assertEqual(chat.users, {})\n\n def test_remove_user_5(self):\n chat = Chat()\n chat.users = {'John': [], 'Mary': []}\n self.assertEqual(chat.remove_user('Amy'), False)\n self.assertEqual(chat.users, {'John': [], 'Mary': []})\n\nclass ChatTestSendMessage(unittest.TestCase):\n def test_send_message(self):\n chat = Chat()\n chat.users = {'John': [], 'Mary': []}\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n self.assertEqual(chat.send_message('John', 'Mary', 'Hello'), True)\n self.assertEqual(chat.users, {'John': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}], 'Mary': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}]})\n\n def test_send_message_2(self):\n chat = Chat()\n chat.users = {'John': [], 'Mary': []}\n self.assertEqual(chat.send_message('John', 'Tom', 'Hello'), False)\n self.assertEqual(chat.users, {'John': [], 'Mary': []})\n\n def test_send_message_3(self):\n chat = Chat()\n chat.users = {'John': [], 'Mary': []}\n self.assertEqual(chat.send_message('Amy', 'Mary', 'Hello'), False)\n self.assertEqual(chat.users, {'John': [], 'Mary': []})\n\n def test_send_message_4(self):\n chat = Chat()\n chat.users = {'John': [], 'Mary': []}\n self.assertEqual(chat.send_message('Amy', 'Tom', 'Hello'), False)\n self.assertEqual(chat.users, {'John': [], 'Mary': []})\n\n def test_send_message_5(self):\n chat = Chat()\n chat.users = {'John': [], 'Mary': []}\n self.assertEqual(chat.send_message('Amy', 'Amy', 'Hello'), False)\n self.assertEqual(chat.users, {'John': [], 'Mary': []})\n\n\nclass ChatTestGetMessages(unittest.TestCase):\n def test_get_messages(self):\n chat = Chat()\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n chat.users = {'John': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}]}\n self.assertEqual(chat.get_messages('John'), [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}])\n\n def test_get_messages_2(self):\n chat = Chat()\n chat.users = {'John': [], 'Mary': []}\n self.assertEqual(chat.get_messages('John'), [])\n\n def test_get_messages_3(self):\n chat = Chat()\n chat.users = {'John': [], 'Mary': []}\n self.assertEqual(chat.get_messages('Amy'), [])\n\n def test_get_messages_4(self):\n chat = Chat()\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n chat.users = {'John': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}]}\n self.assertEqual(chat.get_messages('Mary'), [])\n\n def test_get_messages_5(self):\n chat = Chat()\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n chat.users = {'John': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}]}\n self.assertEqual(chat.get_messages('Amy'), [])\n\nclass ChatTestMain(unittest.TestCase):\n def test_main(self):\n chat = Chat()\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n self.assertEqual(chat.add_user('John'), True)\n self.assertEqual(chat.add_user('Mary'), True)\n self.assertEqual(chat.add_user('Amy'), True)\n self.assertEqual(chat.users, {'John': [], 'Mary': [], 'Amy': []})\n self.assertEqual(chat.remove_user('Amy'), True)\n self.assertEqual(chat.users, {'John': [], 'Mary': []})\n self.assertEqual(chat.send_message('John', 'Mary', 'Hello'), True)\n self.assertEqual(chat.send_message('John', 'Tom', 'Hello'), False)\n self.assertEqual(chat.users, {'John': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}], 'Mary': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}]})\n self.assertEqual(chat.get_messages('John'), [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}])\n self.assertEqual(chat.get_messages('Mary'), [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}])\n\n def test_main_2(self):\n chat = Chat()\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n self.assertEqual(chat.remove_user('Amy'), False)\n self.assertEqual(chat.add_user('John'), True)\n self.assertEqual(chat.add_user('Mary'), True)\n self.assertEqual(chat.add_user('Amy'), True)\n self.assertEqual(chat.users, {'John': [], 'Mary': [], 'Amy': []})\n self.assertEqual(chat.send_message('John', 'Mary', 'Hello'), True)\n self.assertEqual(chat.send_message('John', 'Tom', 'Hello'), False)\n self.assertEqual(chat.remove_user('Amy'), True)\n self.assertEqual(chat.users, {'John': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}], 'Mary': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}]})\n self.assertEqual(chat.users, {'John': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}], 'Mary': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}]})\n self.assertEqual(chat.get_messages('John'), [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}])", "solution_code": "from datetime import datetime\n\nclass Chat:\n def __init__(self):\n self.users = {}\n\n def add_user(self, username):\n if username in self.users:\n return False\n else:\n self.users[username] = []\n return True\n\n def remove_user(self, username):\n if username in self.users:\n del self.users[username]\n return True\n else:\n return False\n\n def send_message(self, sender, receiver, message):\n if sender not in self.users or receiver not in self.users:\n return False\n\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n message_info = {\n 'sender': sender,\n 'receiver': receiver,\n 'message': message,\n 'timestamp': timestamp\n }\n self.users[sender].append(message_info)\n self.users[receiver].append(message_info)\n return True\n\n def get_messages(self, username):\n if username not in self.users:\n return []\n return self.users[username]", "import_statement": [ "from datetime import datetime" ], "class_description": " \"\"\"\n This is a chat class with the functions of adding users, removing users, sending messages, and obtaining messages.\n \"\"\"\n", "class_name": "Chat", "test_classes": [ "ChatTestAddUser", "ChatTestRemoveUser", "ChatTestSendMessage", "ChatTestGetMessages", "ChatTestMain" ], "class_constructor": "class Chat: \n def __init__(self):\n \"\"\"\n Initialize the Chat with an attribute users, which is an empty dictionary.\n \"\"\"\n self.users = {}\n\n", "fields": [ "self.users" ], "methods_info": [ { "method_name": "add_user", "method_description": "def add_user(self, username):\n \"\"\"\n Add a new user to the Chat.\n :param username: The user's name, str.\n :return: If the user is already in the Chat, returns False, otherwise, returns True.\n >>> chat = Chat()\n >>> chat.add_user('John')\n True\n self.users = {'John': []}\n >>> chat.add_user('John')\n False\n\n \"\"\"", "test_class": "ChatTestAddUser", "test_code": "class ChatTestAddUser(unittest.TestCase):\n def test_add_user(self):\n chat = Chat()\n self.assertEqual(chat.add_user('John'), True)\n self.assertEqual(chat.users, {'John': []})\n def test_add_user_2(self):\n chat = Chat()\n chat.users = {'John': []}\n self.assertEqual(chat.add_user('John'), False)\n self.assertEqual(chat.users, {'John': []})\n\n def test_add_user_3(self):\n chat = Chat()\n chat.users = {'John': []}\n self.assertEqual(chat.add_user('Mary'), True)\n self.assertEqual(chat.users, {'John': [], 'Mary': []})\n\n def test_add_user_4(self):\n chat = Chat()\n chat.users = {'John': []}\n self.assertEqual(chat.add_user('Mary'), True)\n self.assertEqual(chat.users, {'John': [], 'Mary': []})\n\n def test_add_user_5(self):\n chat = Chat()\n self.assertEqual(chat.add_user('John'), True)\n self.assertEqual(chat.add_user('Mary'), True)\n self.assertEqual(chat.users, {'John': [], 'Mary': []})", "solution_code": "def add_user(self, username):\n if username in self.users:\n return False\n else:\n self.users[username] = []\n return True", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.users" ], "method_dependencies": [] } }, { "method_name": "remove_user", "method_description": "def remove_user(self, username):\n \"\"\"\n Remove a user from the Chat.\n :param username: The user's name, str.\n :return: If the user is already in the Chat, returns True, otherwise, returns False.\n >>> chat = Chat()\n >>> chat.users = {'John': []}\n >>> chat.remove_user('John')\n True\n >>> chat.remove_user('John')\n False\n\n \"\"\"", "test_class": "ChatTestRemoveUser", "test_code": "class ChatTestRemoveUser(unittest.TestCase):\n def test_remove_user(self):\n chat = Chat()\n chat.users = {'John': []}\n self.assertEqual(chat.remove_user('John'), True)\n self.assertEqual(chat.users, {})\n def test_remove_user_2(self):\n chat = Chat()\n self.assertEqual(chat.remove_user('John'), False)\n self.assertEqual(chat.users, {})\n\n def test_remove_user_3(self):\n chat = Chat()\n chat.users = {'John': [], 'Mary': []}\n self.assertEqual(chat.remove_user('John'), True)\n self.assertEqual(chat.users, {'Mary': []})\n\n def test_remove_user_4(self):\n chat = Chat()\n chat.users = {'John': [], 'Mary': []}\n self.assertEqual(chat.remove_user('Mary'), True)\n self.assertEqual(chat.remove_user('John'), True)\n self.assertEqual(chat.users, {})\n\n def test_remove_user_5(self):\n chat = Chat()\n chat.users = {'John': [], 'Mary': []}\n self.assertEqual(chat.remove_user('Amy'), False)\n self.assertEqual(chat.users, {'John': [], 'Mary': []})", "solution_code": "def remove_user(self, username):\n if username in self.users:\n del self.users[username]\n return True\n else:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.users" ], "method_dependencies": [] } }, { "method_name": "send_message", "method_description": "def send_message(self, sender, receiver, message):\n \"\"\"\n Send a message from a user to another user.\n :param sender: The sender's name, str.\n :param receiver: The receiver's name, str.\n :param message: The message, str.\n :return: If the sender or the receiver is not in the Chat, returns False, otherwise, returns True.\n >>> chat = Chat()\n >>> chat.users = {'John': [], 'Mary': []}\n >>> chat.send_message('John', 'Mary', 'Hello')\n True\n >>> chat.send_message('John', 'Tom', 'Hello')\n False\n\n \"\"\"", "test_class": "ChatTestSendMessage", "test_code": "class ChatTestSendMessage(unittest.TestCase):\n def test_send_message(self):\n chat = Chat()\n chat.users = {'John': [], 'Mary': []}\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n self.assertEqual(chat.send_message('John', 'Mary', 'Hello'), True)\n self.assertEqual(chat.users, {'John': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}], 'Mary': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}]})\n\n def test_send_message_2(self):\n chat = Chat()\n chat.users = {'John': [], 'Mary': []}\n self.assertEqual(chat.send_message('John', 'Tom', 'Hello'), False)\n self.assertEqual(chat.users, {'John': [], 'Mary': []})\n\n def test_send_message_3(self):\n chat = Chat()\n chat.users = {'John': [], 'Mary': []}\n self.assertEqual(chat.send_message('Amy', 'Mary', 'Hello'), False)\n self.assertEqual(chat.users, {'John': [], 'Mary': []})\n\n def test_send_message_4(self):\n chat = Chat()\n chat.users = {'John': [], 'Mary': []}\n self.assertEqual(chat.send_message('Amy', 'Tom', 'Hello'), False)\n self.assertEqual(chat.users, {'John': [], 'Mary': []})\n\n def test_send_message_5(self):\n chat = Chat()\n chat.users = {'John': [], 'Mary': []}\n self.assertEqual(chat.send_message('Amy', 'Amy', 'Hello'), False)\n self.assertEqual(chat.users, {'John': [], 'Mary': []})", "solution_code": "def send_message(self, sender, receiver, message):\n if sender not in self.users or receiver not in self.users:\n return False\n\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n message_info = {\n 'sender': sender,\n 'receiver': receiver,\n 'message': message,\n 'timestamp': timestamp\n }\n self.users[sender].append(message_info)\n self.users[receiver].append(message_info)\n return True", "dependencies": { "Standalone": false, "lib_dependencies": [ "datetime" ], "field_dependencies": [ "self.users" ], "method_dependencies": [] } }, { "method_name": "get_messages", "method_description": "def get_messages(self, username):\n \"\"\"\n Get all the messages of a user from the Chat.\n :param username: The user's name, str.\n :return: A list of messages, each message is a dictionary with keys 'sender', 'receiver', 'message', 'timestamp'.\n >>> chat = Chat()\n >>> chat.users = {'John': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': '2023-01-01 00:00:00'}]}\n >>> chat.get_messages('John')\n [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': '2023-01-01 00:00:00'}]\n >>> chat.get_messages('Mary')\n []\n\n \"\"\"", "test_class": "ChatTestGetMessages", "test_code": "class ChatTestGetMessages(unittest.TestCase):\n def test_get_messages(self):\n chat = Chat()\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n chat.users = {'John': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}]}\n self.assertEqual(chat.get_messages('John'), [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}])\n\n def test_get_messages_2(self):\n chat = Chat()\n chat.users = {'John': [], 'Mary': []}\n self.assertEqual(chat.get_messages('John'), [])\n\n def test_get_messages_3(self):\n chat = Chat()\n chat.users = {'John': [], 'Mary': []}\n self.assertEqual(chat.get_messages('Amy'), [])\n\n def test_get_messages_4(self):\n chat = Chat()\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n chat.users = {'John': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}]}\n self.assertEqual(chat.get_messages('Mary'), [])\n\n def test_get_messages_5(self):\n chat = Chat()\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n chat.users = {'John': [{'sender': 'John', 'receiver': 'Mary', 'message': 'Hello', 'timestamp': timestamp}]}\n self.assertEqual(chat.get_messages('Amy'), [])", "solution_code": "def get_messages(self, username):\n if username not in self.users:\n return []\n return self.users[username]", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.users" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_21", "skeleton": "\nfrom datetime import datetime\n\nclass Classroom:\n \"\"\"\n This is a class representing a classroom, capable of adding and removing courses, checking availability at a given time, and detecting conflicts when scheduling new courses.\n \"\"\"\n\n def __init__(self, id):\n \"\"\"\n Initialize the classroom management system.\n :param id: int, the id of classroom\n \"\"\"\n self.id = id\n self.courses = []\n\n def add_course(self, course):\n \"\"\"\n Add course to self.courses list if the course wasn't in it.\n :param course: dict, information of the course, including 'start_time', 'end_time' and 'name'\n >>> classroom = Classroom(1)\n >>> classroom.add_course({'name': 'math', 'start_time': '8:00', 'end_time': '9:40'})\n \"\"\"\n\n def remove_course(self, course):\n \"\"\"\n Remove course from self.courses list if the course was in it.\n :param course: dict, information of the course, including 'start_time', 'end_time' and 'name'\n >>> classroom = Classroom(1)\n >>> classroom.add_course({'name': 'math', 'start_time': '8:00', 'end_time': '9:40'})\n >>> classroom.add_course({'name': 'math', 'start_time': '8:00', 'end_time': '9:40'})\n \"\"\"\n\n def is_free_at(self, check_time):\n \"\"\"\n change the time format as '%H:%M' and check the time is free or not in the classroom.\n :param check_time: str, the time need to be checked\n :return: True if the check_time does not conflict with every course time, or False otherwise.\n >>> classroom = Classroom(1)\n >>> classroom.add_course({'name': 'math', 'start_time': '8:00', 'end_time': '9:40'})\n >>> classroom.is_free_at('10:00')\n True\n >>> classroom.is_free_at('9:00')\n False\n \"\"\"\n\n def check_course_conflict(self, new_course):\n \"\"\"\n Before adding a new course, check if the new course time conflicts with any other course.\n :param new_course: dict, information of the course, including 'start_time', 'end_time' and 'name'\n :return: False if the new course time conflicts(including two courses have the same boundary time) with other courses, or True otherwise.\n >>> classroom = Classroom(1)\n >>> classroom.add_course({'name': 'math', 'start_time': '8:00', 'end_time': '9:40'})\n >>> classroom.check_course_conflict({'name': 'SE', 'start_time': '9:40', 'end_time': '10:40'})\n False\n \"\"\"", "test": "import unittest\nfrom datetime import datetime\n\n\nclass ClassroomTestAddCourse(unittest.TestCase):\n def test_add_course_1(self):\n classroom = Classroom(1)\n course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(course)\n self.assertIn(course, classroom.courses)\n\n def test_add_course_2(self):\n classroom = Classroom(1)\n course = {'name': 'Chinese', 'start_time': '10:00', 'end_time': '11:00'}\n classroom.add_course(course)\n self.assertIn(course, classroom.courses)\n\n def test_add_course_3(self):\n classroom = Classroom(1)\n course = {'name': 'English', 'start_time': '11:00', 'end_time': '12:00'}\n classroom.add_course(course)\n self.assertIn(course, classroom.courses)\n\n def test_add_course_4(self):\n classroom = Classroom(1)\n course = {'name': 'Art', 'start_time': '14:00', 'end_time': '15:00'}\n classroom.add_course(course)\n self.assertIn(course, classroom.courses)\n\n def test_add_course_5(self):\n classroom = Classroom(1)\n course = {'name': 'P.E.', 'start_time': '15:00', 'end_time': '16:00'}\n classroom.add_course(course)\n self.assertIn(course, classroom.courses)\n\n def test_add_course_6(self):\n classroom = Classroom(1)\n course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(course)\n classroom.add_course(course)\n self.assertIn(course, classroom.courses)\n\n\nclass ClassroomTestRemoveCourse(unittest.TestCase):\n def test_remove_course_1(self):\n classroom = Classroom(1)\n course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(course)\n classroom.remove_course(course)\n self.assertNotIn(course, classroom.courses)\n\n def test_remove_course_2(self):\n classroom = Classroom(1)\n course = {'name': 'Chinese', 'start_time': '10:00', 'end_time': '11:00'}\n classroom.add_course(course)\n classroom.remove_course(course)\n self.assertNotIn(course, classroom.courses)\n\n def test_remove_course_3(self):\n classroom = Classroom(1)\n course = {'name': 'English', 'start_time': '11:00', 'end_time': '12:00'}\n classroom.add_course(course)\n classroom.remove_course(course)\n self.assertNotIn(course, classroom.courses)\n\n def test_remove_course_4(self):\n classroom = Classroom(1)\n course = {'name': 'Art', 'start_time': '14:00', 'end_time': '15:00'}\n classroom.add_course(course)\n classroom.remove_course(course)\n self.assertNotIn(course, classroom.courses)\n\n def test_remove_course_5(self):\n classroom = Classroom(1)\n course = {'name': 'P.E.', 'start_time': '15:00', 'end_time': '16:00'}\n classroom.add_course(course)\n classroom.remove_course(course)\n self.assertNotIn(course, classroom.courses)\n\n def test_remove_course_6(self):\n classroom = Classroom(1)\n course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.remove_course(course)\n self.assertNotIn(course, classroom.courses)\n\n\nclass ClassroomTestIsFreeAt(unittest.TestCase):\n def test_is_free_at_1(self):\n classroom = Classroom(1)\n course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(course)\n check_time = '11:00'\n result = classroom.is_free_at(check_time)\n self.assertTrue(result)\n\n def test_is_free_at_2(self):\n classroom = Classroom(1)\n course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(course)\n check_time = '09:30'\n result = classroom.is_free_at(check_time)\n self.assertFalse(result)\n\n def test_is_free_at_3(self):\n classroom = Classroom(1)\n course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(course)\n check_time = '12:00'\n result = classroom.is_free_at(check_time)\n self.assertTrue(result)\n\n def test_is_free_at_4(self):\n classroom = Classroom(1)\n course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(course)\n check_time = '14:00'\n result = classroom.is_free_at(check_time)\n self.assertTrue(result)\n\n def test_is_free_at_5(self):\n classroom = Classroom(1)\n course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(course)\n check_time = '09:40'\n result = classroom.is_free_at(check_time)\n self.assertFalse(result)\n\n\nclass ClassroomTestCheckCourseConflict(unittest.TestCase):\n def test_check_course_conflict_1(self):\n classroom = Classroom(1)\n existing_course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(existing_course)\n new_course = {'name': 'SE', 'start_time': '10:30', 'end_time': '11:30'}\n result = classroom.check_course_conflict(new_course)\n self.assertTrue(result)\n\n def test_check_course_conflict_2(self):\n classroom = Classroom(1)\n existing_course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(existing_course)\n new_course = {'name': 'SE', 'start_time': '09:30', 'end_time': '10:30'}\n result = classroom.check_course_conflict(new_course)\n self.assertFalse(result)\n\n # have the same boundary time\n # existing_course['end_time'] == new_course['start_time']\n def test_check_course_conflict_3(self):\n classroom = Classroom(1)\n existing_course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(existing_course)\n new_course = {'name': 'SE', 'start_time': '10:00', 'end_time': '11:30'}\n result = classroom.check_course_conflict(new_course)\n self.assertFalse(result)\n\n def test_check_course_conflict_4(self):\n classroom = Classroom(1)\n existing_course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(existing_course)\n new_course = {'name': 'SE', 'start_time': '09:40', 'end_time': '10:40'}\n result = classroom.check_course_conflict(new_course)\n self.assertFalse(result)\n\n def test_check_course_conflict_5(self):\n classroom = Classroom(1)\n existing_course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(existing_course)\n new_course = {'name': 'SE', 'start_time': '14:30', 'end_time': '15:30'}\n result = classroom.check_course_conflict(new_course)\n self.assertTrue(result)\n\n def test_check_course_conflict_6(self):\n classroom = Classroom(1)\n existing_course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(existing_course)\n new_course = {'name': 'SE', 'start_time': '8:30', 'end_time': '9:30'}\n result = classroom.check_course_conflict(new_course)\n self.assertFalse(result)\n\n\nclass ClassroomTestMain(unittest.TestCase):\n def test_main(self):\n classroom = Classroom(1)\n course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(course)\n self.assertIn(course, classroom.courses)\n\n classroom.remove_course(course)\n self.assertNotIn(course, classroom.courses)\n\n classroom.add_course(course)\n self.assertIn(course, classroom.courses)\n check_time = '09:30'\n result = classroom.is_free_at(check_time)\n self.assertFalse(result)\n\n new_course = {'name': 'SE', 'start_time': '09:30', 'end_time': '10:30'}\n result = classroom.check_course_conflict(new_course)\n self.assertFalse(result)", "solution_code": "from datetime import datetime\n\n\nclass Classroom:\n def __init__(self, id):\n self.id = id\n self.courses = []\n\n def add_course(self, course):\n\n if course not in self.courses:\n self.courses.append(course)\n\n def remove_course(self, course):\n if course in self.courses:\n self.courses.remove(course)\n\n def is_free_at(self, check_time):\n check_time = datetime.strptime(check_time, '%H:%M')\n\n for course in self.courses:\n if datetime.strptime(course['start_time'], '%H:%M') <= check_time <= datetime.strptime(course['end_time'],\n '%H:%M'):\n return False\n return True\n\n def check_course_conflict(self, new_course):\n new_start_time = datetime.strptime(new_course['start_time'], '%H:%M')\n new_end_time = datetime.strptime(new_course['end_time'], '%H:%M')\n\n flag = True\n for course in self.courses:\n start_time = datetime.strptime(course['start_time'], '%H:%M')\n end_time = datetime.strptime(course['end_time'], '%H:%M')\n if start_time <= new_start_time and end_time >= new_start_time:\n flag = False\n if start_time <= new_end_time and end_time >= new_end_time:\n flag = False\n return flag", "import_statement": [ "from datetime import datetime" ], "class_description": " \"\"\"\n This is a class representing a classroom, capable of adding and removing courses, checking availability at a given time, and detecting conflicts when scheduling new courses.\n \"\"\"\n", "class_name": "Classroom", "test_classes": [ "ClassroomTestAddCourse", "ClassroomTestRemoveCourse", "ClassroomTestIsFreeAt", "ClassroomTestCheckCourseConflict", "ClassroomTestMain" ], "class_constructor": "class Classroom: \n def __init__(self, id):\n \"\"\"\n Initialize the classroom management system.\n :param id: int, the id of classroom\n \"\"\"\n self.id = id\n self.courses = []\n\n", "fields": [ "self.courses", "self.id" ], "methods_info": [ { "method_name": "add_course", "method_description": "def add_course(self, course):\n \"\"\"\n Add course to self.courses list if the course wasn't in it.\n :param course: dict, information of the course, including 'start_time', 'end_time' and 'name'\n >>> classroom = Classroom(1)\n >>> classroom.add_course({'name': 'math', 'start_time': '8:00', 'end_time': '9:40'})\n \"\"\"", "test_class": "ClassroomTestAddCourse", "test_code": "class ClassroomTestAddCourse(unittest.TestCase):\n def test_add_course_1(self):\n classroom = Classroom(1)\n course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(course)\n self.assertIn(course, classroom.courses)\n\n def test_add_course_2(self):\n classroom = Classroom(1)\n course = {'name': 'Chinese', 'start_time': '10:00', 'end_time': '11:00'}\n classroom.add_course(course)\n self.assertIn(course, classroom.courses)\n\n def test_add_course_3(self):\n classroom = Classroom(1)\n course = {'name': 'English', 'start_time': '11:00', 'end_time': '12:00'}\n classroom.add_course(course)\n self.assertIn(course, classroom.courses)\n\n def test_add_course_4(self):\n classroom = Classroom(1)\n course = {'name': 'Art', 'start_time': '14:00', 'end_time': '15:00'}\n classroom.add_course(course)\n self.assertIn(course, classroom.courses)\n\n def test_add_course_5(self):\n classroom = Classroom(1)\n course = {'name': 'P.E.', 'start_time': '15:00', 'end_time': '16:00'}\n classroom.add_course(course)\n self.assertIn(course, classroom.courses)\n\n def test_add_course_6(self):\n classroom = Classroom(1)\n course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(course)\n classroom.add_course(course)\n self.assertIn(course, classroom.courses)", "solution_code": "def add_course(self, course):\n\n if course not in self.courses:\n self.courses.append(course)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.courses" ], "method_dependencies": [] } }, { "method_name": "remove_course", "method_description": "def remove_course(self, course):\n \"\"\"\n Remove course from self.courses list if the course was in it.\n :param course: dict, information of the course, including 'start_time', 'end_time' and 'name'\n >>> classroom = Classroom(1)\n >>> classroom.add_course({'name': 'math', 'start_time': '8:00', 'end_time': '9:40'})\n >>> classroom.add_course({'name': 'math', 'start_time': '8:00', 'end_time': '9:40'})\n \"\"\"", "test_class": "ClassroomTestRemoveCourse", "test_code": "class ClassroomTestRemoveCourse(unittest.TestCase):\n def test_remove_course_1(self):\n classroom = Classroom(1)\n course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(course)\n classroom.remove_course(course)\n self.assertNotIn(course, classroom.courses)\n\n def test_remove_course_2(self):\n classroom = Classroom(1)\n course = {'name': 'Chinese', 'start_time': '10:00', 'end_time': '11:00'}\n classroom.add_course(course)\n classroom.remove_course(course)\n self.assertNotIn(course, classroom.courses)\n\n def test_remove_course_3(self):\n classroom = Classroom(1)\n course = {'name': 'English', 'start_time': '11:00', 'end_time': '12:00'}\n classroom.add_course(course)\n classroom.remove_course(course)\n self.assertNotIn(course, classroom.courses)\n\n def test_remove_course_4(self):\n classroom = Classroom(1)\n course = {'name': 'Art', 'start_time': '14:00', 'end_time': '15:00'}\n classroom.add_course(course)\n classroom.remove_course(course)\n self.assertNotIn(course, classroom.courses)\n\n def test_remove_course_5(self):\n classroom = Classroom(1)\n course = {'name': 'P.E.', 'start_time': '15:00', 'end_time': '16:00'}\n classroom.add_course(course)\n classroom.remove_course(course)\n self.assertNotIn(course, classroom.courses)\n\n def test_remove_course_6(self):\n classroom = Classroom(1)\n course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.remove_course(course)\n self.assertNotIn(course, classroom.courses)", "solution_code": "def remove_course(self, course):\n if course in self.courses:\n self.courses.remove(course)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.courses" ], "method_dependencies": [] } }, { "method_name": "is_free_at", "method_description": "def is_free_at(self, check_time):\n \"\"\"\n change the time format as '%H:%M' and check the time is free or not in the classroom.\n :param check_time: str, the time need to be checked\n :return: True if the check_time does not conflict with every course time, or False otherwise.\n >>> classroom = Classroom(1)\n >>> classroom.add_course({'name': 'math', 'start_time': '8:00', 'end_time': '9:40'})\n >>> classroom.is_free_at('10:00')\n True\n >>> classroom.is_free_at('9:00')\n False\n \"\"\"", "test_class": "ClassroomTestIsFreeAt", "test_code": "class ClassroomTestIsFreeAt(unittest.TestCase):\n def test_is_free_at_1(self):\n classroom = Classroom(1)\n course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(course)\n check_time = '11:00'\n result = classroom.is_free_at(check_time)\n self.assertTrue(result)\n\n def test_is_free_at_2(self):\n classroom = Classroom(1)\n course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(course)\n check_time = '09:30'\n result = classroom.is_free_at(check_time)\n self.assertFalse(result)\n\n def test_is_free_at_3(self):\n classroom = Classroom(1)\n course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(course)\n check_time = '12:00'\n result = classroom.is_free_at(check_time)\n self.assertTrue(result)\n\n def test_is_free_at_4(self):\n classroom = Classroom(1)\n course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(course)\n check_time = '14:00'\n result = classroom.is_free_at(check_time)\n self.assertTrue(result)\n\n def test_is_free_at_5(self):\n classroom = Classroom(1)\n course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(course)\n check_time = '09:40'\n result = classroom.is_free_at(check_time)\n self.assertFalse(result)", "solution_code": "def is_free_at(self, check_time):\n check_time = datetime.strptime(check_time, '%H:%M')\n\n for course in self.courses:\n if datetime.strptime(course['start_time'], '%H:%M') <= check_time <= datetime.strptime(course['end_time'],\n '%H:%M'):\n return False\n return True", "dependencies": { "Standalone": false, "lib_dependencies": [ "datetime" ], "field_dependencies": [ "self.courses" ], "method_dependencies": [] } }, { "method_name": "check_course_conflict", "method_description": "def check_course_conflict(self, new_course):\n \"\"\"\n Before adding a new course, check if the new course time conflicts with any other course.\n :param new_course: dict, information of the course, including 'start_time', 'end_time' and 'name'\n :return: False if the new course time conflicts(including two courses have the same boundary time) with other courses, or True otherwise.\n >>> classroom = Classroom(1)\n >>> classroom.add_course({'name': 'math', 'start_time': '8:00', 'end_time': '9:40'})\n >>> classroom.check_course_conflict({'name': 'SE', 'start_time': '9:40', 'end_time': '10:40'})\n False\n \"\"\"", "test_class": "ClassroomTestCheckCourseConflict", "test_code": "class ClassroomTestCheckCourseConflict(unittest.TestCase):\n def test_check_course_conflict_1(self):\n classroom = Classroom(1)\n existing_course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(existing_course)\n new_course = {'name': 'SE', 'start_time': '10:30', 'end_time': '11:30'}\n result = classroom.check_course_conflict(new_course)\n self.assertTrue(result)\n\n def test_check_course_conflict_2(self):\n classroom = Classroom(1)\n existing_course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(existing_course)\n new_course = {'name': 'SE', 'start_time': '09:30', 'end_time': '10:30'}\n result = classroom.check_course_conflict(new_course)\n self.assertFalse(result)\n\n # have the same boundary time\n # existing_course['end_time'] == new_course['start_time']\n def test_check_course_conflict_3(self):\n classroom = Classroom(1)\n existing_course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(existing_course)\n new_course = {'name': 'SE', 'start_time': '10:00', 'end_time': '11:30'}\n result = classroom.check_course_conflict(new_course)\n self.assertFalse(result)\n\n def test_check_course_conflict_4(self):\n classroom = Classroom(1)\n existing_course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(existing_course)\n new_course = {'name': 'SE', 'start_time': '09:40', 'end_time': '10:40'}\n result = classroom.check_course_conflict(new_course)\n self.assertFalse(result)\n\n def test_check_course_conflict_5(self):\n classroom = Classroom(1)\n existing_course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(existing_course)\n new_course = {'name': 'SE', 'start_time': '14:30', 'end_time': '15:30'}\n result = classroom.check_course_conflict(new_course)\n self.assertTrue(result)\n\n def test_check_course_conflict_6(self):\n classroom = Classroom(1)\n existing_course = {'name': 'math', 'start_time': '09:00', 'end_time': '10:00'}\n classroom.add_course(existing_course)\n new_course = {'name': 'SE', 'start_time': '8:30', 'end_time': '9:30'}\n result = classroom.check_course_conflict(new_course)\n self.assertFalse(result)", "solution_code": "def check_course_conflict(self, new_course):\n new_start_time = datetime.strptime(new_course['start_time'], '%H:%M')\n new_end_time = datetime.strptime(new_course['end_time'], '%H:%M')\n\n flag = True\n for course in self.courses:\n start_time = datetime.strptime(course['start_time'], '%H:%M')\n end_time = datetime.strptime(course['end_time'], '%H:%M')\n if start_time <= new_start_time and end_time >= new_start_time:\n flag = False\n if start_time <= new_end_time and end_time >= new_end_time:\n flag = False\n return flag", "dependencies": { "Standalone": false, "lib_dependencies": [ "datetime" ], "field_dependencies": [ "self.courses" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_22", "skeleton": "\nclass ClassRegistrationSystem:\n \"\"\"\n This is a class as a class registration system, allowing to register students, register them for classes, retrieve students by major, get a list of all majors, and determine the most popular class within a specific major.\n \"\"\"\n\n\n def __init__(self):\n \"\"\"\n Initialize the registration system with the attribute students and students_registration_class.\n students is a list of student dictionaries, each student dictionary has the key of name and major.\n students_registration_class is a dictionaries, key is the student name, value is a list of class names\n \"\"\"\n self.students = []\n self.students_registration_classes = {}\n\n def register_student(self, student):\n \"\"\"\n register a student to the system, add the student to the students list, if the student is already registered, return 0, else return 1\n \"\"\"\n\n def register_class(self, student_name, class_name):\n \"\"\"\n register a class to the student.\n :param student_name: str\n :param class_name: str\n :return a list of class names that the student has registered\n >>> registration_system = ClassRegistrationSystem()\n >>> registration_system.register_class(student_name=\"John\", class_name=\"CS101\")\n >>> registration_system.register_class(student_name=\"John\", class_name=\"CS102\")\n [\"CS101\", \"CS102\"]\n\n def get_students_by_major(self, major):\n \"\"\"\n get all students in the major\n :param major: str\n :return a list of student name\n >>> registration_system = ClassRegistrationSystem()\n >>> student1 = {\"name\": \"John\", \"major\": \"Computer Science\"}\n >>> registration_system.register_student(student1)\n >>> registration_system.get_students_by_major(\"Computer Science\")\n [\"John\"]\n \"\"\"\n\n def get_all_major(self):\n \"\"\"\n get all majors in the system\n :return a list of majors\n >>> registration_system = ClassRegistrationSystem()\n >>> registration_system.students = [{\"name\": \"John\", \"major\": \"Computer Science\"}],\n >>> registration_system.get_all_major(student1)\n [\"Computer Science\"]\n \"\"\"\n\n def get_most_popular_class_in_major(self, major):\n \"\"\"\n get the class with the highest enrollment in the major.\n :return a string of the most popular class in this major\n >>> registration_system = ClassRegistrationSystem()\n >>> registration_system.students = [{\"name\": \"John\", \"major\": \"Computer Science\"},\n {\"name\": \"Bob\", \"major\": \"Computer Science\"},\n {\"name\": \"Alice\", \"major\": \"Computer Science\"}]\n >>> registration_system.students_registration_classes = {\"John\": [\"Algorithms\", \"Data Structures\"],\n \"Bob\": [\"Operating Systems\", \"Data Structures\", \"Algorithms\"]}\n >>> registration_system.get_most_popular_class_in_major(\"Computer Science\")\n \"Data Structures\"\n \"\"\"", "test": "import unittest\n\n\nclass ClassRegistrationSystemTestRegisterStudent(unittest.TestCase):\n\n def setUp(self):\n self.registration_system = ClassRegistrationSystem()\n\n def test_register_student(self):\n student1 = {\"name\": \"John\", \"major\": \"Computer Science\"}\n self.assertEqual(self.registration_system.register_student(student1), 1)\n\n def test_register_student2(self):\n student1 = {\"name\": \"John\", \"major\": \"Computer Science\"}\n self.registration_system.register_student(student1)\n self.assertEqual(self.registration_system.register_student(student1), 0)\n\n def test_register_student3(self):\n student1 = {\"name\": \"John\", \"major\": \"Computer Science\"}\n student2 = {\"name\": \"Alice\", \"major\": \"Mathematics\"}\n self.assertEqual(self.registration_system.register_student(student1), 1)\n self.assertEqual(self.registration_system.register_student(student2), 1)\n self.assertEqual(self.registration_system.register_student(student2), 0)\n\nclass ClassRegistrationSystemTestRegisterClass(unittest.TestCase):\n\n def setUp(self):\n self.registration_system = ClassRegistrationSystem()\n\n def test_register_class(self):\n self.assertEqual(self.registration_system.register_class(student_name=\"John\", class_name=\"CS101\"), [\"CS101\"])\n\n def test_register_class2(self):\n self.registration_system.register_class(student_name=\"John\", class_name=\"CS101\")\n self.registration_system.register_class(student_name=\"John\", class_name=\"CS102\")\n self.assertEqual(self.registration_system.register_class(student_name=\"John\", class_name=\"CS103\"), [\"CS101\", \"CS102\", \"CS103\"])\n\n def test_register_class3(self):\n self.registration_system.register_class(student_name=\"John\", class_name=\"CS101\")\n self.registration_system.register_class(student_name=\"Tom\", class_name=\"CS102\")\n self.assertEqual(self.registration_system.register_class(student_name=\"John\", class_name=\"CS103\"), [\"CS101\", \"CS103\"])\n\n\nclass ClassRegistrationSystemTestGetStudent(unittest.TestCase):\n\n def setUp(self):\n self.registration_system = ClassRegistrationSystem()\n\n def test_get_students_by_major(self):\n self.registration_system.students = [{\"name\": \"John\", \"major\": \"Computer Science\"},\n {\"name\": \"Bob\", \"major\": \"Computer Science\"}]\n\n cs_students = self.registration_system.get_students_by_major(\"Computer Science\")\n\n self.assertEqual(cs_students, [\"John\", \"Bob\"])\n\n def test_get_students_by_major2(self):\n self.registration_system.students = [{\"name\": \"John\", \"major\": \"Computer Science\"},\n {\"name\": \"Bob\", \"major\": \"Computer Science\"}]\n\n cs_students = self.registration_system.get_students_by_major(\"Computer Science\")\n math_students = self.registration_system.get_students_by_major(\"Mathematics\")\n\n self.assertEqual(cs_students, [\"John\", \"Bob\"])\n self.assertEqual(math_students, [])\n\n def test_get_students_by_major3(self):\n self.registration_system.students = [{\"name\": \"John\", \"major\": \"Computer Science\"},\n {\"name\": \"Bob\", \"major\": \"Computer Science\"},\n {\"name\": \"Alice\", \"major\": \"Mathematics\"}]\n\n cs_students = self.registration_system.get_students_by_major(\"Computer Science\")\n math_students = self.registration_system.get_students_by_major(\"Mathematics\")\n\n self.assertEqual(cs_students, [\"John\", \"Bob\"])\n self.assertEqual(math_students, [\"Alice\"])\n\n def test_get_students_by_major4(self):\n self.registration_system.students = [{\"name\": \"John\", \"major\": \"Computer Science\"},\n {\"name\": \"Bob\", \"major\": \"Computer Science\"},\n {\"name\": \"Alice\", \"major\": \"Mathematics\"},\n {\"name\": \"Tom\", \"major\": \"Mathematics\"},\n {\"name\": \"Jerry\", \"major\": \"Mathematics\"}]\n\n cs_students = self.registration_system.get_students_by_major(\"Computer Science\")\n math_students = self.registration_system.get_students_by_major(\"Mathematics\")\n self.assertEqual(cs_students, [\"John\", \"Bob\"])\n self.assertEqual(math_students, [\"Alice\", \"Tom\", \"Jerry\"])\n\n\n\nclass ClassRegistrationSystemTestGetMajor(unittest.TestCase):\n\n def setUp(self):\n self.registration_system = ClassRegistrationSystem()\n\n def test_get_all_major(self):\n self.registration_system.students = [{\"name\": \"John\", \"major\": \"Computer Science\"},\n {\"name\": \"Bob\", \"major\": \"Computer Science\"}]\n\n majors = self.registration_system.get_all_major()\n\n self.assertEqual(majors, [\"Computer Science\"])\n\n def test_get_all_major2(self):\n self.registration_system.students = [{\"name\": \"John\", \"major\": \"Computer Science\"},\n {\"name\": \"Bob\", \"major\": \"Computer Science\"},\n {\"name\": \"Alice\", \"major\": \"Mathematics\"}]\n\n majors = self.registration_system.get_all_major()\n\n self.assertEqual(majors, [\"Computer Science\", \"Mathematics\"])\n\n def test_get_all_major3(self):\n self.registration_system.students = [{\"name\": \"John\", \"major\": \"Computer Science\"},\n {\"name\": \"Bob\", \"major\": \"Computer Science\"},\n {\"name\": \"Alice\", \"major\": \"Mathematics\"},\n {\"name\": \"Tom\", \"major\": \"Mathematics\"},\n {\"name\": \"Jerry\", \"major\": \"Physics\"}]\n\n majors = self.registration_system.get_all_major()\n\n self.assertEqual(majors, [\"Computer Science\", \"Mathematics\", \"Physics\"])\n\nclass ClassRegistrationSystemTestPopularClass(unittest.TestCase):\n\n def setUp(self):\n self.registration_system = ClassRegistrationSystem()\n\n def test_get_most_popular_class_in_major(self):\n self.registration_system.students = [{\"name\": \"John\", \"major\": \"Computer Science\"},\n {\"name\": \"Bob\", \"major\": \"Computer Science\"},\n {\"name\": \"Alice\", \"major\": \"Computer Science\"}]\n\n self.registration_system.students_registration_classes = {\"John\": [\"Algorithms\", \"Data Structures\"],\n \"Bob\": [\"Operating Systems\", \"Data Structures\", \"Algorithms\"],\n \"Alice\": [\"Data Structures\", \"Operating Systems\", \"Calculus\"]}\n\n cs_most_popular_class = self.registration_system.get_most_popular_class_in_major(\"Computer Science\")\n\n self.assertEqual(cs_most_popular_class, \"Data Structures\")\n\n def test_get_most_popular_class_in_major2(self):\n self.registration_system.students = [{\"name\": \"John\", \"major\": \"Computer Science\"},\n {\"name\": \"Bob\", \"major\": \"Computer Science\"},\n {\"name\": \"Alice\", \"major\": \"Computer Science\"},\n {\"name\": \"Tom\", \"major\": \"Mathematics\"},\n {\"name\": \"Jerry\", \"major\": \"Mathematics\"}]\n\n self.registration_system.students_registration_classes = {\"John\": [\"Algorithms\", \"Data Structures\"],\n \"Bob\": [\"Data Structures\", \"Algorithms\",\n \"Operating Systems\"],\n \"Alice\": [\"Data Structures\", \"Operating Systems\",\n \"Calculus\"],\n \"Tom\": [\"Calculus\", \"Linear Algebra\"],\n \"Jerry\": [\"Linear Algebra\", \"Statistics\"]}\n\n cs_most_popular_class = self.registration_system.get_most_popular_class_in_major(\"Computer Science\")\n math_most_popular_class = self.registration_system.get_most_popular_class_in_major(\"Mathematics\")\n self.assertEqual(cs_most_popular_class, \"Data Structures\")\n self.assertEqual(math_most_popular_class, \"Linear Algebra\")\n\nclass ClassRegistrationSystemTest(unittest.TestCase):\n\n def setUp(self):\n self.registration_system = ClassRegistrationSystem()\n\n def test(self):\n student1 = {\"name\": \"John\", \"major\": \"Computer Science\"}\n student2 = {\"name\": \"Bob\", \"major\": \"Computer Science\"}\n student3 = {\"name\": \"Alice\", \"major\": \"Mathematics\"}\n student4 = {\"name\": \"Tom\", \"major\": \"Mathematics\"}\n self.registration_system.register_student(student1)\n self.registration_system.register_student(student2)\n self.registration_system.register_student(student3)\n self.registration_system.register_student(student4)\n self.registration_system.register_class(\"John\", \"Algorithms\")\n self.registration_system.register_class(\"John\", \"Data Structures\")\n self.registration_system.register_class(\"Bob\", \"Operating Systems\")\n self.registration_system.register_class(\"Bob\", \"Data Structures\")\n self.assertEqual(self.registration_system.get_students_by_major(\"Computer Science\"), [\"John\", \"Bob\"])\n self.assertEqual(self.registration_system.get_students_by_major(\"Mathematics\"), [\"Alice\", \"Tom\"])\n self.assertEqual(self.registration_system.get_all_major(), [\"Computer Science\", \"Mathematics\"])\n self.assertEqual(self.registration_system.get_most_popular_class_in_major(\"Computer Science\"), \"Data Structures\")", "solution_code": "class ClassRegistrationSystem:\n\n def __init__(self):\n self.students = []\n self.students_registration_classes = {}\n\n def register_student(self, student):\n if student in self.students:\n return 0\n else:\n self.students.append(student)\n return 1\n\n def register_class(self, student_name, class_name):\n if student_name in self.students_registration_classes:\n self.students_registration_classes[student_name].append(class_name)\n else:\n self.students_registration_classes[student_name] = [class_name]\n return self.students_registration_classes[student_name]\n\n def get_students_by_major(self, major):\n student_list = []\n for student in self.students:\n if student[\"major\"] == major:\n student_list.append(student[\"name\"])\n return student_list\n\n def get_all_major(self):\n major_list = []\n for student in self.students:\n if student[\"major\"] not in major_list:\n major_list.append(student[\"major\"])\n return major_list\n\n def get_most_popular_class_in_major(self, major):\n class_list = []\n for student in self.students:\n if student[\"major\"] == major:\n class_list += self.students_registration_classes[student[\"name\"]]\n most_popular_class = max(set(class_list), key=class_list.count)\n return most_popular_class", "import_statement": [], "class_description": " \"\"\"\n This is a class as a class registration system, allowing to register students, register them for classes, retrieve students by major, get a list of all majors, and determine the most popular class within a specific major.\n \"\"\"\n", "class_name": "ClassRegistrationSystem", "test_classes": [ "ClassRegistrationSystemTestRegisterStudent", "ClassRegistrationSystemTestRegisterClass", "ClassRegistrationSystemTestGetStudent", "ClassRegistrationSystemTestGetMajor", "ClassRegistrationSystemTestPopularClass", "ClassRegistrationSystemTest" ], "class_constructor": "class ClassRegistrationSystem: \n def __init__(self):\n \"\"\"\n Initialize the registration system with the attribute students and students_registration_class.\n students is a list of student dictionaries, each student dictionary has the key of name and major.\n students_registration_class is a dictionaries, key is the student name, value is a list of class names\n \"\"\"\n self.students = []\n self.students_registration_classes = {}\n\n", "fields": [ "self.students", "self.students_registration_classes" ], "methods_info": [ { "method_name": "register_student", "method_description": "def register_student(self, student):\n \"\"\"\n register a student to the system, add the student to the students list, if the student is already registered, return 0, else return 1\n \"\"\"", "test_class": "ClassRegistrationSystemTestRegisterStudent", "test_code": "class ClassRegistrationSystemTestRegisterStudent(unittest.TestCase):\n\n def setUp(self):\n self.registration_system = ClassRegistrationSystem()\n\n def test_register_student(self):\n student1 = {\"name\": \"John\", \"major\": \"Computer Science\"}\n self.assertEqual(self.registration_system.register_student(student1), 1)\n\n def test_register_student2(self):\n student1 = {\"name\": \"John\", \"major\": \"Computer Science\"}\n self.registration_system.register_student(student1)\n self.assertEqual(self.registration_system.register_student(student1), 0)\n\n def test_register_student3(self):\n student1 = {\"name\": \"John\", \"major\": \"Computer Science\"}\n student2 = {\"name\": \"Alice\", \"major\": \"Mathematics\"}\n self.assertEqual(self.registration_system.register_student(student1), 1)\n self.assertEqual(self.registration_system.register_student(student2), 1)\n self.assertEqual(self.registration_system.register_student(student2), 0)", "solution_code": "def register_student(self, student):\n if student in self.students:\n return 0\n else:\n self.students.append(student)\n return 1", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.students" ], "method_dependencies": [] } }, { "method_name": "register_class", "method_description": "def register_class(self, student_name, class_name):\n \"\"\"\n register a class to the student.\n :param student_name: str\n :param class_name: str\n :return a list of class names that the student has registered\n >>> registration_system = ClassRegistrationSystem()\n >>> registration_system.register_class(student_name=\"John\", class_name=\"CS101\")\n >>> registration_system.register_class(student_name=\"John\", class_name=\"CS102\")\n [\"CS101\", \"CS102\"]", "test_class": "ClassRegistrationSystemTestRegisterClass", "test_code": "class ClassRegistrationSystemTestRegisterClass(unittest.TestCase):\n\n def setUp(self):\n self.registration_system = ClassRegistrationSystem()\n\n def test_register_class(self):\n self.assertEqual(self.registration_system.register_class(student_name=\"John\", class_name=\"CS101\"), [\"CS101\"])\n\n def test_register_class2(self):\n self.registration_system.register_class(student_name=\"John\", class_name=\"CS101\")\n self.registration_system.register_class(student_name=\"John\", class_name=\"CS102\")\n self.assertEqual(self.registration_system.register_class(student_name=\"John\", class_name=\"CS103\"), [\"CS101\", \"CS102\", \"CS103\"])\n\n def test_register_class3(self):\n self.registration_system.register_class(student_name=\"John\", class_name=\"CS101\")\n self.registration_system.register_class(student_name=\"Tom\", class_name=\"CS102\")\n self.assertEqual(self.registration_system.register_class(student_name=\"John\", class_name=\"CS103\"), [\"CS101\", \"CS103\"])", "solution_code": "def register_class(self, student_name, class_name):\n if student_name in self.students_registration_classes:\n self.students_registration_classes[student_name].append(class_name)\n else:\n self.students_registration_classes[student_name] = [class_name]\n return self.students_registration_classes[student_name]", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.students", "self.students_registration_classes" ], "method_dependencies": [] } }, { "method_name": "get_students_by_major", "method_description": "def get_students_by_major(self, major):\n \"\"\"\n get all students in the major\n :param major: str\n :return a list of student name\n >>> registration_system = ClassRegistrationSystem()\n >>> student1 = {\"name\": \"John\", \"major\": \"Computer Science\"}\n >>> registration_system.register_student(student1)\n >>> registration_system.get_students_by_major(\"Computer Science\")\n [\"John\"]\n \"\"\"", "test_class": "ClassRegistrationSystemTestGetStudent", "test_code": "class ClassRegistrationSystemTestGetStudent(unittest.TestCase):\n\n def setUp(self):\n self.registration_system = ClassRegistrationSystem()\n\n def test_get_students_by_major(self):\n self.registration_system.students = [{\"name\": \"John\", \"major\": \"Computer Science\"},\n {\"name\": \"Bob\", \"major\": \"Computer Science\"}]\n\n cs_students = self.registration_system.get_students_by_major(\"Computer Science\")\n\n self.assertEqual(cs_students, [\"John\", \"Bob\"])\n\n def test_get_students_by_major2(self):\n self.registration_system.students = [{\"name\": \"John\", \"major\": \"Computer Science\"},\n {\"name\": \"Bob\", \"major\": \"Computer Science\"}]\n\n cs_students = self.registration_system.get_students_by_major(\"Computer Science\")\n math_students = self.registration_system.get_students_by_major(\"Mathematics\")\n\n self.assertEqual(cs_students, [\"John\", \"Bob\"])\n self.assertEqual(math_students, [])\n\n def test_get_students_by_major3(self):\n self.registration_system.students = [{\"name\": \"John\", \"major\": \"Computer Science\"},\n {\"name\": \"Bob\", \"major\": \"Computer Science\"},\n {\"name\": \"Alice\", \"major\": \"Mathematics\"}]\n\n cs_students = self.registration_system.get_students_by_major(\"Computer Science\")\n math_students = self.registration_system.get_students_by_major(\"Mathematics\")\n\n self.assertEqual(cs_students, [\"John\", \"Bob\"])\n self.assertEqual(math_students, [\"Alice\"])\n\n def test_get_students_by_major4(self):\n self.registration_system.students = [{\"name\": \"John\", \"major\": \"Computer Science\"},\n {\"name\": \"Bob\", \"major\": \"Computer Science\"},\n {\"name\": \"Alice\", \"major\": \"Mathematics\"},\n {\"name\": \"Tom\", \"major\": \"Mathematics\"},\n {\"name\": \"Jerry\", \"major\": \"Mathematics\"}]\n\n cs_students = self.registration_system.get_students_by_major(\"Computer Science\")\n math_students = self.registration_system.get_students_by_major(\"Mathematics\")\n self.assertEqual(cs_students, [\"John\", \"Bob\"])\n self.assertEqual(math_students, [\"Alice\", \"Tom\", \"Jerry\"])", "solution_code": "def get_students_by_major(self, major):\n student_list = []\n for student in self.students:\n if student[\"major\"] == major:\n student_list.append(student[\"name\"])\n return student_list", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.students" ], "method_dependencies": [] } }, { "method_name": "get_all_major", "method_description": "def get_all_major(self):\n \"\"\"\n get all majors in the system\n :return a list of majors\n >>> registration_system = ClassRegistrationSystem()\n >>> registration_system.students = [{\"name\": \"John\", \"major\": \"Computer Science\"}],\n >>> registration_system.get_all_major(student1)\n [\"Computer Science\"]\n \"\"\"", "test_class": "ClassRegistrationSystemTestGetMajor", "test_code": "class ClassRegistrationSystemTestGetMajor(unittest.TestCase):\n\n def setUp(self):\n self.registration_system = ClassRegistrationSystem()\n\n def test_get_all_major(self):\n self.registration_system.students = [{\"name\": \"John\", \"major\": \"Computer Science\"},\n {\"name\": \"Bob\", \"major\": \"Computer Science\"}]\n\n majors = self.registration_system.get_all_major()\n\n self.assertEqual(majors, [\"Computer Science\"])\n\n def test_get_all_major2(self):\n self.registration_system.students = [{\"name\": \"John\", \"major\": \"Computer Science\"},\n {\"name\": \"Bob\", \"major\": \"Computer Science\"},\n {\"name\": \"Alice\", \"major\": \"Mathematics\"}]\n\n majors = self.registration_system.get_all_major()\n\n self.assertEqual(majors, [\"Computer Science\", \"Mathematics\"])\n\n def test_get_all_major3(self):\n self.registration_system.students = [{\"name\": \"John\", \"major\": \"Computer Science\"},\n {\"name\": \"Bob\", \"major\": \"Computer Science\"},\n {\"name\": \"Alice\", \"major\": \"Mathematics\"},\n {\"name\": \"Tom\", \"major\": \"Mathematics\"},\n {\"name\": \"Jerry\", \"major\": \"Physics\"}]\n\n majors = self.registration_system.get_all_major()\n\n self.assertEqual(majors, [\"Computer Science\", \"Mathematics\", \"Physics\"])", "solution_code": "def get_all_major(self):\n major_list = []\n for student in self.students:\n if student[\"major\"] not in major_list:\n major_list.append(student[\"major\"])\n return major_list", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.students" ], "method_dependencies": [] } }, { "method_name": "get_most_popular_class_in_major", "method_description": "def get_most_popular_class_in_major(self, major):\n \"\"\"\n get the class with the highest enrollment in the major.\n :return a string of the most popular class in this major\n >>> registration_system = ClassRegistrationSystem()\n >>> registration_system.students = [{\"name\": \"John\", \"major\": \"Computer Science\"},\n {\"name\": \"Bob\", \"major\": \"Computer Science\"},\n {\"name\": \"Alice\", \"major\": \"Computer Science\"}]\n >>> registration_system.students_registration_classes = {\"John\": [\"Algorithms\", \"Data Structures\"],\n \"Bob\": [\"Operating Systems\", \"Data Structures\", \"Algorithms\"]}\n >>> registration_system.get_most_popular_class_in_major(\"Computer Science\")\n \"Data Structures\"\n \"\"\"", "test_class": "ClassRegistrationSystemTestPopularClass", "test_code": "class ClassRegistrationSystemTestPopularClass(unittest.TestCase):\n\n def setUp(self):\n self.registration_system = ClassRegistrationSystem()\n\n def test_get_most_popular_class_in_major(self):\n self.registration_system.students = [{\"name\": \"John\", \"major\": \"Computer Science\"},\n {\"name\": \"Bob\", \"major\": \"Computer Science\"},\n {\"name\": \"Alice\", \"major\": \"Computer Science\"}]\n\n self.registration_system.students_registration_classes = {\"John\": [\"Algorithms\", \"Data Structures\"],\n \"Bob\": [\"Operating Systems\", \"Data Structures\", \"Algorithms\"],\n \"Alice\": [\"Data Structures\", \"Operating Systems\", \"Calculus\"]}\n\n cs_most_popular_class = self.registration_system.get_most_popular_class_in_major(\"Computer Science\")\n\n self.assertEqual(cs_most_popular_class, \"Data Structures\")\n\n def test_get_most_popular_class_in_major2(self):\n self.registration_system.students = [{\"name\": \"John\", \"major\": \"Computer Science\"},\n {\"name\": \"Bob\", \"major\": \"Computer Science\"},\n {\"name\": \"Alice\", \"major\": \"Computer Science\"},\n {\"name\": \"Tom\", \"major\": \"Mathematics\"},\n {\"name\": \"Jerry\", \"major\": \"Mathematics\"}]\n\n self.registration_system.students_registration_classes = {\"John\": [\"Algorithms\", \"Data Structures\"],\n \"Bob\": [\"Data Structures\", \"Algorithms\",\n \"Operating Systems\"],\n \"Alice\": [\"Data Structures\", \"Operating Systems\",\n \"Calculus\"],\n \"Tom\": [\"Calculus\", \"Linear Algebra\"],\n \"Jerry\": [\"Linear Algebra\", \"Statistics\"]}\n\n cs_most_popular_class = self.registration_system.get_most_popular_class_in_major(\"Computer Science\")\n math_most_popular_class = self.registration_system.get_most_popular_class_in_major(\"Mathematics\")\n self.assertEqual(cs_most_popular_class, \"Data Structures\")\n self.assertEqual(math_most_popular_class, \"Linear Algebra\")", "solution_code": "def get_most_popular_class_in_major(self, major):\n class_list = []\n for student in self.students:\n if student[\"major\"] == major:\n class_list += self.students_registration_classes[student[\"name\"]]\n most_popular_class = max(set(class_list), key=class_list.count)\n return most_popular_class", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.students", "self.students_registration_classes" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_23", "skeleton": "\nimport math\nfrom typing import List\n\nclass CombinationCalculator:\n \"\"\"\n This is a class that provides methods to calculate the number of combinations for a specific count, calculate all possible combinations, and generate combinations with a specified number of elements.\n \"\"\"\n\n def __init__(self, datas: List[str]):\n \"\"\"\n Initialize the calculator with a list of data.\n \"\"\"\n self.datas = datas\n\n @staticmethod\n def count(n: int, m: int) -> int:\n \"\"\"\n Calculate the number of combinations for a specific count.\n :param n: The total number of elements,int.\n :param m: The number of elements in each combination,int.\n :return: The number of combinations,int.\n >>> CombinationCalculator.count(4, 2)\n 6\n \"\"\"\n\n @staticmethod\n def count_all(n: int) -> int:\n \"\"\"\n Calculate the number of all possible combinations.\n :param n: The total number of elements,int.\n :return: The number of all possible combinations,int,if the number of combinations is greater than 2^63-1,return float(\"inf\").\n >>> CombinationCalculator.count_all(4)\n 15\n \"\"\"\n\n def select(self, m: int) -> List[List[str]]:\n \"\"\"\n Generate combinations with a specified number of elements.\n :param m: The number of elements in each combination,int.\n :return: A list of combinations,List[List[str]].\n >>> calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n >>> calc.select(2)\n [['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D'], ['C', 'D']]\n\n \"\"\"\n\n def select_all(self) -> List[List[str]]:\n \"\"\"\n Generate all possible combinations of selecting elements from the given data list,and it uses the select method.\n :return: A list of combinations,List[List[str]].\n >>> calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n >>> calc.select_all()\n [['A'], ['B'], ['C'], ['D'], ['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D'], ['C', 'D'], ['A', 'B', 'C'], ['A', 'B', 'D'], ['A', 'C', 'D'], ['B', 'C', 'D'], ['A', 'B', 'C', 'D']]\n\n \"\"\"\n\n def _select(self, dataIndex: int, resultList: List[str], resultIndex: int, result: List[List[str]]):\n \"\"\"\n Generate combinations with a specified number of elements by recursion.\n :param dataIndex: The index of the data to be selected,int.\n :param resultList: The list of elements in the combination,List[str].\n :param resultIndex: The index of the element in the combination,int.\n :param result: The list of combinations,List[List[str]].\n :return: None.\n >>> calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n >>> result = []\n >>> calc._select(0, [None] * 2, 0, result)\n >>> result\n [['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D'], ['C', 'D']]\n\n \"\"\"", "test": "import unittest\n\nclass CombinationCalculatorTestCount(unittest.TestCase):\n def test_count(self):\n self.assertEqual(CombinationCalculator.count(4, 2), 6)\n def test_count_2(self):\n self.assertEqual(CombinationCalculator.count(5, 3), 10)\n\n def test_count_3(self):\n self.assertEqual(CombinationCalculator.count(6, 6), 1)\n\n def test_count_4(self):\n self.assertEqual(CombinationCalculator.count(6, 0), 1)\n\n def test_count_5(self):\n self.assertEqual(CombinationCalculator.count(6, 3), 20)\n\nclass CombinationCalculatorTestCountAll(unittest.TestCase):\n def test_count_all(self):\n self.assertEqual(CombinationCalculator.count_all(4), 15)\n\n def test_count_all_2(self):\n self.assertEqual(CombinationCalculator.count_all(-1), False)\n\n def test_count_all_3(self):\n self.assertEqual(CombinationCalculator.count_all(65), False)\n\n def test_count_all_4(self):\n self.assertEqual(CombinationCalculator.count_all(0), 0)\n\n def test_count_all_5(self):\n self.assertEqual(CombinationCalculator.count_all(63), float(\"inf\"))\n\nclass CombinationCalculatorTestSelect(unittest.TestCase):\n def test_select(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n self.assertEqual(calc.count(4, 2), 6)\n\n def test_select_2(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n self.assertEqual(calc.count(5, 3), 10)\n\n def test_select_3(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n self.assertEqual(calc.count(6, 6), 1)\n\n def test_select_4(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n self.assertEqual(calc.count(6, 0), 1)\n\n def test_select_5(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n self.assertEqual(calc.count(6, 3), 20)\n\nclass CombinationCalculatorTestSelectAll(unittest.TestCase):\n def test_select_all(self):\n calc = CombinationCalculator([\"A\"])\n self.assertEqual(calc.select_all(), [['A']])\n\n def test_select_all_2(self):\n calc = CombinationCalculator([\"A\", \"B\"])\n self.assertEqual(calc.select_all(), [['A'], ['B'], ['A', 'B']])\n\n def test_select_all_3(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\"])\n self.assertEqual(calc.select_all(),[['A'], ['B'], ['C'], ['A', 'B'], ['A', 'C'], ['B', 'C'], ['A', 'B', 'C']])\n\n def test_select_all_4(self):\n calc = CombinationCalculator([])\n self.assertEqual(calc.select_all(),[])\n\n def test_select_all_5(self):\n calc = CombinationCalculator([\"B\"])\n self.assertEqual(calc.select_all(),[['B']])\n\n\nclass CombinationCalculatorTestSelect2(unittest.TestCase):\n def test_select2(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n result = []\n calc._select(0, [None] * 2, 0, result)\n self.assertEqual(result, [['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D'], ['C', 'D']])\n\n def test_select2_2(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n result = []\n calc._select(0, [None] * 3, 0, result)\n self.assertEqual(result, [['A', 'B', 'C'], ['A', 'B', 'D'], ['A', 'C', 'D'], ['B', 'C', 'D']])\n\n def test_select2_3(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n result = []\n calc._select(0, [None] * 1, 0, result)\n self.assertEqual(result, [['A'], ['B'], ['C'], ['D']])\n\n def test_select2_4(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n result = []\n calc._select(0, [None] * 0, 0, result)\n self.assertEqual(result, [[]])\n\n def test_select2_5(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n result = []\n calc._select(0, [None] * 4, 0, result)\n self.assertEqual(result, [['A', 'B', 'C', 'D']])\n\nclass CombinationCalculatorTestMain(unittest.TestCase):\n def test_main(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n self.assertEqual(calc.count(4, 2), 6)\n self.assertEqual(calc.count_all(4), 15)\n self.assertEqual(calc.select(2), [['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D'], ['C', 'D']])\n self.assertEqual(calc.select_all(), [['A'], ['B'], ['C'], ['D'], ['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D'], ['C', 'D'], ['A', 'B', 'C'], ['A', 'B', 'D'], ['A', 'C', 'D'], ['B', 'C', 'D'], ['A', 'B', 'C', 'D']])\n result = []\n calc._select(0, [None] * 2, 0, result)\n self.assertEqual(result, [['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D'], ['C', 'D']])", "solution_code": "import math\nfrom typing import List\n\nclass CombinationCalculator:\n def __init__(self, datas: List[str]):\n self.datas = datas\n\n @staticmethod\n def count(n: int, m: int) -> int:\n if m == 0 or n == m:\n return 1\n return math.factorial(n) // (math.factorial(n - m) * math.factorial(m))\n\n @staticmethod\n def count_all(n: int) -> int:\n if n < 0 or n > 63:\n return False\n return (1 << n) - 1 if n != 63 else float(\"inf\")\n\n def select(self, m: int) -> List[List[str]]:\n result = []\n self._select(0, [None] * m, 0, result)\n return result\n\n def select_all(self) -> List[List[str]]:\n result = []\n for i in range(1, len(self.datas) + 1):\n result.extend(self.select(i))\n return result\n\n def _select(self, dataIndex: int, resultList: List[str], resultIndex: int, result: List[List[str]]):\n resultLen = len(resultList)\n resultCount = resultIndex + 1\n if resultCount > resultLen:\n result.append(resultList.copy())\n return\n\n for i in range(dataIndex, len(self.datas) + resultCount - resultLen):\n resultList[resultIndex] = self.datas[i]\n self._select(i + 1, resultList, resultIndex + 1, result)", "import_statement": [ "import math", "from typing import List" ], "class_description": " \"\"\"\n This is a class that provides methods to calculate the number of combinations for a specific count, calculate all possible combinations, and generate combinations with a specified number of elements.\n \"\"\"\n", "class_name": "CombinationCalculator", "test_classes": [ "CombinationCalculatorTestCount", "CombinationCalculatorTestCountAll", "CombinationCalculatorTestSelect", "CombinationCalculatorTestSelectAll", "CombinationCalculatorTestSelect2", "CombinationCalculatorTestMain" ], "class_constructor": "class CombinationCalculator: \n def __init__(self, datas: List[str]):\n \"\"\"\n Initialize the calculator with a list of data.\n \"\"\"\n self.datas = datas\n\n @staticmethod\n", "fields": [ "self.datas" ], "methods_info": [ { "method_name": "count", "method_description": "def count(n: int, m: int) -> int:\n \"\"\"\n Calculate the number of combinations for a specific count.\n :param n: The total number of elements,int.\n :param m: The number of elements in each combination,int.\n :return: The number of combinations,int.\n >>> CombinationCalculator.count(4, 2)\n 6\n \"\"\"", "test_class": "CombinationCalculatorTestCount", "test_code": "class CombinationCalculatorTestCount(unittest.TestCase):\n def test_count(self):\n self.assertEqual(CombinationCalculator.count(4, 2), 6)\n def test_count_2(self):\n self.assertEqual(CombinationCalculator.count(5, 3), 10)\n\n def test_count_3(self):\n self.assertEqual(CombinationCalculator.count(6, 6), 1)\n\n def test_count_4(self):\n self.assertEqual(CombinationCalculator.count(6, 0), 1)\n\n def test_count_5(self):\n self.assertEqual(CombinationCalculator.count(6, 3), 20)", "solution_code": "def count(n: int, m: int) -> int:\n if m == 0 or n == m:\n return 1\n return math.factorial(n) // (math.factorial(n - m) * math.factorial(m))", "dependencies": { "Standalone": false, "lib_dependencies": [ "math" ], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "count_all", "method_description": "@staticmethod\n def count_all(n: int) -> int:\n \"\"\"\n Calculate the number of all possible combinations.\n :param n: The total number of elements,int.\n :return: The number of all possible combinations,int,if the number of combinations is greater than 2^63-1,return float(\"inf\").\n >>> CombinationCalculator.count_all(4)\n 15\n \"\"\"", "test_class": "CombinationCalculatorTestCountAll", "test_code": "class CombinationCalculatorTestCountAll(unittest.TestCase):\n def test_count_all(self):\n self.assertEqual(CombinationCalculator.count_all(4), 15)\n\n def test_count_all_2(self):\n self.assertEqual(CombinationCalculator.count_all(-1), False)\n\n def test_count_all_3(self):\n self.assertEqual(CombinationCalculator.count_all(65), False)\n\n def test_count_all_4(self):\n self.assertEqual(CombinationCalculator.count_all(0), 0)\n\n def test_count_all_5(self):\n self.assertEqual(CombinationCalculator.count_all(63), float(\"inf\"))", "solution_code": "@staticmethod\n def count_all(n: int) -> int:\n if n < 0 or n > 63:\n return False\n return (1 << n) - 1 if n != 63 else float(\"inf\")", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "select", "method_description": "def select(self, m: int) -> List[List[str]]:\n \"\"\"\n Generate combinations with a specified number of elements.\n :param m: The number of elements in each combination,int.\n :return: A list of combinations,List[List[str]].\n >>> calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n >>> calc.select(2)\n [['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D'], ['C', 'D']]\n\n \"\"\"", "test_class": "CombinationCalculatorTestSelect", "test_code": "class CombinationCalculatorTestSelect(unittest.TestCase):\n def test_select(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n self.assertEqual(calc.count(4, 2), 6)\n\n def test_select_2(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n self.assertEqual(calc.count(5, 3), 10)\n\n def test_select_3(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n self.assertEqual(calc.count(6, 6), 1)\n\n def test_select_4(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n self.assertEqual(calc.count(6, 0), 1)\n\n def test_select_5(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n self.assertEqual(calc.count(6, 3), 20)", "solution_code": "def select(self, m: int) -> List[List[str]]:\n result = []\n self._select(0, [None] * m, 0, result)\n return result", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "_select" ] } }, { "method_name": "select_all", "method_description": "def select_all(self) -> List[List[str]]:\n \"\"\"\n Generate all possible combinations of selecting elements from the given data list,and it uses the select method.\n :return: A list of combinations,List[List[str]].\n >>> calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n >>> calc.select_all()\n [['A'], ['B'], ['C'], ['D'], ['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D'], ['C', 'D'], ['A', 'B', 'C'], ['A', 'B', 'D'], ['A', 'C', 'D'], ['B', 'C', 'D'], ['A', 'B', 'C', 'D']]\n\n \"\"\"", "test_class": "CombinationCalculatorTestSelectAll", "test_code": "class CombinationCalculatorTestSelectAll(unittest.TestCase):\n def test_select_all(self):\n calc = CombinationCalculator([\"A\"])\n self.assertEqual(calc.select_all(), [['A']])\n\n def test_select_all_2(self):\n calc = CombinationCalculator([\"A\", \"B\"])\n self.assertEqual(calc.select_all(), [['A'], ['B'], ['A', 'B']])\n\n def test_select_all_3(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\"])\n self.assertEqual(calc.select_all(),[['A'], ['B'], ['C'], ['A', 'B'], ['A', 'C'], ['B', 'C'], ['A', 'B', 'C']])\n\n def test_select_all_4(self):\n calc = CombinationCalculator([])\n self.assertEqual(calc.select_all(),[])\n\n def test_select_all_5(self):\n calc = CombinationCalculator([\"B\"])\n self.assertEqual(calc.select_all(),[['B']])", "solution_code": "def select_all(self) -> List[List[str]]:\n result = []\n for i in range(1, len(self.datas) + 1):\n result.extend(self.select(i))\n return result", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.datas" ], "method_dependencies": [ "select" ] } }, { "method_name": "_select", "method_description": "def _select(self, dataIndex: int, resultList: List[str], resultIndex: int, result: List[List[str]]):\n \"\"\"\n Generate combinations with a specified number of elements by recursion.\n :param dataIndex: The index of the data to be selected,int.\n :param resultList: The list of elements in the combination,List[str].\n :param resultIndex: The index of the element in the combination,int.\n :param result: The list of combinations,List[List[str]].\n :return: None.\n >>> calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n >>> result = []\n >>> calc._select(0, [None] * 2, 0, result)\n >>> result\n [['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D'], ['C', 'D']]\n\n \"\"\"", "test_class": "CombinationCalculatorTestSelect2", "test_code": "class CombinationCalculatorTestSelect2(unittest.TestCase):\n def test_select2(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n result = []\n calc._select(0, [None] * 2, 0, result)\n self.assertEqual(result, [['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D'], ['C', 'D']])\n\n def test_select2_2(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n result = []\n calc._select(0, [None] * 3, 0, result)\n self.assertEqual(result, [['A', 'B', 'C'], ['A', 'B', 'D'], ['A', 'C', 'D'], ['B', 'C', 'D']])\n\n def test_select2_3(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n result = []\n calc._select(0, [None] * 1, 0, result)\n self.assertEqual(result, [['A'], ['B'], ['C'], ['D']])\n\n def test_select2_4(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n result = []\n calc._select(0, [None] * 0, 0, result)\n self.assertEqual(result, [[]])\n\n def test_select2_5(self):\n calc = CombinationCalculator([\"A\", \"B\", \"C\", \"D\"])\n result = []\n calc._select(0, [None] * 4, 0, result)\n self.assertEqual(result, [['A', 'B', 'C', 'D']])", "solution_code": "def _select(self, dataIndex: int, resultList: List[str], resultIndex: int, result: List[List[str]]):\n resultLen = len(resultList)\n resultCount = resultIndex + 1\n if resultCount > resultLen:\n result.append(resultList.copy())\n return\n\n for i in range(dataIndex, len(self.datas) + resultCount - resultLen):\n resultList[resultIndex] = self.datas[i]\n self._select(i + 1, resultList, resultIndex + 1, result)", "dependencies": { "Standalone": false, "lib_dependencies": [ "List" ], "field_dependencies": [ "self.datas" ], "method_dependencies": [ "select" ] } } ] }, { "task_id": "ClassEval_24", "skeleton": "\nclass ComplexCalculator:\n \"\"\"\n This is a class that implements addition, subtraction, multiplication, and division operations for complex numbers.\n \"\"\"\n\n\n def __init__(self):\n pass\n\n @staticmethod\n def add(c1, c2):\n \"\"\"\n Adds two complex numbers.\n :param c1: The first complex number,complex.\n :param c2: The second complex number,complex.\n :return: The sum of the two complex numbers,complex.\n >>> complexCalculator = ComplexCalculator()\n >>> complexCalculator.add(1+2j, 3+4j)\n (4+6j)\n\n \"\"\"\n\n @staticmethod\n def subtract(c1, c2):\n \"\"\"\n Subtracts two complex numbers.\n :param c1: The first complex number,complex.\n :param c2: The second complex number,complex.\n :return: The difference of the two complex numbers,complex.\n >>> complexCalculator = ComplexCalculator()\n >>> complexCalculator.subtract(1+2j, 3+4j)\n (-2-2j)\n\n \"\"\"\n\n @staticmethod\n def multiply(c1, c2):\n \"\"\"\n Multiplies two complex numbers.\n :param c1: The first complex number,complex.\n :param c2: The second complex number,complex.\n :return: The product of the two complex numbers,complex.\n >>> complexCalculator = ComplexCalculator()\n >>> complexCalculator.multiply(1+2j, 3+4j)\n (-5+10j)\n\n \"\"\"\n\n @staticmethod\n def divide(c1, c2):\n \"\"\"\n Divides two complex numbers.\n :param c1: The first complex number,complex.\n :param c2: The second complex number,complex.\n :return: The quotient of the two complex numbers,complex.\n >>> complexCalculator = ComplexCalculator()\n >>> complexCalculator.divide(1+2j, 3+4j)\n (0.44+0.08j)\n\n \"\"\"", "test": "import unittest\n\nclass ComplexCalculatorTestAdd(unittest.TestCase):\n def test_add(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.add(1+2j, 3+4j), (4+6j))\n\n def test_add_2(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.add(-1 - 2j, -3 - 4j), (-4 - 6j))\n\n def test_add_3(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.add(1-2j, 3-4j), (4-6j))\n\n def test_add_4(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.add(-1+2j, -3+4j), (-4+6j))\n\n def test_add_5(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.add(1+2j, -1-2j), (0+0j))\n\nclass ComplexCalculatorTestSubtract(unittest.TestCase):\n def test_subtract(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.subtract(1+2j, 3+4j), (-2-2j))\n\n def test_subtract_2(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.subtract(-1-2j, -3-4j), (2+2j))\n\n def test_subtract_3(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.subtract(1-2j, 3-4j), (-2+2j))\n\n def test_subtract_4(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.subtract(-1+2j, -3+4j), (2-2j))\n\n def test_subtract_5(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.subtract(1+2j, 1+2j), (0+0j))\n\nclass ComplexCalculatorTestMultiply(unittest.TestCase):\n def test_multiply(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.multiply(1+2j, 3+4j), (-5+10j))\n\n def test_multiply_2(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.multiply(-1-2j, -3-4j), (-5+10j))\n\n def test_multiply_3(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.multiply(1-2j, 3-4j), (-5-10j))\n\n def test_multiply_4(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.multiply(-1+2j, -3+4j), (-5-10j))\n\n def test_multiply_5(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.multiply(1+2j, -1-2j), (3-4j))\n\nclass ComplexCalculatorTestDivide(unittest.TestCase):\n def test_divide(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.divide(1+2j, 3+4j), (0.44+0.08j))\n\n def test_divide_2(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.divide(-1-2j, -3-4j), (0.44+0.08j))\n\n def test_divide_3(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.divide(1-2j, 3-4j), (0.44-0.08j))\n\n def test_divide_4(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.divide(-1+2j, -3+4j), (0.44-0.08j))\n\n def test_divide_5(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.divide(1+2j, -1-2j), (-1+0j))\n\nclass ComplexCalculatorTestMain(unittest.TestCase):\n def test_main(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.add(1+2j, 3+4j), (4+6j))\n self.assertEqual(complexCalculator.subtract(1+2j, 3+4j), (-2-2j))\n self.assertEqual(complexCalculator.multiply(1+2j, 3+4j), (-5+10j))\n self.assertEqual(complexCalculator.divide(1+2j, 3+4j), (0.44+0.08j))", "solution_code": "class ComplexCalculator:\n def __init__(self):\n pass\n\n @staticmethod\n def add(c1, c2):\n real = c1.real + c2.real\n imaginary = c1.imag + c2.imag\n answer = complex(real, imaginary)\n return answer\n \n @staticmethod\n def subtract(c1, c2):\n real = c1.real - c2.real\n imaginary = c1.imag - c2.imag\n return complex(real, imaginary)\n \n @staticmethod\n def multiply(c1, c2):\n real = c1.real * c2.real - c1.imag * c2.imag\n imaginary = c1.real * c2.imag + c1.imag * c2.real\n return complex(real, imaginary)\n \n @staticmethod\n def divide(c1, c2):\n denominator = c2.real**2 + c2.imag**2\n real = (c1.real * c2.real + c1.imag * c2.imag) / denominator\n imaginary = (c1.imag * c2.real - c1.real * c2.imag) / denominator\n return complex(real, imaginary)", "import_statement": [], "class_description": " \"\"\"\n This is a class that implements addition, subtraction, multiplication, and division operations for complex numbers.\n \"\"\"\n", "class_name": "ComplexCalculator", "test_classes": [ "ComplexCalculatorTestAdd", "ComplexCalculatorTestSubtract", "ComplexCalculatorTestMultiply", "ComplexCalculatorTestDivide", "ComplexCalculatorTestMain" ], "class_constructor": "class ComplexCalculator: \n def __init__(self):\n pass\n\n @staticmethod\n", "fields": [], "methods_info": [ { "method_name": "add", "method_description": "def add(c1, c2):\n \"\"\"\n Adds two complex numbers.\n :param c1: The first complex number,complex.\n :param c2: The second complex number,complex.\n :return: The sum of the two complex numbers,complex.\n >>> complexCalculator = ComplexCalculator()\n >>> complexCalculator.add(1+2j, 3+4j)\n (4+6j)\n\n \"\"\"", "test_class": "ComplexCalculatorTestAdd", "test_code": "class ComplexCalculatorTestAdd(unittest.TestCase):\n def test_add(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.add(1+2j, 3+4j), (4+6j))\n\n def test_add_2(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.add(-1 - 2j, -3 - 4j), (-4 - 6j))\n\n def test_add_3(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.add(1-2j, 3-4j), (4-6j))\n\n def test_add_4(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.add(-1+2j, -3+4j), (-4+6j))\n\n def test_add_5(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.add(1+2j, -1-2j), (0+0j))", "solution_code": "def add(c1, c2):\n real = c1.real + c2.real\n imaginary = c1.imag + c2.imag\n answer = complex(real, imaginary)\n return answer", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "subtract", "method_description": "@staticmethod\n def subtract(c1, c2):\n \"\"\"\n Subtracts two complex numbers.\n :param c1: The first complex number,complex.\n :param c2: The second complex number,complex.\n :return: The difference of the two complex numbers,complex.\n >>> complexCalculator = ComplexCalculator()\n >>> complexCalculator.subtract(1+2j, 3+4j)\n (-2-2j)\n\n \"\"\"", "test_class": "ComplexCalculatorTestSubtract", "test_code": "class ComplexCalculatorTestSubtract(unittest.TestCase):\n def test_subtract(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.subtract(1+2j, 3+4j), (-2-2j))\n\n def test_subtract_2(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.subtract(-1-2j, -3-4j), (2+2j))\n\n def test_subtract_3(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.subtract(1-2j, 3-4j), (-2+2j))\n\n def test_subtract_4(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.subtract(-1+2j, -3+4j), (2-2j))\n\n def test_subtract_5(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.subtract(1+2j, 1+2j), (0+0j))", "solution_code": "@staticmethod\n def subtract(c1, c2):\n real = c1.real - c2.real\n imaginary = c1.imag - c2.imag\n return complex(real, imaginary)", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "multiply", "method_description": "@staticmethod\n def multiply(c1, c2):\n \"\"\"\n Multiplies two complex numbers.\n :param c1: The first complex number,complex.\n :param c2: The second complex number,complex.\n :return: The product of the two complex numbers,complex.\n >>> complexCalculator = ComplexCalculator()\n >>> complexCalculator.multiply(1+2j, 3+4j)\n (-5+10j)\n\n \"\"\"", "test_class": "ComplexCalculatorTestMultiply", "test_code": "class ComplexCalculatorTestMultiply(unittest.TestCase):\n def test_multiply(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.multiply(1+2j, 3+4j), (-5+10j))\n\n def test_multiply_2(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.multiply(-1-2j, -3-4j), (-5+10j))\n\n def test_multiply_3(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.multiply(1-2j, 3-4j), (-5-10j))\n\n def test_multiply_4(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.multiply(-1+2j, -3+4j), (-5-10j))\n\n def test_multiply_5(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.multiply(1+2j, -1-2j), (3-4j))", "solution_code": "@staticmethod\n def multiply(c1, c2):\n real = c1.real * c2.real - c1.imag * c2.imag\n imaginary = c1.real * c2.imag + c1.imag * c2.real\n return complex(real, imaginary)", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "divide", "method_description": "@staticmethod\n def divide(c1, c2):\n \"\"\"\n Divides two complex numbers.\n :param c1: The first complex number,complex.\n :param c2: The second complex number,complex.\n :return: The quotient of the two complex numbers,complex.\n >>> complexCalculator = ComplexCalculator()\n >>> complexCalculator.divide(1+2j, 3+4j)\n (0.44+0.08j)\n\n \"\"\"", "test_class": "ComplexCalculatorTestDivide", "test_code": "class ComplexCalculatorTestDivide(unittest.TestCase):\n def test_divide(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.divide(1+2j, 3+4j), (0.44+0.08j))\n\n def test_divide_2(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.divide(-1-2j, -3-4j), (0.44+0.08j))\n\n def test_divide_3(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.divide(1-2j, 3-4j), (0.44-0.08j))\n\n def test_divide_4(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.divide(-1+2j, -3+4j), (0.44-0.08j))\n\n def test_divide_5(self):\n complexCalculator = ComplexCalculator()\n self.assertEqual(complexCalculator.divide(1+2j, -1-2j), (-1+0j))", "solution_code": "@staticmethod\n def divide(c1, c2):\n denominator = c2.real**2 + c2.imag**2\n real = (c1.real * c2.real + c1.imag * c2.imag) / denominator\n imaginary = (c1.imag * c2.real - c1.real * c2.imag) / denominator\n return complex(real, imaginary)", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_25", "skeleton": "\nimport json\n\nclass CookiesUtil:\n \"\"\"\n This is a class as utility for managing and manipulating Cookies, including methods for retrieving, saving, and setting Cookies data.\n \"\"\"\n\n def __init__(self, cookies_file):\n \"\"\"\n Initializes the CookiesUtil with the specified cookies file.\n :param cookies_file: The cookies file to use, str.\n \"\"\"\n self.cookies_file = cookies_file\n self.cookies = None\n\n def get_cookies(self, reponse):\n \"\"\"\n Gets the cookies from the specified response,and save it to cookies_file.\n :param reponse: The response to get cookies from, dict.\n >>> cookies_util = CookiesUtil('cookies.json')\n >>> cookies_util.get_cookies({'cookies': {'key1': 'value1', 'key2': 'value2'}})\n >>> cookies_util.cookies\n {'key1': 'value1', 'key2': 'value2'}\n\n \"\"\"\n\n def load_cookies(self):\n \"\"\"\n Loads the cookies from the cookies_file to the cookies data.\n :return: The cookies data, dict.\n >>> cookies_util = CookiesUtil('cookies.json')\n >>> cookies_util.load_cookies()\n {'key1': 'value1', 'key2': 'value2'}\n\n \"\"\"\n\n def _save_cookies(self):\n \"\"\"\n Saves the cookies to the cookies_file, and returns True if successful, False otherwise.\n :return: True if successful, False otherwise.\n >>> cookies_util = CookiesUtil('cookies.json')\n >>> cookies_util.cookies = {'key1': 'value1', 'key2': 'value2'}\n >>> cookies_util._save_cookies()\n True\n\n \"\"\"", "test": "import unittest\n\n\nclass CookiesUtilTestGetCookies(unittest.TestCase):\n\n def test_get_cookies(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.response = {'cookies': {'key1': 'value1', 'key2': 'value2'}}\n self.cookies_util.get_cookies(self.response)\n self.assertEqual(self.cookies_util.cookies, {'key1': 'value1', 'key2': 'value2'})\n\n def test_get_cookies_2(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.response = {'cookies': {'key1': 'value1', 'key2': 'value2'},\n 'cookies2': {'key3': 'value3', 'key4': 'value4'}}\n self.cookies_util.get_cookies(self.response)\n self.assertEqual(self.cookies_util.cookies, {'key1': 'value1', 'key2': 'value2'})\n\n def test_get_cookies_3(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.response = {'cookies': {'key1': 'value1', 'key2': 'value2'},\n 'cookies2': {'key3': 'value3', 'key4': 'value4'},\n 'cookies3': {'key5': 'value5', 'key6': 'value6'}}\n self.cookies_util.get_cookies(self.response)\n self.assertEqual(self.cookies_util.cookies, {'key1': 'value1', 'key2': 'value2'})\n\n def test_get_cookies_4(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.response = {'cookies': {'key1': 'value1', 'key2': 'value2'},\n 'cookies2': {'key3': 'value3', 'key4': 'value4'},\n 'cookies3': {'key5': 'value5', 'key6': 'value6'},\n 'cookies4': {'key7': 'value7', 'key8': 'value8'}}\n self.cookies_util.get_cookies(self.response)\n self.assertEqual(self.cookies_util.cookies, {'key1': 'value1', 'key2': 'value2'})\n\n def test_get_cookies_5(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.response = {'cookies': {'key1': 'value1', 'key2': 'value2'},\n 'cookies2': {'key3': 'value3', 'key4': 'value4'},\n 'cookies3': {'key5': 'value5', 'key6': 'value6'},\n 'cookies4': {'key7': 'value7', 'key8': 'value8'},\n 'cookies5': {'key9': 'value9', 'key10': 'value10'}}\n self.cookies_util.get_cookies(self.response)\n self.assertEqual(self.cookies_util.cookies, {'key1': 'value1', 'key2': 'value2'})\n\n\nclass CookiesUtilTestLoadCookies(unittest.TestCase):\n\n def test_load_cookies(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.assertEqual(self.cookies_util.load_cookies(), {'key1': 'value1', 'key2': 'value2'})\n\n def test_load_cookies_2(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'}}\n self.assertEqual(self.cookies_util.load_cookies(), {'key1': 'value1', 'key2': 'value2'})\n\n def test_load_cookies_3(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'},\n 'cookies2': {'key3': 'value3', 'key4': 'value4'}}\n self.assertEqual(self.cookies_util.load_cookies(), {'key1': 'value1', 'key2': 'value2'})\n\n def test_load_cookies_4(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'},\n 'cookies2': {'key3': 'value3', 'key4': 'value4'},\n 'cookies3': {'key5': 'value5', 'key6': 'value6'}}\n self.assertEqual(self.cookies_util.load_cookies(), {'key1': 'value1', 'key2': 'value2'})\n\n def test_load_cookies_5(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'},\n 'cookies2': {'key3': 'value3', 'key4': 'value4'},\n 'cookies3': {'key5': 'value5', 'key6': 'value6'},\n 'cookies4': {'key7': 'value7', 'key8': 'value8'}}\n self.assertEqual(self.cookies_util.load_cookies(), {'key1': 'value1', 'key2': 'value2'})\n\n def test_load_cookies_6(self):\n self.cookies_util = CookiesUtil('')\n self.assertEqual(self.cookies_util.load_cookies(), {})\n\n\nclass CookiesUtilTestSaveCookies(unittest.TestCase):\n def setUp(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'}}\n\n def test_save_cookies(self):\n self.assertTrue(self.cookies_util._save_cookies())\n\n def test_save_cookies_2(self):\n self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'},\n 'cookies2': {'key3': 'value3', 'key4': 'value4'}}\n self.assertTrue(self.cookies_util._save_cookies())\n\n def test_save_cookies_3(self):\n self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'},\n 'cookies2': {'key3': 'value3', 'key4': 'value4'},\n 'cookies3': {'key5': 'value5', 'key6': 'value6'}}\n self.assertTrue(self.cookies_util._save_cookies())\n\n def test_save_cookies_4(self):\n self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'},\n 'cookies2': {'key3': 'value3', 'key4': 'value4'},\n 'cookies3': {'key5': 'value5', 'key6': 'value6'},\n 'cookies4': {'key7': 'value7', 'key8': 'value8'}}\n self.assertTrue(self.cookies_util._save_cookies())\n\n def test_save_cookies_5(self):\n self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'},\n 'cookies2': {'key3': 'value3', 'key4': 'value4'},\n 'cookies3': {'key5': 'value5', 'key6': 'value6'},\n 'cookies4': {'key7': 'value7', 'key8': 'value8'},\n 'cookies5': {'key9': 'value9', 'key10': 'value10'}}\n self.assertTrue(self.cookies_util._save_cookies())\n\n def test_save_cookies_6(self):\n self.cookies_util = CookiesUtil('')\n self.assertFalse(self.cookies_util._save_cookies())\n\n\nclass CookiesUtilTestSetCookies(unittest.TestCase):\n def setUp(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'}}\n\n def test_set_cookies(self):\n request = {}\n self.cookies_util.set_cookies(request)\n self.assertEqual(request['cookies'], \"cookies={'key1': 'value1', 'key2': 'value2'}\")\n\n\nclass CookiesUtilTestMain(unittest.TestCase):\n def setUp(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.cookies_data = {'cookies': {'key1': 'value1', 'key2': 'value2'}}\n\n def test_main(self):\n self.cookies_util.get_cookies(self.cookies_data)\n self.assertEqual(self.cookies_util.cookies, {'key1': 'value1', 'key2': 'value2'})\n self.assertEqual(self.cookies_util.load_cookies(), {'key1': 'value1', 'key2': 'value2'})\n self.assertTrue(self.cookies_util._save_cookies())", "solution_code": "import json\n\nclass CookiesUtil:\n def __init__(self, cookies_file):\n self.cookies_file = cookies_file\n self.cookies = None\n\n def get_cookies(self, reponse):\n self.cookies = reponse['cookies']\n self._save_cookies()\n\n def load_cookies(self):\n try:\n with open(self.cookies_file, 'r') as file:\n cookies_data = json.load(file)\n return cookies_data\n except FileNotFoundError:\n return {}\n\n def _save_cookies(self):\n try:\n with open(self.cookies_file, 'w') as file:\n json.dump(self.cookies, file)\n return True\n except:\n return False\n\n def set_cookies(self, request):\n request['cookies'] = '; '.join([f'{key}={value}' for key, value in self.cookies.items()])", "import_statement": [ "import json" ], "class_description": " \"\"\"\n This is a class as utility for managing and manipulating Cookies, including methods for retrieving, saving, and setting Cookies data.\n \"\"\"\n", "class_name": "CookiesUtil", "test_classes": [ "CookiesUtilTestGetCookies", "CookiesUtilTestLoadCookies", "CookiesUtilTestSaveCookies", "CookiesUtilTestSetCookies", "CookiesUtilTestMain" ], "class_constructor": "class CookiesUtil: \n def __init__(self, cookies_file):\n \"\"\"\n Initializes the CookiesUtil with the specified cookies file.\n :param cookies_file: The cookies file to use, str.\n \"\"\"\n self.cookies_file = cookies_file\n self.cookies = None\n\n", "fields": [ "self.cookies", "self.cookies_file" ], "methods_info": [ { "method_name": "get_cookies", "method_description": "def get_cookies(self, reponse):\n \"\"\"\n Gets the cookies from the specified response,and save it to cookies_file.\n :param reponse: The response to get cookies from, dict.\n >>> cookies_util = CookiesUtil('cookies.json')\n >>> cookies_util.get_cookies({'cookies': {'key1': 'value1', 'key2': 'value2'}})\n >>> cookies_util.cookies\n {'key1': 'value1', 'key2': 'value2'}\n\n \"\"\"", "test_class": "CookiesUtilTestGetCookies", "test_code": "class CookiesUtilTestGetCookies(unittest.TestCase):\n\n def test_get_cookies(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.response = {'cookies': {'key1': 'value1', 'key2': 'value2'}}\n self.cookies_util.get_cookies(self.response)\n self.assertEqual(self.cookies_util.cookies, {'key1': 'value1', 'key2': 'value2'})\n\n def test_get_cookies_2(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.response = {'cookies': {'key1': 'value1', 'key2': 'value2'},\n 'cookies2': {'key3': 'value3', 'key4': 'value4'}}\n self.cookies_util.get_cookies(self.response)\n self.assertEqual(self.cookies_util.cookies, {'key1': 'value1', 'key2': 'value2'})\n\n def test_get_cookies_3(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.response = {'cookies': {'key1': 'value1', 'key2': 'value2'},\n 'cookies2': {'key3': 'value3', 'key4': 'value4'},\n 'cookies3': {'key5': 'value5', 'key6': 'value6'}}\n self.cookies_util.get_cookies(self.response)\n self.assertEqual(self.cookies_util.cookies, {'key1': 'value1', 'key2': 'value2'})\n\n def test_get_cookies_4(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.response = {'cookies': {'key1': 'value1', 'key2': 'value2'},\n 'cookies2': {'key3': 'value3', 'key4': 'value4'},\n 'cookies3': {'key5': 'value5', 'key6': 'value6'},\n 'cookies4': {'key7': 'value7', 'key8': 'value8'}}\n self.cookies_util.get_cookies(self.response)\n self.assertEqual(self.cookies_util.cookies, {'key1': 'value1', 'key2': 'value2'})\n\n def test_get_cookies_5(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.response = {'cookies': {'key1': 'value1', 'key2': 'value2'},\n 'cookies2': {'key3': 'value3', 'key4': 'value4'},\n 'cookies3': {'key5': 'value5', 'key6': 'value6'},\n 'cookies4': {'key7': 'value7', 'key8': 'value8'},\n 'cookies5': {'key9': 'value9', 'key10': 'value10'}}\n self.cookies_util.get_cookies(self.response)\n self.assertEqual(self.cookies_util.cookies, {'key1': 'value1', 'key2': 'value2'})", "solution_code": "def get_cookies(self, reponse):\n self.cookies = reponse['cookies']\n self._save_cookies()", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.cookies" ], "method_dependencies": [ "_save_cookies" ] } }, { "method_name": "load_cookies", "method_description": "def load_cookies(self):\n \"\"\"\n Loads the cookies from the cookies_file to the cookies data.\n :return: The cookies data, dict.\n >>> cookies_util = CookiesUtil('cookies.json')\n >>> cookies_util.load_cookies()\n {'key1': 'value1', 'key2': 'value2'}\n\n \"\"\"", "test_class": "CookiesUtilTestLoadCookies", "test_code": "class CookiesUtilTestLoadCookies(unittest.TestCase):\n\n def test_load_cookies(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.assertEqual(self.cookies_util.load_cookies(), {'key1': 'value1', 'key2': 'value2'})\n\n def test_load_cookies_2(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'}}\n self.assertEqual(self.cookies_util.load_cookies(), {'key1': 'value1', 'key2': 'value2'})\n\n def test_load_cookies_3(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'},\n 'cookies2': {'key3': 'value3', 'key4': 'value4'}}\n self.assertEqual(self.cookies_util.load_cookies(), {'key1': 'value1', 'key2': 'value2'})\n\n def test_load_cookies_4(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'},\n 'cookies2': {'key3': 'value3', 'key4': 'value4'},\n 'cookies3': {'key5': 'value5', 'key6': 'value6'}}\n self.assertEqual(self.cookies_util.load_cookies(), {'key1': 'value1', 'key2': 'value2'})\n\n def test_load_cookies_5(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'},\n 'cookies2': {'key3': 'value3', 'key4': 'value4'},\n 'cookies3': {'key5': 'value5', 'key6': 'value6'},\n 'cookies4': {'key7': 'value7', 'key8': 'value8'}}\n self.assertEqual(self.cookies_util.load_cookies(), {'key1': 'value1', 'key2': 'value2'})\n\n def test_load_cookies_6(self):\n self.cookies_util = CookiesUtil('')\n self.assertEqual(self.cookies_util.load_cookies(), {})", "solution_code": "def load_cookies(self):\n try:\n with open(self.cookies_file, 'r') as file:\n cookies_data = json.load(file)\n return cookies_data\n except FileNotFoundError:\n return {}", "dependencies": { "Standalone": false, "lib_dependencies": [ "json" ], "field_dependencies": [ "self.cookies", "self.cookies_file" ], "method_dependencies": [] } }, { "method_name": "_save_cookies", "method_description": "def _save_cookies(self):\n \"\"\"\n Saves the cookies to the cookies_file, and returns True if successful, False otherwise.\n :return: True if successful, False otherwise.\n >>> cookies_util = CookiesUtil('cookies.json')\n >>> cookies_util.cookies = {'key1': 'value1', 'key2': 'value2'}\n >>> cookies_util._save_cookies()\n True\n\n \"\"\"", "test_class": "CookiesUtilTestSaveCookies", "test_code": "class CookiesUtilTestSaveCookies(unittest.TestCase):\n def setUp(self):\n self.cookies_util = CookiesUtil('cookies.json')\n self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'}}\n\n def test_save_cookies(self):\n self.assertTrue(self.cookies_util._save_cookies())\n\n def test_save_cookies_2(self):\n self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'},\n 'cookies2': {'key3': 'value3', 'key4': 'value4'}}\n self.assertTrue(self.cookies_util._save_cookies())\n\n def test_save_cookies_3(self):\n self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'},\n 'cookies2': {'key3': 'value3', 'key4': 'value4'},\n 'cookies3': {'key5': 'value5', 'key6': 'value6'}}\n self.assertTrue(self.cookies_util._save_cookies())\n\n def test_save_cookies_4(self):\n self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'},\n 'cookies2': {'key3': 'value3', 'key4': 'value4'},\n 'cookies3': {'key5': 'value5', 'key6': 'value6'},\n 'cookies4': {'key7': 'value7', 'key8': 'value8'}}\n self.assertTrue(self.cookies_util._save_cookies())\n\n def test_save_cookies_5(self):\n self.cookies_util.cookies = {'cookies': {'key1': 'value1', 'key2': 'value2'},\n 'cookies2': {'key3': 'value3', 'key4': 'value4'},\n 'cookies3': {'key5': 'value5', 'key6': 'value6'},\n 'cookies4': {'key7': 'value7', 'key8': 'value8'},\n 'cookies5': {'key9': 'value9', 'key10': 'value10'}}\n self.assertTrue(self.cookies_util._save_cookies())\n\n def test_save_cookies_6(self):\n self.cookies_util = CookiesUtil('')\n self.assertFalse(self.cookies_util._save_cookies())", "solution_code": "def _save_cookies(self):\n try:\n with open(self.cookies_file, 'w') as file:\n json.dump(self.cookies, file)\n return True\n except:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [ "json" ], "field_dependencies": [ "self.cookies", "self.cookies_file" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_26", "skeleton": "\nimport csv\n\nclass CSVProcessor:\n \"\"\"\n This is a class for processing CSV files, including readring and writing CSV data, as well as processing specific operations and saving as a new CSV file.\n \"\"\"\n\n\n def __init__(self):\n pass\n\n def read_csv(self, file_name):\n \"\"\"\n Read the csv file by file_name, get the title and data from it\n :param file_name: str, name of the csv file\n :return title, data: (list, list), first row is title, the rest is data\n >>> csvProcessor = CSVProcessor()\n >>> csvProcessor.read_csv('read_test.csv')\n (['a', 'b', 'c', 'd'], [['hElLo', 'YoU', 'ME', 'LoW']])\n \"\"\"\n\n def write_csv(self, data, file_name):\n \"\"\"\n Write data into a csv file.\n :param file_name: str, name of the csv file\n :return:int, if success return 1, or 0 otherwise\n >>> csvProcessor = CSVProcessor()\n >>> csvProcessor.write_csv([['a', 'b', 'c', 'd'], ['1', '2', '3', '4']], 'write_test.csv')\n 1\n \"\"\"\n\n def process_csv_data(self, N, save_file_name):\n \"\"\"\n Read a csv file into variable title and data.\n Only remain the N th (from 0) column data and Capitalize them, store the title and new data into a new csv file.\n Add '_process' suffix after old file name, as a new file name.\n :param N: int, the N th column(from 0)\n :param save_file_name, the name of file that needs to be processed.\n :return:int, if success return 1, or 0 otherwise\n >>> csvProcessor = CSVProcessor()\n >>> csvProcessor.read_csv('read_test.csv')\n (['a', 'b', 'c', 'd'], [['hElLo', 'YoU', 'ME', 'LoW']])\n >>> csvProcessor.process_csv_data(0, 'read_test.csv')\n 1\n >>> csvProcessor.read_csv('read_test_process.csv')\n (['a', 'b', 'c', 'd'], [['HELLO']])\n \"\"\"", "test": "import unittest\nimport os\n\n\nclass CSVProcessorTestReadCSV(unittest.TestCase):\n def test_read_csv_1(self):\n self.file = 'read_test.csv'\n\n with open(self.file, 'w') as f:\n f.write('a,b,c,d\\nhElLo,YoU,ME,LoW')\n\n expected_title = ['a', 'b', 'c', 'd']\n expected_data = [['hElLo', 'YoU', 'ME', 'LoW']]\n csvProcessor = CSVProcessor()\n title, data = csvProcessor.read_csv(self.file)\n self.assertEqual(expected_data, data)\n self.assertEqual(expected_title, title)\n\n def test_read_csv_2(self):\n self.file = 'read_test.csv'\n with open(self.file, 'w') as f:\n f.write('1234\\nhElLo,YoU,ME,LoW')\n\n expected_title = ['1234']\n expected_data = [['hElLo', 'YoU', 'ME', 'LoW']]\n csvProcessor = CSVProcessor()\n title, data = csvProcessor.read_csv(self.file)\n self.assertEqual(expected_data, data)\n self.assertEqual(expected_title, title)\n\n def test_read_csv_3(self):\n self.file = 'read_test.csv'\n\n with open(self.file, 'w') as f:\n f.write('title\\nhElLo,YoU,ME,LoW')\n\n expected_title = ['title']\n expected_data = [['hElLo', 'YoU', 'ME', 'LoW']]\n csvProcessor = CSVProcessor()\n title, data = csvProcessor.read_csv(self.file)\n self.assertEqual(expected_data, data)\n self.assertEqual(expected_title, title)\n\n def test_read_csv_4(self):\n self.file = 'read_test.csv'\n\n with open(self.file, 'w') as f:\n f.write('title4\\nhElLo,YoU,ME,LoW')\n\n expected_title = ['title4']\n expected_data = [['hElLo', 'YoU', 'ME', 'LoW']]\n csvProcessor = CSVProcessor()\n title, data = csvProcessor.read_csv(self.file)\n self.assertEqual(expected_data, data)\n self.assertEqual(expected_title, title)\n\n def test_read_csv_5(self):\n self.file = 'read_test.csv'\n\n with open(self.file, 'w') as f:\n f.write('title5\\nhElLo,YoU,ME,LoW')\n\n expected_title = ['title5']\n expected_data = [['hElLo', 'YoU', 'ME', 'LoW']]\n csvProcessor = CSVProcessor()\n title, data = csvProcessor.read_csv(self.file)\n self.assertEqual(expected_data, data)\n self.assertEqual(expected_title, title)\n\n\nclass CSVProcessorTestWriteCSV(unittest.TestCase):\n def test_write_csv_1(self):\n self.file = 'read_test.csv'\n\n file_path = self.file\n csvProcessor = CSVProcessor()\n data = [['a', 'b', 'c', 'd'], ['1', '2', '3', '4']]\n # assert return value\n self.assertEqual(1, csvProcessor.write_csv(data, file_path))\n\n # read to test if write correctly\n read_title, read_data = csvProcessor.read_csv(file_path)\n self.assertEqual(read_title, data[0])\n self.assertEqual(read_data[0], data[1])\n os.remove(file_path)\n\n def test_write_csv_2(self):\n self.file = 'read_test.csv'\n\n file_path = self.file\n csvProcessor = CSVProcessor()\n data = [['aa', 'bb', 'cc', 'dd'], ['1', '2', '3', '4']]\n # assert return value\n self.assertEqual(1, csvProcessor.write_csv(data, file_path))\n\n # read to test if write correctly\n read_title, read_data = csvProcessor.read_csv(file_path)\n self.assertEqual(read_title, data[0])\n self.assertEqual(read_data[0], data[1])\n os.remove(file_path)\n\n def test_write_csv_3(self):\n self.file = 'read_test.csv'\n\n file_path = self.file\n csvProcessor = CSVProcessor()\n data = [['a', 'b', 'c', 'd'], ['11', '22', '33', '44']]\n # assert return value\n self.assertEqual(1, csvProcessor.write_csv(data, file_path))\n\n # read to test if write correctly\n read_title, read_data = csvProcessor.read_csv(file_path)\n self.assertEqual(read_title, data[0])\n self.assertEqual(read_data[0], data[1])\n os.remove(file_path)\n\n def test_write_csv_4(self):\n self.file = 'read_test.csv'\n\n file_path = self.file\n csvProcessor = CSVProcessor()\n data = [['e', 'f', 'g', 'h'], ['1', '2', '3', '4']]\n # assert return value\n self.assertEqual(1, csvProcessor.write_csv(data, file_path))\n\n # read to test if write correctly\n read_title, read_data = csvProcessor.read_csv(file_path)\n self.assertEqual(read_title, data[0])\n self.assertEqual(read_data[0], data[1])\n os.remove(file_path)\n\n def test_write_csv_5(self):\n self.file = 'read_test.csv'\n\n file_path = self.file\n csvProcessor = CSVProcessor()\n data = [['a', 'b', 'c', 'd'], ['5', '6', '7', '8']]\n # assert return value\n self.assertEqual(1, csvProcessor.write_csv(data, file_path))\n\n # read to test if write correctly\n read_title, read_data = csvProcessor.read_csv(file_path)\n self.assertEqual(read_title, data[0])\n self.assertEqual(read_data[0], data[1])\n os.remove(file_path)\n\n def test_write_csv_6(self):\n self.file = ''\n file_path = self.file\n csvProcessor = CSVProcessor()\n # assert return value\n self.assertEqual(0, csvProcessor.write_csv([], file_path))\n\n\nclass CSVProcessorTestProcessCSVData(unittest.TestCase):\n def setUp(self) -> None:\n self.file = 'read_test.csv'\n self.file_process = 'read_test_process.csv'\n with open(self.file, 'w') as f:\n f.write('a,b,c,d\\nhElLo,YoU,ME,LoW,aBc')\n\n def test_process_csv_data_1(self):\n title = ['a', 'b', 'c', 'd']\n data = ['HELLO']\n csvProcessor = CSVProcessor()\n self.assertEqual(1, csvProcessor.process_csv_data(0, self.file))\n\n read_title, read_data = csvProcessor.read_csv(self.file_process)\n self.assertEqual(read_title, title)\n self.assertEqual(read_data[0], data)\n\n def test_process_csv_data_2(self):\n title = ['a', 'b', 'c', 'd']\n data = ['YOU']\n csvProcessor = CSVProcessor()\n self.assertEqual(1, csvProcessor.process_csv_data(1, self.file))\n\n read_title, read_data = csvProcessor.read_csv(self.file_process)\n self.assertEqual(read_title, title)\n self.assertEqual(read_data[0], data)\n\n def test_process_csv_data_3(self):\n title = ['a', 'b', 'c', 'd']\n data = ['ME']\n csvProcessor = CSVProcessor()\n self.assertEqual(1, csvProcessor.process_csv_data(2, self.file))\n\n read_title, read_data = csvProcessor.read_csv(self.file_process)\n self.assertEqual(read_title, title)\n self.assertEqual(read_data[0], data)\n\n def test_process_csv_data_4(self):\n title = ['a', 'b', 'c', 'd']\n data = ['LOW']\n csvProcessor = CSVProcessor()\n self.assertEqual(1, csvProcessor.process_csv_data(3, self.file))\n\n read_title, read_data = csvProcessor.read_csv(self.file_process)\n self.assertEqual(read_title, title)\n self.assertEqual(read_data[0], data)\n\n def test_process_csv_data_5(self):\n title = ['a', 'b', 'c', 'd']\n data = ['ABC']\n csvProcessor = CSVProcessor()\n self.assertEqual(1, csvProcessor.process_csv_data(4, self.file))\n\n read_title, read_data = csvProcessor.read_csv(self.file_process)\n self.assertEqual(read_title, title)\n self.assertEqual(read_data[0], data)\n\n\nclass CSVProcessorTestMain(unittest.TestCase):\n def setUp(self) -> None:\n self.file = 'test.csv'\n self.file_process = 'test_process.csv'\n with open(self.file, 'w') as f:\n f.write('a,b,c,d\\nhElLo,YoU,ME,LoW')\n\n def test_main(self):\n csvProcessor = CSVProcessor()\n data = [['a', 'b', 'c', 'd'], ['hElLo', 'YoU', 'ME', 'LoW']]\n # assert return value\n self.assertEqual(1, csvProcessor.write_csv(data, self.file))\n expected_title = ['a', 'b', 'c', 'd']\n expected_data = [['hElLo', 'YoU', 'ME', 'LoW']]\n title, data = csvProcessor.read_csv(self.file)\n self.assertEqual(expected_data, data)\n self.assertEqual(expected_title, title)\n\n title = ['a', 'b', 'c', 'd']\n data = ['HELLO']\n self.assertEqual(1, csvProcessor.process_csv_data(0, self.file))\n\n read_title, read_data = csvProcessor.read_csv(self.file_process)\n self.assertEqual(read_title, title)\n self.assertEqual(read_data[0], data)", "solution_code": "import csv\n\n\nclass CSVProcessor:\n\n def __init__(self):\n pass\n\n def read_csv(self, file_name):\n data = []\n with open(file_name, 'r') as file:\n reader = csv.reader(file)\n title = next(reader)\n for row in reader:\n data.append(row)\n return title, data\n\n def write_csv(self, data, file_name):\n try:\n with open(file_name, 'w', newline='') as file:\n writer = csv.writer(file)\n writer.writerows(data)\n return 1\n except:\n return 0\n\n def process_csv_data(self, N, save_file_name):\n title, data = self.read_csv(save_file_name)\n column_data = [row[N] for row in data]\n column_data = [row.upper() for row in column_data]\n new_data = [title, column_data]\n return self.write_csv(new_data, save_file_name.split('.')[0] + '_process.csv')", "import_statement": [ "import csv" ], "class_description": " \"\"\"\n This is a class for processing CSV files, including readring and writing CSV data, as well as processing specific operations and saving as a new CSV file.\n \"\"\"\n", "class_name": "CSVProcessor", "test_classes": [ "CSVProcessorTestReadCSV", "CSVProcessorTestWriteCSV", "CSVProcessorTestProcessCSVData", "CSVProcessorTestMain" ], "class_constructor": "class CSVProcessor: \n def __init__(self):\n pass\n\n", "fields": [], "methods_info": [ { "method_name": "read_csv", "method_description": "def read_csv(self, file_name):\n \"\"\"\n Read the csv file by file_name, get the title and data from it\n :param file_name: str, name of the csv file\n :return title, data: (list, list), first row is title, the rest is data\n >>> csvProcessor = CSVProcessor()\n >>> csvProcessor.read_csv('read_test.csv')\n (['a', 'b', 'c', 'd'], [['hElLo', 'YoU', 'ME', 'LoW']])\n \"\"\"", "test_class": "CSVProcessorTestReadCSV", "test_code": "class CSVProcessorTestReadCSV(unittest.TestCase):\n def test_read_csv_1(self):\n self.file = 'read_test.csv'\n\n with open(self.file, 'w') as f:\n f.write('a,b,c,d\\nhElLo,YoU,ME,LoW')\n\n expected_title = ['a', 'b', 'c', 'd']\n expected_data = [['hElLo', 'YoU', 'ME', 'LoW']]\n csvProcessor = CSVProcessor()\n title, data = csvProcessor.read_csv(self.file)\n self.assertEqual(expected_data, data)\n self.assertEqual(expected_title, title)\n\n def test_read_csv_2(self):\n self.file = 'read_test.csv'\n with open(self.file, 'w') as f:\n f.write('1234\\nhElLo,YoU,ME,LoW')\n\n expected_title = ['1234']\n expected_data = [['hElLo', 'YoU', 'ME', 'LoW']]\n csvProcessor = CSVProcessor()\n title, data = csvProcessor.read_csv(self.file)\n self.assertEqual(expected_data, data)\n self.assertEqual(expected_title, title)\n\n def test_read_csv_3(self):\n self.file = 'read_test.csv'\n\n with open(self.file, 'w') as f:\n f.write('title\\nhElLo,YoU,ME,LoW')\n\n expected_title = ['title']\n expected_data = [['hElLo', 'YoU', 'ME', 'LoW']]\n csvProcessor = CSVProcessor()\n title, data = csvProcessor.read_csv(self.file)\n self.assertEqual(expected_data, data)\n self.assertEqual(expected_title, title)\n\n def test_read_csv_4(self):\n self.file = 'read_test.csv'\n\n with open(self.file, 'w') as f:\n f.write('title4\\nhElLo,YoU,ME,LoW')\n\n expected_title = ['title4']\n expected_data = [['hElLo', 'YoU', 'ME', 'LoW']]\n csvProcessor = CSVProcessor()\n title, data = csvProcessor.read_csv(self.file)\n self.assertEqual(expected_data, data)\n self.assertEqual(expected_title, title)\n\n def test_read_csv_5(self):\n self.file = 'read_test.csv'\n\n with open(self.file, 'w') as f:\n f.write('title5\\nhElLo,YoU,ME,LoW')\n\n expected_title = ['title5']\n expected_data = [['hElLo', 'YoU', 'ME', 'LoW']]\n csvProcessor = CSVProcessor()\n title, data = csvProcessor.read_csv(self.file)\n self.assertEqual(expected_data, data)\n self.assertEqual(expected_title, title)", "solution_code": "def read_csv(self, file_name):\n data = []\n with open(file_name, 'r') as file:\n reader = csv.reader(file)\n title = next(reader)\n for row in reader:\n data.append(row)\n return title, data", "dependencies": { "Standalone": false, "lib_dependencies": [ "csv" ], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "write_csv", "method_description": "def write_csv(self, data, file_name):\n \"\"\"\n Write data into a csv file.\n :param file_name: str, name of the csv file\n :return:int, if success return 1, or 0 otherwise\n >>> csvProcessor = CSVProcessor()\n >>> csvProcessor.write_csv([['a', 'b', 'c', 'd'], ['1', '2', '3', '4']], 'write_test.csv')\n 1\n \"\"\"", "test_class": "CSVProcessorTestWriteCSV", "test_code": "class CSVProcessorTestWriteCSV(unittest.TestCase):\n def test_write_csv_1(self):\n self.file = 'read_test.csv'\n\n file_path = self.file\n csvProcessor = CSVProcessor()\n data = [['a', 'b', 'c', 'd'], ['1', '2', '3', '4']]\n # assert return value\n self.assertEqual(1, csvProcessor.write_csv(data, file_path))\n\n # read to test if write correctly\n read_title, read_data = csvProcessor.read_csv(file_path)\n self.assertEqual(read_title, data[0])\n self.assertEqual(read_data[0], data[1])\n os.remove(file_path)\n\n def test_write_csv_2(self):\n self.file = 'read_test.csv'\n\n file_path = self.file\n csvProcessor = CSVProcessor()\n data = [['aa', 'bb', 'cc', 'dd'], ['1', '2', '3', '4']]\n # assert return value\n self.assertEqual(1, csvProcessor.write_csv(data, file_path))\n\n # read to test if write correctly\n read_title, read_data = csvProcessor.read_csv(file_path)\n self.assertEqual(read_title, data[0])\n self.assertEqual(read_data[0], data[1])\n os.remove(file_path)\n\n def test_write_csv_3(self):\n self.file = 'read_test.csv'\n\n file_path = self.file\n csvProcessor = CSVProcessor()\n data = [['a', 'b', 'c', 'd'], ['11', '22', '33', '44']]\n # assert return value\n self.assertEqual(1, csvProcessor.write_csv(data, file_path))\n\n # read to test if write correctly\n read_title, read_data = csvProcessor.read_csv(file_path)\n self.assertEqual(read_title, data[0])\n self.assertEqual(read_data[0], data[1])\n os.remove(file_path)\n\n def test_write_csv_4(self):\n self.file = 'read_test.csv'\n\n file_path = self.file\n csvProcessor = CSVProcessor()\n data = [['e', 'f', 'g', 'h'], ['1', '2', '3', '4']]\n # assert return value\n self.assertEqual(1, csvProcessor.write_csv(data, file_path))\n\n # read to test if write correctly\n read_title, read_data = csvProcessor.read_csv(file_path)\n self.assertEqual(read_title, data[0])\n self.assertEqual(read_data[0], data[1])\n os.remove(file_path)\n\n def test_write_csv_5(self):\n self.file = 'read_test.csv'\n\n file_path = self.file\n csvProcessor = CSVProcessor()\n data = [['a', 'b', 'c', 'd'], ['5', '6', '7', '8']]\n # assert return value\n self.assertEqual(1, csvProcessor.write_csv(data, file_path))\n\n # read to test if write correctly\n read_title, read_data = csvProcessor.read_csv(file_path)\n self.assertEqual(read_title, data[0])\n self.assertEqual(read_data[0], data[1])\n os.remove(file_path)\n\n def test_write_csv_6(self):\n self.file = ''\n file_path = self.file\n csvProcessor = CSVProcessor()\n # assert return value\n self.assertEqual(0, csvProcessor.write_csv([], file_path))", "solution_code": "def write_csv(self, data, file_name):\n try:\n with open(file_name, 'w', newline='') as file:\n writer = csv.writer(file)\n writer.writerows(data)\n return 1\n except:\n return 0", "dependencies": { "Standalone": false, "lib_dependencies": [ "csv" ], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "process_csv_data", "method_description": "def process_csv_data(self, N, save_file_name):\n \"\"\"\n Read a csv file into variable title and data.\n Only remain the N th (from 0) column data and Capitalize them, store the title and new data into a new csv file.\n Add '_process' suffix after old file name, as a new file name.\n :param N: int, the N th column(from 0)\n :param save_file_name, the name of file that needs to be processed.\n :return:int, if success return 1, or 0 otherwise\n >>> csvProcessor = CSVProcessor()\n >>> csvProcessor.read_csv('read_test.csv')\n (['a', 'b', 'c', 'd'], [['hElLo', 'YoU', 'ME', 'LoW']])\n >>> csvProcessor.process_csv_data(0, 'read_test.csv')\n 1\n >>> csvProcessor.read_csv('read_test_process.csv')\n (['a', 'b', 'c', 'd'], [['HELLO']])\n \"\"\"", "test_class": "CSVProcessorTestProcessCSVData", "test_code": "class CSVProcessorTestProcessCSVData(unittest.TestCase):\n def setUp(self) -> None:\n self.file = 'read_test.csv'\n self.file_process = 'read_test_process.csv'\n with open(self.file, 'w') as f:\n f.write('a,b,c,d\\nhElLo,YoU,ME,LoW,aBc')\n\n def test_process_csv_data_1(self):\n title = ['a', 'b', 'c', 'd']\n data = ['HELLO']\n csvProcessor = CSVProcessor()\n self.assertEqual(1, csvProcessor.process_csv_data(0, self.file))\n\n read_title, read_data = csvProcessor.read_csv(self.file_process)\n self.assertEqual(read_title, title)\n self.assertEqual(read_data[0], data)\n\n def test_process_csv_data_2(self):\n title = ['a', 'b', 'c', 'd']\n data = ['YOU']\n csvProcessor = CSVProcessor()\n self.assertEqual(1, csvProcessor.process_csv_data(1, self.file))\n\n read_title, read_data = csvProcessor.read_csv(self.file_process)\n self.assertEqual(read_title, title)\n self.assertEqual(read_data[0], data)\n\n def test_process_csv_data_3(self):\n title = ['a', 'b', 'c', 'd']\n data = ['ME']\n csvProcessor = CSVProcessor()\n self.assertEqual(1, csvProcessor.process_csv_data(2, self.file))\n\n read_title, read_data = csvProcessor.read_csv(self.file_process)\n self.assertEqual(read_title, title)\n self.assertEqual(read_data[0], data)\n\n def test_process_csv_data_4(self):\n title = ['a', 'b', 'c', 'd']\n data = ['LOW']\n csvProcessor = CSVProcessor()\n self.assertEqual(1, csvProcessor.process_csv_data(3, self.file))\n\n read_title, read_data = csvProcessor.read_csv(self.file_process)\n self.assertEqual(read_title, title)\n self.assertEqual(read_data[0], data)\n\n def test_process_csv_data_5(self):\n title = ['a', 'b', 'c', 'd']\n data = ['ABC']\n csvProcessor = CSVProcessor()\n self.assertEqual(1, csvProcessor.process_csv_data(4, self.file))\n\n read_title, read_data = csvProcessor.read_csv(self.file_process)\n self.assertEqual(read_title, title)\n self.assertEqual(read_data[0], data)", "solution_code": "def process_csv_data(self, N, save_file_name):\n title, data = self.read_csv(save_file_name)\n column_data = [row[N] for row in data]\n column_data = [row.upper() for row in column_data]\n new_data = [title, column_data]\n return self.write_csv(new_data, save_file_name.split('.')[0] + '_process.csv')", "dependencies": { "Standalone": false, "lib_dependencies": [ "csv" ], "field_dependencies": [], "method_dependencies": [ "read_csv", "write_csv" ] } } ] }, { "task_id": "ClassEval_27", "skeleton": "\nclass CurrencyConverter:\n \"\"\"\n This is a class for currency conversion, which supports to convert amounts between different currencies, retrieve supported currencies, add new currency rates, and update existing currency rates.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialize the exchange rate of the US dollar against various currencies\n \"\"\"\n self.rates = {\n 'USD': 1.0,\n 'EUR': 0.85,\n 'GBP': 0.72,\n 'JPY': 110.15,\n 'CAD': 1.23,\n 'AUD': 1.34,\n 'CNY': 6.40,\n }\n\n def convert(self, amount, from_currency, to_currency):\n \"\"\"\n Convert the value of a given currency to another currency type\n :param amount: float, The value of a given currency\n :param from_currency: string, source currency type\n :param to_currency: string, target currency type\n :return: float, value converted to another currency type\n >>> cc = CurrencyConverter()\n >>> cc.convert(64, 'CNY','USD')\n 10.0\n \"\"\"\n\n\n def get_supported_currencies(self):\n \"\"\"\n Returns a list of supported currency types\n :return:list, All supported currency types\n >>> cc = CurrencyConverter()\n >>> cc.get_supported_currencies()\n ['USD','EUR','GBP','JPY','CAD','AUD','CNY']\n \"\"\"\n\n\n def add_currency_rate(self, currency, rate):\n \"\"\"\n Add a new supported currency type, return False if the currency type is already in the support list\n :param currency:string, currency type to be added\n :param rate:float, exchange rate for this type of currency\n :return:If successful, returns None; if unsuccessful, returns False\n >>> cc = CurrencyConverter()\n >>> cc.add_currency_rate('KRW', 1308.84)\n self.rates['KRW'] = 1308.84\n \"\"\"\n\n\n def update_currency_rate(self, currency, new_rate):\n \"\"\"\n Update the exchange rate for a certain currency\n :param currency:string\n :param new_rate:float\n :return:If successful, returns None; if unsuccessful, returns False\n >>> cc = CurrencyConverter()\n >>> cc.update_currency_rate('CNY', 7.18)\n self.rates['CNY'] = 7.18\n \"\"\"", "test": "import unittest\n\n\nclass CurrencyConverterTestConvert(unittest.TestCase):\n def test_convert_1(self):\n cc = CurrencyConverter()\n res = cc.convert(64, 'CNY', 'USD')\n self.assertEqual(res, 10.0)\n\n def test_convert_2(self):\n cc = CurrencyConverter()\n res = cc.convert(64, 'USD', 'USD')\n self.assertEqual(res, 64)\n\n def test_convert_3(self):\n cc = CurrencyConverter()\n res = cc.convert(64, 'CNY', 'GBP')\n self.assertAlmostEqual(res, 7.1999999999999)\n\n def test_convert_4(self):\n cc = CurrencyConverter()\n res = cc.convert(64, 'USD', 'GBP')\n self.assertAlmostEqual(res, 46.08)\n\n def test_convert_5(self):\n cc = CurrencyConverter()\n res = cc.convert(64, 'USD', 'CAD')\n self.assertAlmostEqual(res, 78.72)\n\n def test_convert_6(self):\n cc = CurrencyConverter()\n res = cc.convert(64, '???', 'USD')\n self.assertFalse(res)\n\n\nclass CurrencyConverterTestGetSupportedCurrencies(unittest.TestCase):\n def test_get_supported_currencies_1(self):\n cc = CurrencyConverter()\n res = cc.get_supported_currencies()\n self.assertEqual(res, ['USD', 'EUR', 'GBP', 'JPY', 'CAD', 'AUD', 'CNY'])\n\n def test_get_supported_currencies_2(self):\n cc = CurrencyConverter()\n res = cc.get_supported_currencies()\n self.assertEqual(res, ['USD', 'EUR', 'GBP', 'JPY', 'CAD', 'AUD', 'CNY'])\n\n def test_get_supported_currencies_3(self):\n cc = CurrencyConverter()\n res = cc.get_supported_currencies()\n self.assertEqual(res, ['USD', 'EUR', 'GBP', 'JPY', 'CAD', 'AUD', 'CNY'])\n\n def test_get_supported_currencies_4(self):\n cc = CurrencyConverter()\n res = cc.get_supported_currencies()\n self.assertEqual(res, ['USD', 'EUR', 'GBP', 'JPY', 'CAD', 'AUD', 'CNY'])\n\n def test_get_supported_currencies_5(self):\n cc = CurrencyConverter()\n res = cc.get_supported_currencies()\n self.assertEqual(res, ['USD', 'EUR', 'GBP', 'JPY', 'CAD', 'AUD', 'CNY'])\n\n\nclass CurrencyConverterTestAddCurrencyRate(unittest.TestCase):\n def test_add_currency_rate_1(self):\n cc = CurrencyConverter()\n cc.add_currency_rate('KRW', 1308.84)\n self.assertEqual(cc.rates['KRW'], 1308.84)\n\n def test_add_currency_rate_2(self):\n cc = CurrencyConverter()\n cc.add_currency_rate('aaa', 1.0)\n self.assertEqual(cc.rates['aaa'], 1.0)\n\n def test_add_currency_rate_3(self):\n cc = CurrencyConverter()\n cc.add_currency_rate('bbb', 2.0)\n self.assertEqual(cc.rates['bbb'], 2.0)\n\n def test_add_currency_rate_4(self):\n cc = CurrencyConverter()\n cc.add_currency_rate('ccc', 3.0)\n self.assertEqual(cc.rates['ccc'], 3.0)\n\n def test_add_currency_rate_5(self):\n cc = CurrencyConverter()\n cc.add_currency_rate('ddd', 4.0)\n self.assertEqual(cc.rates['ddd'], 4.0)\n\n def test_add_currency_rate_6(self):\n cc = CurrencyConverter()\n res = cc.add_currency_rate('USD', 1.0)\n self.assertFalse(res)\n\n\nclass CurrencyConverterTestUpdateCurrencyRate(unittest.TestCase):\n def test_update_currency_rate_1(self):\n cc = CurrencyConverter()\n cc.update_currency_rate('CNY', 7.18)\n self.assertEqual(cc.rates['CNY'], 7.18)\n\n def test_update_currency_rate_2(self):\n cc = CurrencyConverter()\n cc.update_currency_rate('CNY', 1.0)\n self.assertEqual(cc.rates['CNY'], 1.0)\n\n def test_update_currency_rate_3(self):\n cc = CurrencyConverter()\n cc.update_currency_rate('CNY', 2.0)\n self.assertEqual(cc.rates['CNY'], 2.0)\n\n def test_update_currency_rate_4(self):\n cc = CurrencyConverter()\n cc.update_currency_rate('CNY', 3.0)\n self.assertEqual(cc.rates['CNY'], 3.0)\n\n def test_update_currency_rate_5(self):\n cc = CurrencyConverter()\n cc.update_currency_rate('CNY', 4.0)\n self.assertEqual(cc.rates['CNY'], 4.0)\n\n def test_update_currency_rate_6(self):\n cc = CurrencyConverter()\n res = cc.update_currency_rate('???', 7.18)\n self.assertFalse(res)\n\n\nclass CurrencyConverterTest(unittest.TestCase):\n def test_currencyconverter(self):\n cc = CurrencyConverter()\n res = cc.convert(64, 'CNY', 'USD')\n self.assertEqual(res, 10.0)\n res = cc.get_supported_currencies()\n self.assertEqual(res, ['USD', 'EUR', 'GBP', 'JPY', 'CAD', 'AUD', 'CNY'])\n cc.add_currency_rate('KRW', 1308.84)\n self.assertEqual(cc.rates['KRW'], 1308.84)\n cc.update_currency_rate('CNY', 7.18)\n self.assertEqual(cc.rates['CNY'], 7.18)", "solution_code": "class CurrencyConverter:\n def __init__(self):\n self.rates = {\n 'USD': 1.0,\n 'EUR': 0.85,\n 'GBP': 0.72,\n 'JPY': 110.15,\n 'CAD': 1.23,\n 'AUD': 1.34,\n 'CNY': 6.40,\n }\n\n def convert(self, amount, from_currency, to_currency):\n if from_currency == to_currency:\n return amount\n\n if from_currency not in self.rates or to_currency not in self.rates:\n return False\n\n from_rate = self.rates[from_currency]\n to_rate = self.rates[to_currency]\n\n converted_amount = (amount / from_rate) * to_rate\n return converted_amount\n\n def get_supported_currencies(self):\n return list(self.rates.keys())\n\n def add_currency_rate(self, currency, rate):\n if currency in self.rates:\n return False\n self.rates[currency] = rate\n\n def update_currency_rate(self, currency, new_rate):\n if currency not in self.rates:\n return False\n self.rates[currency] = new_rate", "import_statement": [], "class_description": " \"\"\"\n This is a class for currency conversion, which supports to convert amounts between different currencies, retrieve supported currencies, add new currency rates, and update existing currency rates.\n \"\"\"\n", "class_name": "CurrencyConverter", "test_classes": [ "CurrencyConverterTestConvert", "CurrencyConverterTestGetSupportedCurrencies", "CurrencyConverterTestAddCurrencyRate", "CurrencyConverterTestUpdateCurrencyRate", "CurrencyConverterTest" ], "class_constructor": "class CurrencyConverter: \n def __init__(self):\n \"\"\"\n Initialize the exchange rate of the US dollar against various currencies\n \"\"\"\n self.rates = {\n 'USD': 1.0,\n 'EUR': 0.85,\n 'GBP': 0.72,\n 'JPY': 110.15,\n 'CAD': 1.23,\n 'AUD': 1.34,\n 'CNY': 6.40,\n }\n\n", "fields": [ "self.rates" ], "methods_info": [ { "method_name": "convert", "method_description": "def convert(self, amount, from_currency, to_currency):\n \"\"\"\n Convert the value of a given currency to another currency type\n :param amount: float, The value of a given currency\n :param from_currency: string, source currency type\n :param to_currency: string, target currency type\n :return: float, value converted to another currency type\n >>> cc = CurrencyConverter()\n >>> cc.convert(64, 'CNY','USD')\n 10.0\n \"\"\"", "test_class": "CurrencyConverterTestConvert", "test_code": "class CurrencyConverterTestConvert(unittest.TestCase):\n def test_convert_1(self):\n cc = CurrencyConverter()\n res = cc.convert(64, 'CNY', 'USD')\n self.assertEqual(res, 10.0)\n\n def test_convert_2(self):\n cc = CurrencyConverter()\n res = cc.convert(64, 'USD', 'USD')\n self.assertEqual(res, 64)\n\n def test_convert_3(self):\n cc = CurrencyConverter()\n res = cc.convert(64, 'CNY', 'GBP')\n self.assertAlmostEqual(res, 7.1999999999999)\n\n def test_convert_4(self):\n cc = CurrencyConverter()\n res = cc.convert(64, 'USD', 'GBP')\n self.assertAlmostEqual(res, 46.08)\n\n def test_convert_5(self):\n cc = CurrencyConverter()\n res = cc.convert(64, 'USD', 'CAD')\n self.assertAlmostEqual(res, 78.72)\n\n def test_convert_6(self):\n cc = CurrencyConverter()\n res = cc.convert(64, '???', 'USD')\n self.assertFalse(res)", "solution_code": "def convert(self, amount, from_currency, to_currency):\n if from_currency == to_currency:\n return amount\n\n if from_currency not in self.rates or to_currency not in self.rates:\n return False\n\n from_rate = self.rates[from_currency]\n to_rate = self.rates[to_currency]\n\n converted_amount = (amount / from_rate) * to_rate\n return converted_amount", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.rates" ], "method_dependencies": [] } }, { "method_name": "get_supported_currencies", "method_description": "def get_supported_currencies(self):\n \"\"\"\n Returns a list of supported currency types\n :return:list, All supported currency types\n >>> cc = CurrencyConverter()\n >>> cc.get_supported_currencies()\n ['USD','EUR','GBP','JPY','CAD','AUD','CNY']\n \"\"\"", "test_class": "CurrencyConverterTestGetSupportedCurrencies", "test_code": "class CurrencyConverterTestGetSupportedCurrencies(unittest.TestCase):\n def test_get_supported_currencies_1(self):\n cc = CurrencyConverter()\n res = cc.get_supported_currencies()\n self.assertEqual(res, ['USD', 'EUR', 'GBP', 'JPY', 'CAD', 'AUD', 'CNY'])\n\n def test_get_supported_currencies_2(self):\n cc = CurrencyConverter()\n res = cc.get_supported_currencies()\n self.assertEqual(res, ['USD', 'EUR', 'GBP', 'JPY', 'CAD', 'AUD', 'CNY'])\n\n def test_get_supported_currencies_3(self):\n cc = CurrencyConverter()\n res = cc.get_supported_currencies()\n self.assertEqual(res, ['USD', 'EUR', 'GBP', 'JPY', 'CAD', 'AUD', 'CNY'])\n\n def test_get_supported_currencies_4(self):\n cc = CurrencyConverter()\n res = cc.get_supported_currencies()\n self.assertEqual(res, ['USD', 'EUR', 'GBP', 'JPY', 'CAD', 'AUD', 'CNY'])\n\n def test_get_supported_currencies_5(self):\n cc = CurrencyConverter()\n res = cc.get_supported_currencies()\n self.assertEqual(res, ['USD', 'EUR', 'GBP', 'JPY', 'CAD', 'AUD', 'CNY'])", "solution_code": "def get_supported_currencies(self):\n return list(self.rates.keys())", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.rates" ], "method_dependencies": [] } }, { "method_name": "add_currency_rate", "method_description": "def add_currency_rate(self, currency, rate):\n \"\"\"\n Add a new supported currency type, return False if the currency type is already in the support list\n :param currency:string, currency type to be added\n :param rate:float, exchange rate for this type of currency\n :return:If successful, returns None; if unsuccessful, returns False\n >>> cc = CurrencyConverter()\n >>> cc.add_currency_rate('KRW', 1308.84)\n self.rates['KRW'] = 1308.84\n \"\"\"", "test_class": "CurrencyConverterTestAddCurrencyRate", "test_code": "class CurrencyConverterTestAddCurrencyRate(unittest.TestCase):\n def test_add_currency_rate_1(self):\n cc = CurrencyConverter()\n cc.add_currency_rate('KRW', 1308.84)\n self.assertEqual(cc.rates['KRW'], 1308.84)\n\n def test_add_currency_rate_2(self):\n cc = CurrencyConverter()\n cc.add_currency_rate('aaa', 1.0)\n self.assertEqual(cc.rates['aaa'], 1.0)\n\n def test_add_currency_rate_3(self):\n cc = CurrencyConverter()\n cc.add_currency_rate('bbb', 2.0)\n self.assertEqual(cc.rates['bbb'], 2.0)\n\n def test_add_currency_rate_4(self):\n cc = CurrencyConverter()\n cc.add_currency_rate('ccc', 3.0)\n self.assertEqual(cc.rates['ccc'], 3.0)\n\n def test_add_currency_rate_5(self):\n cc = CurrencyConverter()\n cc.add_currency_rate('ddd', 4.0)\n self.assertEqual(cc.rates['ddd'], 4.0)\n\n def test_add_currency_rate_6(self):\n cc = CurrencyConverter()\n res = cc.add_currency_rate('USD', 1.0)\n self.assertFalse(res)", "solution_code": "def add_currency_rate(self, currency, rate):\n if currency in self.rates:\n return False\n self.rates[currency] = rate", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.rates" ], "method_dependencies": [] } }, { "method_name": "update_currency_rate", "method_description": "def update_currency_rate(self, currency, new_rate):\n \"\"\"\n Update the exchange rate for a certain currency\n :param currency:string\n :param new_rate:float\n :return:If successful, returns None; if unsuccessful, returns False\n >>> cc = CurrencyConverter()\n >>> cc.update_currency_rate('CNY', 7.18)\n self.rates['CNY'] = 7.18\n \"\"\"", "test_class": "CurrencyConverterTestUpdateCurrencyRate", "test_code": "class CurrencyConverterTestUpdateCurrencyRate(unittest.TestCase):\n def test_update_currency_rate_1(self):\n cc = CurrencyConverter()\n cc.update_currency_rate('CNY', 7.18)\n self.assertEqual(cc.rates['CNY'], 7.18)\n\n def test_update_currency_rate_2(self):\n cc = CurrencyConverter()\n cc.update_currency_rate('CNY', 1.0)\n self.assertEqual(cc.rates['CNY'], 1.0)\n\n def test_update_currency_rate_3(self):\n cc = CurrencyConverter()\n cc.update_currency_rate('CNY', 2.0)\n self.assertEqual(cc.rates['CNY'], 2.0)\n\n def test_update_currency_rate_4(self):\n cc = CurrencyConverter()\n cc.update_currency_rate('CNY', 3.0)\n self.assertEqual(cc.rates['CNY'], 3.0)\n\n def test_update_currency_rate_5(self):\n cc = CurrencyConverter()\n cc.update_currency_rate('CNY', 4.0)\n self.assertEqual(cc.rates['CNY'], 4.0)\n\n def test_update_currency_rate_6(self):\n cc = CurrencyConverter()\n res = cc.update_currency_rate('???', 7.18)\n self.assertFalse(res)", "solution_code": "def update_currency_rate(self, currency, new_rate):\n if currency not in self.rates:\n return False\n self.rates[currency] = new_rate", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.rates" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_28", "skeleton": "\nimport sqlite3\nimport pandas as pd\n\nclass DatabaseProcessor:\n \"\"\"\n This is a class for processing a database, supporting to create tables, insert data into the database, search for data based on name, and delete data from the database.\n \"\"\"\n\n\n def __init__(self, database_name):\n \"\"\"\n Initialize database name of database processor\n \"\"\"\n self.database_name = database_name\n\n\n def create_table(self, table_name, key1, key2):\n \"\"\"\n Create a new table in the database if it doesn't exist.\n And make id (INTEGER) as PRIMARY KEY, make key1 as TEXT, key2 as INTEGER\n :param table_name: str, the name of the table to create.\n :param key1: str, the name of the first column in the table.\n :param key2: str, the name of the second column in the table.\n >>> db.create_table('user', 'name', 'age')\n \"\"\"\n\n\n def insert_into_database(self, table_name, data):\n \"\"\"\n Insert data into the specified table in the database.\n :param table_name: str, the name of the table to insert data into.\n :param data: list, a list of dictionaries where each dictionary represents a row of data.\n >>> db.insert_into_database('user', [\n {'name': 'John', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ])\n \"\"\"\n\n\n def search_database(self, table_name, name):\n \"\"\"\n Search the specified table in the database for rows with a matching name.\n :param table_name: str, the name of the table to search.\n :param name: str, the name to search for.\n :return: list, a list of tuples representing the rows with matching name, if any;\n otherwise, returns None.\n >>> db.search_database('user', 'John')\n [(1, 'John', 25)]\n \"\"\"\n\n\n def delete_from_database(self, table_name, name):\n \"\"\"\n Delete rows from the specified table in the database with a matching name.\n :param table_name: str, the name of the table to delete rows from.\n :param name: str, the name to match for deletion.\n >>> db.delete_from_database('user', 'John')\n \"\"\"", "test": "import unittest\nimport sqlite3\n\n\nclass DatabaseProcessorTestCreateTable(unittest.TestCase):\n def setUp(self):\n self.database_name = \"test.db\"\n self.processor = DatabaseProcessor(self.database_name)\n\n def tearDown(self):\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(\"DROP TABLE IF EXISTS test_table\")\n conn.commit()\n conn.close()\n\n def test_create_table_1(self):\n table_name = \"test_table\"\n self.processor.create_table(table_name, 'name', 'age')\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name=?\", (table_name,))\n result = cursor.fetchone()\n conn.close()\n\n self.assertIsNotNone(result)\n self.assertEqual(result[0], table_name)\n\n def test_create_table_2(self):\n table_name = \"test_table2\"\n self.processor.create_table(table_name, 'name', 'age')\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name=?\", (table_name,))\n result = cursor.fetchone()\n conn.close()\n\n self.assertIsNotNone(result)\n self.assertEqual(result[0], table_name)\n\n def test_create_table_3(self):\n table_name = \"test_table3\"\n self.processor.create_table(table_name, 'name', 'age')\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name=?\", (table_name,))\n result = cursor.fetchone()\n conn.close()\n\n self.assertIsNotNone(result)\n self.assertEqual(result[0], table_name)\n\n def test_create_table_4(self):\n table_name = \"test_table4\"\n self.processor.create_table(table_name, 'name', 'age')\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name=?\", (table_name,))\n result = cursor.fetchone()\n conn.close()\n\n self.assertIsNotNone(result)\n self.assertEqual(result[0], table_name)\n\n def test_create_table_5(self):\n table_name = \"test_table5\"\n self.processor.create_table(table_name, 'name', 'age')\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name=?\", (table_name,))\n result = cursor.fetchone()\n conn.close()\n\n self.assertIsNotNone(result)\n self.assertEqual(result[0], table_name)\n\n\nclass DatabaseProcessorTestInsertIntoDatabase(unittest.TestCase):\n def setUp(self):\n self.database_name = \"test.db\"\n self.processor = DatabaseProcessor(self.database_name)\n\n def tearDown(self):\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(\"DROP TABLE IF EXISTS test_table\")\n conn.commit()\n conn.close()\n\n def test_insert_into_database_1(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(f\"SELECT * FROM {table_name}\")\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), len(data))\n self.assertEqual(result[0][2], 25)\n\n def test_insert_into_database_2(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 15},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(f\"SELECT * FROM {table_name}\")\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), len(data))\n self.assertEqual(result[0][2], 15)\n\n def test_insert_into_database_3(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 16},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(f\"SELECT * FROM {table_name}\")\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), len(data))\n self.assertEqual(result[0][2], 16)\n\n def test_insert_into_database_4(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 17},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(f\"SELECT * FROM {table_name}\")\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), len(data))\n self.assertEqual(result[0][2], 17)\n\n def test_insert_into_database_5(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 18},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(f\"SELECT * FROM {table_name}\")\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), len(data))\n self.assertEqual(result[0][2], 18)\n\n\nclass DatabaseProcessorTestSearchDatabase(unittest.TestCase):\n def setUp(self):\n self.database_name = \"test.db\"\n self.processor = DatabaseProcessor(self.database_name)\n\n def tearDown(self):\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(\"DROP TABLE IF EXISTS test_table\")\n conn.commit()\n conn.close()\n\n def test_search_database_1(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n\n result = self.processor.search_database(table_name, 'John')\n self.assertIsNotNone(result)\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'John')\n\n def test_search_database_2(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n\n result = self.processor.search_database(table_name, 'Alice')\n self.assertIsNotNone(result)\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'Alice')\n\n def test_search_database_3(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n\n result = self.processor.search_database(table_name, 'Bob')\n self.assertIsNone(result)\n\n def test_search_database_4(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n\n result = self.processor.search_database(table_name, 'aaa')\n self.assertIsNone(result)\n\n def test_search_database_5(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n\n result = self.processor.search_database(table_name, 'bbb')\n self.assertIsNone(result)\n\n\nclass DatabaseProcessorTestDeteleFromDatabase(unittest.TestCase):\n def setUp(self):\n self.database_name = \"test.db\"\n self.processor = DatabaseProcessor(self.database_name)\n\n def tearDown(self):\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(\"DROP TABLE IF EXISTS test_table\")\n conn.commit()\n conn.close()\n\n def test_delete_from_database_1(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n\n self.processor.delete_from_database(table_name, 'John')\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(f\"SELECT * FROM {table_name}\")\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'Alice')\n\n def test_delete_from_database_2(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n\n self.processor.delete_from_database(table_name, 'Alice')\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(f\"SELECT * FROM {table_name}\")\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'John')\n\n def test_delete_from_database_3(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n\n self.processor.delete_from_database(table_name, 'John')\n self.processor.delete_from_database(table_name, 'Alice')\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(f\"SELECT * FROM {table_name}\")\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 0)\n\n def test_delete_from_database_4(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 25},\n {'name': 'aaa', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n\n self.processor.delete_from_database(table_name, 'John')\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(f\"SELECT * FROM {table_name}\")\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'aaa')\n\n def test_delete_from_database_5(self):\n table_name = \"test_table\"\n data = [\n {'name': 'bbb', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n\n self.processor.delete_from_database(table_name, 'bbb')\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(f\"SELECT * FROM {table_name}\")\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'Alice')\n\n\nclass DatabaseProcessorTest(unittest.TestCase):\n def setUp(self):\n self.database_name = \"test.db\"\n self.processor = DatabaseProcessor(self.database_name)\n\n def tearDown(self):\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(\"DROP TABLE IF EXISTS test_table\")\n conn.commit()\n conn.close()\n\n def test_DatabaseProcessor(self):\n table_name = \"test_table\"\n self.processor.create_table(table_name, 'name', 'age')\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name=?\", (table_name,))\n result = cursor.fetchone()\n conn.close()\n\n self.assertIsNotNone(result)\n self.assertEqual(result[0], table_name)\n\n data = [\n {'name': 'John', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.insert_into_database(table_name, data)\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(f\"SELECT * FROM {table_name}\")\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), len(data))\n self.assertEqual(result[0][2], 25)\n\n result = self.processor.search_database(table_name, 'John')\n self.assertIsNotNone(result)\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'John')\n\n self.processor.delete_from_database(table_name, 'John')\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(f\"SELECT * FROM {table_name}\")\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'Alice')", "solution_code": "import sqlite3\nimport pandas as pd\n\n\nclass DatabaseProcessor:\n\n def __init__(self, database_name):\n self.database_name = database_name\n\n def create_table(self, table_name, key1, key2):\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n\n create_table_query = f\"CREATE TABLE IF NOT EXISTS {table_name} (id INTEGER PRIMARY KEY, {key1} TEXT, {key2} INTEGER)\"\n cursor.execute(create_table_query)\n\n conn.commit()\n conn.close()\n\n def insert_into_database(self, table_name, data):\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n\n for item in data:\n insert_query = f\"INSERT INTO {table_name} (name, age) VALUES (?, ?)\"\n cursor.execute(insert_query, (item['name'], item['age']))\n\n conn.commit()\n conn.close()\n\n def search_database(self, table_name, name):\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n\n select_query = f\"SELECT * FROM {table_name} WHERE name = ?\"\n cursor.execute(select_query, (name,))\n result = cursor.fetchall()\n\n if result:\n return result\n else:\n return None\n\n def delete_from_database(self, table_name, name):\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n\n delete_query = f\"DELETE FROM {table_name} WHERE name = ?\"\n cursor.execute(delete_query, (name,))\n\n conn.commit()\n conn.close()", "import_statement": [ "import sqlite3", "import pandas as pd" ], "class_description": " \"\"\"\n This is a class for processing a database, supporting to create tables, insert data into the database, search for data based on name, and delete data from the database.\n \"\"\"\n", "class_name": "DatabaseProcessor", "test_classes": [ "DatabaseProcessorTestCreateTable", "DatabaseProcessorTestInsertIntoDatabase", "DatabaseProcessorTestSearchDatabase", "DatabaseProcessorTestDeteleFromDatabase", "DatabaseProcessorTest" ], "class_constructor": "class DatabaseProcessor: \n def __init__(self, database_name):\n \"\"\"\n Initialize database name of database processor\n \"\"\"\n self.database_name = database_name\n\n\n", "fields": [ "self.database_name" ], "methods_info": [ { "method_name": "create_table", "method_description": "def create_table(self, table_name, key1, key2):\n \"\"\"\n Create a new table in the database if it doesn't exist.\n And make id (INTEGER) as PRIMARY KEY, make key1 as TEXT, key2 as INTEGER\n :param table_name: str, the name of the table to create.\n :param key1: str, the name of the first column in the table.\n :param key2: str, the name of the second column in the table.\n >>> db.create_table('user', 'name', 'age')\n \"\"\"", "test_class": "DatabaseProcessorTestCreateTable", "test_code": "class DatabaseProcessorTestCreateTable(unittest.TestCase):\n def setUp(self):\n self.database_name = \"test.db\"\n self.processor = DatabaseProcessor(self.database_name)\n\n def tearDown(self):\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(\"DROP TABLE IF EXISTS test_table\")\n conn.commit()\n conn.close()\n\n def test_create_table_1(self):\n table_name = \"test_table\"\n self.processor.create_table(table_name, 'name', 'age')\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name=?\", (table_name,))\n result = cursor.fetchone()\n conn.close()\n\n self.assertIsNotNone(result)\n self.assertEqual(result[0], table_name)\n\n def test_create_table_2(self):\n table_name = \"test_table2\"\n self.processor.create_table(table_name, 'name', 'age')\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name=?\", (table_name,))\n result = cursor.fetchone()\n conn.close()\n\n self.assertIsNotNone(result)\n self.assertEqual(result[0], table_name)\n\n def test_create_table_3(self):\n table_name = \"test_table3\"\n self.processor.create_table(table_name, 'name', 'age')\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name=?\", (table_name,))\n result = cursor.fetchone()\n conn.close()\n\n self.assertIsNotNone(result)\n self.assertEqual(result[0], table_name)\n\n def test_create_table_4(self):\n table_name = \"test_table4\"\n self.processor.create_table(table_name, 'name', 'age')\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name=?\", (table_name,))\n result = cursor.fetchone()\n conn.close()\n\n self.assertIsNotNone(result)\n self.assertEqual(result[0], table_name)\n\n def test_create_table_5(self):\n table_name = \"test_table5\"\n self.processor.create_table(table_name, 'name', 'age')\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name=?\", (table_name,))\n result = cursor.fetchone()\n conn.close()\n\n self.assertIsNotNone(result)\n self.assertEqual(result[0], table_name)", "solution_code": "def create_table(self, table_name, key1, key2):\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n\n create_table_query = f\"CREATE TABLE IF NOT EXISTS {table_name} (id INTEGER PRIMARY KEY, {key1} TEXT, {key2} INTEGER)\"\n cursor.execute(create_table_query)\n\n conn.commit()\n conn.close()", "dependencies": { "Standalone": false, "lib_dependencies": [ "sqlite3" ], "field_dependencies": [ "self.database_name" ], "method_dependencies": [] } }, { "method_name": "insert_into_database", "method_description": "def insert_into_database(self, table_name, data):\n \"\"\"\n Insert data into the specified table in the database.\n :param table_name: str, the name of the table to insert data into.\n :param data: list, a list of dictionaries where each dictionary represents a row of data.\n >>> db.insert_into_database('user', [\n {'name': 'John', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ])\n \"\"\"", "test_class": "DatabaseProcessorTestInsertIntoDatabase", "test_code": "class DatabaseProcessorTestInsertIntoDatabase(unittest.TestCase):\n def setUp(self):\n self.database_name = \"test.db\"\n self.processor = DatabaseProcessor(self.database_name)\n\n def tearDown(self):\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(\"DROP TABLE IF EXISTS test_table\")\n conn.commit()\n conn.close()\n\n def test_insert_into_database_1(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(f\"SELECT * FROM {table_name}\")\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), len(data))\n self.assertEqual(result[0][2], 25)\n\n def test_insert_into_database_2(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 15},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(f\"SELECT * FROM {table_name}\")\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), len(data))\n self.assertEqual(result[0][2], 15)\n\n def test_insert_into_database_3(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 16},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(f\"SELECT * FROM {table_name}\")\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), len(data))\n self.assertEqual(result[0][2], 16)\n\n def test_insert_into_database_4(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 17},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(f\"SELECT * FROM {table_name}\")\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), len(data))\n self.assertEqual(result[0][2], 17)\n\n def test_insert_into_database_5(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 18},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(f\"SELECT * FROM {table_name}\")\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), len(data))\n self.assertEqual(result[0][2], 18)", "solution_code": "def insert_into_database(self, table_name, data):\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n\n for item in data:\n insert_query = f\"INSERT INTO {table_name} (name, age) VALUES (?, ?)\"\n cursor.execute(insert_query, (item['name'], item['age']))\n\n conn.commit()\n conn.close()", "dependencies": { "Standalone": false, "lib_dependencies": [ "sqlite3" ], "field_dependencies": [ "self.database_name" ], "method_dependencies": [] } }, { "method_name": "search_database", "method_description": "def search_database(self, table_name, name):\n \"\"\"\n Search the specified table in the database for rows with a matching name.\n :param table_name: str, the name of the table to search.\n :param name: str, the name to search for.\n :return: list, a list of tuples representing the rows with matching name, if any;\n otherwise, returns None.\n >>> db.search_database('user', 'John')\n [(1, 'John', 25)]\n \"\"\"", "test_class": "DatabaseProcessorTestSearchDatabase", "test_code": "class DatabaseProcessorTestSearchDatabase(unittest.TestCase):\n def setUp(self):\n self.database_name = \"test.db\"\n self.processor = DatabaseProcessor(self.database_name)\n\n def tearDown(self):\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(\"DROP TABLE IF EXISTS test_table\")\n conn.commit()\n conn.close()\n\n def test_search_database_1(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n\n result = self.processor.search_database(table_name, 'John')\n self.assertIsNotNone(result)\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'John')\n\n def test_search_database_2(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n\n result = self.processor.search_database(table_name, 'Alice')\n self.assertIsNotNone(result)\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'Alice')\n\n def test_search_database_3(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n\n result = self.processor.search_database(table_name, 'Bob')\n self.assertIsNone(result)\n\n def test_search_database_4(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n\n result = self.processor.search_database(table_name, 'aaa')\n self.assertIsNone(result)\n\n def test_search_database_5(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n\n result = self.processor.search_database(table_name, 'bbb')\n self.assertIsNone(result)", "solution_code": "def search_database(self, table_name, name):\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n\n select_query = f\"SELECT * FROM {table_name} WHERE name = ?\"\n cursor.execute(select_query, (name,))\n result = cursor.fetchall()\n\n if result:\n return result\n else:\n return None", "dependencies": { "Standalone": false, "lib_dependencies": [ "sqlite3" ], "field_dependencies": [ "self.database_name" ], "method_dependencies": [] } }, { "method_name": "delete_from_database", "method_description": "def delete_from_database(self, table_name, name):\n \"\"\"\n Delete rows from the specified table in the database with a matching name.\n :param table_name: str, the name of the table to delete rows from.\n :param name: str, the name to match for deletion.\n >>> db.delete_from_database('user', 'John')\n \"\"\"", "test_class": "DatabaseProcessorTestDeteleFromDatabase", "test_code": "class DatabaseProcessorTestDeteleFromDatabase(unittest.TestCase):\n def setUp(self):\n self.database_name = \"test.db\"\n self.processor = DatabaseProcessor(self.database_name)\n\n def tearDown(self):\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(\"DROP TABLE IF EXISTS test_table\")\n conn.commit()\n conn.close()\n\n def test_delete_from_database_1(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n\n self.processor.delete_from_database(table_name, 'John')\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(f\"SELECT * FROM {table_name}\")\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'Alice')\n\n def test_delete_from_database_2(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n\n self.processor.delete_from_database(table_name, 'Alice')\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(f\"SELECT * FROM {table_name}\")\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'John')\n\n def test_delete_from_database_3(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n\n self.processor.delete_from_database(table_name, 'John')\n self.processor.delete_from_database(table_name, 'Alice')\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(f\"SELECT * FROM {table_name}\")\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 0)\n\n def test_delete_from_database_4(self):\n table_name = \"test_table\"\n data = [\n {'name': 'John', 'age': 25},\n {'name': 'aaa', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n\n self.processor.delete_from_database(table_name, 'John')\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(f\"SELECT * FROM {table_name}\")\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'aaa')\n\n def test_delete_from_database_5(self):\n table_name = \"test_table\"\n data = [\n {'name': 'bbb', 'age': 25},\n {'name': 'Alice', 'age': 30}\n ]\n self.processor.create_table(table_name, 'name', 'age')\n self.processor.insert_into_database(table_name, data)\n\n self.processor.delete_from_database(table_name, 'bbb')\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n cursor.execute(f\"SELECT * FROM {table_name}\")\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'Alice')", "solution_code": "def delete_from_database(self, table_name, name):\n\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n\n delete_query = f\"DELETE FROM {table_name} WHERE name = ?\"\n cursor.execute(delete_query, (name,))\n\n conn.commit()\n conn.close()", "dependencies": { "Standalone": false, "lib_dependencies": [ "sqlite3" ], "field_dependencies": [ "self.database_name" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_29", "skeleton": "\nfrom collections import Counter\n\nclass DataStatistics:\n \"\"\"\n This is a class for performing data statistics, supporting to calculate the mean, median, and mode of a given data set.\n \"\"\"\n\n def mean(self, data):\n \"\"\"\n Calculate the average value of a group of data, accurate to two digits after the Decimal separator\n :param data:list, data list\n :return:float, the mean value\n >>> ds = DataStatistics()\n >>> ds.mean([1, 2, 3, 4, 5])\n 3.00\n \"\"\"\n\n def median(self, data):\n \"\"\"\n Calculate the median of a group of data, accurate to two digits after the Decimal separator\n :param data:list, data list\n :return:float, the median value\n >>> ds = DataStatistics()\n >>> ds.median([2, 5, 1, 3, 4])\n 3.00\n \"\"\"\n\n def mode(self, data):\n \"\"\"\n Calculate the mode of a set of data\n :param data:list, data list\n :return:float, the mode\n >>> ds = DataStatistics()\n >>> ds.mode([2, 2, 3, 3, 4])\n [2, 3]\n \"\"\"", "test": "import unittest\n\n\nclass DataStatisticsTestMean(unittest.TestCase):\n def test_mean_1(self):\n ds = DataStatistics()\n res = ds.mean([1, 2, 3, 4, 5])\n self.assertEqual(res, 3.00)\n\n def test_mean_2(self):\n ds = DataStatistics()\n res = ds.mean([1, 2, 3, 4, 5, 6])\n self.assertEqual(res, 3.50)\n\n def test_mean_3(self):\n ds = DataStatistics()\n res = ds.mean([1, 2, 4, 5, 6, 7])\n self.assertEqual(res, 4.17)\n\n def test_mean_4(self):\n ds = DataStatistics()\n res = ds.mean([1, 2, 4, 5, 6, 7, 8])\n self.assertEqual(res, 4.71)\n\n def test_mean_5(self):\n ds = DataStatistics()\n res = ds.mean([1, 2, 4, 5, 6, 7, 8, 9])\n self.assertEqual(res, 5.25)\n\n\nclass DataStatisticsTestMedian(unittest.TestCase):\n def test_median_1(self):\n ds = DataStatistics()\n res = ds.median([2, 5, 1, 3, 4])\n self.assertEqual(res, 3)\n\n def test_median_2(self):\n ds = DataStatistics()\n res = ds.median([2, 5, 1, 3, 4, 6])\n self.assertEqual(res, 3.50)\n\n def test_median_3(self):\n ds = DataStatistics()\n res = ds.median([2, 5, 1, 4, 6, 7])\n self.assertEqual(res, 4.5)\n\n def test_median_4(self):\n ds = DataStatistics()\n res = ds.median([2, 5, 1, 4, 6, 7, 8])\n self.assertEqual(res, 5)\n\n def test_median_5(self):\n ds = DataStatistics()\n res = ds.median([2, 5, 1, 4, 6, 7, 8, 9])\n self.assertEqual(res, 5.5)\n\n\nclass DataStatisticsTestMode(unittest.TestCase):\n def test_mode_1(self):\n ds = DataStatistics()\n res = ds.mode([2, 2, 3, 3, 4])\n self.assertEqual(res, [2, 3])\n\n def test_mode_2(self):\n ds = DataStatistics()\n res = ds.mode([2, 2, 2, 3, 3, 4])\n self.assertEqual(res, [2])\n\n def test_mode_3(self):\n ds = DataStatistics()\n res = ds.mode([2, 2, 3, 3, 4, 4])\n self.assertEqual(res, [2, 3, 4])\n\n def test_mode_4(self):\n ds = DataStatistics()\n res = ds.mode([2, 2, 3, 3, 4, 4, 4])\n self.assertEqual(res, [4])\n\n def test_mode_5(self):\n ds = DataStatistics()\n res = ds.mode([2, 2, 3, 3, 4, 4, 4, 5])\n self.assertEqual(res, [4])\n\n\nclass DataStatisticsTest(unittest.TestCase):\n def test_datastatistics(self):\n ds = DataStatistics()\n res = ds.mean([1, 2, 3, 4, 5])\n self.assertEqual(res, 3.00)\n res = ds.median([2, 5, 1, 3, 4])\n self.assertEqual(res, 3.00)\n res = ds.mode([2, 2, 3, 3, 4])\n self.assertEqual(res, [2, 3])", "solution_code": "from collections import Counter\n\n\nclass DataStatistics:\n def mean(self, data):\n return round(sum(data) / len(data), 2)\n\n def median(self, data):\n sorted_data = sorted(data)\n n = len(sorted_data)\n if n % 2 == 0:\n middle = n // 2\n return round((sorted_data[middle - 1] + sorted_data[middle]) / 2, 2)\n else:\n middle = n // 2\n return sorted_data[middle]\n\n def mode(self, data):\n counter = Counter(data)\n mode_count = max(counter.values())\n mode = [x for x, count in counter.items() if count == mode_count]\n return mode", "import_statement": [ "from collections import Counter" ], "class_description": " \"\"\"\n This is a class for performing data statistics, supporting to calculate the mean, median, and mode of a given data set.\n \"\"\"\n", "class_name": "DataStatistics", "test_classes": [ "DataStatisticsTestMean", "DataStatisticsTestMedian", "DataStatisticsTestMode", "DataStatisticsTest" ], "class_constructor": "class DataStatistics: \n", "fields": [], "methods_info": [ { "method_name": "mean", "method_description": "def mean(self, data):\n \"\"\"\n Calculate the average value of a group of data, accurate to two digits after the Decimal separator\n :param data:list, data list\n :return:float, the mean value\n >>> ds = DataStatistics()\n >>> ds.mean([1, 2, 3, 4, 5])\n 3.00\n \"\"\"", "test_class": "DataStatisticsTestMean", "test_code": "class DataStatisticsTestMean(unittest.TestCase):\n def test_mean_1(self):\n ds = DataStatistics()\n res = ds.mean([1, 2, 3, 4, 5])\n self.assertEqual(res, 3.00)\n\n def test_mean_2(self):\n ds = DataStatistics()\n res = ds.mean([1, 2, 3, 4, 5, 6])\n self.assertEqual(res, 3.50)\n\n def test_mean_3(self):\n ds = DataStatistics()\n res = ds.mean([1, 2, 4, 5, 6, 7])\n self.assertEqual(res, 4.17)\n\n def test_mean_4(self):\n ds = DataStatistics()\n res = ds.mean([1, 2, 4, 5, 6, 7, 8])\n self.assertEqual(res, 4.71)\n\n def test_mean_5(self):\n ds = DataStatistics()\n res = ds.mean([1, 2, 4, 5, 6, 7, 8, 9])\n self.assertEqual(res, 5.25)", "solution_code": "def mean(self, data):\n return round(sum(data) / len(data), 2)", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "median", "method_description": "def median(self, data):\n \"\"\"\n Calculate the median of a group of data, accurate to two digits after the Decimal separator\n :param data:list, data list\n :return:float, the median value\n >>> ds = DataStatistics()\n >>> ds.median([2, 5, 1, 3, 4])\n 3.00\n \"\"\"", "test_class": "DataStatisticsTestMedian", "test_code": "class DataStatisticsTestMedian(unittest.TestCase):\n def test_median_1(self):\n ds = DataStatistics()\n res = ds.median([2, 5, 1, 3, 4])\n self.assertEqual(res, 3)\n\n def test_median_2(self):\n ds = DataStatistics()\n res = ds.median([2, 5, 1, 3, 4, 6])\n self.assertEqual(res, 3.50)\n\n def test_median_3(self):\n ds = DataStatistics()\n res = ds.median([2, 5, 1, 4, 6, 7])\n self.assertEqual(res, 4.5)\n\n def test_median_4(self):\n ds = DataStatistics()\n res = ds.median([2, 5, 1, 4, 6, 7, 8])\n self.assertEqual(res, 5)\n\n def test_median_5(self):\n ds = DataStatistics()\n res = ds.median([2, 5, 1, 4, 6, 7, 8, 9])\n self.assertEqual(res, 5.5)", "solution_code": "def median(self, data):\n sorted_data = sorted(data)\n n = len(sorted_data)\n if n % 2 == 0:\n middle = n // 2\n return round((sorted_data[middle - 1] + sorted_data[middle]) / 2, 2)\n else:\n middle = n // 2\n return sorted_data[middle]", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "mode", "method_description": "def mode(self, data):\n \"\"\"\n Calculate the mode of a set of data\n :param data:list, data list\n :return:float, the mode\n >>> ds = DataStatistics()\n >>> ds.mode([2, 2, 3, 3, 4])\n [2, 3]\n \"\"\"", "test_class": "DataStatisticsTestMode", "test_code": "class DataStatisticsTestMode(unittest.TestCase):\n def test_mode_1(self):\n ds = DataStatistics()\n res = ds.mode([2, 2, 3, 3, 4])\n self.assertEqual(res, [2, 3])\n\n def test_mode_2(self):\n ds = DataStatistics()\n res = ds.mode([2, 2, 2, 3, 3, 4])\n self.assertEqual(res, [2])\n\n def test_mode_3(self):\n ds = DataStatistics()\n res = ds.mode([2, 2, 3, 3, 4, 4])\n self.assertEqual(res, [2, 3, 4])\n\n def test_mode_4(self):\n ds = DataStatistics()\n res = ds.mode([2, 2, 3, 3, 4, 4, 4])\n self.assertEqual(res, [4])\n\n def test_mode_5(self):\n ds = DataStatistics()\n res = ds.mode([2, 2, 3, 3, 4, 4, 4, 5])\n self.assertEqual(res, [4])", "solution_code": "def mode(self, data):\n counter = Counter(data)\n mode_count = max(counter.values())\n mode = [x for x, count in counter.items() if count == mode_count]\n return mode", "dependencies": { "Standalone": false, "lib_dependencies": [ "Counter" ], "field_dependencies": [], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_30", "skeleton": "\nimport numpy as np\n\nclass DataStatistics2:\n \"\"\"\n This is a class for performing data statistics, supporting to get the sum, minimum, maximum, variance, standard deviation, and correlation of a given dataset.\n \"\"\"\n\n def __init__(self, data):\n \"\"\"\n Initialize Data List\n :param data:list\n \"\"\"\n self.data = np.array(data)\n\n def get_sum(self):\n \"\"\"\n Calculate the sum of data\n :return:float\n >>> ds2 = DataStatistics2([1, 2, 3, 4])\n >>> ds2.get_sum()\n 10\n \"\"\"\n\n def get_min(self):\n \"\"\"\n Calculate the minimum value in the data\n :return:float\n >>> ds2 = DataStatistics2([1, 2, 3, 4])\n >>> ds2.get_min()\n 1\n \"\"\"\n\n def get_max(self):\n \"\"\"\n Calculate the maximum value in the data\n :return:float\n >>> ds2 = DataStatistics2([1, 2, 3, 4])\n >>> ds2.get_max()\n 4\n \"\"\"\n\n def get_variance(self):\n \"\"\"\n Calculate variance, accurate to two digits after the Decimal separator\n :return:float\n >>> ds2 = DataStatistics2([1, 2, 3, 4])\n >>> ds2.get_variance()\n 1.25\n \"\"\"\n\n def get_std_deviation(self):\n \"\"\"\n Calculate standard deviation, accurate to two digits after the Decimal separator\n :return:float\n >>> ds2 = DataStatistics2([1, 2, 3, 4])\n >>> ds2.get_std_deviation()\n 1.12\n \"\"\"\n\n def get_correlation(self):\n \"\"\"\n Calculate correlation\n :return:float\n >>> ds2 = DataStatistics2([1, 2, 3, 4])\n >>> ds2.get_correlation()\n 1.0\n \"\"\"", "test": "import unittest\n\n\nclass DataStatistics2TestGetSum(unittest.TestCase):\n def test_get_sum_1(self):\n ds2 = DataStatistics2([1, 2, 3, 4])\n res = ds2.get_sum()\n self.assertEqual(res, 10)\n\n def test_get_sum_2(self):\n ds2 = DataStatistics2([1, 2, 203, 4])\n res = ds2.get_sum()\n self.assertEqual(res, 210)\n\n def test_get_sum_3(self):\n ds2 = DataStatistics2([1, 2, 33, 4])\n res = ds2.get_sum()\n self.assertEqual(res, 40)\n\n def test_get_sum_4(self):\n ds2 = DataStatistics2([1, 2, 333, 4])\n res = ds2.get_sum()\n self.assertEqual(res, 340)\n\n def test_get_sum_5(self):\n ds2 = DataStatistics2([1, 2, 6, 4])\n res = ds2.get_sum()\n self.assertEqual(res, 13)\n\n\nclass DataStatistics2TestGetMin(unittest.TestCase):\n def test_get_min_1(self):\n ds2 = DataStatistics2([1, 2, 3, 4])\n res = ds2.get_min()\n self.assertEqual(res, 1)\n\n def test_get_min_2(self):\n ds2 = DataStatistics2([1, 2, 203, 4])\n res = ds2.get_min()\n self.assertEqual(res, 1)\n\n def test_get_min_3(self):\n ds2 = DataStatistics2([0, -1, -3, 2])\n res = ds2.get_min()\n self.assertEqual(res, -3)\n\n def test_get_min_4(self):\n ds2 = DataStatistics2([-111, -1, -3, 2])\n res = ds2.get_min()\n self.assertEqual(res, -111)\n\n def test_get_min_5(self):\n ds2 = DataStatistics2([0, -1111, -3, 2])\n res = ds2.get_min()\n self.assertEqual(res, -1111)\n\n\nclass DataStatistics2TestGetMax(unittest.TestCase):\n def test_get_max_1(self):\n ds2 = DataStatistics2([1, 2, 3, 4])\n res = ds2.get_max()\n self.assertEqual(res, 4)\n\n def test_get_max_2(self):\n ds2 = DataStatistics2([1, 2, 203, 4])\n res = ds2.get_max()\n self.assertEqual(res, 203)\n\n def test_get_max_3(self):\n ds2 = DataStatistics2([-1, -4, 3, 2])\n res = ds2.get_max()\n self.assertEqual(res, 3)\n\n def test_get_max_4(self):\n ds2 = DataStatistics2([-1, 4, 3, 2])\n res = ds2.get_max()\n self.assertEqual(res, 4)\n\n def test_get_max_5(self):\n ds2 = DataStatistics2([-1, 444, 3, 2])\n res = ds2.get_max()\n self.assertEqual(res, 444)\n\n\nclass DataStatistics2TestGetVariance(unittest.TestCase):\n def test_get_variance_1(self):\n ds2 = DataStatistics2([1, 2, 3, 4])\n res = ds2.get_variance()\n self.assertEqual(res, 1.25)\n\n def test_get_variance_2(self):\n ds2 = DataStatistics2([1, 2, 203, 4])\n res = ds2.get_variance()\n self.assertEqual(res, 7551.25)\n\n def test_get_variance_3(self):\n ds2 = DataStatistics2([1, 4, 3, 2])\n res = ds2.get_variance()\n self.assertEqual(res, 1.25)\n\n def test_get_variance_4(self):\n ds2 = DataStatistics2([11, 14, 13, 12])\n res = ds2.get_variance()\n self.assertEqual(res, 1.25)\n\n def test_get_variance_5(self):\n ds2 = DataStatistics2([111, 114, 113, 112])\n res = ds2.get_variance()\n self.assertEqual(res, 1.25)\n\n\nclass DataStatistics2TestGetStdDeviation(unittest.TestCase):\n def test_get_std_deviation_1(self):\n ds2 = DataStatistics2([1, 2, 3, 4])\n res = ds2.get_std_deviation()\n self.assertEqual(res, 1.12)\n\n def test_get_std_deviation_2(self):\n ds2 = DataStatistics2([1, 2, 203, 4])\n res = ds2.get_std_deviation()\n self.assertEqual(res, 86.9)\n\n def test_get_std_deviation_3(self):\n ds2 = DataStatistics2([1, 4, 3, 2])\n res = ds2.get_std_deviation()\n self.assertEqual(res, 1.12)\n\n def test_get_std_deviation_4(self):\n ds2 = DataStatistics2([11, 14, 13, 12])\n res = ds2.get_std_deviation()\n self.assertEqual(res, 1.12)\n\n def test_get_std_deviation_5(self):\n ds2 = DataStatistics2([111, 114, 113, 112])\n res = ds2.get_std_deviation()\n self.assertEqual(res, 1.12)\n\n\nclass DataStatistics2TestGetCorrelation(unittest.TestCase):\n def test_get_correlation_1(self):\n ds2 = DataStatistics2([1, 2, 3, 4])\n res = ds2.get_correlation()\n self.assertEqual(res, 1.0)\n\n def test_get_correlation_2(self):\n ds2 = DataStatistics2([1, 2, 203, 4])\n res = ds2.get_correlation()\n self.assertEqual(res, 1.0)\n\n def test_get_correlation_3(self):\n ds2 = DataStatistics2([1, 4, 3, 2])\n res = ds2.get_correlation()\n self.assertEqual(res, 1.0)\n\n def test_get_correlation_4(self):\n ds2 = DataStatistics2([11, 14, 13, 12])\n res = ds2.get_correlation()\n self.assertEqual(res, 1.0)\n\n def test_get_correlation_5(self):\n ds2 = DataStatistics2([111, 114, 113, 112])\n res = ds2.get_correlation()\n self.assertEqual(res, 1.0)\n\n\nclass DataStatistics2Test(unittest.TestCase):\n def test_datastatistics2(self):\n ds2 = DataStatistics2([1, 2, 3, 4])\n res = ds2.get_sum()\n self.assertEqual(res, 10)\n\n res = ds2.get_min()\n self.assertEqual(res, 1)\n\n res = ds2.get_max()\n self.assertEqual(res, 4)\n\n res = ds2.get_variance()\n self.assertEqual(res, 1.25)\n\n res = ds2.get_std_deviation()\n self.assertEqual(res, 1.12)\n\n res = ds2.get_correlation()\n self.assertEqual(res, 1.0)", "solution_code": "import numpy as np\n\n\nclass DataStatistics2:\n def __init__(self, data):\n self.data = np.array(data)\n\n def get_sum(self):\n return np.sum(self.data)\n\n def get_min(self):\n return np.min(self.data)\n\n def get_max(self):\n return np.max(self.data)\n\n def get_variance(self):\n return round(np.var(self.data), 2)\n\n def get_std_deviation(self):\n return round(np.std(self.data), 2)\n\n def get_correlation(self):\n return np.corrcoef(self.data, rowvar=False)", "import_statement": [ "import numpy as np" ], "class_description": " \"\"\"\n This is a class for performing data statistics, supporting to get the sum, minimum, maximum, variance, standard deviation, and correlation of a given dataset.\n \"\"\"\n", "class_name": "DataStatistics2", "test_classes": [ "DataStatistics2TestGetSum", "DataStatistics2TestGetMin", "DataStatistics2TestGetMax", "DataStatistics2TestGetVariance", "DataStatistics2TestGetStdDeviation", "DataStatistics2TestGetCorrelation", "DataStatistics2Test" ], "class_constructor": "class DataStatistics2: \n def __init__(self, data):\n \"\"\"\n Initialize Data List\n :param data:list\n \"\"\"\n self.data = np.array(data)\n\n", "fields": [ "self.data" ], "methods_info": [ { "method_name": "get_sum", "method_description": "def get_sum(self):\n \"\"\"\n Calculate the sum of data\n :return:float\n >>> ds2 = DataStatistics2([1, 2, 3, 4])\n >>> ds2.get_sum()\n 10\n \"\"\"", "test_class": "DataStatistics2TestGetSum", "test_code": "class DataStatistics2TestGetSum(unittest.TestCase):\n def test_get_sum_1(self):\n ds2 = DataStatistics2([1, 2, 3, 4])\n res = ds2.get_sum()\n self.assertEqual(res, 10)\n\n def test_get_sum_2(self):\n ds2 = DataStatistics2([1, 2, 203, 4])\n res = ds2.get_sum()\n self.assertEqual(res, 210)\n\n def test_get_sum_3(self):\n ds2 = DataStatistics2([1, 2, 33, 4])\n res = ds2.get_sum()\n self.assertEqual(res, 40)\n\n def test_get_sum_4(self):\n ds2 = DataStatistics2([1, 2, 333, 4])\n res = ds2.get_sum()\n self.assertEqual(res, 340)\n\n def test_get_sum_5(self):\n ds2 = DataStatistics2([1, 2, 6, 4])\n res = ds2.get_sum()\n self.assertEqual(res, 13)", "solution_code": "def get_sum(self):\n return np.sum(self.data)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.data" ], "method_dependencies": [] } }, { "method_name": "get_min", "method_description": "def get_min(self):\n \"\"\"\n Calculate the minimum value in the data\n :return:float\n >>> ds2 = DataStatistics2([1, 2, 3, 4])\n >>> ds2.get_min()\n 1\n \"\"\"", "test_class": "DataStatistics2TestGetMin", "test_code": "class DataStatistics2TestGetMin(unittest.TestCase):\n def test_get_min_1(self):\n ds2 = DataStatistics2([1, 2, 3, 4])\n res = ds2.get_min()\n self.assertEqual(res, 1)\n\n def test_get_min_2(self):\n ds2 = DataStatistics2([1, 2, 203, 4])\n res = ds2.get_min()\n self.assertEqual(res, 1)\n\n def test_get_min_3(self):\n ds2 = DataStatistics2([0, -1, -3, 2])\n res = ds2.get_min()\n self.assertEqual(res, -3)\n\n def test_get_min_4(self):\n ds2 = DataStatistics2([-111, -1, -3, 2])\n res = ds2.get_min()\n self.assertEqual(res, -111)\n\n def test_get_min_5(self):\n ds2 = DataStatistics2([0, -1111, -3, 2])\n res = ds2.get_min()\n self.assertEqual(res, -1111)", "solution_code": "def get_min(self):\n return np.min(self.data)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.data" ], "method_dependencies": [] } }, { "method_name": "get_max", "method_description": "def get_max(self):\n \"\"\"\n Calculate the maximum value in the data\n :return:float\n >>> ds2 = DataStatistics2([1, 2, 3, 4])\n >>> ds2.get_max()\n 4\n \"\"\"", "test_class": "DataStatistics2TestGetMax", "test_code": "class DataStatistics2TestGetMax(unittest.TestCase):\n def test_get_max_1(self):\n ds2 = DataStatistics2([1, 2, 3, 4])\n res = ds2.get_max()\n self.assertEqual(res, 4)\n\n def test_get_max_2(self):\n ds2 = DataStatistics2([1, 2, 203, 4])\n res = ds2.get_max()\n self.assertEqual(res, 203)\n\n def test_get_max_3(self):\n ds2 = DataStatistics2([-1, -4, 3, 2])\n res = ds2.get_max()\n self.assertEqual(res, 3)\n\n def test_get_max_4(self):\n ds2 = DataStatistics2([-1, 4, 3, 2])\n res = ds2.get_max()\n self.assertEqual(res, 4)\n\n def test_get_max_5(self):\n ds2 = DataStatistics2([-1, 444, 3, 2])\n res = ds2.get_max()\n self.assertEqual(res, 444)", "solution_code": "def get_max(self):\n return np.max(self.data)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.data" ], "method_dependencies": [] } }, { "method_name": "get_variance", "method_description": "def get_variance(self):\n \"\"\"\n Calculate variance, accurate to two digits after the Decimal separator\n :return:float\n >>> ds2 = DataStatistics2([1, 2, 3, 4])\n >>> ds2.get_variance()\n 1.25\n \"\"\"", "test_class": "DataStatistics2TestGetVariance", "test_code": "class DataStatistics2TestGetVariance(unittest.TestCase):\n def test_get_variance_1(self):\n ds2 = DataStatistics2([1, 2, 3, 4])\n res = ds2.get_variance()\n self.assertEqual(res, 1.25)\n\n def test_get_variance_2(self):\n ds2 = DataStatistics2([1, 2, 203, 4])\n res = ds2.get_variance()\n self.assertEqual(res, 7551.25)\n\n def test_get_variance_3(self):\n ds2 = DataStatistics2([1, 4, 3, 2])\n res = ds2.get_variance()\n self.assertEqual(res, 1.25)\n\n def test_get_variance_4(self):\n ds2 = DataStatistics2([11, 14, 13, 12])\n res = ds2.get_variance()\n self.assertEqual(res, 1.25)\n\n def test_get_variance_5(self):\n ds2 = DataStatistics2([111, 114, 113, 112])\n res = ds2.get_variance()\n self.assertEqual(res, 1.25)", "solution_code": "def get_variance(self):\n return round(np.var(self.data), 2)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.data" ], "method_dependencies": [] } }, { "method_name": "get_std_deviation", "method_description": "def get_std_deviation(self):\n \"\"\"\n Calculate standard deviation, accurate to two digits after the Decimal separator\n :return:float\n >>> ds2 = DataStatistics2([1, 2, 3, 4])\n >>> ds2.get_std_deviation()\n 1.12\n \"\"\"", "test_class": "DataStatistics2TestGetStdDeviation", "test_code": "class DataStatistics2TestGetStdDeviation(unittest.TestCase):\n def test_get_std_deviation_1(self):\n ds2 = DataStatistics2([1, 2, 3, 4])\n res = ds2.get_std_deviation()\n self.assertEqual(res, 1.12)\n\n def test_get_std_deviation_2(self):\n ds2 = DataStatistics2([1, 2, 203, 4])\n res = ds2.get_std_deviation()\n self.assertEqual(res, 86.9)\n\n def test_get_std_deviation_3(self):\n ds2 = DataStatistics2([1, 4, 3, 2])\n res = ds2.get_std_deviation()\n self.assertEqual(res, 1.12)\n\n def test_get_std_deviation_4(self):\n ds2 = DataStatistics2([11, 14, 13, 12])\n res = ds2.get_std_deviation()\n self.assertEqual(res, 1.12)\n\n def test_get_std_deviation_5(self):\n ds2 = DataStatistics2([111, 114, 113, 112])\n res = ds2.get_std_deviation()\n self.assertEqual(res, 1.12)", "solution_code": "def get_std_deviation(self):\n return round(np.std(self.data), 2)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.data" ], "method_dependencies": [] } }, { "method_name": "get_correlation", "method_description": "def get_correlation(self):\n \"\"\"\n Calculate correlation\n :return:float\n >>> ds2 = DataStatistics2([1, 2, 3, 4])\n >>> ds2.get_correlation()\n 1.0\n \"\"\"", "test_class": "DataStatistics2TestGetCorrelation", "test_code": "class DataStatistics2TestGetCorrelation(unittest.TestCase):\n def test_get_correlation_1(self):\n ds2 = DataStatistics2([1, 2, 3, 4])\n res = ds2.get_correlation()\n self.assertEqual(res, 1.0)\n\n def test_get_correlation_2(self):\n ds2 = DataStatistics2([1, 2, 203, 4])\n res = ds2.get_correlation()\n self.assertEqual(res, 1.0)\n\n def test_get_correlation_3(self):\n ds2 = DataStatistics2([1, 4, 3, 2])\n res = ds2.get_correlation()\n self.assertEqual(res, 1.0)\n\n def test_get_correlation_4(self):\n ds2 = DataStatistics2([11, 14, 13, 12])\n res = ds2.get_correlation()\n self.assertEqual(res, 1.0)\n\n def test_get_correlation_5(self):\n ds2 = DataStatistics2([111, 114, 113, 112])\n res = ds2.get_correlation()\n self.assertEqual(res, 1.0)", "solution_code": "def get_correlation(self):\n return np.corrcoef(self.data, rowvar=False)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.data" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_31", "skeleton": "\nimport math\n\nclass DataStatistics4:\n \"\"\"\n This is a class that performs advanced mathematical calculations and statistics, including correlation coefficient, skewness, kurtosis, and probability density function (PDF) for a normal distribution.\n \"\"\"\n\n\n @staticmethod\n def correlation_coefficient(data1, data2):\n \"\"\"\n Calculate the correlation coefficient of two sets of data.\n :param data1: The first set of data,list.\n :param data2: The second set of data,list.\n :return: The correlation coefficient, float.\n >>> DataStatistics4.correlation_coefficient([1, 2, 3], [4, 5, 6])\n 0.9999999999999998\n\n \"\"\"\n\n @staticmethod\n def skewness(data):\n \"\"\"\n Calculate the skewness of a set of data.\n :param data: The input data list, list.\n :return: The skewness, float.\n >>> DataStatistics4.skewness([1, 2, 5])\n 2.3760224064818463\n\n \"\"\"\n\n @staticmethod\n def kurtosis(data):\n \"\"\"\n Calculate the kurtosis of a set of data.\n :param data: The input data list, list.\n :return: The kurtosis, float.\n >>> DataStatistics4.kurtosis([1, 20,100])\n -1.5000000000000007\n\n \"\"\"\n\n @staticmethod\n def pdf(data, mu, sigma):\n \"\"\"\n Calculate the probability density function (PDF) of a set of data under a normal distribution.\n :param data: The input data list, list.\n :param mu: The mean of the normal distribution, float.\n :param sigma: The standard deviation of the normal distribution, float.\n :return: The probability density function (PDF), list.\n >>> DataStatistics4.pdf([1, 2, 3], 1, 1)\n [0.3989422804014327, 0.24197072451914337, 0.05399096651318806]\n\n \"\"\"", "test": "import unittest\n\n\nclass DataStatistics4TestCorrelationCoefficient(unittest.TestCase):\n def test_correlation_coefficient(self):\n self.assertEqual(DataStatistics4.correlation_coefficient([1, 2, 3], [4, 5, 6]), 0.9999999999999998)\n\n def test_correlation_coefficient_2(self):\n self.assertEqual(DataStatistics4.correlation_coefficient([1, 1, 1], [2, 2, 2]), 0)\n\n def test_correlation_coefficient_3(self):\n self.assertEqual(DataStatistics4.correlation_coefficient([1, 2, 3], [1, 2, 3]), 0.9999999999999998)\n\n def test_correlation_coefficient_4(self):\n self.assertEqual(DataStatistics4.correlation_coefficient([1, 2, 3], [1, 2, 4]), 0.9819805060619659)\n\n def test_correlation_coefficient_5(self):\n self.assertEqual(DataStatistics4.correlation_coefficient([1, 2, 3], [1, 5, 3]), 0.4999999999999999)\n\n\nclass DataStatistics4TestSkewness(unittest.TestCase):\n def test_skewness(self):\n self.assertEqual(DataStatistics4.skewness([1, 2, 5]), 2.3760224064818463)\n\n def test_skewness_2(self):\n self.assertEqual(DataStatistics4.skewness([1, 1, 1]), 0)\n\n def test_skewness_3(self):\n self.assertEqual(DataStatistics4.skewness([1, 2, 3]), 0)\n\n def test_skewness_4(self):\n self.assertEqual(DataStatistics4.skewness([1, 2, 4]), 1.7181079837227264)\n\n def test_skewness_5(self):\n self.assertEqual(DataStatistics4.skewness([1, 5, 3]), 0.0)\n\n\nclass DataStatistics4TestKurtosis(unittest.TestCase):\n def test_kurtosis(self):\n self.assertEqual(DataStatistics4.kurtosis([1, 2, 5]), -1.5000000000000002)\n\n def test_kurtosis_2(self):\n self.assertTrue(math.isnan(DataStatistics4.kurtosis([1, 1, 1])))\n\n def test_kurtosis_3(self):\n self.assertEqual(DataStatistics4.kurtosis([1, 2, 3]), -1.5000000000000002)\n\n def test_kurtosis_4(self):\n self.assertEqual(DataStatistics4.kurtosis([1, 2, 4]), -1.4999999999999996)\n\n def test_kurtosis_5(self):\n self.assertEqual(DataStatistics4.kurtosis([1, 5, 3]), -1.5000000000000002)\n\n\nclass DataStatistics4TestPDF(unittest.TestCase):\n def test_pdf(self):\n self.assertEqual(DataStatistics4.pdf([1, 2, 3], 1, 1),\n [0.3989422804014327, 0.24197072451914337, 0.05399096651318806])\n\n def test_pdf_2(self):\n self.assertEqual(DataStatistics4.pdf([1, 1, 1], 1, 1),\n [0.3989422804014327, 0.3989422804014327, 0.3989422804014327])\n\n def test_pdf_3(self):\n self.assertEqual(DataStatistics4.pdf([1, 2, 3], 2, 1),\n [0.24197072451914337, 0.3989422804014327, 0.24197072451914337])\n\n def test_pdf_4(self):\n self.assertEqual(DataStatistics4.pdf([1, 2, 3], 1, 2),\n [0.19947114020071635, 0.17603266338214976, 0.12098536225957168])\n\n def test_pdf_5(self):\n self.assertEqual(DataStatistics4.pdf([1, 2, 3], 2, 2),\n [0.17603266338214976, 0.19947114020071635, 0.17603266338214976])\n\n\nclass DataStatistics4TestMain(unittest.TestCase):\n def test_main(self):\n self.assertEqual(DataStatistics4.correlation_coefficient([1, 2, 3], [4, 5, 6]), 0.9999999999999998)\n self.assertEqual(DataStatistics4.skewness([1, 2, 5]), 2.3760224064818463)\n self.assertEqual(DataStatistics4.kurtosis([1, 2, 5]), -1.5000000000000002)\n self.assertEqual(DataStatistics4.pdf([1, 2, 3], 1, 1),\n [0.3989422804014327, 0.24197072451914337, 0.05399096651318806])", "solution_code": "import math\n\nclass DataStatistics4:\n\n @staticmethod\n def correlation_coefficient(data1, data2):\n n = len(data1)\n mean1 = sum(data1) / n\n mean2 = sum(data2) / n\n\n numerator = sum((data1[i] - mean1) * (data2[i] - mean2) for i in range(n))\n denominator = math.sqrt(sum((data1[i] - mean1) ** 2 for i in range(n))) * math.sqrt(sum((data2[i] - mean2) ** 2 for i in range(n)))\n\n return numerator / denominator if denominator != 0 else 0\n \n @staticmethod\n def skewness(data):\n n = len(data)\n mean = sum(data) / n\n variance = sum((x - mean) ** 2 for x in data) / n\n std_deviation = math.sqrt(variance)\n\n skewness = sum((x - mean) ** 3 for x in data) * n / ((n - 1) * (n - 2) * std_deviation ** 3) if std_deviation != 0 else 0\n\n return skewness\n \n @staticmethod\n def kurtosis(data):\n\n n = len(data)\n mean = sum(data) / n\n std_dev = math.sqrt(sum((x - mean) ** 2 for x in data) / n)\n\n if std_dev == 0:\n return math.nan\n\n centered_data = [(x - mean) for x in data]\n fourth_moment = sum(x ** 4 for x in centered_data) / n\n\n kurtosis_value = (fourth_moment / std_dev ** 4) - 3\n\n return kurtosis_value\n \n @staticmethod\n def pdf(data, mu, sigma):\n pdf_values = [1 / (sigma * math.sqrt(2 * math.pi)) * math.exp(-0.5 * ((x - mu) / sigma) ** 2) for x in data]\n return pdf_values", "import_statement": [ "import math" ], "class_description": " \"\"\"\n This is a class that performs advanced mathematical calculations and statistics, including correlation coefficient, skewness, kurtosis, and probability density function (PDF) for a normal distribution.\n \"\"\"\n", "class_name": "DataStatistics4", "test_classes": [ "DataStatistics4TestCorrelationCoefficient", "DataStatistics4TestSkewness", "DataStatistics4TestKurtosis", "DataStatistics4TestPDF", "DataStatistics4TestMain" ], "class_constructor": "class DataStatistics4: \n", "fields": [], "methods_info": [ { "method_name": "correlation_coefficient", "method_description": "def correlation_coefficient(data1, data2):\n \"\"\"\n Calculate the correlation coefficient of two sets of data.\n :param data1: The first set of data,list.\n :param data2: The second set of data,list.\n :return: The correlation coefficient, float.\n >>> DataStatistics4.correlation_coefficient([1, 2, 3], [4, 5, 6])\n 0.9999999999999998\n\n \"\"\"", "test_class": "DataStatistics4TestCorrelationCoefficient", "test_code": "class DataStatistics4TestCorrelationCoefficient(unittest.TestCase):\n def test_correlation_coefficient(self):\n self.assertEqual(DataStatistics4.correlation_coefficient([1, 2, 3], [4, 5, 6]), 0.9999999999999998)\n\n def test_correlation_coefficient_2(self):\n self.assertEqual(DataStatistics4.correlation_coefficient([1, 1, 1], [2, 2, 2]), 0)\n\n def test_correlation_coefficient_3(self):\n self.assertEqual(DataStatistics4.correlation_coefficient([1, 2, 3], [1, 2, 3]), 0.9999999999999998)\n\n def test_correlation_coefficient_4(self):\n self.assertEqual(DataStatistics4.correlation_coefficient([1, 2, 3], [1, 2, 4]), 0.9819805060619659)\n\n def test_correlation_coefficient_5(self):\n self.assertEqual(DataStatistics4.correlation_coefficient([1, 2, 3], [1, 5, 3]), 0.4999999999999999)", "solution_code": "def correlation_coefficient(data1, data2):\n n = len(data1)\n mean1 = sum(data1) / n\n mean2 = sum(data2) / n\n\n numerator = sum((data1[i] - mean1) * (data2[i] - mean2) for i in range(n))\n denominator = math.sqrt(sum((data1[i] - mean1) ** 2 for i in range(n))) * math.sqrt(sum((data2[i] - mean2) ** 2 for i in range(n)))\n\n return numerator / denominator if denominator != 0 else 0", "dependencies": { "Standalone": false, "lib_dependencies": [ "math" ], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "skewness", "method_description": "@staticmethod\n def skewness(data):\n \"\"\"\n Calculate the skewness of a set of data.\n :param data: The input data list, list.\n :return: The skewness, float.\n >>> DataStatistics4.skewness([1, 2, 5])\n 2.3760224064818463\n\n \"\"\"", "test_class": "DataStatistics4TestSkewness", "test_code": "class DataStatistics4TestSkewness(unittest.TestCase):\n def test_skewness(self):\n self.assertEqual(DataStatistics4.skewness([1, 2, 5]), 2.3760224064818463)\n\n def test_skewness_2(self):\n self.assertEqual(DataStatistics4.skewness([1, 1, 1]), 0)\n\n def test_skewness_3(self):\n self.assertEqual(DataStatistics4.skewness([1, 2, 3]), 0)\n\n def test_skewness_4(self):\n self.assertEqual(DataStatistics4.skewness([1, 2, 4]), 1.7181079837227264)\n\n def test_skewness_5(self):\n self.assertEqual(DataStatistics4.skewness([1, 5, 3]), 0.0)", "solution_code": "@staticmethod\n def skewness(data):\n n = len(data)\n mean = sum(data) / n\n variance = sum((x - mean) ** 2 for x in data) / n\n std_deviation = math.sqrt(variance)\n\n skewness = sum((x - mean) ** 3 for x in data) * n / ((n - 1) * (n - 2) * std_deviation ** 3) if std_deviation != 0 else 0\n\n return skewness", "dependencies": { "Standalone": false, "lib_dependencies": [ "math" ], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "kurtosis", "method_description": "@staticmethod\n def kurtosis(data):\n \"\"\"\n Calculate the kurtosis of a set of data.\n :param data: The input data list, list.\n :return: The kurtosis, float.\n >>> DataStatistics4.kurtosis([1, 20,100])\n -1.5000000000000007\n\n \"\"\"", "test_class": "DataStatistics4TestKurtosis", "test_code": "class DataStatistics4TestKurtosis(unittest.TestCase):\n def test_kurtosis(self):\n self.assertEqual(DataStatistics4.kurtosis([1, 2, 5]), -1.5000000000000002)\n\n def test_kurtosis_2(self):\n self.assertTrue(math.isnan(DataStatistics4.kurtosis([1, 1, 1])))\n\n def test_kurtosis_3(self):\n self.assertEqual(DataStatistics4.kurtosis([1, 2, 3]), -1.5000000000000002)\n\n def test_kurtosis_4(self):\n self.assertEqual(DataStatistics4.kurtosis([1, 2, 4]), -1.4999999999999996)\n\n def test_kurtosis_5(self):\n self.assertEqual(DataStatistics4.kurtosis([1, 5, 3]), -1.5000000000000002)", "solution_code": "@staticmethod\n def kurtosis(data):\n\n n = len(data)\n mean = sum(data) / n\n std_dev = math.sqrt(sum((x - mean) ** 2 for x in data) / n)\n\n if std_dev == 0:\n return math.nan\n\n centered_data = [(x - mean) for x in data]\n fourth_moment = sum(x ** 4 for x in centered_data) / n\n\n kurtosis_value = (fourth_moment / std_dev ** 4) - 3\n\n return kurtosis_value", "dependencies": { "Standalone": false, "lib_dependencies": [ "math" ], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "pdf", "method_description": "@staticmethod\n def pdf(data, mu, sigma):\n \"\"\"\n Calculate the probability density function (PDF) of a set of data under a normal distribution.\n :param data: The input data list, list.\n :param mu: The mean of the normal distribution, float.\n :param sigma: The standard deviation of the normal distribution, float.\n :return: The probability density function (PDF), list.\n >>> DataStatistics4.pdf([1, 2, 3], 1, 1)\n [0.3989422804014327, 0.24197072451914337, 0.05399096651318806]\n\n \"\"\"", "test_class": "DataStatistics4TestPDF", "test_code": "class DataStatistics4TestPDF(unittest.TestCase):\n def test_pdf(self):\n self.assertEqual(DataStatistics4.pdf([1, 2, 3], 1, 1),\n [0.3989422804014327, 0.24197072451914337, 0.05399096651318806])\n\n def test_pdf_2(self):\n self.assertEqual(DataStatistics4.pdf([1, 1, 1], 1, 1),\n [0.3989422804014327, 0.3989422804014327, 0.3989422804014327])\n\n def test_pdf_3(self):\n self.assertEqual(DataStatistics4.pdf([1, 2, 3], 2, 1),\n [0.24197072451914337, 0.3989422804014327, 0.24197072451914337])\n\n def test_pdf_4(self):\n self.assertEqual(DataStatistics4.pdf([1, 2, 3], 1, 2),\n [0.19947114020071635, 0.17603266338214976, 0.12098536225957168])\n\n def test_pdf_5(self):\n self.assertEqual(DataStatistics4.pdf([1, 2, 3], 2, 2),\n [0.17603266338214976, 0.19947114020071635, 0.17603266338214976])", "solution_code": "@staticmethod\n def pdf(data, mu, sigma):\n pdf_values = [1 / (sigma * math.sqrt(2 * math.pi)) * math.exp(-0.5 * ((x - mu) / sigma) ** 2) for x in data]\n return pdf_values", "dependencies": { "Standalone": false, "lib_dependencies": [ "math" ], "field_dependencies": [], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_32", "skeleton": "\nclass DecryptionUtils:\n \"\"\"\n This is a class that provides methods for decryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.\n \"\"\"\n\n def __init__(self, key):\n \"\"\"\n Initializes the decryption utility with a key.\n :param key: The key to use for decryption,str.\n \"\"\"\n self.key = key\n\n def caesar_decipher(self, ciphertext, shift):\n \"\"\"\n Deciphers the given ciphertext using the Caesar cipher\n :param ciphertext: The ciphertext to decipher,str.\n :param shift: The shift to use for decryption,int.\n :return: The deciphered plaintext,str.\n >>> d = DecryptionUtils('key')\n >>> d.caesar_decipher('ifmmp', 1)\n 'hello'\n\n \"\"\"\n\n def vigenere_decipher(self, ciphertext):\n \"\"\"\n Deciphers the given ciphertext using the Vigenere cipher\n :param ciphertext: The ciphertext to decipher,str.\n :return: The deciphered plaintext,str.\n >>> d = DecryptionUtils('key')\n >>> d.vigenere_decipher('ifmmp')\n 'ybocl'\n\n \"\"\"\n\n def rail_fence_decipher(self, encrypted_text, rails):\n \"\"\"\n Deciphers the given ciphertext using the Rail Fence cipher\n :param encrypted_text: The ciphertext to decipher,str.\n :param rails: The number of rails to use for decryption,int.\n :return: The deciphered plaintext,str.\n >>> d = DecryptionUtils('key')\n >>> d.rail_fence_decipher('Hoo!el,Wrdl l', 3)\n 'Hello, World!'\n\n \"\"\"", "test": "import unittest\n\n\nclass DecryptionUtilsTestCaesarDecipher(unittest.TestCase):\n def test_caesar_decipher(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.caesar_decipher('ifmmp', 1), 'hello')\n\n def test_caesar_decipher_2(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.caesar_decipher('bcdyza', 27), 'abcxyz')\n\n def test_caesar_decipher_3(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.caesar_decipher('bcd', 0), 'bcd')\n\n def test_caesar_decipher_4(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.caesar_decipher('bcd', 26), 'bcd')\n\n def test_caesar_decipher_5(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.caesar_decipher('bcd', -26), 'bcd')\n\n def test_caesar_decipher_6(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.caesar_decipher('IFMMP', 1), 'HELLO')\n\n def test_caesar_decipher_7(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.caesar_decipher('123', 1), '123')\n\n\nclass DecryptionUtilsTestVigenereDecipher(unittest.TestCase):\n def test_vigenere_decipher(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.vigenere_decipher('ifmmp'), 'ybocl')\n\n def test_vigenere_decipher_2(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.vigenere_decipher('rijvs'), 'hello')\n\n def test_vigenere_decipher_3(self):\n d = DecryptionUtils('longkey')\n self.assertEqual(d.vigenere_decipher('LpPjOjE'), 'AbCdEfG')\n\n def test_vigenere_decipher_4(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.vigenere_decipher('bcd'), 'ryf')\n\n def test_vigenere_decipher_5(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.vigenere_decipher('bcdaa'), 'ryfqw')\n\n def test_vigenere_decipher_6(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.vigenere_decipher('123'), '123')\n\n\nclass DecryptionUtilsTestRailFenceDecipher(unittest.TestCase):\n def test_rail_fence_decipher(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.rail_fence_decipher('Hoo!el,Wrdl l', 3), 'Hello, World!')\n\n def test_rail_fence_decipher_2(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.rail_fence_decipher('Hoo!el,Wrdl l', 4), 'H!W reoldll,o')\n\n def test_rail_fence_decipher_3(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.rail_fence_decipher('Hoo!el,Wrdl l', 5), 'Holr d,!oeWll')\n\n def test_rail_fence_decipher_4(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.rail_fence_decipher('Hoo!el,Wrdl l', 6), 'Holrll d,!oeW')\n\n def test_rail_fence_decipher_5(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.rail_fence_decipher('Hoo!el,Wrdl l', 7), 'Hoe,rll dWl!o')\n\n\nclass DecryptionUtilsTestMain(unittest.TestCase):\n def test_main(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.caesar_decipher('ifmmp', 1), 'hello')\n self.assertEqual(d.vigenere_decipher('ifmmp'), 'ybocl')\n self.assertEqual(d.rail_fence_decipher('Hoo!el,Wrdl l', 3), 'Hello, World!')", "solution_code": "class DecryptionUtils:\n def __init__(self, key):\n self.key = key\n \n def caesar_decipher(self, ciphertext, shift):\n plaintext = \"\"\n for char in ciphertext:\n if char.isalpha():\n if char.isupper():\n ascii_offset = 65\n else:\n ascii_offset = 97\n shifted_char = chr((ord(char) - ascii_offset - shift) % 26 + ascii_offset)\n plaintext += shifted_char\n else:\n plaintext += char\n return plaintext\n \n def vigenere_decipher(self, ciphertext):\n decrypted_text = \"\"\n key_index = 0\n for char in ciphertext:\n if char.isalpha():\n shift = ord(self.key[key_index % len(self.key)].lower()) - ord('a')\n decrypted_char = chr((ord(char.lower()) - ord('a') - shift) % 26 + ord('a'))\n decrypted_text += decrypted_char.upper() if char.isupper() else decrypted_char\n key_index += 1\n else:\n decrypted_text += char\n return decrypted_text\n \n def rail_fence_decipher(self, encrypted_text, rails):\n fence = [['\\n' for _ in range(len(encrypted_text))] for _ in range(rails)]\n direction = -1\n row, col = 0, 0\n\n for _ in range(len(encrypted_text)):\n if row == 0 or row == rails - 1:\n direction = -direction\n\n fence[row][col] = ''\n col += 1\n row += direction\n\n index = 0\n for i in range(rails):\n for j in range(len(encrypted_text)):\n if fence[i][j] == '':\n fence[i][j] = encrypted_text[index]\n index += 1\n\n plain_text = ''\n direction = -1\n row, col = 0, 0\n for _ in range(len(encrypted_text)):\n if row == 0 or row == rails - 1:\n direction = -direction\n\n plain_text += fence[row][col]\n col += 1\n row += direction\n\n return plain_text", "import_statement": [], "class_description": " \"\"\"\n This is a class that provides methods for decryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.\n \"\"\"\n", "class_name": "DecryptionUtils", "test_classes": [ "DecryptionUtilsTestCaesarDecipher", "DecryptionUtilsTestVigenereDecipher", "DecryptionUtilsTestRailFenceDecipher", "DecryptionUtilsTestMain" ], "class_constructor": "class DecryptionUtils: \n def __init__(self, key):\n \"\"\"\n Initializes the decryption utility with a key.\n :param key: The key to use for decryption,str.\n \"\"\"\n self.key = key\n\n", "fields": [ "self.key" ], "methods_info": [ { "method_name": "caesar_decipher", "method_description": "def caesar_decipher(self, ciphertext, shift):\n \"\"\"\n Deciphers the given ciphertext using the Caesar cipher\n :param ciphertext: The ciphertext to decipher,str.\n :param shift: The shift to use for decryption,int.\n :return: The deciphered plaintext,str.\n >>> d = DecryptionUtils('key')\n >>> d.caesar_decipher('ifmmp', 1)\n 'hello'\n\n \"\"\"", "test_class": "DecryptionUtilsTestCaesarDecipher", "test_code": "class DecryptionUtilsTestCaesarDecipher(unittest.TestCase):\n def test_caesar_decipher(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.caesar_decipher('ifmmp', 1), 'hello')\n\n def test_caesar_decipher_2(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.caesar_decipher('bcdyza', 27), 'abcxyz')\n\n def test_caesar_decipher_3(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.caesar_decipher('bcd', 0), 'bcd')\n\n def test_caesar_decipher_4(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.caesar_decipher('bcd', 26), 'bcd')\n\n def test_caesar_decipher_5(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.caesar_decipher('bcd', -26), 'bcd')\n\n def test_caesar_decipher_6(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.caesar_decipher('IFMMP', 1), 'HELLO')\n\n def test_caesar_decipher_7(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.caesar_decipher('123', 1), '123')", "solution_code": "def caesar_decipher(self, ciphertext, shift):\n plaintext = \"\"\n for char in ciphertext:\n if char.isalpha():\n if char.isupper():\n ascii_offset = 65\n else:\n ascii_offset = 97\n shifted_char = chr((ord(char) - ascii_offset - shift) % 26 + ascii_offset)\n plaintext += shifted_char\n else:\n plaintext += char\n return plaintext", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "vigenere_decipher", "method_description": "def vigenere_decipher(self, ciphertext):\n \"\"\"\n Deciphers the given ciphertext using the Vigenere cipher\n :param ciphertext: The ciphertext to decipher,str.\n :return: The deciphered plaintext,str.\n >>> d = DecryptionUtils('key')\n >>> d.vigenere_decipher('ifmmp')\n 'ybocl'\n\n \"\"\"", "test_class": "DecryptionUtilsTestVigenereDecipher", "test_code": "class DecryptionUtilsTestVigenereDecipher(unittest.TestCase):\n def test_vigenere_decipher(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.vigenere_decipher('ifmmp'), 'ybocl')\n\n def test_vigenere_decipher_2(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.vigenere_decipher('rijvs'), 'hello')\n\n def test_vigenere_decipher_3(self):\n d = DecryptionUtils('longkey')\n self.assertEqual(d.vigenere_decipher('LpPjOjE'), 'AbCdEfG')\n\n def test_vigenere_decipher_4(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.vigenere_decipher('bcd'), 'ryf')\n\n def test_vigenere_decipher_5(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.vigenere_decipher('bcdaa'), 'ryfqw')\n\n def test_vigenere_decipher_6(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.vigenere_decipher('123'), '123')", "solution_code": "def vigenere_decipher(self, ciphertext):\n decrypted_text = \"\"\n key_index = 0\n for char in ciphertext:\n if char.isalpha():\n shift = ord(self.key[key_index % len(self.key)].lower()) - ord('a')\n decrypted_char = chr((ord(char.lower()) - ord('a') - shift) % 26 + ord('a'))\n decrypted_text += decrypted_char.upper() if char.isupper() else decrypted_char\n key_index += 1\n else:\n decrypted_text += char\n return decrypted_text", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.key" ], "method_dependencies": [] } }, { "method_name": "rail_fence_decipher", "method_description": "def rail_fence_decipher(self, encrypted_text, rails):\n \"\"\"\n Deciphers the given ciphertext using the Rail Fence cipher\n :param encrypted_text: The ciphertext to decipher,str.\n :param rails: The number of rails to use for decryption,int.\n :return: The deciphered plaintext,str.\n >>> d = DecryptionUtils('key')\n >>> d.rail_fence_decipher('Hoo!el,Wrdl l', 3)\n 'Hello, World!'\n\n \"\"\"", "test_class": "DecryptionUtilsTestRailFenceDecipher", "test_code": "class DecryptionUtilsTestRailFenceDecipher(unittest.TestCase):\n def test_rail_fence_decipher(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.rail_fence_decipher('Hoo!el,Wrdl l', 3), 'Hello, World!')\n\n def test_rail_fence_decipher_2(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.rail_fence_decipher('Hoo!el,Wrdl l', 4), 'H!W reoldll,o')\n\n def test_rail_fence_decipher_3(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.rail_fence_decipher('Hoo!el,Wrdl l', 5), 'Holr d,!oeWll')\n\n def test_rail_fence_decipher_4(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.rail_fence_decipher('Hoo!el,Wrdl l', 6), 'Holrll d,!oeW')\n\n def test_rail_fence_decipher_5(self):\n d = DecryptionUtils('key')\n self.assertEqual(d.rail_fence_decipher('Hoo!el,Wrdl l', 7), 'Hoe,rll dWl!o')", "solution_code": "def rail_fence_decipher(self, encrypted_text, rails):\n fence = [['\\n' for _ in range(len(encrypted_text))] for _ in range(rails)]\n direction = -1\n row, col = 0, 0\n\n for _ in range(len(encrypted_text)):\n if row == 0 or row == rails - 1:\n direction = -direction\n\n fence[row][col] = ''\n col += 1\n row += direction\n\n index = 0\n for i in range(rails):\n for j in range(len(encrypted_text)):\n if fence[i][j] == '':\n fence[i][j] = encrypted_text[index]\n index += 1\n\n plain_text = ''\n direction = -1\n row, col = 0, 0\n for _ in range(len(encrypted_text)):\n if row == 0 or row == rails - 1:\n direction = -direction\n\n plain_text += fence[row][col]\n col += 1\n row += direction\n\n return plain_text", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_33", "skeleton": "\nclass DiscountStrategy:\n \"\"\"\n This is a class that allows to use different discount strategy based on shopping credit or shopping cart in supermarket.\n \"\"\"\n\n def __init__(self, customer, cart, promotion=None):\n \"\"\"\n Initialize the DiscountStrategy with customer information, a cart of items, and an optional promotion.\n :param customer: dict, customer information\n :param cart: list of dicts, a cart of items with details\n :param promotion: function, optional promotion applied to the order\n >>> customer = {'name': 'John Doe', 'fidelity': 1200}\n >>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]\n >>> DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)\n\n \"\"\"\n self.customer = customer\n self.cart = cart\n self.promotion = promotion\n self.total()\n\n def total(self):\n \"\"\"\n Calculate the total cost of items in the cart.\n :return: float, total cost of items\n >>> customer = {'name': 'John Doe', 'fidelity': 1200}\n >>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]\n >>> ds = DiscountStrategy(customer, cart)\n >>> ds.total()\n 329.0\n\n \"\"\"\n\n\n def due(self):\n \"\"\"\n Calculate the final amount to be paid after applying the discount.\n :return: float, final amount to be paid\n >>> customer = {'name': 'John Doe', 'fidelity': 1200}\n >>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]\n >>> ds = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)\n >>> ds.due()\n 312.55\n\n \"\"\"\n\n\n @staticmethod\n def FidelityPromo(order):\n \"\"\"\n Calculate the discount based on the fidelity points of the customer.Customers with over 1000 points can enjoy a 5% discount on the entire order.\n :param order: object, the order to apply the discount to\n :return: float, discount amount\n >>> customer = {'name': 'John Doe', 'fidelity': 1200}\n >>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]\n >>> order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)\n >>> DiscountStrategy.FidelityPromo(order)\n 16.45\n\n \"\"\"\n\n\n @staticmethod\n def BulkItemPromo(order):\n \"\"\"\n Calculate the discount based on bulk item quantity in the order.In the same order, if the quantity of a single item reaches 20 or more, each item will enjoy a 10% discount.\n :param order: object, the order to apply the discount to\n :return: float, discount amount\n >>> customer = {'name': 'John Doe', 'fidelity': 1200}\n >>> cart = [{'product': 'product', 'quantity': 20, 'price': 23.5}]\n >>> order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)\n >>> DiscountStrategy.BulkItemPromo(order)\n 47.0\n\n \"\"\"\n\n\n @staticmethod\n def LargeOrderPromo(order):\n \"\"\"\n Calculate the discount based on the number of different products in the order.If the quantity of different products in the order reaches 10 or more, the entire order will enjoy a 7% discount.\n :param order: object, the order to apply the discount to\n :return: float, discount amount\n >>> customer = {'name': 'John Doe', 'fidelity': 1200}\n >>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]\n >>> order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)\n >>> DiscountStrategy.LargeOrderPromo(order)\n 0.0\n\n \"\"\"", "test": "import unittest\n\n\nclass DiscountStrategyTestTotal(unittest.TestCase):\n def test_total_1(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart)\n expected_total = 250.0\n actual_total = order.total()\n self.assertEqual(actual_total, expected_total)\n\n def test_total_2(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 10.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart)\n expected_total = 150.0\n actual_total = order.total()\n self.assertEqual(actual_total, expected_total)\n\n def test_total_3(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 200.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart)\n expected_total = 2050.0\n actual_total = order.total()\n self.assertEqual(actual_total, expected_total)\n\n def test_total_4(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 1, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart)\n expected_total = 70.0\n actual_total = order.total()\n self.assertEqual(actual_total, expected_total)\n\n def test_total_5(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = []\n order = DiscountStrategy(customer, cart)\n expected_total = 0\n actual_total = order.total()\n self.assertEqual(actual_total, expected_total)\n\n\nclass DiscountStrategyTestDue(unittest.TestCase):\n def test_due_1(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart)\n expected_due = 250.0\n actual_due = order.due()\n self.assertEqual(actual_due, expected_due)\n\n def test_due_2(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)\n expected_due = 237.5\n actual_due = order.due()\n self.assertEqual(actual_due, expected_due)\n\n def test_due_3(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 20, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)\n expected_due = 410.0\n actual_due = order.due()\n self.assertEqual(actual_due, expected_due)\n\n def test_due_4(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': f'product{i}', 'quantity': 1, 'price': 10.0} for i in range(15)]\n order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)\n expected_due = 139.5\n actual_due = order.due()\n self.assertEqual(actual_due, expected_due)\n\n def test_due_5(self):\n customer = {'name': 'John Doe', 'fidelity': 900}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)\n expected_due = 250.0\n actual_due = order.due()\n self.assertEqual(actual_due, expected_due)\n\n\nclass DiscountStrategyTestFidelityPromo(unittest.TestCase):\n def test_fidelity_promo_1(self):\n customer = {'name': 'John Doe', 'fidelity': 1000}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)\n expected_discount = 12.5\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)\n\n def test_fidelity_promo_2(self):\n customer = {'name': 'John Doe', 'fidelity': 800}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)\n expected_discount = 0\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)\n\n def test_fidelity_promo_3(self):\n customer = {'name': 'John Doe', 'fidelity': 0}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)\n expected_discount = 0\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)\n\n def test_fidelity_promo_4(self):\n customer = {'name': 'John Doe', 'fidelity': 10000}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)\n expected_discount = 12.5\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)\n\n def test_fidelity_promo_5(self):\n customer = {'name': 'John Doe', 'fidelity': 1800}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)\n expected_discount = 12.5\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)\n\n\nclass DiscountStrategyTestBulkItemPromo(unittest.TestCase):\n def test_bulk_item_promo_1(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 20, 'price': 10.0},\n {'product': 'product2', 'quantity': 5, 'price': 5.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)\n expected_discount = 20.0\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)\n\n def test_bulk_item_promo_2(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 10.0},\n {'product': 'product2', 'quantity': 5, 'price': 5.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)\n expected_discount = 0\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)\n\n def test_bulk_item_promo_3(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 100, 'price': 10.0},\n {'product': 'product2', 'quantity': 5, 'price': 5.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)\n expected_discount = 100.0\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)\n\n def test_bulk_item_promo_4(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 1, 'price': 10.0},\n {'product': 'product2', 'quantity': 5, 'price': 5.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)\n expected_discount = 0.0\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)\n\n def test_bulk_item_promo_5(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 30, 'price': 10.0},\n {'product': 'product2', 'quantity': 5, 'price': 5.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)\n expected_discount = 30.0\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)\n\n\nclass DiscountStrategyTestLargeOrderPromo(unittest.TestCase):\n def test_large_order_promo_1(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': f'product{i}', 'quantity': 1, 'price': 10.0} for i in range(10)]\n order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)\n expected_discount = 7.0\n actual_discount = order.promotion(order)\n self.assertAlmostEqual(actual_discount, expected_discount)\n\n def test_large_order_promo_2(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': f'product{i}', 'quantity': 1, 'price': 10.0} for i in range(5)]\n order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)\n expected_discount = 0\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)\n\n def test_large_order_promo_3(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': f'product{i}', 'quantity': 1, 'price': 10.0} for i in range(100)]\n order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)\n expected_discount = 70.0\n actual_discount = order.promotion(order)\n self.assertAlmostEqual(actual_discount, expected_discount)\n\n def test_large_order_promo_4(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': f'product{i}', 'quantity': 1, 'price': 10.0} for i in range(1000)]\n order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)\n expected_discount = 700.0\n actual_discount = order.promotion(order)\n self.assertAlmostEqual(actual_discount, expected_discount)\n\n def test_large_order_promo_5(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': f'product{i}', 'quantity': 1, 'price': 10.0} for i in range(1)]\n order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)\n expected_discount = 0.0\n actual_discount = order.promotion(order)\n self.assertAlmostEqual(actual_discount, expected_discount)\n\n\nclass DiscountStrategyTest(unittest.TestCase):\n def test_DiscountStrategy(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart)\n expected_total = 250.0\n actual_total = order.total()\n self.assertEqual(actual_total, expected_total)\n\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart)\n expected_due = 250.0\n actual_due = order.due()\n self.assertEqual(actual_due, expected_due)\n\n customer = {'name': 'John Doe', 'fidelity': 1000}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)\n expected_discount = 12.5\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)\n\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 20, 'price': 10.0},\n {'product': 'product2', 'quantity': 5, 'price': 5.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)\n expected_discount = 20.0\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)\n\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': f'product{i}', 'quantity': 1, 'price': 10.0} for i in range(10)]\n order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)\n expected_discount = 7.0\n actual_discount = order.promotion(order)\n self.assertAlmostEqual(actual_discount, expected_discount)", "solution_code": "class DiscountStrategy:\n def __init__(self, customer, cart, promotion=None):\n self.customer = customer\n self.cart = cart\n self.promotion = promotion\n self.__total = self.total()\n\n def total(self):\n self.__total = sum(item['quantity'] * item['price'] for item in self.cart)\n return self.__total\n\n def due(self):\n if self.promotion is None:\n discount = 0\n else:\n discount = self.promotion(self)\n return self.__total - discount\n\n @staticmethod\n def FidelityPromo(order):\n return order.total() * 0.05 if order.customer['fidelity'] >= 1000 else 0\n\n @staticmethod\n def BulkItemPromo(order):\n discount = 0\n for item in order.cart:\n if item['quantity'] >= 20:\n discount += item['quantity'] * item['price'] * 0.1\n return discount\n\n @staticmethod\n def LargeOrderPromo(order):\n return order.total() * 0.07 if len({item['product'] for item in order.cart}) >= 10 else 0", "import_statement": [], "class_description": " \"\"\"\n This is a class that allows to use different discount strategy based on shopping credit or shopping cart in supermarket.\n \"\"\"\n", "class_name": "DiscountStrategy", "test_classes": [ "DiscountStrategyTestTotal", "DiscountStrategyTestDue", "DiscountStrategyTestFidelityPromo", "DiscountStrategyTestBulkItemPromo", "DiscountStrategyTestLargeOrderPromo", "DiscountStrategyTest" ], "class_constructor": "class DiscountStrategy: \n def __init__(self, customer, cart, promotion=None):\n \"\"\"\n Initialize the DiscountStrategy with customer information, a cart of items, and an optional promotion.\n :param customer: dict, customer information\n :param cart: list of dicts, a cart of items with details\n :param promotion: function, optional promotion applied to the order\n >>> customer = {'name': 'John Doe', 'fidelity': 1200}\n >>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]\n >>> DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)\n\n \"\"\"\n self.customer = customer\n self.cart = cart\n self.promotion = promotion\n self.total()\n\n", "fields": [ "self.cart", "self.customer", "self.promotion" ], "methods_info": [ { "method_name": "total", "method_description": "def total(self):\n \"\"\"\n Calculate the total cost of items in the cart.\n :return: float, total cost of items\n >>> customer = {'name': 'John Doe', 'fidelity': 1200}\n >>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]\n >>> ds = DiscountStrategy(customer, cart)\n >>> ds.total()\n 329.0\n\n \"\"\"", "test_class": "DiscountStrategyTestTotal", "test_code": "class DiscountStrategyTestTotal(unittest.TestCase):\n def test_total_1(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart)\n expected_total = 250.0\n actual_total = order.total()\n self.assertEqual(actual_total, expected_total)\n\n def test_total_2(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 10.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart)\n expected_total = 150.0\n actual_total = order.total()\n self.assertEqual(actual_total, expected_total)\n\n def test_total_3(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 200.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart)\n expected_total = 2050.0\n actual_total = order.total()\n self.assertEqual(actual_total, expected_total)\n\n def test_total_4(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 1, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart)\n expected_total = 70.0\n actual_total = order.total()\n self.assertEqual(actual_total, expected_total)\n\n def test_total_5(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = []\n order = DiscountStrategy(customer, cart)\n expected_total = 0\n actual_total = order.total()\n self.assertEqual(actual_total, expected_total)", "solution_code": "def total(self):\n self.__total = sum(item['quantity'] * item['price'] for item in self.cart)\n return self.__total", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.cart" ], "method_dependencies": [] } }, { "method_name": "due", "method_description": "def due(self):\n \"\"\"\n Calculate the final amount to be paid after applying the discount.\n :return: float, final amount to be paid\n >>> customer = {'name': 'John Doe', 'fidelity': 1200}\n >>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]\n >>> ds = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)\n >>> ds.due()\n 312.55\n\n \"\"\"", "test_class": "DiscountStrategyTestDue", "test_code": "class DiscountStrategyTestDue(unittest.TestCase):\n def test_due_1(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart)\n expected_due = 250.0\n actual_due = order.due()\n self.assertEqual(actual_due, expected_due)\n\n def test_due_2(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)\n expected_due = 237.5\n actual_due = order.due()\n self.assertEqual(actual_due, expected_due)\n\n def test_due_3(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 20, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)\n expected_due = 410.0\n actual_due = order.due()\n self.assertEqual(actual_due, expected_due)\n\n def test_due_4(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': f'product{i}', 'quantity': 1, 'price': 10.0} for i in range(15)]\n order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)\n expected_due = 139.5\n actual_due = order.due()\n self.assertEqual(actual_due, expected_due)\n\n def test_due_5(self):\n customer = {'name': 'John Doe', 'fidelity': 900}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)\n expected_due = 250.0\n actual_due = order.due()\n self.assertEqual(actual_due, expected_due)", "solution_code": "def due(self):\n if self.promotion is None:\n discount = 0\n else:\n discount = self.promotion(self)\n return self.__total - discount", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.promotion" ], "method_dependencies": [ "total" ] } }, { "method_name": "FidelityPromo", "method_description": "@staticmethod\n def FidelityPromo(order):\n \"\"\"\n Calculate the discount based on the fidelity points of the customer.Customers with over 1000 points can enjoy a 5% discount on the entire order.\n :param order: object, the order to apply the discount to\n :return: float, discount amount\n >>> customer = {'name': 'John Doe', 'fidelity': 1200}\n >>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]\n >>> order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)\n >>> DiscountStrategy.FidelityPromo(order)\n 16.45\n\n \"\"\"", "test_class": "DiscountStrategyTestFidelityPromo", "test_code": "class DiscountStrategyTestFidelityPromo(unittest.TestCase):\n def test_fidelity_promo_1(self):\n customer = {'name': 'John Doe', 'fidelity': 1000}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)\n expected_discount = 12.5\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)\n\n def test_fidelity_promo_2(self):\n customer = {'name': 'John Doe', 'fidelity': 800}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)\n expected_discount = 0\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)\n\n def test_fidelity_promo_3(self):\n customer = {'name': 'John Doe', 'fidelity': 0}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)\n expected_discount = 0\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)\n\n def test_fidelity_promo_4(self):\n customer = {'name': 'John Doe', 'fidelity': 10000}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)\n expected_discount = 12.5\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)\n\n def test_fidelity_promo_5(self):\n customer = {'name': 'John Doe', 'fidelity': 1800}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 20.0},\n {'product': 'product2', 'quantity': 5, 'price': 10.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.FidelityPromo)\n expected_discount = 12.5\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)", "solution_code": "@staticmethod\n def FidelityPromo(order):\n return order.total() * 0.05 if order.customer['fidelity'] >= 1000 else 0", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "total" ] } }, { "method_name": "BulkItemPromo", "method_description": "@staticmethod\n def BulkItemPromo(order):\n \"\"\"\n Calculate the discount based on bulk item quantity in the order.In the same order, if the quantity of a single item reaches 20 or more, each item will enjoy a 10% discount.\n :param order: object, the order to apply the discount to\n :return: float, discount amount\n >>> customer = {'name': 'John Doe', 'fidelity': 1200}\n >>> cart = [{'product': 'product', 'quantity': 20, 'price': 23.5}]\n >>> order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)\n >>> DiscountStrategy.BulkItemPromo(order)\n 47.0\n\n \"\"\"", "test_class": "DiscountStrategyTestBulkItemPromo", "test_code": "class DiscountStrategyTestBulkItemPromo(unittest.TestCase):\n def test_bulk_item_promo_1(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 20, 'price': 10.0},\n {'product': 'product2', 'quantity': 5, 'price': 5.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)\n expected_discount = 20.0\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)\n\n def test_bulk_item_promo_2(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 10, 'price': 10.0},\n {'product': 'product2', 'quantity': 5, 'price': 5.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)\n expected_discount = 0\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)\n\n def test_bulk_item_promo_3(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 100, 'price': 10.0},\n {'product': 'product2', 'quantity': 5, 'price': 5.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)\n expected_discount = 100.0\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)\n\n def test_bulk_item_promo_4(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 1, 'price': 10.0},\n {'product': 'product2', 'quantity': 5, 'price': 5.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)\n expected_discount = 0.0\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)\n\n def test_bulk_item_promo_5(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': 'product1', 'quantity': 30, 'price': 10.0},\n {'product': 'product2', 'quantity': 5, 'price': 5.0}]\n order = DiscountStrategy(customer, cart, DiscountStrategy.BulkItemPromo)\n expected_discount = 30.0\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)", "solution_code": "@staticmethod\n def BulkItemPromo(order):\n discount = 0\n for item in order.cart:\n if item['quantity'] >= 20:\n discount += item['quantity'] * item['price'] * 0.1\n return discount", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "LargeOrderPromo", "method_description": "@staticmethod\n def LargeOrderPromo(order):\n \"\"\"\n Calculate the discount based on the number of different products in the order.If the quantity of different products in the order reaches 10 or more, the entire order will enjoy a 7% discount.\n :param order: object, the order to apply the discount to\n :return: float, discount amount\n >>> customer = {'name': 'John Doe', 'fidelity': 1200}\n >>> cart = [{'product': 'product', 'quantity': 14, 'price': 23.5}]\n >>> order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)\n >>> DiscountStrategy.LargeOrderPromo(order)\n 0.0\n\n \"\"\"", "test_class": "DiscountStrategyTestLargeOrderPromo", "test_code": "class DiscountStrategyTestLargeOrderPromo(unittest.TestCase):\n def test_large_order_promo_1(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': f'product{i}', 'quantity': 1, 'price': 10.0} for i in range(10)]\n order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)\n expected_discount = 7.0\n actual_discount = order.promotion(order)\n self.assertAlmostEqual(actual_discount, expected_discount)\n\n def test_large_order_promo_2(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': f'product{i}', 'quantity': 1, 'price': 10.0} for i in range(5)]\n order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)\n expected_discount = 0\n actual_discount = order.promotion(order)\n self.assertEqual(actual_discount, expected_discount)\n\n def test_large_order_promo_3(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': f'product{i}', 'quantity': 1, 'price': 10.0} for i in range(100)]\n order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)\n expected_discount = 70.0\n actual_discount = order.promotion(order)\n self.assertAlmostEqual(actual_discount, expected_discount)\n\n def test_large_order_promo_4(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': f'product{i}', 'quantity': 1, 'price': 10.0} for i in range(1000)]\n order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)\n expected_discount = 700.0\n actual_discount = order.promotion(order)\n self.assertAlmostEqual(actual_discount, expected_discount)\n\n def test_large_order_promo_5(self):\n customer = {'name': 'John Doe', 'fidelity': 1200}\n cart = [{'product': f'product{i}', 'quantity': 1, 'price': 10.0} for i in range(1)]\n order = DiscountStrategy(customer, cart, DiscountStrategy.LargeOrderPromo)\n expected_discount = 0.0\n actual_discount = order.promotion(order)\n self.assertAlmostEqual(actual_discount, expected_discount)", "solution_code": "@staticmethod\n def LargeOrderPromo(order):\n return order.total() * 0.07 if len({item['product'] for item in order.cart}) >= 10 else 0", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "total" ] } } ] }, { "task_id": "ClassEval_34", "skeleton": "\nfrom docx import Document\nfrom docx.shared import Pt\nfrom docx.enum.text import WD_PARAGRAPH_ALIGNMENT\n\n\nclass DocFileHandler:\n \"\"\"\n This is a class that handles Word documents and provides functionalities for reading, writing, and modifying the content of Word documents.\n \"\"\"\n\n def __init__(self, file_path):\n \"\"\"\n Initializes the DocFileHandler object with the specified file path.\n :param file_path: str, the path to the Word document file.\n \"\"\"\n self.file_path = file_path\n\n def read_text(self):\n \"\"\"\n Reads the content of a Word document and returns it as a string.\n :return: str, the content of the Word document.\n \"\"\"\n\n def write_text(self, content, font_size=12, alignment='left'):\n \"\"\"\n Writes the specified content to a Word document.\n :param content: str, the text content to write.\n :param font_size: int, optional, the font size of the text (default is 12).\n :param alignment: str, optional, the alignment of the text ('left', 'center', or 'right'; default is 'left').\n :return: bool, True if the write operation is successful, False otherwise.\n \"\"\"\n\n def add_heading(self, heading, level=1):\n \"\"\"\n Adds a heading to the Word document.\n :param heading: str, the text of the heading.\n :param level: int, optional, the level of the heading (1, 2, 3, etc.; default is 1).\n :return: bool, True if the heading is successfully added, False otherwise.\n \"\"\"\n\n def add_table(self, data):\n \"\"\"\n Adds a table to the Word document with the specified data.\n :param data: list of lists, the data to populate the table.\n :return: bool, True if the table is successfully added, False otherwise.\n \"\"\"\n\n def _get_alignment_value(self, alignment):\n \"\"\"\n Returns the alignment value corresponding to the given alignment string.\n :param alignment: str, the alignment string ('left', 'center', or 'right').\n :return: int, the alignment value.\n \"\"\"", "test": "import unittest\nimport os\n\n\nclass DocFileHandlerTestReadText(unittest.TestCase):\n def test_read_text_1(self):\n self.file_path = \"test_example.docx\"\n self.handler = DocFileHandler(self.file_path)\n doc = Document()\n doc.add_paragraph(\"Initial content\")\n doc.save(self.file_path)\n\n text_content = self.handler.read_text()\n expected_content = \"Initial content\"\n self.assertEqual(text_content, expected_content)\n\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n\n def test_read_text_2(self):\n self.file_path = \"test_example.docx\"\n self.handler = DocFileHandler(self.file_path)\n doc = Document()\n doc.add_paragraph(\"111\")\n doc.save(self.file_path)\n\n text_content = self.handler.read_text()\n expected_content = \"111\"\n self.assertEqual(text_content, expected_content)\n\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n\n def test_read_text_3(self):\n self.file_path = \"test_example.docx\"\n self.handler = DocFileHandler(self.file_path)\n doc = Document()\n doc.add_paragraph(\"aaa\")\n doc.save(self.file_path)\n\n text_content = self.handler.read_text()\n expected_content = \"aaa\"\n self.assertEqual(text_content, expected_content)\n\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n\n def test_read_text_4(self):\n self.file_path = \"test_example.docx\"\n self.handler = DocFileHandler(self.file_path)\n doc = Document()\n doc.add_paragraph(\"aaa\\nbbb\")\n doc.save(self.file_path)\n\n text_content = self.handler.read_text()\n expected_content = \"aaa\\nbbb\"\n self.assertEqual(text_content, expected_content)\n\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n\n def test_read_text_5(self):\n self.file_path = \"test_example.docx\"\n self.handler = DocFileHandler(self.file_path)\n doc = Document()\n doc.add_paragraph(\"\")\n doc.save(self.file_path)\n\n text_content = self.handler.read_text()\n expected_content = \"\"\n self.assertEqual(text_content, expected_content)\n\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n\n\nclass DocFileHandlerTestWriteText(unittest.TestCase):\n def setUp(self):\n self.file_path = \"test_example.docx\"\n self.handler = DocFileHandler(self.file_path)\n doc = Document()\n doc.add_paragraph(\"Initial content\")\n doc.save(self.file_path)\n\n def tearDown(self):\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n\n def test_write_text_1(self):\n new_content = \"New content 1\"\n self.handler.write_text(new_content)\n text_content = self.handler.read_text()\n self.assertEqual(text_content, new_content)\n\n def test_write_text_2(self):\n new_content = \"New content 2\"\n self.handler.write_text(new_content)\n text_content = self.handler.read_text()\n self.assertEqual(text_content, new_content)\n\n def test_write_text_3(self):\n new_content = \"New content 3\"\n self.handler.write_text(new_content)\n text_content = self.handler.read_text()\n self.assertEqual(text_content, new_content)\n\n def test_write_text_4(self):\n new_content = \"New content 4\"\n self.handler.write_text(new_content)\n text_content = self.handler.read_text()\n self.assertEqual(text_content, new_content)\n\n def test_write_text_5(self):\n new_content = \"\"\n self.handler.write_text(new_content)\n text_content = self.handler.read_text()\n self.assertEqual(text_content, new_content)\n\n\nclass DocFileHandlerTestAddHeading(unittest.TestCase):\n def setUp(self):\n self.file_path = \"test_example.docx\"\n self.handler = DocFileHandler(self.file_path)\n doc = Document()\n doc.add_paragraph(\"Initial content\")\n doc.save(self.file_path)\n\n def tearDown(self):\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n\n def test_add_heading_1(self):\n heading = \"Test Heading 1\"\n self.handler.add_heading(heading)\n doc = Document(self.file_path)\n headings = [p.text for p in doc.paragraphs if p.style.name.startswith('Heading')]\n self.assertIn(heading, headings)\n\n def test_add_heading_2(self):\n heading = \"Test Heading 2\"\n self.handler.add_heading(heading)\n doc = Document(self.file_path)\n headings = [p.text for p in doc.paragraphs if p.style.name.startswith('Heading')]\n self.assertIn(heading, headings)\n\n def test_add_heading_3(self):\n heading = \"Test Heading 3\"\n self.handler.add_heading(heading)\n doc = Document(self.file_path)\n headings = [p.text for p in doc.paragraphs if p.style.name.startswith('Heading')]\n self.assertIn(heading, headings)\n\n def test_add_heading_4(self):\n heading = \"Test Heading 4\"\n self.handler.add_heading(heading)\n doc = Document(self.file_path)\n headings = [p.text for p in doc.paragraphs if p.style.name.startswith('Heading')]\n self.assertIn(heading, headings)\n\n def test_add_heading_5(self):\n heading = \"Test Heading 5\"\n self.handler.add_heading(heading)\n doc = Document(self.file_path)\n headings = [p.text for p in doc.paragraphs if p.style.name.startswith('Heading')]\n self.assertIn(heading, headings)\n\n\nclass DocFileHandlerTestAddTable(unittest.TestCase):\n def setUp(self):\n self.file_path = \"test_example.docx\"\n self.handler = DocFileHandler(self.file_path)\n doc = Document()\n doc.add_paragraph(\"Initial content\")\n doc.save(self.file_path)\n\n def tearDown(self):\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n\n def test_add_table_1(self):\n data = [['Name', 'Age']]\n self.handler.add_table(data)\n doc = Document(self.file_path)\n table = doc.tables[0]\n self.assertEqual(len(table.rows), 1)\n self.assertEqual(len(table.columns), 2)\n\n def test_add_table_2(self):\n data = [['Name', 'Age'], ['John', '25']]\n self.handler.add_table(data)\n doc = Document(self.file_path)\n table = doc.tables[0]\n self.assertEqual(len(table.rows), 2)\n self.assertEqual(len(table.columns), 2)\n self.assertEqual(table.cell(1, 0).text, 'John')\n\n def test_add_table_3(self):\n data = [['Name', 'Age'], ['John', '25'], ['Emma', '30']]\n self.handler.add_table(data)\n doc = Document(self.file_path)\n table = doc.tables[0]\n self.assertEqual(len(table.rows), 3)\n self.assertEqual(len(table.columns), 2)\n self.assertEqual(table.cell(1, 0).text, 'John')\n self.assertEqual(table.cell(2, 1).text, '30')\n\n def test_add_table_4(self):\n data = [['Name', 'Age'], ['aaa', '25'], ['Emma', '30']]\n self.handler.add_table(data)\n doc = Document(self.file_path)\n table = doc.tables[0]\n self.assertEqual(len(table.rows), 3)\n self.assertEqual(len(table.columns), 2)\n self.assertEqual(table.cell(1, 0).text, 'aaa')\n self.assertEqual(table.cell(2, 1).text, '30')\n\n def test_add_table_5(self):\n data = [['Name', 'Age'], ['John', '25'], ['Emma', '90']]\n self.handler.add_table(data)\n doc = Document(self.file_path)\n table = doc.tables[0]\n self.assertEqual(len(table.rows), 3)\n self.assertEqual(len(table.columns), 2)\n self.assertEqual(table.cell(1, 0).text, 'John')\n self.assertEqual(table.cell(2, 1).text, '90')\n\n\nclass DocFileHandlerTest(unittest.TestCase):\n def test_DocFileHandler(self):\n self.file_path = \"test_example.docx\"\n self.handler = DocFileHandler(self.file_path)\n doc = Document()\n doc.add_paragraph(\"Initial content\")\n doc.save(self.file_path)\n\n text_content = self.handler.read_text()\n expected_content = \"Initial content\"\n self.assertEqual(text_content, expected_content)\n\n new_content = \"New content 1\"\n self.handler.write_text(new_content)\n text_content = self.handler.read_text()\n self.assertEqual(text_content, new_content)\n\n heading = \"Test Heading 1\"\n self.handler.add_heading(heading)\n doc = Document(self.file_path)\n headings = [p.text for p in doc.paragraphs if p.style.name.startswith('Heading')]\n self.assertIn(heading, headings)\n\n data = [['Name', 'Age']]\n self.handler.add_table(data)\n doc = Document(self.file_path)\n table = doc.tables[0]\n self.assertEqual(len(table.rows), 1)\n self.assertEqual(len(table.columns), 2)\n\n if os.path.exists(self.file_path):\n os.remove(self.file_path)", "solution_code": "from docx import Document\nfrom docx.shared import Pt\nfrom docx.enum.text import WD_PARAGRAPH_ALIGNMENT\n\n\nclass DocFileHandler:\n def __init__(self, file_path):\n self.file_path = file_path\n\n def read_text(self):\n doc = Document(self.file_path)\n text = []\n for paragraph in doc.paragraphs:\n text.append(paragraph.text)\n return \"\\n\".join(text)\n\n def write_text(self, content, font_size=12, alignment='left'):\n try:\n doc = Document()\n paragraph = doc.add_paragraph()\n run = paragraph.add_run(content)\n font = run.font\n font.size = Pt(font_size)\n alignment_value = self._get_alignment_value(alignment)\n paragraph.alignment = alignment_value\n doc.save(self.file_path)\n return True\n except:\n return False\n\n def add_heading(self, heading, level=1):\n try:\n doc = Document(self.file_path)\n doc.add_heading(heading, level)\n doc.save(self.file_path)\n return True\n except:\n return False\n\n def add_table(self, data):\n try:\n doc = Document(self.file_path)\n table = doc.add_table(rows=len(data), cols=len(data[0]))\n for i, row in enumerate(data):\n for j, cell_value in enumerate(row):\n table.cell(i, j).text = str(cell_value)\n doc.save(self.file_path)\n return True\n except:\n return False\n\n def _get_alignment_value(self, alignment):\n alignment_options = {\n 'left': WD_PARAGRAPH_ALIGNMENT.LEFT,\n 'center': WD_PARAGRAPH_ALIGNMENT.CENTER,\n 'right': WD_PARAGRAPH_ALIGNMENT.RIGHT\n }\n return alignment_options.get(alignment.lower(), WD_PARAGRAPH_ALIGNMENT.LEFT)", "import_statement": [ "from docx import Document", "from docx.shared import Pt", "from docx.enum.text import WD_PARAGRAPH_ALIGNMENT" ], "class_description": " \"\"\"\n This is a class that handles Word documents and provides functionalities for reading, writing, and modifying the content of Word documents.\n \"\"\"\n", "class_name": "DocFileHandler", "test_classes": [ "DocFileHandlerTestReadText", "DocFileHandlerTestWriteText", "DocFileHandlerTestAddHeading", "DocFileHandlerTestAddTable", "DocFileHandlerTest" ], "class_constructor": "class DocFileHandler: \n def __init__(self, file_path):\n \"\"\"\n Initializes the DocFileHandler object with the specified file path.\n :param file_path: str, the path to the Word document file.\n \"\"\"\n self.file_path = file_path\n\n", "fields": [ "self.file_path" ], "methods_info": [ { "method_name": "read_text", "method_description": "def read_text(self):\n \"\"\"\n Reads the content of a Word document and returns it as a string.\n :return: str, the content of the Word document.\n \"\"\"", "test_class": "DocFileHandlerTestReadText", "test_code": "class DocFileHandlerTestReadText(unittest.TestCase):\n def test_read_text_1(self):\n self.file_path = \"test_example.docx\"\n self.handler = DocFileHandler(self.file_path)\n doc = Document()\n doc.add_paragraph(\"Initial content\")\n doc.save(self.file_path)\n\n text_content = self.handler.read_text()\n expected_content = \"Initial content\"\n self.assertEqual(text_content, expected_content)\n\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n\n def test_read_text_2(self):\n self.file_path = \"test_example.docx\"\n self.handler = DocFileHandler(self.file_path)\n doc = Document()\n doc.add_paragraph(\"111\")\n doc.save(self.file_path)\n\n text_content = self.handler.read_text()\n expected_content = \"111\"\n self.assertEqual(text_content, expected_content)\n\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n\n def test_read_text_3(self):\n self.file_path = \"test_example.docx\"\n self.handler = DocFileHandler(self.file_path)\n doc = Document()\n doc.add_paragraph(\"aaa\")\n doc.save(self.file_path)\n\n text_content = self.handler.read_text()\n expected_content = \"aaa\"\n self.assertEqual(text_content, expected_content)\n\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n\n def test_read_text_4(self):\n self.file_path = \"test_example.docx\"\n self.handler = DocFileHandler(self.file_path)\n doc = Document()\n doc.add_paragraph(\"aaa\\nbbb\")\n doc.save(self.file_path)\n\n text_content = self.handler.read_text()\n expected_content = \"aaa\\nbbb\"\n self.assertEqual(text_content, expected_content)\n\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n\n def test_read_text_5(self):\n self.file_path = \"test_example.docx\"\n self.handler = DocFileHandler(self.file_path)\n doc = Document()\n doc.add_paragraph(\"\")\n doc.save(self.file_path)\n\n text_content = self.handler.read_text()\n expected_content = \"\"\n self.assertEqual(text_content, expected_content)\n\n if os.path.exists(self.file_path):\n os.remove(self.file_path)", "solution_code": "def read_text(self):\n doc = Document(self.file_path)\n text = []\n for paragraph in doc.paragraphs:\n text.append(paragraph.text)\n return \"\\n\".join(text)", "dependencies": { "Standalone": false, "lib_dependencies": [ "Document" ], "field_dependencies": [ "self.file_path" ], "method_dependencies": [] } }, { "method_name": "write_text", "method_description": "def write_text(self, content, font_size=12, alignment='left'):\n \"\"\"\n Writes the specified content to a Word document.\n :param content: str, the text content to write.\n :param font_size: int, optional, the font size of the text (default is 12).\n :param alignment: str, optional, the alignment of the text ('left', 'center', or 'right'; default is 'left').\n :return: bool, True if the write operation is successful, False otherwise.\n \"\"\"", "test_class": "DocFileHandlerTestWriteText", "test_code": "class DocFileHandlerTestWriteText(unittest.TestCase):\n def setUp(self):\n self.file_path = \"test_example.docx\"\n self.handler = DocFileHandler(self.file_path)\n doc = Document()\n doc.add_paragraph(\"Initial content\")\n doc.save(self.file_path)\n\n def tearDown(self):\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n\n def test_write_text_1(self):\n new_content = \"New content 1\"\n self.handler.write_text(new_content)\n text_content = self.handler.read_text()\n self.assertEqual(text_content, new_content)\n\n def test_write_text_2(self):\n new_content = \"New content 2\"\n self.handler.write_text(new_content)\n text_content = self.handler.read_text()\n self.assertEqual(text_content, new_content)\n\n def test_write_text_3(self):\n new_content = \"New content 3\"\n self.handler.write_text(new_content)\n text_content = self.handler.read_text()\n self.assertEqual(text_content, new_content)\n\n def test_write_text_4(self):\n new_content = \"New content 4\"\n self.handler.write_text(new_content)\n text_content = self.handler.read_text()\n self.assertEqual(text_content, new_content)\n\n def test_write_text_5(self):\n new_content = \"\"\n self.handler.write_text(new_content)\n text_content = self.handler.read_text()\n self.assertEqual(text_content, new_content)", "solution_code": "def write_text(self, content, font_size=12, alignment='left'):\n try:\n doc = Document()\n paragraph = doc.add_paragraph()\n run = paragraph.add_run(content)\n font = run.font\n font.size = Pt(font_size)\n alignment_value = self._get_alignment_value(alignment)\n paragraph.alignment = alignment_value\n doc.save(self.file_path)\n return True\n except:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [ "Document", "Pt" ], "field_dependencies": [ "self.file_path" ], "method_dependencies": [ "_get_alignment_value" ] } }, { "method_name": "add_heading", "method_description": "def add_heading(self, heading, level=1):\n \"\"\"\n Adds a heading to the Word document.\n :param heading: str, the text of the heading.\n :param level: int, optional, the level of the heading (1, 2, 3, etc.; default is 1).\n :return: bool, True if the heading is successfully added, False otherwise.\n \"\"\"", "test_class": "DocFileHandlerTestAddHeading", "test_code": "class DocFileHandlerTestAddHeading(unittest.TestCase):\n def setUp(self):\n self.file_path = \"test_example.docx\"\n self.handler = DocFileHandler(self.file_path)\n doc = Document()\n doc.add_paragraph(\"Initial content\")\n doc.save(self.file_path)\n\n def tearDown(self):\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n\n def test_add_heading_1(self):\n heading = \"Test Heading 1\"\n self.handler.add_heading(heading)\n doc = Document(self.file_path)\n headings = [p.text for p in doc.paragraphs if p.style.name.startswith('Heading')]\n self.assertIn(heading, headings)\n\n def test_add_heading_2(self):\n heading = \"Test Heading 2\"\n self.handler.add_heading(heading)\n doc = Document(self.file_path)\n headings = [p.text for p in doc.paragraphs if p.style.name.startswith('Heading')]\n self.assertIn(heading, headings)\n\n def test_add_heading_3(self):\n heading = \"Test Heading 3\"\n self.handler.add_heading(heading)\n doc = Document(self.file_path)\n headings = [p.text for p in doc.paragraphs if p.style.name.startswith('Heading')]\n self.assertIn(heading, headings)\n\n def test_add_heading_4(self):\n heading = \"Test Heading 4\"\n self.handler.add_heading(heading)\n doc = Document(self.file_path)\n headings = [p.text for p in doc.paragraphs if p.style.name.startswith('Heading')]\n self.assertIn(heading, headings)\n\n def test_add_heading_5(self):\n heading = \"Test Heading 5\"\n self.handler.add_heading(heading)\n doc = Document(self.file_path)\n headings = [p.text for p in doc.paragraphs if p.style.name.startswith('Heading')]\n self.assertIn(heading, headings)", "solution_code": "def add_heading(self, heading, level=1):\n try:\n doc = Document(self.file_path)\n doc.add_heading(heading, level)\n doc.save(self.file_path)\n return True\n except:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [ "Document" ], "field_dependencies": [ "self.file_path" ], "method_dependencies": [] } }, { "method_name": "add_table", "method_description": "def add_table(self, data):\n \"\"\"\n Adds a table to the Word document with the specified data.\n :param data: list of lists, the data to populate the table.\n :return: bool, True if the table is successfully added, False otherwise.\n \"\"\"", "test_class": "DocFileHandlerTestAddTable", "test_code": "class DocFileHandlerTestAddTable(unittest.TestCase):\n def setUp(self):\n self.file_path = \"test_example.docx\"\n self.handler = DocFileHandler(self.file_path)\n doc = Document()\n doc.add_paragraph(\"Initial content\")\n doc.save(self.file_path)\n\n def tearDown(self):\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n\n def test_add_table_1(self):\n data = [['Name', 'Age']]\n self.handler.add_table(data)\n doc = Document(self.file_path)\n table = doc.tables[0]\n self.assertEqual(len(table.rows), 1)\n self.assertEqual(len(table.columns), 2)\n\n def test_add_table_2(self):\n data = [['Name', 'Age'], ['John', '25']]\n self.handler.add_table(data)\n doc = Document(self.file_path)\n table = doc.tables[0]\n self.assertEqual(len(table.rows), 2)\n self.assertEqual(len(table.columns), 2)\n self.assertEqual(table.cell(1, 0).text, 'John')\n\n def test_add_table_3(self):\n data = [['Name', 'Age'], ['John', '25'], ['Emma', '30']]\n self.handler.add_table(data)\n doc = Document(self.file_path)\n table = doc.tables[0]\n self.assertEqual(len(table.rows), 3)\n self.assertEqual(len(table.columns), 2)\n self.assertEqual(table.cell(1, 0).text, 'John')\n self.assertEqual(table.cell(2, 1).text, '30')\n\n def test_add_table_4(self):\n data = [['Name', 'Age'], ['aaa', '25'], ['Emma', '30']]\n self.handler.add_table(data)\n doc = Document(self.file_path)\n table = doc.tables[0]\n self.assertEqual(len(table.rows), 3)\n self.assertEqual(len(table.columns), 2)\n self.assertEqual(table.cell(1, 0).text, 'aaa')\n self.assertEqual(table.cell(2, 1).text, '30')\n\n def test_add_table_5(self):\n data = [['Name', 'Age'], ['John', '25'], ['Emma', '90']]\n self.handler.add_table(data)\n doc = Document(self.file_path)\n table = doc.tables[0]\n self.assertEqual(len(table.rows), 3)\n self.assertEqual(len(table.columns), 2)\n self.assertEqual(table.cell(1, 0).text, 'John')\n self.assertEqual(table.cell(2, 1).text, '90')", "solution_code": "def add_table(self, data):\n try:\n doc = Document(self.file_path)\n table = doc.add_table(rows=len(data), cols=len(data[0]))\n for i, row in enumerate(data):\n for j, cell_value in enumerate(row):\n table.cell(i, j).text = str(cell_value)\n doc.save(self.file_path)\n return True\n except:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [ "Document" ], "field_dependencies": [ "self.file_path" ], "method_dependencies": [] } }, { "method_name": "_get_alignment_value", "method_description": "def _get_alignment_value(self, alignment):\n \"\"\"\n Returns the alignment value corresponding to the given alignment string.\n :param alignment: str, the alignment string ('left', 'center', or 'right').\n :return: int, the alignment value.\n \"\"\"", "test_class": "DocFileHandlerTest", "test_code": "class DocFileHandlerTest(unittest.TestCase):\n def test_DocFileHandler(self):\n self.file_path = \"test_example.docx\"\n self.handler = DocFileHandler(self.file_path)\n doc = Document()\n doc.add_paragraph(\"Initial content\")\n doc.save(self.file_path)\n\n text_content = self.handler.read_text()\n expected_content = \"Initial content\"\n self.assertEqual(text_content, expected_content)\n\n new_content = \"New content 1\"\n self.handler.write_text(new_content)\n text_content = self.handler.read_text()\n self.assertEqual(text_content, new_content)\n\n heading = \"Test Heading 1\"\n self.handler.add_heading(heading)\n doc = Document(self.file_path)\n headings = [p.text for p in doc.paragraphs if p.style.name.startswith('Heading')]\n self.assertIn(heading, headings)\n\n data = [['Name', 'Age']]\n self.handler.add_table(data)\n doc = Document(self.file_path)\n table = doc.tables[0]\n self.assertEqual(len(table.rows), 1)\n self.assertEqual(len(table.columns), 2)\n\n if os.path.exists(self.file_path):\n os.remove(self.file_path)", "solution_code": "def _get_alignment_value(self, alignment):\n alignment_options = {\n 'left': WD_PARAGRAPH_ALIGNMENT.LEFT,\n 'center': WD_PARAGRAPH_ALIGNMENT.CENTER,\n 'right': WD_PARAGRAPH_ALIGNMENT.RIGHT\n }\n return alignment_options.get(alignment.lower(), WD_PARAGRAPH_ALIGNMENT.LEFT)", "dependencies": { "Standalone": false, "lib_dependencies": [ "WD_PARAGRAPH_ALIGNMENT" ], "field_dependencies": [], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_35", "skeleton": "\nclass EightPuzzle:\n \"\"\"\n This class is an implementation of the classic 8-puzzle game, including methods for finding the blank tile, making moves, getting possible moves, and solving the puzzle using a breadth-first search algorithm.\n \"\"\"\n\n def __init__(self, initial_state):\n \"\"\"\n Initializing the initial state of Eight Puzzle Game, stores in attribute self.initial_state.\n And set the goal state of this game, stores in self.goal_state. In this case, set the size as 3*3\n :param initial_state: a 3*3 size list of Integer, stores the initial state\n \"\"\"\n self.initial_state = initial_state\n self.goal_state = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]\n\n def find_blank(self, state):\n \"\"\"\n Find the blank position of current state, which is the 0 element.\n :param state: a 3*3 size list of Integer, stores the current state.\n :return i, j: two Integers, represent the coordinate of the blank block.\n >>> eightPuzzle = EightPuzzle([[2, 3, 4], [5, 8, 1], [6, 0, 7]])\n >>> eightPuzzle.find_blank([[2, 3, 4], [5, 8, 1], [6, 0, 7]])\n (2, 1)\n \"\"\"\n\n def move(self, state, direction):\n \"\"\"\n Find the blank block, then makes the board moves forward the given direction.\n :param state: a 3*3 size list of Integer, stores the state before moving.\n :param direction: str, only has 4 direction 'up', 'down', 'left', 'right'\n :return new_state: a 3*3 size list of Integer, stores the state after moving.\n >>> eightPuzzle.move([[2, 3, 4], [5, 8, 1], [6, 0, 7]], 'left')\n [[2, 3, 4], [5, 8, 1], [0, 6, 7]]\n \"\"\"\n\n def get_possible_moves(self, state):\n \"\"\"\n According the current state, find all the possible moving directions. Only has 4 direction 'up', 'down', 'left', 'right'.\n :param state: a 3*3 size list of Integer, stores the current state.\n :return moves: a list of str, store all the possible moving directions according to the current state.\n >>> eightPuzzle.get_possible_moves([[2, 3, 4], [5, 8, 1], [6, 0, 7]])\n ['up', 'left', 'right']\n \"\"\"\n\n def solve(self):\n \"\"\"\n Use BFS algorithm to find the path solution which makes the initial state to the goal method.\n Maintain a list as a queue, named as open_list, append the initial state.\n Always visit and pop the 0 index element, invoke get_possible_moves method find all the possible directions.\n Traversal the possible_moves list and invoke move method to get several new states.Then append them.\n redo the above steps until the open_list is empty or the state has changed to the goal state.\n :return path: list of str, the solution to the goal state.\n >>> eightPuzzle = EightPuzzle([[1, 2, 3], [4, 5, 6], [7, 0, 8]])\n >>> eightPuzzle.solve()\n ['right']\n \"\"\"", "test": "import unittest\n\nclass EightPuzzleTestFindBlank(unittest.TestCase):\n def test_find_blank_1(self):\n state = [[2, 3, 4], [5, 8, 1], [6, 0, 7]]\n eightPuzzle = EightPuzzle(state)\n self.assertEqual(eightPuzzle.find_blank(state), (2, 1))\n\n def test_find_blank_2(self):\n state = [[2, 3, 4], [5, 0, 1], [6, 8, 7]]\n eightPuzzle = EightPuzzle(state)\n self.assertEqual(eightPuzzle.find_blank(state), (1, 1))\n\n def test_find_blank_3(self):\n state = [[2, 3, 4], [5, 8, 1], [6, 8, 7]]\n eightPuzzle = EightPuzzle(state)\n self.assertEqual(eightPuzzle.find_blank(state), None)\n\n def test_find_blank_4(self):\n state = [[2, 3, 4], [5, 8, 1], [6, 8, 7]]\n eightPuzzle = EightPuzzle(state)\n self.assertEqual(eightPuzzle.find_blank(state), None)\n\n def test_find_blank_5(self):\n state = [[2, 3, 4], [5, 8, 1], [6, 8, 7]]\n eightPuzzle = EightPuzzle(state)\n self.assertEqual(eightPuzzle.find_blank(state), None)\n\n\nclass EightPuzzleTestMove(unittest.TestCase):\n def setUp(self):\n self.initial_state = [[2, 3, 4], [5, 0, 1], [6, 8, 7]]\n self.eightPuzzle = EightPuzzle(self.initial_state)\n\n def test_move_1(self):\n result = self.eightPuzzle.move(self.initial_state, 'up')\n expected = [[2, 0, 4], [5, 3, 1], [6, 8, 7]]\n self.assertEqual(result, expected)\n\n def test_move_2(self):\n result = self.eightPuzzle.move(self.initial_state, 'down')\n expected = [[2, 3, 4], [5, 8, 1], [6, 0, 7]]\n self.assertEqual(result, expected)\n\n def test_move_3(self):\n result = self.eightPuzzle.move(self.initial_state, 'left')\n expected = [[2, 3, 4], [0, 5, 1], [6, 8, 7]]\n self.assertEqual(result, expected)\n\n def test_move_4(self):\n result = self.eightPuzzle.move(self.initial_state, 'right')\n expected = [[2, 3, 4], [5, 1, 0], [6, 8, 7]]\n self.assertEqual(result, expected)\n\n def test_move_5(self):\n result = self.eightPuzzle.move(self.initial_state, '???')\n expected = [[2, 3, 4], [5, 0, 1], [6, 8, 7]]\n self.assertEqual(result, expected)\n\n\nclass EightPuzzleTestGetPossibleMoves(unittest.TestCase):\n def test_get_possible_moves_1(self):\n eightPuzzle = EightPuzzle(None)\n state = [[2, 3, 4], [5, 0, 1], [6, 8, 7]]\n result = eightPuzzle.get_possible_moves(state)\n expected = ['up', 'down', 'left', 'right']\n for direction in result:\n self.assertIn(direction, expected)\n\n def test_get_possible_moves_2(self):\n eightPuzzle = EightPuzzle(None)\n state = [[2, 3, 4], [5, 8, 1], [6, 0, 7]]\n result = eightPuzzle.get_possible_moves(state)\n expected = ['up', 'left', 'right']\n for direction in result:\n self.assertIn(direction, expected)\n\n def test_get_possible_moves_3(self):\n eightPuzzle = EightPuzzle(None)\n state = [[2, 0, 4], [5, 3, 1], [6, 8, 7]]\n result = eightPuzzle.get_possible_moves(state)\n expected = ['down', 'left', 'right']\n for direction in result:\n self.assertIn(direction, expected)\n\n def test_get_possible_moves_4(self):\n eightPuzzle = EightPuzzle(None)\n state = [[2, 3, 4], [5, 1, 0], [6, 8, 7]]\n result = eightPuzzle.get_possible_moves(state)\n expected = ['up', 'down', 'left']\n for direction in result:\n self.assertIn(direction, expected)\n\n def test_get_possible_moves_5(self):\n eightPuzzle = EightPuzzle(None)\n state = [[2, 3, 4], [0, 5, 1], [6, 8, 7]]\n result = eightPuzzle.get_possible_moves(state)\n expected = ['up', 'down', 'right']\n for direction in result:\n self.assertIn(direction, expected)\n\n\nclass EightPuzzleTestSolve(unittest.TestCase):\n def test_solve_1(self):\n eightPuzzle = EightPuzzle([[1, 2, 3], [4, 5, 6], [7, 0, 8]])\n result = eightPuzzle.solve()\n expected = ['right']\n self.assertEqual(result, expected)\n\n def test_solve_2(self):\n eightPuzzle = EightPuzzle([[1, 2, 3], [4, 0, 6], [7, 5, 8]])\n result = eightPuzzle.solve()\n expected = ['down', 'right']\n self.assertEqual(result, expected)\n\n def test_solve_3(self):\n eightPuzzle = EightPuzzle([[1, 2, 3], [0, 4, 5], [6, 7, 8]])\n result = eightPuzzle.solve()\n expected = ['right', 'right', 'down', 'left', 'left', 'up', 'right', 'down', 'right', 'up', 'left', 'left', 'down', 'right', 'right']\n self.assertEqual(result, expected)\n\n def test_solve_4(self):\n eightPuzzle = EightPuzzle([[1, 2, 3], [4, 5, 6], [7, 8, 0]])\n result = eightPuzzle.solve()\n expected = []\n self.assertEqual(result, expected)\n\n def test_solve_5(self):\n eightPuzzle = EightPuzzle([[1, 2, 3], [4, 5, 6], [0, 7, 8]])\n result = eightPuzzle.solve()\n expected = ['right', 'right']\n self.assertEqual(result, expected)\n\n def test_solve_6(self):\n eightPuzzle = EightPuzzle([[0, 0, 0], [0, 0, 0], [0, 0, 0]])\n result = eightPuzzle.solve()\n expected = None\n self.assertEqual(result, expected)", "solution_code": "class EightPuzzle:\n def __init__(self, initial_state):\n self.initial_state = initial_state\n self.goal_state = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]\n\n def find_blank(self, state):\n for i in range(3):\n for j in range(3):\n if state[i][j] == 0:\n return i, j\n\n def move(self, state, direction):\n i, j = self.find_blank(state)\n new_state = [row[:] for row in state]\n\n if direction == 'up':\n new_state[i][j], new_state[i - 1][j] = new_state[i - 1][j], new_state[i][j]\n elif direction == 'down':\n new_state[i][j], new_state[i + 1][j] = new_state[i + 1][j], new_state[i][j]\n elif direction == 'left':\n new_state[i][j], new_state[i][j - 1] = new_state[i][j - 1], new_state[i][j]\n elif direction == 'right':\n new_state[i][j], new_state[i][j + 1] = new_state[i][j + 1], new_state[i][j]\n\n return new_state\n\n def get_possible_moves(self, state):\n moves = []\n i, j = self.find_blank(state)\n\n if i > 0:\n moves.append('up')\n if i < 2:\n moves.append('down')\n if j > 0:\n moves.append('left')\n if j < 2:\n moves.append('right')\n\n return moves\n\n def solve(self):\n open_list = [(self.initial_state, [])]\n closed_list = []\n\n while open_list:\n current_state, path = open_list.pop(0)\n closed_list.append(current_state)\n\n if current_state == self.goal_state:\n return path\n\n for move in self.get_possible_moves(current_state):\n new_state = self.move(current_state, move)\n if new_state not in closed_list:\n open_list.append((new_state, path + [move]))\n\n return None", "import_statement": [], "class_description": " \"\"\"\n This class is an implementation of the classic 8-puzzle game, including methods for finding the blank tile, making moves, getting possible moves, and solving the puzzle using a breadth-first search algorithm.\n \"\"\"\n", "class_name": "EightPuzzle", "test_classes": [ "EightPuzzleTestFindBlank", "EightPuzzleTestMove", "EightPuzzleTestGetPossibleMoves", "EightPuzzleTestSolve" ], "class_constructor": "class EightPuzzle: \n def __init__(self, initial_state):\n \"\"\"\n Initializing the initial state of Eight Puzzle Game, stores in attribute self.initial_state.\n And set the goal state of this game, stores in self.goal_state. In this case, set the size as 3*3\n :param initial_state: a 3*3 size list of Integer, stores the initial state\n \"\"\"\n self.initial_state = initial_state\n self.goal_state = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]\n\n", "fields": [ "self.goal_state", "self.initial_state" ], "methods_info": [ { "method_name": "find_blank", "method_description": "def find_blank(self, state):\n \"\"\"\n Find the blank position of current state, which is the 0 element.\n :param state: a 3*3 size list of Integer, stores the current state.\n :return i, j: two Integers, represent the coordinate of the blank block.\n >>> eightPuzzle = EightPuzzle([[2, 3, 4], [5, 8, 1], [6, 0, 7]])\n >>> eightPuzzle.find_blank([[2, 3, 4], [5, 8, 1], [6, 0, 7]])\n (2, 1)\n \"\"\"", "test_class": "EightPuzzleTestFindBlank", "test_code": "class EightPuzzleTestFindBlank(unittest.TestCase):\n def test_find_blank_1(self):\n state = [[2, 3, 4], [5, 8, 1], [6, 0, 7]]\n eightPuzzle = EightPuzzle(state)\n self.assertEqual(eightPuzzle.find_blank(state), (2, 1))\n\n def test_find_blank_2(self):\n state = [[2, 3, 4], [5, 0, 1], [6, 8, 7]]\n eightPuzzle = EightPuzzle(state)\n self.assertEqual(eightPuzzle.find_blank(state), (1, 1))\n\n def test_find_blank_3(self):\n state = [[2, 3, 4], [5, 8, 1], [6, 8, 7]]\n eightPuzzle = EightPuzzle(state)\n self.assertEqual(eightPuzzle.find_blank(state), None)\n\n def test_find_blank_4(self):\n state = [[2, 3, 4], [5, 8, 1], [6, 8, 7]]\n eightPuzzle = EightPuzzle(state)\n self.assertEqual(eightPuzzle.find_blank(state), None)\n\n def test_find_blank_5(self):\n state = [[2, 3, 4], [5, 8, 1], [6, 8, 7]]\n eightPuzzle = EightPuzzle(state)\n self.assertEqual(eightPuzzle.find_blank(state), None)", "solution_code": "def find_blank(self, state):\n for i in range(3):\n for j in range(3):\n if state[i][j] == 0:\n return i, j", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "move", "method_description": "def move(self, state, direction):\n \"\"\"\n Find the blank block, then makes the board moves forward the given direction.\n :param state: a 3*3 size list of Integer, stores the state before moving.\n :param direction: str, only has 4 direction 'up', 'down', 'left', 'right'\n :return new_state: a 3*3 size list of Integer, stores the state after moving.\n >>> eightPuzzle.move([[2, 3, 4], [5, 8, 1], [6, 0, 7]], 'left')\n [[2, 3, 4], [5, 8, 1], [0, 6, 7]]\n \"\"\"", "test_class": "EightPuzzleTestMove", "test_code": "class EightPuzzleTestMove(unittest.TestCase):\n def setUp(self):\n self.initial_state = [[2, 3, 4], [5, 0, 1], [6, 8, 7]]\n self.eightPuzzle = EightPuzzle(self.initial_state)\n\n def test_move_1(self):\n result = self.eightPuzzle.move(self.initial_state, 'up')\n expected = [[2, 0, 4], [5, 3, 1], [6, 8, 7]]\n self.assertEqual(result, expected)\n\n def test_move_2(self):\n result = self.eightPuzzle.move(self.initial_state, 'down')\n expected = [[2, 3, 4], [5, 8, 1], [6, 0, 7]]\n self.assertEqual(result, expected)\n\n def test_move_3(self):\n result = self.eightPuzzle.move(self.initial_state, 'left')\n expected = [[2, 3, 4], [0, 5, 1], [6, 8, 7]]\n self.assertEqual(result, expected)\n\n def test_move_4(self):\n result = self.eightPuzzle.move(self.initial_state, 'right')\n expected = [[2, 3, 4], [5, 1, 0], [6, 8, 7]]\n self.assertEqual(result, expected)\n\n def test_move_5(self):\n result = self.eightPuzzle.move(self.initial_state, '???')\n expected = [[2, 3, 4], [5, 0, 1], [6, 8, 7]]\n self.assertEqual(result, expected)", "solution_code": "def move(self, state, direction):\n i, j = self.find_blank(state)\n new_state = [row[:] for row in state]\n\n if direction == 'up':\n new_state[i][j], new_state[i - 1][j] = new_state[i - 1][j], new_state[i][j]\n elif direction == 'down':\n new_state[i][j], new_state[i + 1][j] = new_state[i + 1][j], new_state[i][j]\n elif direction == 'left':\n new_state[i][j], new_state[i][j - 1] = new_state[i][j - 1], new_state[i][j]\n elif direction == 'right':\n new_state[i][j], new_state[i][j + 1] = new_state[i][j + 1], new_state[i][j]\n\n return new_state", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "find_blank" ] } }, { "method_name": "get_possible_moves", "method_description": "def get_possible_moves(self, state):\n \"\"\"\n According the current state, find all the possible moving directions. Only has 4 direction 'up', 'down', 'left', 'right'.\n :param state: a 3*3 size list of Integer, stores the current state.\n :return moves: a list of str, store all the possible moving directions according to the current state.\n >>> eightPuzzle.get_possible_moves([[2, 3, 4], [5, 8, 1], [6, 0, 7]])\n ['up', 'left', 'right']\n \"\"\"", "test_class": "EightPuzzleTestGetPossibleMoves", "test_code": "class EightPuzzleTestGetPossibleMoves(unittest.TestCase):\n def test_get_possible_moves_1(self):\n eightPuzzle = EightPuzzle(None)\n state = [[2, 3, 4], [5, 0, 1], [6, 8, 7]]\n result = eightPuzzle.get_possible_moves(state)\n expected = ['up', 'down', 'left', 'right']\n for direction in result:\n self.assertIn(direction, expected)\n\n def test_get_possible_moves_2(self):\n eightPuzzle = EightPuzzle(None)\n state = [[2, 3, 4], [5, 8, 1], [6, 0, 7]]\n result = eightPuzzle.get_possible_moves(state)\n expected = ['up', 'left', 'right']\n for direction in result:\n self.assertIn(direction, expected)\n\n def test_get_possible_moves_3(self):\n eightPuzzle = EightPuzzle(None)\n state = [[2, 0, 4], [5, 3, 1], [6, 8, 7]]\n result = eightPuzzle.get_possible_moves(state)\n expected = ['down', 'left', 'right']\n for direction in result:\n self.assertIn(direction, expected)\n\n def test_get_possible_moves_4(self):\n eightPuzzle = EightPuzzle(None)\n state = [[2, 3, 4], [5, 1, 0], [6, 8, 7]]\n result = eightPuzzle.get_possible_moves(state)\n expected = ['up', 'down', 'left']\n for direction in result:\n self.assertIn(direction, expected)\n\n def test_get_possible_moves_5(self):\n eightPuzzle = EightPuzzle(None)\n state = [[2, 3, 4], [0, 5, 1], [6, 8, 7]]\n result = eightPuzzle.get_possible_moves(state)\n expected = ['up', 'down', 'right']\n for direction in result:\n self.assertIn(direction, expected)", "solution_code": "def get_possible_moves(self, state):\n moves = []\n i, j = self.find_blank(state)\n\n if i > 0:\n moves.append('up')\n if i < 2:\n moves.append('down')\n if j > 0:\n moves.append('left')\n if j < 2:\n moves.append('right')\n\n return moves", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "find_blank", "move" ] } }, { "method_name": "solve", "method_description": "def solve(self):\n \"\"\"\n Use BFS algorithm to find the path solution which makes the initial state to the goal method.\n Maintain a list as a queue, named as open_list, append the initial state.\n Always visit and pop the 0 index element, invoke get_possible_moves method find all the possible directions.\n Traversal the possible_moves list and invoke move method to get several new states.Then append them.\n redo the above steps until the open_list is empty or the state has changed to the goal state.\n :return path: list of str, the solution to the goal state.\n >>> eightPuzzle = EightPuzzle([[1, 2, 3], [4, 5, 6], [7, 0, 8]])\n >>> eightPuzzle.solve()\n ['right']\n \"\"\"", "test_class": "EightPuzzleTestSolve", "test_code": "class EightPuzzleTestSolve(unittest.TestCase):\n def test_solve_1(self):\n eightPuzzle = EightPuzzle([[1, 2, 3], [4, 5, 6], [7, 0, 8]])\n result = eightPuzzle.solve()\n expected = ['right']\n self.assertEqual(result, expected)\n\n def test_solve_2(self):\n eightPuzzle = EightPuzzle([[1, 2, 3], [4, 0, 6], [7, 5, 8]])\n result = eightPuzzle.solve()\n expected = ['down', 'right']\n self.assertEqual(result, expected)\n\n def test_solve_3(self):\n eightPuzzle = EightPuzzle([[1, 2, 3], [0, 4, 5], [6, 7, 8]])\n result = eightPuzzle.solve()\n expected = ['right', 'right', 'down', 'left', 'left', 'up', 'right', 'down', 'right', 'up', 'left', 'left', 'down', 'right', 'right']\n self.assertEqual(result, expected)\n\n def test_solve_4(self):\n eightPuzzle = EightPuzzle([[1, 2, 3], [4, 5, 6], [7, 8, 0]])\n result = eightPuzzle.solve()\n expected = []\n self.assertEqual(result, expected)\n\n def test_solve_5(self):\n eightPuzzle = EightPuzzle([[1, 2, 3], [4, 5, 6], [0, 7, 8]])\n result = eightPuzzle.solve()\n expected = ['right', 'right']\n self.assertEqual(result, expected)\n\n def test_solve_6(self):\n eightPuzzle = EightPuzzle([[0, 0, 0], [0, 0, 0], [0, 0, 0]])\n result = eightPuzzle.solve()\n expected = None\n self.assertEqual(result, expected)", "solution_code": "def solve(self):\n open_list = [(self.initial_state, [])]\n closed_list = []\n\n while open_list:\n current_state, path = open_list.pop(0)\n closed_list.append(current_state)\n\n if current_state == self.goal_state:\n return path\n\n for move in self.get_possible_moves(current_state):\n new_state = self.move(current_state, move)\n if new_state not in closed_list:\n open_list.append((new_state, path + [move]))\n\n return None", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.goal_state", "self.initial_state" ], "method_dependencies": [ "move", "get_possible_moves" ] } } ] }, { "task_id": "ClassEval_36", "skeleton": "\nfrom datetime import datetime\n\nclass EmailClient:\n \"\"\"\n This is a class that serves as an email client, implementing functions such as checking emails, determining whether there is sufficient space, and cleaning up space\n \"\"\"\n\n def __init__(self, addr, capacity) -> None:\n \"\"\"\n Initializes the EmailClient class with the email address and the capacity of the email box.\n :param addr: The email address, str.\n :param capacity: The capacity of the email box, float.\n \"\"\"\n self.addr = addr\n self.capacity = capacity\n self.inbox = []\n\n def send_to(self, recv, content, size):\n \"\"\"\n Sends an email to the given email address.\n :param recv: The email address of the receiver, str.\n :param content: The content of the email, str.\n :param size: The size of the email, float.\n :return: True if the email is sent successfully, False if the receiver's email box is full.\n >>> sender = EmailClient('sender@example.com', 100)\n >>> receiver = EmailClient('receiver@example.com', 50)\n >>> sender.send_to(receiver, 'Hello', 10)\n True\n >>> receiver.inbox\n {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'unread'}\n\n \"\"\"\n\n def fetch(self):\n \"\"\"\n Retrieves the first unread email in the email box and marks it as read.\n :return: The first unread email in the email box, dict.\n >>> sender = EmailClient('sender@example.com', 100)\n >>> receiver = EmailClient('receiver@example.com', 50)\n >>> receiver.inbox = [{'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'unread'}]\n >>> receiver.fetch()\n {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'read'}\n\n \"\"\"\n\n def is_full_with_one_more_email(self, size):\n \"\"\"\n Determines whether the email box is full after adding an email of the given size.\n :param size: The size of the email, float.\n :return: True if the email box is full, False otherwise.\n >>> sender = EmailClient('sender@example.com', 100)\n >>> receiver = EmailClient('receiver@example.com', 50)\n >>> receiver.is_full_with_one_more_email(10)\n False\n\n \"\"\"\n\n def get_occupied_size(self):\n \"\"\"\n Gets the total size of the emails in the email box.\n :return: The total size of the emails in the email box, float.\n >>> sender = EmailClient('sender@example.com', 100)\n >>> receiver = EmailClient('receiver@example.com', 50)\n >>> sender.inbox = [{'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 10, 'time': datetime.now, 'state': 'unread'}]\n >>> sender.get_occupied_size()\n 10\n\n \"\"\"\n\n def clear_inbox(self, size):\n \"\"\"\n Clears the email box by deleting the oldest emails until the email box has enough space to accommodate the given size.\n :param size: The size of the email, float.\n >>> sender = EmailClient('sender@example.com', 100)\n >>> receiver = EmailClient('receiver@example.com', 50)\n >>> receiver.inbox = [{'size': 10},{'size': 20},{'size': 15}]\n >>> receiver.clear_inbox(30)\n >>> receiver.inbox\n [{'size': 15}]\n\n \"\"\"", "test": "import unittest\n\nclass EmailClientTestSendTo(unittest.TestCase):\n def test_send_to(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n self.assertTrue(sender.send_to(receiver, 'Hello', 10))\n self.assertEqual(receiver.inbox[0], {\"sender\": 'sender@example.com','receiver': 'receiver@example.com','content': 'Hello','size': 10,'time': timestamp,'state': 'unread'})\n\n def test_send_to_2(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 0)\n self.assertFalse(sender.send_to(receiver, 'Hello', 10))\n\n def test_send_to_3(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n receiver.inbox = [{'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 50, 'time': '2021-01-01 00:00:00', 'state': 'unread'}]\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n self.assertFalse(sender.send_to(receiver, 'Hello', 10))\n self.assertEqual(receiver.inbox, [{'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 50, 'time': '2021-01-01 00:00:00', 'state': 'unread'}])\n\n def test_send_to_4(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 30)\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n self.assertTrue(sender.send_to(receiver, 'Hello', 20))\n self.assertEqual(receiver.inbox, [{'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 20, 'time': timestamp, 'state': 'unread'}])\n\n def test_send_to_5(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 30)\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n self.assertTrue(sender.send_to(receiver, 'bye', 20))\n self.assertEqual(receiver.inbox, [{'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'bye', 'size': 20, 'time': timestamp, 'state': 'unread'}])\nclass EmailClientTestFetch(unittest.TestCase):\n def test_fetch(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n receiver.inbox = [\n {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 10,\n 'time': timestamp, 'state': 'unread'}]\n self.assertEqual(receiver.fetch(), {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 10, 'time':timestamp, 'state': 'read'})\n\n def test_fetch_2(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n self.assertEqual(receiver.fetch(),None)\n\n def test_fetch_3(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n receiver.inbox = [\n {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 10,\n 'time': timestamp, 'state': 'read'}]\n self.assertEqual(receiver.fetch(), None)\n\n def test_fetch_4(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n receiver.inbox = [\n {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 10,\n 'time': '2021-01-01 00:00:00', 'state': 'unread'},\n {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 10,\n 'time': timestamp, 'state': 'unread'}]\n self.assertEqual(receiver.fetch(), {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 10,\n 'time': '2021-01-01 00:00:00', 'state': 'read'})\n\n def test_fetch_5(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n receiver.inbox = [\n {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 10,\n 'time': '2021-01-01 00:00:00', 'state': 'read'},\n {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 10,\n 'time': timestamp, 'state': 'unread'}]\n self.assertEqual(receiver.fetch(), {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 10,\n 'time': timestamp, 'state': 'read'})\n\nclass EmailClientTestIsFullWithOneMoreEmail(unittest.TestCase):\n def test_is_full_with_one_more_email(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n self.assertFalse(receiver.is_full_with_one_more_email(10))\n\n def test_is_full_with_one_more_email_2(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 0)\n self.assertTrue(receiver.is_full_with_one_more_email(10))\n\n def test_is_full_with_one_more_email_3(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 10)\n self.assertFalse(receiver.is_full_with_one_more_email(10))\n\n def test_is_full_with_one_more_email_4(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 10)\n self.assertTrue(receiver.is_full_with_one_more_email(20))\n\n def test_is_full_with_one_more_email_5(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 20)\n self.assertFalse(receiver.is_full_with_one_more_email(20))\n\nclass EmailClientTestGetOccupiedSize(unittest.TestCase):\n def test_get_occupied_size(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n sender.inbox = [{'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 10, 'time': datetime.now, 'state': 'unread'}]\n self.assertEqual(sender.get_occupied_size(), 10)\n\n def test_get_occupied_size_2(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n sender.inbox =[]\n self.assertEqual(sender.get_occupied_size(), 0)\n\n def test_get_occupied_size_3(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n sender.inbox = [\n {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 20,\n 'time': datetime.now, 'state': 'unread'}]\n self.assertEqual(sender.get_occupied_size(), 20)\n\n def test_get_occupied_size_4(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n sender.inbox = [\n {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 20,\n 'time': datetime.now, 'state': 'unread'},\n {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 30,\n 'time': datetime.now, 'state': 'unread'}]\n self.assertEqual(sender.get_occupied_size(), 50)\n\n def test_get_occupied_size_5(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n sender.inbox = [\n {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 20,\n 'time': datetime.now, 'state': 'unread'},\n {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 60,\n 'time': datetime.now, 'state': 'unread'}]\n self.assertEqual(sender.get_occupied_size(), 80)\n\nclass EmailClientTestClearInbox(unittest.TestCase):\n def test_clear_inbox(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n receiver.inbox = [{'size': 10},{'size': 20},{'size': 15}]\n receiver.clear_inbox(30)\n self.assertEqual(receiver.inbox, [{'size': 15}])\n\n def test_clear_inbox_2(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('', 50)\n receiver.inbox = [{'size': 10},{'size': 20},{'size': 15}]\n self.assertEqual(receiver.clear_inbox(30),None)\n self.assertEqual(receiver.inbox, [{'size': 10},{'size': 20},{'size': 15}])\n\n def test_clear_inbox_3(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n receiver.inbox = [{'size': 10}, {'size': 20}, {'size': 15}]\n self.assertEqual(receiver.clear_inbox(50), None)\n\n def test_clear_inbox_4(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n receiver.inbox = [{'size': 10}, {'size': 20}, {'size': 15}]\n receiver.clear_inbox(45)\n self.assertEqual(receiver.inbox, [])\n def test_clear_inbox_5(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n receiver.inbox = [{'size': 10}, {'size': 20}, {'size': 15}]\n receiver.clear_inbox(10)\n self.assertEqual(receiver.inbox, [{'size': 20}, {'size': 15}])\n\n\n\n\nclass EmailClientTestMain(unittest.TestCase):\n def test_main(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n self.assertTrue(sender.send_to(receiver, 'Hello', 10))\n self.assertEqual(receiver.inbox[0], {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 10, 'time': timestamp, 'state': 'unread'})\n self.assertEqual(receiver.fetch(), {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 10, 'time': timestamp, 'state': 'read'})\n self.assertFalse(receiver.is_full_with_one_more_email(10))\n self.assertEqual(receiver.get_occupied_size(), 10)\n receiver.inbox = [{'size': 10},{'size': 20},{'size': 15}]\n receiver.clear_inbox(30)\n self.assertEqual(receiver.inbox, [{'size': 15}])", "solution_code": "from datetime import datetime\n\nclass EmailClient:\n def __init__(self, addr, capacity) -> None:\n self.addr = addr\n self.capacity = capacity\n self.inbox = []\n \n def send_to(self, recv, content, size):\n if not recv.is_full_with_one_more_email(size):\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n email = {\n \"sender\": self.addr,\n \"receiver\": recv.addr,\n \"content\": content,\n \"size\": size,\n \"time\": timestamp,\n \"state\": \"unread\"\n }\n recv.inbox.append(email)\n return True\n else:\n self.clear_inbox(size)\n return False\n \n def fetch(self):\n if len(self.inbox) == 0:\n return None\n for i in range(len(self.inbox)):\n if self.inbox[i]['state'] == \"unread\":\n self.inbox[i]['state'] = \"read\"\n return self.inbox[i]\n return None\n\n def is_full_with_one_more_email(self, size):\n occupied_size = self.get_occupied_size()\n return True if occupied_size + size > self.capacity else False\n \n def get_occupied_size(self):\n occupied_size = 0\n for email in self.inbox:\n occupied_size += email[\"size\"]\n return occupied_size\n\n def clear_inbox(self, size):\n if len(self.addr) == 0:\n return\n freed_space = 0\n while freed_space < size and self.inbox:\n email = self.inbox[0]\n freed_space += email['size']\n del self.inbox[0]", "import_statement": [ "from datetime import datetime" ], "class_description": " \"\"\"\n This is a class that serves as an email client, implementing functions such as checking emails, determining whether there is sufficient space, and cleaning up space\n \"\"\"\n", "class_name": "EmailClient", "test_classes": [ "EmailClientTestSendTo", "EmailClientTestFetch", "EmailClientTestIsFullWithOneMoreEmail", "EmailClientTestGetOccupiedSize", "EmailClientTestClearInbox", "EmailClientTestMain" ], "class_constructor": "class EmailClient: \n def __init__(self, addr, capacity) -> None:\n \"\"\"\n Initializes the EmailClient class with the email address and the capacity of the email box.\n :param addr: The email address, str.\n :param capacity: The capacity of the email box, float.\n \"\"\"\n self.addr = addr\n self.capacity = capacity\n self.inbox = []\n\n", "fields": [ "self.addr", "self.capacity", "self.inbox" ], "methods_info": [ { "method_name": "send_to", "method_description": "def send_to(self, recv, content, size):\n \"\"\"\n Sends an email to the given email address.\n :param recv: The email address of the receiver, str.\n :param content: The content of the email, str.\n :param size: The size of the email, float.\n :return: True if the email is sent successfully, False if the receiver's email box is full.\n >>> sender = EmailClient('sender@example.com', 100)\n >>> receiver = EmailClient('receiver@example.com', 50)\n >>> sender.send_to(receiver, 'Hello', 10)\n True\n >>> receiver.inbox\n {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'unread'}\n\n \"\"\"", "test_class": "EmailClientTestSendTo", "test_code": "class EmailClientTestSendTo(unittest.TestCase):\n def test_send_to(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n self.assertTrue(sender.send_to(receiver, 'Hello', 10))\n self.assertEqual(receiver.inbox[0], {\"sender\": 'sender@example.com','receiver': 'receiver@example.com','content': 'Hello','size': 10,'time': timestamp,'state': 'unread'})\n\n def test_send_to_2(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 0)\n self.assertFalse(sender.send_to(receiver, 'Hello', 10))\n\n def test_send_to_3(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n receiver.inbox = [{'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 50, 'time': '2021-01-01 00:00:00', 'state': 'unread'}]\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n self.assertFalse(sender.send_to(receiver, 'Hello', 10))\n self.assertEqual(receiver.inbox, [{'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 50, 'time': '2021-01-01 00:00:00', 'state': 'unread'}])\n\n def test_send_to_4(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 30)\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n self.assertTrue(sender.send_to(receiver, 'Hello', 20))\n self.assertEqual(receiver.inbox, [{'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 20, 'time': timestamp, 'state': 'unread'}])\n\n def test_send_to_5(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 30)\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n self.assertTrue(sender.send_to(receiver, 'bye', 20))\n self.assertEqual(receiver.inbox, [{'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'bye', 'size': 20, 'time': timestamp, 'state': 'unread'}])", "solution_code": "def send_to(self, recv, content, size):\n if not recv.is_full_with_one_more_email(size):\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n email = {\n \"sender\": self.addr,\n \"receiver\": recv.addr,\n \"content\": content,\n \"size\": size,\n \"time\": timestamp,\n \"state\": \"unread\"\n }\n recv.inbox.append(email)\n return True\n else:\n self.clear_inbox(size)\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [ "datetime" ], "field_dependencies": [ "self.addr" ], "method_dependencies": [ "is_full_with_one_more_email", "clear_inbox" ] } }, { "method_name": "fetch", "method_description": "def fetch(self):\n \"\"\"\n Retrieves the first unread email in the email box and marks it as read.\n :return: The first unread email in the email box, dict.\n >>> sender = EmailClient('sender@example.com', 100)\n >>> receiver = EmailClient('receiver@example.com', 50)\n >>> receiver.inbox = [{'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'unread'}]\n >>> receiver.fetch()\n {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 10, 'time': '2023-07-13 11:36:40', 'state': 'read'}\n\n \"\"\"", "test_class": "EmailClientTestFetch", "test_code": "class EmailClientTestFetch(unittest.TestCase):\n def test_fetch(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n receiver.inbox = [\n {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 10,\n 'time': timestamp, 'state': 'unread'}]\n self.assertEqual(receiver.fetch(), {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 10, 'time':timestamp, 'state': 'read'})\n\n def test_fetch_2(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n self.assertEqual(receiver.fetch(),None)\n\n def test_fetch_3(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n receiver.inbox = [\n {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 10,\n 'time': timestamp, 'state': 'read'}]\n self.assertEqual(receiver.fetch(), None)\n\n def test_fetch_4(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n receiver.inbox = [\n {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 10,\n 'time': '2021-01-01 00:00:00', 'state': 'unread'},\n {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 10,\n 'time': timestamp, 'state': 'unread'}]\n self.assertEqual(receiver.fetch(), {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 10,\n 'time': '2021-01-01 00:00:00', 'state': 'read'})\n\n def test_fetch_5(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n receiver.inbox = [\n {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 10,\n 'time': '2021-01-01 00:00:00', 'state': 'read'},\n {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 10,\n 'time': timestamp, 'state': 'unread'}]\n self.assertEqual(receiver.fetch(), {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 10,\n 'time': timestamp, 'state': 'read'})", "solution_code": "def fetch(self):\n if len(self.inbox) == 0:\n return None\n for i in range(len(self.inbox)):\n if self.inbox[i]['state'] == \"unread\":\n self.inbox[i]['state'] = \"read\"\n return self.inbox[i]\n return None", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.inbox" ], "method_dependencies": [] } }, { "method_name": "is_full_with_one_more_email", "method_description": "def is_full_with_one_more_email(self, size):\n \"\"\"\n Determines whether the email box is full after adding an email of the given size.\n :param size: The size of the email, float.\n :return: True if the email box is full, False otherwise.\n >>> sender = EmailClient('sender@example.com', 100)\n >>> receiver = EmailClient('receiver@example.com', 50)\n >>> receiver.is_full_with_one_more_email(10)\n False\n\n \"\"\"", "test_class": "EmailClientTestIsFullWithOneMoreEmail", "test_code": "class EmailClientTestIsFullWithOneMoreEmail(unittest.TestCase):\n def test_is_full_with_one_more_email(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n self.assertFalse(receiver.is_full_with_one_more_email(10))\n\n def test_is_full_with_one_more_email_2(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 0)\n self.assertTrue(receiver.is_full_with_one_more_email(10))\n\n def test_is_full_with_one_more_email_3(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 10)\n self.assertFalse(receiver.is_full_with_one_more_email(10))\n\n def test_is_full_with_one_more_email_4(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 10)\n self.assertTrue(receiver.is_full_with_one_more_email(20))\n\n def test_is_full_with_one_more_email_5(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 20)\n self.assertFalse(receiver.is_full_with_one_more_email(20))", "solution_code": "def is_full_with_one_more_email(self, size):\n occupied_size = self.get_occupied_size()\n return True if occupied_size + size > self.capacity else False", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.capacity" ], "method_dependencies": [ "get_occupied_size" ] } }, { "method_name": "get_occupied_size", "method_description": "def get_occupied_size(self):\n \"\"\"\n Gets the total size of the emails in the email box.\n :return: The total size of the emails in the email box, float.\n >>> sender = EmailClient('sender@example.com', 100)\n >>> receiver = EmailClient('receiver@example.com', 50)\n >>> sender.inbox = [{'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 10, 'time': datetime.now, 'state': 'unread'}]\n >>> sender.get_occupied_size()\n 10\n\n \"\"\"", "test_class": "EmailClientTestGetOccupiedSize", "test_code": "class EmailClientTestGetOccupiedSize(unittest.TestCase):\n def test_get_occupied_size(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n sender.inbox = [{'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 10, 'time': datetime.now, 'state': 'unread'}]\n self.assertEqual(sender.get_occupied_size(), 10)\n\n def test_get_occupied_size_2(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n sender.inbox =[]\n self.assertEqual(sender.get_occupied_size(), 0)\n\n def test_get_occupied_size_3(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n sender.inbox = [\n {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 20,\n 'time': datetime.now, 'state': 'unread'}]\n self.assertEqual(sender.get_occupied_size(), 20)\n\n def test_get_occupied_size_4(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n sender.inbox = [\n {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 20,\n 'time': datetime.now, 'state': 'unread'},\n {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 30,\n 'time': datetime.now, 'state': 'unread'}]\n self.assertEqual(sender.get_occupied_size(), 50)\n\n def test_get_occupied_size_5(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n sender.inbox = [\n {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 20,\n 'time': datetime.now, 'state': 'unread'},\n {'sender': 'sender@example.com', 'receiver': 'receiver@example.com', 'content': 'Hello', 'size': 60,\n 'time': datetime.now, 'state': 'unread'}]\n self.assertEqual(sender.get_occupied_size(), 80)", "solution_code": "def get_occupied_size(self):\n occupied_size = 0\n for email in self.inbox:\n occupied_size += email[\"size\"]\n return occupied_size", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.inbox" ], "method_dependencies": [] } }, { "method_name": "clear_inbox", "method_description": "def clear_inbox(self, size):\n \"\"\"\n Clears the email box by deleting the oldest emails until the email box has enough space to accommodate the given size.\n :param size: The size of the email, float.\n >>> sender = EmailClient('sender@example.com', 100)\n >>> receiver = EmailClient('receiver@example.com', 50)\n >>> receiver.inbox = [{'size': 10},{'size': 20},{'size': 15}]\n >>> receiver.clear_inbox(30)\n >>> receiver.inbox\n [{'size': 15}]\n\n \"\"\"", "test_class": "EmailClientTestClearInbox", "test_code": "class EmailClientTestClearInbox(unittest.TestCase):\n def test_clear_inbox(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n receiver.inbox = [{'size': 10},{'size': 20},{'size': 15}]\n receiver.clear_inbox(30)\n self.assertEqual(receiver.inbox, [{'size': 15}])\n\n def test_clear_inbox_2(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('', 50)\n receiver.inbox = [{'size': 10},{'size': 20},{'size': 15}]\n self.assertEqual(receiver.clear_inbox(30),None)\n self.assertEqual(receiver.inbox, [{'size': 10},{'size': 20},{'size': 15}])\n\n def test_clear_inbox_3(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n receiver.inbox = [{'size': 10}, {'size': 20}, {'size': 15}]\n self.assertEqual(receiver.clear_inbox(50), None)\n\n def test_clear_inbox_4(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n receiver.inbox = [{'size': 10}, {'size': 20}, {'size': 15}]\n receiver.clear_inbox(45)\n self.assertEqual(receiver.inbox, [])\n def test_clear_inbox_5(self):\n sender = EmailClient('sender@example.com', 100)\n receiver = EmailClient('receiver@example.com', 50)\n receiver.inbox = [{'size': 10}, {'size': 20}, {'size': 15}]\n receiver.clear_inbox(10)\n self.assertEqual(receiver.inbox, [{'size': 20}, {'size': 15}])", "solution_code": "def clear_inbox(self, size):\n if len(self.addr) == 0:\n return\n freed_space = 0\n while freed_space < size and self.inbox:\n email = self.inbox[0]\n freed_space += email['size']\n del self.inbox[0]", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.addr", "self.inbox" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_37", "skeleton": "\nclass EncryptionUtils:\n \"\"\"\n This is a class that provides methods for encryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.\n \"\"\"\n\n def __init__(self, key):\n \"\"\"\n Initializes the class with a key.\n :param key: The key to use for encryption, str.\n \"\"\"\n self.key = key\n\n def caesar_cipher(self, plaintext, shift):\n \"\"\"\n Encrypts the plaintext using the Caesar cipher.\n :param plaintext: The plaintext to encrypt, str.\n :param shift: The number of characters to shift each character in the plaintext, int.\n :return: The ciphertext, str.\n >>> e = EncryptionUtils(\"key\")\n >>> e.caesar_cipher(\"abc\", 1)\n 'bcd'\n\n \"\"\"\n\n def vigenere_cipher(self, plaintext):\n \"\"\"\n Encrypts the plaintext using the Vigenere cipher.\n :param plaintext: The plaintext to encrypt, str.\n :return: The ciphertext, str.\n >>> e = EncryptionUtils(\"key\")\n >>> e.vigenere_cipher(\"abc\")\n 'kfa'\n\n \"\"\"\n\n def rail_fence_cipher(self,plain_text, rails):\n \"\"\"\n Encrypts the plaintext using the Rail Fence cipher.\n :param plaintext: The plaintext to encrypt, str.\n :return: The ciphertext, str.\n >>> e = EncryptionUtils(\"key\")\n >>> e.rail_fence_cipher(\"abc\", 2)\n 'acb'\n\n \"\"\"", "test": "import unittest\n\n\nclass EncryptionUtilsTestCaesarCipher(unittest.TestCase):\n def test_caesar_cipher(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.caesar_cipher(\"abc\", 1), \"bcd\")\n\n def test_caesar_cipher_2(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.caesar_cipher(\"WORLD\", -2), \"UMPJB\")\n\n def test_caesar_cipher_3(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.caesar_cipher(\"\", 4), \"\")\n\n def test_caesar_cipher_4(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.caesar_cipher(\"abcxyz\", 26), \"abcxyz\")\n\n def test_caesar_cipher_5(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.caesar_cipher(\"abcxyz\", 27), \"bcdyza\")\n\n def test_caesar_cipher_6(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.caesar_cipher(\"123\", 27), \"123\")\n\n\nclass EncryptionUtilsTestVigenereCipher(unittest.TestCase):\n def test_vigenere_cipher(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.vigenere_cipher(\"abc\"), \"kfa\")\n\n def test_vigenere_cipher_2(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.vigenere_cipher(\"hello\"), \"rijvs\")\n\n def test_vigenere_cipher_3(self):\n encryption_utils = EncryptionUtils(\"longkey\")\n self.assertEqual(encryption_utils.vigenere_cipher(\"AbCdEfG\"), \"LpPjOjE\")\n\n def test_vigenere_cipher_4(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.vigenere_cipher(\"Hello, World! 123\"), \"Rijvs, Uyvjn! 123\")\n\n def test_vigenere_cipher_5(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.vigenere_cipher(\"\"), \"\")\n\n\nclass EncryptionUtilsTestRailFenceCipher(unittest.TestCase):\n def test_rail_fence_cipher(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.rail_fence_cipher(\"abc\", 2), \"acb\")\n\n def test_rail_fence_cipher_2(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.rail_fence_cipher(\"hello\", 2), \"hloel\")\n\n def test_rail_fence_cipher_3(self):\n encryption_utils = EncryptionUtils(\"longkey\")\n self.assertEqual(encryption_utils.rail_fence_cipher(\"AbCdEfG\", 2), \"ACEGbdf\")\n\n def test_rail_fence_cipher_4(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.rail_fence_cipher(\"Hello, World! 123\", 2), \"Hlo ol!13el,Wrd 2\")\n\n def test_rail_fence_cipher_5(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.rail_fence_cipher(\"\", 2), \"\")\n\n def test_rail_fence_cipher_6(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.rail_fence_cipher(\"abcdefg\", 3), \"aebdfcg\")\n\n\nclass EncryptionUtilsTestMain(unittest.TestCase):\n def test_main(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.caesar_cipher(\"abc\", 1), \"bcd\")\n self.assertEqual(encryption_utils.vigenere_cipher(\"abc\"), \"kfa\")\n self.assertEqual(encryption_utils.rail_fence_cipher(\"abc\", 2), \"acb\")", "solution_code": "class EncryptionUtils:\n def __init__(self, key):\n self.key = key\n\n def caesar_cipher(self, plaintext, shift):\n ciphertext = \"\"\n for char in plaintext:\n if char.isalpha():\n if char.isupper():\n ascii_offset = 65\n else:\n ascii_offset = 97\n shifted_char = chr((ord(char) - ascii_offset + shift) % 26 + ascii_offset)\n ciphertext += shifted_char\n else:\n ciphertext += char\n return ciphertext\n \n def vigenere_cipher(self, plain_text):\n encrypted_text = \"\"\n key_index = 0\n for char in plain_text:\n if char.isalpha():\n shift = ord(self.key[key_index % len(self.key)].lower()) - ord('a')\n encrypted_char = chr((ord(char.lower()) - ord('a') + shift) % 26 + ord('a'))\n encrypted_text += encrypted_char.upper() if char.isupper() else encrypted_char\n key_index += 1\n else:\n encrypted_text += char\n return encrypted_text\n\n def rail_fence_cipher(self, plain_text, rails):\n fence = [['\\n' for _ in range(len(plain_text))] for _ in range(rails)]\n direction = -1\n row, col = 0, 0\n\n for char in plain_text:\n if row == 0 or row == rails-1:\n direction = -direction\n\n fence[row][col] = char\n col += 1\n row += direction\n\n encrypted_text = ''\n for i in range(rails):\n for j in range(len(plain_text)):\n if fence[i][j] != '\\n':\n encrypted_text += fence[i][j]\n\n return encrypted_text", "import_statement": [], "class_description": " \"\"\"\n This is a class that provides methods for encryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.\n \"\"\"\n", "class_name": "EncryptionUtils", "test_classes": [ "EncryptionUtilsTestCaesarCipher", "EncryptionUtilsTestVigenereCipher", "EncryptionUtilsTestRailFenceCipher", "EncryptionUtilsTestMain" ], "class_constructor": "class EncryptionUtils: \n def __init__(self, key):\n \"\"\"\n Initializes the class with a key.\n :param key: The key to use for encryption, str.\n \"\"\"\n self.key = key\n\n", "fields": [ "self.key" ], "methods_info": [ { "method_name": "caesar_cipher", "method_description": "def caesar_cipher(self, plaintext, shift):\n \"\"\"\n Encrypts the plaintext using the Caesar cipher.\n :param plaintext: The plaintext to encrypt, str.\n :param shift: The number of characters to shift each character in the plaintext, int.\n :return: The ciphertext, str.\n >>> e = EncryptionUtils(\"key\")\n >>> e.caesar_cipher(\"abc\", 1)\n 'bcd'\n\n \"\"\"", "test_class": "EncryptionUtilsTestCaesarCipher", "test_code": "class EncryptionUtilsTestCaesarCipher(unittest.TestCase):\n def test_caesar_cipher(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.caesar_cipher(\"abc\", 1), \"bcd\")\n\n def test_caesar_cipher_2(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.caesar_cipher(\"WORLD\", -2), \"UMPJB\")\n\n def test_caesar_cipher_3(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.caesar_cipher(\"\", 4), \"\")\n\n def test_caesar_cipher_4(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.caesar_cipher(\"abcxyz\", 26), \"abcxyz\")\n\n def test_caesar_cipher_5(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.caesar_cipher(\"abcxyz\", 27), \"bcdyza\")\n\n def test_caesar_cipher_6(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.caesar_cipher(\"123\", 27), \"123\")", "solution_code": "def caesar_cipher(self, plaintext, shift):\n ciphertext = \"\"\n for char in plaintext:\n if char.isalpha():\n if char.isupper():\n ascii_offset = 65\n else:\n ascii_offset = 97\n shifted_char = chr((ord(char) - ascii_offset + shift) % 26 + ascii_offset)\n ciphertext += shifted_char\n else:\n ciphertext += char\n return ciphertext", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "vigenere_cipher", "method_description": "def vigenere_cipher(self, plaintext):\n \"\"\"\n Encrypts the plaintext using the Vigenere cipher.\n :param plaintext: The plaintext to encrypt, str.\n :return: The ciphertext, str.\n >>> e = EncryptionUtils(\"key\")\n >>> e.vigenere_cipher(\"abc\")\n 'kfa'\n\n \"\"\"", "test_class": "EncryptionUtilsTestVigenereCipher", "test_code": "class EncryptionUtilsTestVigenereCipher(unittest.TestCase):\n def test_vigenere_cipher(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.vigenere_cipher(\"abc\"), \"kfa\")\n\n def test_vigenere_cipher_2(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.vigenere_cipher(\"hello\"), \"rijvs\")\n\n def test_vigenere_cipher_3(self):\n encryption_utils = EncryptionUtils(\"longkey\")\n self.assertEqual(encryption_utils.vigenere_cipher(\"AbCdEfG\"), \"LpPjOjE\")\n\n def test_vigenere_cipher_4(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.vigenere_cipher(\"Hello, World! 123\"), \"Rijvs, Uyvjn! 123\")\n\n def test_vigenere_cipher_5(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.vigenere_cipher(\"\"), \"\")", "solution_code": "def vigenere_cipher(self, plain_text):\n encrypted_text = \"\"\n key_index = 0\n for char in plain_text:\n if char.isalpha():\n shift = ord(self.key[key_index % len(self.key)].lower()) - ord('a')\n encrypted_char = chr((ord(char.lower()) - ord('a') + shift) % 26 + ord('a'))\n encrypted_text += encrypted_char.upper() if char.isupper() else encrypted_char\n key_index += 1\n else:\n encrypted_text += char\n return encrypted_text", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.key" ], "method_dependencies": [] } }, { "method_name": "rail_fence_cipher", "method_description": "def rail_fence_cipher(self,plain_text, rails):\n \"\"\"\n Encrypts the plaintext using the Rail Fence cipher.\n :param plaintext: The plaintext to encrypt, str.\n :return: The ciphertext, str.\n >>> e = EncryptionUtils(\"key\")\n >>> e.rail_fence_cipher(\"abc\", 2)\n 'acb'\n\n \"\"\"", "test_class": "EncryptionUtilsTestRailFenceCipher", "test_code": "class EncryptionUtilsTestRailFenceCipher(unittest.TestCase):\n def test_rail_fence_cipher(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.rail_fence_cipher(\"abc\", 2), \"acb\")\n\n def test_rail_fence_cipher_2(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.rail_fence_cipher(\"hello\", 2), \"hloel\")\n\n def test_rail_fence_cipher_3(self):\n encryption_utils = EncryptionUtils(\"longkey\")\n self.assertEqual(encryption_utils.rail_fence_cipher(\"AbCdEfG\", 2), \"ACEGbdf\")\n\n def test_rail_fence_cipher_4(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.rail_fence_cipher(\"Hello, World! 123\", 2), \"Hlo ol!13el,Wrd 2\")\n\n def test_rail_fence_cipher_5(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.rail_fence_cipher(\"\", 2), \"\")\n\n def test_rail_fence_cipher_6(self):\n encryption_utils = EncryptionUtils(\"key\")\n self.assertEqual(encryption_utils.rail_fence_cipher(\"abcdefg\", 3), \"aebdfcg\")", "solution_code": "def rail_fence_cipher(self, plain_text, rails):\n fence = [['\\n' for _ in range(len(plain_text))] for _ in range(rails)]\n direction = -1\n row, col = 0, 0\n\n for char in plain_text:\n if row == 0 or row == rails-1:\n direction = -direction\n\n fence[row][col] = char\n col += 1\n row += direction\n\n encrypted_text = ''\n for i in range(rails):\n for j in range(len(plain_text)):\n if fence[i][j] != '\\n':\n encrypted_text += fence[i][j]\n\n return encrypted_text", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_38", "skeleton": "\nimport openpyxl\n\n\nclass ExcelProcessor:\n \"\"\"\n This is a class for processing excel files, including readring and writing excel data, as well as processing specific operations and saving as a new excel file.\n \"\"\"\n\n def __init__(self):\n pass\n\n def read_excel(self, file_name):\n \"\"\"\n Reading data from Excel files\n :param file_name:str, Excel file name to read\n :return:list of data, Data in Excel\n \"\"\"\n\n\n def write_excel(self, data, file_name):\n \"\"\"\n Write data to the specified Excel file\n :param data: list, Data to be written\n :param file_name: str, Excel file name to write to\n :return: 0 or 1, 1 represents successful writing, 0 represents failed writing\n >>> processor = ExcelProcessor()\n >>> new_data = [\n >>> ('Name', 'Age', 'Country'),\n >>> ('John', 25, 'USA'),\n >>> ('Alice', 30, 'Canada'),\n >>> ('Bob', 35, 'Australia'),\n >>> ('Julia', 28, 'Germany')\n >>> ]\n >>> data = processor.write_excel(new_data, 'test_data.xlsx')\n \"\"\"\n\n\n def process_excel_data(self, N, save_file_name):\n \"\"\"\n Change the specified column in the Excel file to uppercase\n :param N: int, The serial number of the column that want to change\n :param save_file_name: str, source file name\n :return:(int, str), The former is the return value of write_excel, while the latter is the saved file name of the processed data\n >>> processor = ExcelProcessor()\n >>> success, output_file = processor.process_excel_data(1, 'test_data.xlsx')\n \"\"\"", "test": "import unittest\nimport os\n\n\nclass ExcelProcessorTestReadExcel(unittest.TestCase):\n def test_read_excel_1(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name', 'Age', 'Country'],\n ['John', 25, 'USA'],\n ['Alice', 30, 'Canada'],\n ['Bob', 35, 'Australia']]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n data = processor.read_excel(self.test_file_name)\n expected_data = [\n ('Name', 'Age', 'Country'),\n ('John', 25, 'USA'),\n ('Alice', 30, 'Canada'),\n ('Bob', 35, 'Australia')\n ]\n self.assertEqual(data, expected_data)\n\n def test_read_excel_2(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name', 'Age'],\n ['John', 25],\n ['Alice', 30],\n ['Bob', 35]]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n data = processor.read_excel(self.test_file_name)\n expected_data = [\n ('Name', 'Age'),\n ('John', 25),\n ('Alice', 30),\n ('Bob', 35)\n ]\n self.assertEqual(data, expected_data)\n\n def test_read_excel_3(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name'],\n ['John'],\n ['Alice'],\n ['Bob']]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n data = processor.read_excel(self.test_file_name)\n expected_data = [\n ('Name',),\n ('John',),\n ('Alice',),\n ('Bob',)\n ]\n self.assertEqual(data, expected_data)\n\n def test_read_excel_4(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name', 'Country'],\n ['John', 'USA'],\n ['Alice', 'Canada'],\n ['Bob', 'Australia']]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n data = processor.read_excel(self.test_file_name)\n expected_data = [\n ('Name', 'Country'),\n ('John', 'USA'),\n ('Alice', 'Canada'),\n ('Bob', 'Australia')\n ]\n self.assertEqual(data, expected_data)\n\n def test_read_excel_5(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name', 'Country'],\n ['John', 'USA']]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n data = processor.read_excel(self.test_file_name)\n expected_data = [\n ('Name', 'Country'),\n ('John', 'USA')\n ]\n self.assertEqual(data, expected_data)\n\n def test_read_excel_6(self):\n self.test_file_name = ''\n processor = ExcelProcessor()\n res = processor.read_excel(self.test_file_name)\n self.assertEqual(res, None)\n\n\nclass ExcelProcessorTestWriteExcel(unittest.TestCase):\n def test_write_excel_1(self):\n processor = ExcelProcessor()\n new_data = [\n ('Name', 'Age', 'Country'),\n ('John', 25, 'USA'),\n ('Alice', 30, 'Canada'),\n ('Bob', 35, 'Australia'),\n ('Julia', 28, 'Germany')\n ]\n save_file_name = 'test_output.xlsx'\n success = processor.write_excel(new_data, save_file_name)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(save_file_name))\n saved_data = processor.read_excel(save_file_name)\n self.assertEqual(saved_data, new_data)\n os.remove(save_file_name)\n\n def test_write_excel_2(self):\n processor = ExcelProcessor()\n new_data = [\n ('Name', 'Age'),\n ('John', 25),\n ('Alice', 30),\n ('Bob', 35),\n ('Julia', 28)\n ]\n save_file_name = 'test_output.xlsx'\n success = processor.write_excel(new_data, save_file_name)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(save_file_name))\n saved_data = processor.read_excel(save_file_name)\n self.assertEqual(saved_data, new_data)\n os.remove(save_file_name)\n\n def test_write_excel_3(self):\n processor = ExcelProcessor()\n new_data = [\n ('Name', 'Age', 'Country'),\n ('John', 25, 'USA'),\n ('Alice', 30, 'Canada'),\n ('Bob', 35, 'Australia')\n ]\n save_file_name = 'test_output.xlsx'\n success = processor.write_excel(new_data, save_file_name)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(save_file_name))\n saved_data = processor.read_excel(save_file_name)\n self.assertEqual(saved_data, new_data)\n os.remove(save_file_name)\n\n def test_write_excel_4(self):\n processor = ExcelProcessor()\n new_data = [\n ('Name', 'Age', 'Country'),\n ('John', 25, 'USA'),\n ('Alice', 30, 'Canada')\n ]\n save_file_name = 'test_output.xlsx'\n success = processor.write_excel(new_data, save_file_name)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(save_file_name))\n saved_data = processor.read_excel(save_file_name)\n self.assertEqual(saved_data, new_data)\n os.remove(save_file_name)\n\n def test_write_excel_5(self):\n processor = ExcelProcessor()\n new_data = [\n ('Name', 'Age', 'Country'),\n ('John', 25, 'USA')\n ]\n save_file_name = 'test_output.xlsx'\n success = processor.write_excel(new_data, save_file_name)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(save_file_name))\n saved_data = processor.read_excel(save_file_name)\n self.assertEqual(saved_data, new_data)\n os.remove(save_file_name)\n\n def test_write_excel_6(self):\n processor = ExcelProcessor()\n new_data = [\n ('Name', 'Age', 'Country'),\n ('John', 25, 'USA')\n ]\n save_file_name = ''\n success = processor.write_excel(new_data, save_file_name)\n self.assertEqual(success, 0)\n\n\nclass ExcelProcessorTestProcessExcelData(unittest.TestCase):\n def test_process_excel_data_1(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name', 'Age', 'Country'],\n ['John', 25, 'USA'],\n ['Alice', 30, 'Canada'],\n ['Bob', 35, 'Australia']]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n N = 1\n success, output_file = processor.process_excel_data(N, self.test_file_name)\n self.assertTrue(success)\n self.assertTrue(os.path.isfile(output_file))\n processed_data = processor.read_excel(output_file)\n expected_processed_data = [\n ('Name', 'Age', 'Country', 'AGE'),\n ('John', 25, 'USA', 25),\n ('Alice', 30, 'Canada', 30),\n ('Bob', 35, 'Australia', 35)\n ]\n self.assertEqual(processed_data, expected_processed_data)\n os.remove(output_file)\n\n def test_process_excel_data_2(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name', 'Age', 'Country'],\n ['John', 25, 'USA'],\n ['Alice', 30, 'Canada'],\n ['Bob', 35, 'Australia']]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n N = 0\n success, output_file = processor.process_excel_data(N, self.test_file_name)\n self.assertTrue(success)\n self.assertTrue(os.path.isfile(output_file))\n processed_data = processor.read_excel(output_file)\n expected_processed_data = [\n ('Name', 'Age', 'Country', 'NAME'),\n ('John', 25, 'USA', 'JOHN'),\n ('Alice', 30, 'Canada', 'ALICE'),\n ('Bob', 35, 'Australia', 'BOB')\n ]\n self.assertEqual(processed_data, expected_processed_data)\n os.remove(output_file)\n\n def test_process_excel_data_3(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name', 'Age', 'Country'],\n ['John', 25, 'USA'],\n ['Alice', 30, 'Canada'],\n ['Bob', 35, 'Australia']]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n N = 2\n success, output_file = processor.process_excel_data(N, self.test_file_name)\n self.assertTrue(success)\n self.assertTrue(os.path.isfile(output_file))\n processed_data = processor.read_excel(output_file)\n expected_processed_data = [\n ('Name', 'Age', 'Country', 'COUNTRY'),\n ('John', 25, 'USA', 'USA'),\n ('Alice', 30, 'Canada', 'CANADA'),\n ('Bob', 35, 'Australia', 'AUSTRALIA')\n ]\n self.assertEqual(processed_data, expected_processed_data)\n os.remove(output_file)\n\n def test_process_excel_data_4(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name', 'Age', 'COUNTRY'],\n ['John', 25, 'USA'],\n ['Alice', 30, 'CANADA'],\n ['Bob', 35, 'AUSTRALIA']]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n N = 2\n success, output_file = processor.process_excel_data(N, self.test_file_name)\n self.assertTrue(success)\n self.assertTrue(os.path.isfile(output_file))\n processed_data = processor.read_excel(output_file)\n expected_processed_data = [\n ('Name', 'Age', 'COUNTRY', 'COUNTRY'),\n ('John', 25, 'USA', 'USA'),\n ('Alice', 30, 'CANADA', 'CANADA'),\n ('Bob', 35, 'AUSTRALIA', 'AUSTRALIA')\n ]\n self.assertEqual(processed_data, expected_processed_data)\n os.remove(output_file)\n\n def test_process_excel_data_5(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name', 'AGE', 'COUNTRY'],\n ['John', 25, 'USA'],\n ['Alice', 30, 'CANADA'],\n ['Bob', 35, 'AUSTRALIA']]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n N = 1\n success, output_file = processor.process_excel_data(N, self.test_file_name)\n self.assertTrue(success)\n self.assertTrue(os.path.isfile(output_file))\n processed_data = processor.read_excel(output_file)\n expected_processed_data = [\n ('Name', 'AGE', 'COUNTRY', 'AGE'),\n ('John', 25, 'USA', 25),\n ('Alice', 30, 'CANADA', 30),\n ('Bob', 35, 'AUSTRALIA', 35)\n ]\n self.assertEqual(processed_data, expected_processed_data)\n os.remove(output_file)\n\n def test_process_excel_data_6(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name', 'AGE', 'COUNTRY'],\n ['John', 25, 'USA'],\n ['Alice', 30, 'CANADA'],\n ['Bob', 35, 'AUSTRALIA']]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n res = processor.process_excel_data(100, self.test_file_name)\n self.assertEqual(res, 0)\n\n\nclass ExcelProcessorTest(unittest.TestCase):\n def test_ExcelProcessor(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name', 'Age', 'Country'],\n ['John', 25, 'USA'],\n ['Alice', 30, 'Canada'],\n ['Bob', 35, 'Australia']]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n data = processor.read_excel(self.test_file_name)\n expected_data = [\n ('Name', 'Age', 'Country'),\n ('John', 25, 'USA'),\n ('Alice', 30, 'Canada'),\n ('Bob', 35, 'Australia')\n ]\n self.assertEqual(data, expected_data)\n\n processor = ExcelProcessor()\n new_data = [\n ('Name', 'Age', 'Country'),\n ('John', 25, 'USA'),\n ('Alice', 30, 'Canada'),\n ('Bob', 35, 'Australia'),\n ('Julia', 28, 'Germany')\n ]\n save_file_name = 'test_output.xlsx'\n success = processor.write_excel(new_data, save_file_name)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(save_file_name))\n saved_data = processor.read_excel(save_file_name)\n self.assertEqual(saved_data, new_data)\n os.remove(save_file_name)\n\n self.test_file_name = 'test_data.xlsx'\n data = [['Name', 'Age', 'Country'],\n ['John', 25, 'USA'],\n ['Alice', 30, 'Canada'],\n ['Bob', 35, 'Australia']]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n N = 1\n success, output_file = processor.process_excel_data(N, self.test_file_name)\n self.assertTrue(success)\n self.assertTrue(os.path.isfile(output_file))\n processed_data = processor.read_excel(output_file)\n expected_processed_data = [\n ('Name', 'Age', 'Country', 'AGE'),\n ('John', 25, 'USA', 25),\n ('Alice', 30, 'Canada', 30),\n ('Bob', 35, 'Australia', 35)\n ]\n self.assertEqual(processed_data, expected_processed_data)\n os.remove(output_file)", "solution_code": "import openpyxl\n\n\nclass ExcelProcessor:\n def __init__(self):\n pass\n\n def read_excel(self, file_name):\n data = []\n try:\n workbook = openpyxl.load_workbook(file_name)\n sheet = workbook.active\n for row in sheet.iter_rows(values_only=True):\n data.append(row)\n workbook.close()\n return data\n except:\n return None\n\n def write_excel(self, data, file_name):\n try:\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(file_name)\n workbook.close()\n return 1\n except:\n return 0\n\n def process_excel_data(self, N, save_file_name):\n data = self.read_excel(save_file_name)\n if data is None or N >= len(data[0]):\n return 0\n new_data = []\n for row in data:\n new_row = list(row[:])\n if not str(row[N]).isdigit():\n new_row.append(str(row[N]).upper())\n else:\n new_row.append(row[N])\n new_data.append(new_row)\n new_file_name = save_file_name.split('.')[0] + '_process.xlsx'\n success = self.write_excel(new_data, new_file_name)\n return success, new_file_name", "import_statement": [ "import openpyxl" ], "class_description": " \"\"\"\n This is a class for processing excel files, including readring and writing excel data, as well as processing specific operations and saving as a new excel file.\n \"\"\"\n", "class_name": "ExcelProcessor", "test_classes": [ "ExcelProcessorTestReadExcel", "ExcelProcessorTestWriteExcel", "ExcelProcessorTestProcessExcelData", "ExcelProcessorTest" ], "class_constructor": "class ExcelProcessor: \n def __init__(self):\n pass\n\n", "fields": [], "methods_info": [ { "method_name": "read_excel", "method_description": "def read_excel(self, file_name):\n \"\"\"\n Reading data from Excel files\n :param file_name:str, Excel file name to read\n :return:list of data, Data in Excel\n \"\"\"", "test_class": "ExcelProcessorTestReadExcel", "test_code": "class ExcelProcessorTestReadExcel(unittest.TestCase):\n def test_read_excel_1(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name', 'Age', 'Country'],\n ['John', 25, 'USA'],\n ['Alice', 30, 'Canada'],\n ['Bob', 35, 'Australia']]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n data = processor.read_excel(self.test_file_name)\n expected_data = [\n ('Name', 'Age', 'Country'),\n ('John', 25, 'USA'),\n ('Alice', 30, 'Canada'),\n ('Bob', 35, 'Australia')\n ]\n self.assertEqual(data, expected_data)\n\n def test_read_excel_2(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name', 'Age'],\n ['John', 25],\n ['Alice', 30],\n ['Bob', 35]]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n data = processor.read_excel(self.test_file_name)\n expected_data = [\n ('Name', 'Age'),\n ('John', 25),\n ('Alice', 30),\n ('Bob', 35)\n ]\n self.assertEqual(data, expected_data)\n\n def test_read_excel_3(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name'],\n ['John'],\n ['Alice'],\n ['Bob']]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n data = processor.read_excel(self.test_file_name)\n expected_data = [\n ('Name',),\n ('John',),\n ('Alice',),\n ('Bob',)\n ]\n self.assertEqual(data, expected_data)\n\n def test_read_excel_4(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name', 'Country'],\n ['John', 'USA'],\n ['Alice', 'Canada'],\n ['Bob', 'Australia']]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n data = processor.read_excel(self.test_file_name)\n expected_data = [\n ('Name', 'Country'),\n ('John', 'USA'),\n ('Alice', 'Canada'),\n ('Bob', 'Australia')\n ]\n self.assertEqual(data, expected_data)\n\n def test_read_excel_5(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name', 'Country'],\n ['John', 'USA']]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n data = processor.read_excel(self.test_file_name)\n expected_data = [\n ('Name', 'Country'),\n ('John', 'USA')\n ]\n self.assertEqual(data, expected_data)\n\n def test_read_excel_6(self):\n self.test_file_name = ''\n processor = ExcelProcessor()\n res = processor.read_excel(self.test_file_name)\n self.assertEqual(res, None)", "solution_code": "def read_excel(self, file_name):\n data = []\n try:\n workbook = openpyxl.load_workbook(file_name)\n sheet = workbook.active\n for row in sheet.iter_rows(values_only=True):\n data.append(row)\n workbook.close()\n return data\n except:\n return None", "dependencies": { "Standalone": false, "lib_dependencies": [ "openpyxl" ], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "write_excel", "method_description": "def write_excel(self, data, file_name):\n \"\"\"\n Write data to the specified Excel file\n :param data: list, Data to be written\n :param file_name: str, Excel file name to write to\n :return: 0 or 1, 1 represents successful writing, 0 represents failed writing\n >>> processor = ExcelProcessor()\n >>> new_data = [\n >>> ('Name', 'Age', 'Country'),\n >>> ('John', 25, 'USA'),\n >>> ('Alice', 30, 'Canada'),\n >>> ('Bob', 35, 'Australia'),\n >>> ('Julia', 28, 'Germany')\n >>> ]\n >>> data = processor.write_excel(new_data, 'test_data.xlsx')\n \"\"\"", "test_class": "ExcelProcessorTestWriteExcel", "test_code": "class ExcelProcessorTestWriteExcel(unittest.TestCase):\n def test_write_excel_1(self):\n processor = ExcelProcessor()\n new_data = [\n ('Name', 'Age', 'Country'),\n ('John', 25, 'USA'),\n ('Alice', 30, 'Canada'),\n ('Bob', 35, 'Australia'),\n ('Julia', 28, 'Germany')\n ]\n save_file_name = 'test_output.xlsx'\n success = processor.write_excel(new_data, save_file_name)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(save_file_name))\n saved_data = processor.read_excel(save_file_name)\n self.assertEqual(saved_data, new_data)\n os.remove(save_file_name)\n\n def test_write_excel_2(self):\n processor = ExcelProcessor()\n new_data = [\n ('Name', 'Age'),\n ('John', 25),\n ('Alice', 30),\n ('Bob', 35),\n ('Julia', 28)\n ]\n save_file_name = 'test_output.xlsx'\n success = processor.write_excel(new_data, save_file_name)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(save_file_name))\n saved_data = processor.read_excel(save_file_name)\n self.assertEqual(saved_data, new_data)\n os.remove(save_file_name)\n\n def test_write_excel_3(self):\n processor = ExcelProcessor()\n new_data = [\n ('Name', 'Age', 'Country'),\n ('John', 25, 'USA'),\n ('Alice', 30, 'Canada'),\n ('Bob', 35, 'Australia')\n ]\n save_file_name = 'test_output.xlsx'\n success = processor.write_excel(new_data, save_file_name)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(save_file_name))\n saved_data = processor.read_excel(save_file_name)\n self.assertEqual(saved_data, new_data)\n os.remove(save_file_name)\n\n def test_write_excel_4(self):\n processor = ExcelProcessor()\n new_data = [\n ('Name', 'Age', 'Country'),\n ('John', 25, 'USA'),\n ('Alice', 30, 'Canada')\n ]\n save_file_name = 'test_output.xlsx'\n success = processor.write_excel(new_data, save_file_name)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(save_file_name))\n saved_data = processor.read_excel(save_file_name)\n self.assertEqual(saved_data, new_data)\n os.remove(save_file_name)\n\n def test_write_excel_5(self):\n processor = ExcelProcessor()\n new_data = [\n ('Name', 'Age', 'Country'),\n ('John', 25, 'USA')\n ]\n save_file_name = 'test_output.xlsx'\n success = processor.write_excel(new_data, save_file_name)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(save_file_name))\n saved_data = processor.read_excel(save_file_name)\n self.assertEqual(saved_data, new_data)\n os.remove(save_file_name)\n\n def test_write_excel_6(self):\n processor = ExcelProcessor()\n new_data = [\n ('Name', 'Age', 'Country'),\n ('John', 25, 'USA')\n ]\n save_file_name = ''\n success = processor.write_excel(new_data, save_file_name)\n self.assertEqual(success, 0)", "solution_code": "def write_excel(self, data, file_name):\n try:\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(file_name)\n workbook.close()\n return 1\n except:\n return 0", "dependencies": { "Standalone": false, "lib_dependencies": [ "openpyxl" ], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "process_excel_data", "method_description": "def process_excel_data(self, N, save_file_name):\n \"\"\"\n Change the specified column in the Excel file to uppercase\n :param N: int, The serial number of the column that want to change\n :param save_file_name: str, source file name\n :return:(int, str), The former is the return value of write_excel, while the latter is the saved file name of the processed data\n >>> processor = ExcelProcessor()\n >>> success, output_file = processor.process_excel_data(1, 'test_data.xlsx')\n \"\"\"", "test_class": "ExcelProcessorTestProcessExcelData", "test_code": "class ExcelProcessorTestProcessExcelData(unittest.TestCase):\n def test_process_excel_data_1(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name', 'Age', 'Country'],\n ['John', 25, 'USA'],\n ['Alice', 30, 'Canada'],\n ['Bob', 35, 'Australia']]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n N = 1\n success, output_file = processor.process_excel_data(N, self.test_file_name)\n self.assertTrue(success)\n self.assertTrue(os.path.isfile(output_file))\n processed_data = processor.read_excel(output_file)\n expected_processed_data = [\n ('Name', 'Age', 'Country', 'AGE'),\n ('John', 25, 'USA', 25),\n ('Alice', 30, 'Canada', 30),\n ('Bob', 35, 'Australia', 35)\n ]\n self.assertEqual(processed_data, expected_processed_data)\n os.remove(output_file)\n\n def test_process_excel_data_2(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name', 'Age', 'Country'],\n ['John', 25, 'USA'],\n ['Alice', 30, 'Canada'],\n ['Bob', 35, 'Australia']]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n N = 0\n success, output_file = processor.process_excel_data(N, self.test_file_name)\n self.assertTrue(success)\n self.assertTrue(os.path.isfile(output_file))\n processed_data = processor.read_excel(output_file)\n expected_processed_data = [\n ('Name', 'Age', 'Country', 'NAME'),\n ('John', 25, 'USA', 'JOHN'),\n ('Alice', 30, 'Canada', 'ALICE'),\n ('Bob', 35, 'Australia', 'BOB')\n ]\n self.assertEqual(processed_data, expected_processed_data)\n os.remove(output_file)\n\n def test_process_excel_data_3(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name', 'Age', 'Country'],\n ['John', 25, 'USA'],\n ['Alice', 30, 'Canada'],\n ['Bob', 35, 'Australia']]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n N = 2\n success, output_file = processor.process_excel_data(N, self.test_file_name)\n self.assertTrue(success)\n self.assertTrue(os.path.isfile(output_file))\n processed_data = processor.read_excel(output_file)\n expected_processed_data = [\n ('Name', 'Age', 'Country', 'COUNTRY'),\n ('John', 25, 'USA', 'USA'),\n ('Alice', 30, 'Canada', 'CANADA'),\n ('Bob', 35, 'Australia', 'AUSTRALIA')\n ]\n self.assertEqual(processed_data, expected_processed_data)\n os.remove(output_file)\n\n def test_process_excel_data_4(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name', 'Age', 'COUNTRY'],\n ['John', 25, 'USA'],\n ['Alice', 30, 'CANADA'],\n ['Bob', 35, 'AUSTRALIA']]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n N = 2\n success, output_file = processor.process_excel_data(N, self.test_file_name)\n self.assertTrue(success)\n self.assertTrue(os.path.isfile(output_file))\n processed_data = processor.read_excel(output_file)\n expected_processed_data = [\n ('Name', 'Age', 'COUNTRY', 'COUNTRY'),\n ('John', 25, 'USA', 'USA'),\n ('Alice', 30, 'CANADA', 'CANADA'),\n ('Bob', 35, 'AUSTRALIA', 'AUSTRALIA')\n ]\n self.assertEqual(processed_data, expected_processed_data)\n os.remove(output_file)\n\n def test_process_excel_data_5(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name', 'AGE', 'COUNTRY'],\n ['John', 25, 'USA'],\n ['Alice', 30, 'CANADA'],\n ['Bob', 35, 'AUSTRALIA']]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n N = 1\n success, output_file = processor.process_excel_data(N, self.test_file_name)\n self.assertTrue(success)\n self.assertTrue(os.path.isfile(output_file))\n processed_data = processor.read_excel(output_file)\n expected_processed_data = [\n ('Name', 'AGE', 'COUNTRY', 'AGE'),\n ('John', 25, 'USA', 25),\n ('Alice', 30, 'CANADA', 30),\n ('Bob', 35, 'AUSTRALIA', 35)\n ]\n self.assertEqual(processed_data, expected_processed_data)\n os.remove(output_file)\n\n def test_process_excel_data_6(self):\n self.test_file_name = 'test_data.xlsx'\n data = [['Name', 'AGE', 'COUNTRY'],\n ['John', 25, 'USA'],\n ['Alice', 30, 'CANADA'],\n ['Bob', 35, 'AUSTRALIA']]\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n for row in data:\n sheet.append(row)\n workbook.save(self.test_file_name)\n workbook.close()\n\n processor = ExcelProcessor()\n res = processor.process_excel_data(100, self.test_file_name)\n self.assertEqual(res, 0)", "solution_code": "def process_excel_data(self, N, save_file_name):\n data = self.read_excel(save_file_name)\n if data is None or N >= len(data[0]):\n return 0\n new_data = []\n for row in data:\n new_row = list(row[:])\n if not str(row[N]).isdigit():\n new_row.append(str(row[N]).upper())\n else:\n new_row.append(row[N])\n new_data.append(new_row)\n new_file_name = save_file_name.split('.')[0] + '_process.xlsx'\n success = self.write_excel(new_data, new_file_name)\n return success, new_file_name", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "read_excel", "write_excel" ] } } ] }, { "task_id": "ClassEval_39", "skeleton": "\nclass ExpressionCalculator:\n \"\"\"\n This is a class in Python that can perform calculations with basic arithmetic operations, including addition, subtraction, multiplication, division, and modulo.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialize the expression calculator\n \"\"\"\n self.postfix_stack = deque()\n self.operat_priority = [0, 3, 2, 1, -1, 1, 0, 2]\n\n def calculate(self, expression):\n \"\"\"\n Calculate the result of the given postfix expression\n :param expression: string, the postfix expression to be calculated\n :return: float, the calculated result\n >>> expression_calculator = ExpressionCalculator()\n >>> expression_calculator.calculate(\"2 + 3 * 4\")\n 14.0\n\n \"\"\"\n\n\n def prepare(self, expression):\n \"\"\"\n Prepare the infix expression for conversion to postfix notation\n :param expression: string, the infix expression to be prepared\n >>> expression_calculator = ExpressionCalculator()\n >>> expression_calculator.prepare(\"2+3*4\")\n\n expression_calculator.postfix_stack = ['2', '3', '4', '*', '+']\n \"\"\"\n\n\n @staticmethod\n def is_operator(c):\n \"\"\"\n Check if a character is an operator in {'+', '-', '*', '/', '(', ')', '%'}\n :param c: string, the character to be checked\n :return: bool, True if the character is an operator, False otherwise\n >>> expression_calculator = ExpressionCalculator()\n >>> expression_calculator.is_operator(\"+\")\n True\n\n \"\"\"\n\n\n def compare(self, cur, peek):\n \"\"\"\n Compare the precedence of two operators\n :param cur: string, the current operator\n :param peek: string, the operator at the top of the operator stack\n :return: bool, True if the current operator has higher or equal precedence, False otherwise\n >>> expression_calculator = ExpressionCalculator()\n >>> expression_calculator.compare(\"+\", \"-\")\n True\n\n \"\"\"\n\n\n @staticmethod\n def _calculate(first_value, second_value, current_op):\n \"\"\"\n Perform the mathematical calculation based on the given operands and operator\n :param first_value: string, the first operand\n :param second_value: string, the second operand\n :param current_op: string, the operator\n :return: decimal.Decimal, the calculated result\n >>> expression_calculator = ExpressionCalculator()\n >>> expression_calculator._calculate(\"2\", \"3\", \"+\")\n 5.0\n\n \"\"\"\n\n\n @staticmethod\n def transform(expression):\n \"\"\"\n Transform the infix expression to a format suitable for conversion\n :param expression: string, the infix expression to be transformed\n :return: string, the transformed expression\n >>> expression_calculator = ExpressionCalculator()\n >>> expression_calculator.transform(\"2 + 3 * 4\")\n \"2+3*4\"\n\n \"\"\"", "test": "import unittest\n\n\nclass ExpressionCalculatorTestCalculate(unittest.TestCase):\n def setUp(self):\n self.expression_calculator = ExpressionCalculator()\n\n def test_calculate_1(self):\n result = self.expression_calculator.calculate(\"2 + 3 * 4\")\n self.assertEqual(result, 14.0)\n\n def test_calculate_2(self):\n result = self.expression_calculator.calculate(\"2 + 3 + 4\")\n self.assertEqual(result, 9.0)\n\n def test_calculate_3(self):\n result = self.expression_calculator.calculate(\"2 * 3 * 4\")\n self.assertEqual(result, 24.0)\n\n def test_calculate_4(self):\n result = self.expression_calculator.calculate(\"2 + 4 / 4\")\n self.assertEqual(result, 3.0)\n\n def test_calculate_5(self):\n result = self.expression_calculator.calculate(\"(2 + 3) * 4\")\n self.assertEqual(result, 20.0)\n\n\nclass ExpressionCalculatorTestPrepare(unittest.TestCase):\n def setUp(self):\n self.expression_calculator = ExpressionCalculator()\n\n def test_prepare_1(self):\n self.expression_calculator.prepare(\"2+3*4\")\n self.assertEqual(self.expression_calculator.postfix_stack, deque(['2', '3', '4', '*', '+']))\n\n def test_prepare_2(self):\n self.expression_calculator.prepare(\"2+3/4\")\n self.assertEqual(self.expression_calculator.postfix_stack, deque(['2', '3', '4', '/', '+']))\n\n def test_prepare_3(self):\n self.expression_calculator.prepare(\"2-3*4\")\n self.assertEqual(self.expression_calculator.postfix_stack, deque(['2', '3', '4', '*', '-']))\n\n def test_prepare_4(self):\n self.expression_calculator.prepare(\"1+3*4\")\n self.assertEqual(self.expression_calculator.postfix_stack, deque(['1', '3', '4', '*', '+']))\n\n def test_prepare_5(self):\n self.expression_calculator.prepare(\"(2+3)*4\")\n self.assertEqual(self.expression_calculator.postfix_stack, deque(['2', '3', '+', '4', '*']))\n\n def test_prepare_6(self):\n self.expression_calculator.prepare(\"\")\n self.assertEqual(self.expression_calculator.postfix_stack, deque([]))\n\n\nclass ExpressionCalculatorTestIsOperator(unittest.TestCase):\n def setUp(self):\n self.expression_calculator = ExpressionCalculator()\n\n def test_is_operator_1(self):\n self.assertTrue(self.expression_calculator.is_operator(\"+\"))\n\n def test_is_operator_2(self):\n self.assertTrue(self.expression_calculator.is_operator(\"-\"))\n\n def test_is_operator_3(self):\n self.assertTrue(self.expression_calculator.is_operator(\"*\"))\n\n def test_is_operator_4(self):\n self.assertTrue(self.expression_calculator.is_operator(\"/\"))\n\n def test_is_operator_5(self):\n self.assertFalse(self.expression_calculator.is_operator(\"5\"))\n\n\nclass ExpressionCalculatorTestCompare(unittest.TestCase):\n def setUp(self):\n self.expression_calculator = ExpressionCalculator()\n\n def test_compare_1(self):\n result = self.expression_calculator.compare(\"+\", \"-\")\n self.assertTrue(result)\n\n def test_compare_2(self):\n result = self.expression_calculator.compare(\"*\", \"/\")\n self.assertTrue(result)\n\n def test_compare_3(self):\n result = self.expression_calculator.compare(\"+\", \"*\")\n self.assertTrue(result)\n\n def test_compare_4(self):\n result = self.expression_calculator.compare(\"*\", \"+\")\n self.assertFalse(result)\n\n def test_compare_5(self):\n result = self.expression_calculator.compare(\"/\", \"+\")\n self.assertFalse(result)\n\n def test_compare_6(self):\n result = self.expression_calculator.compare(\"%\", \"+\")\n self.assertFalse(result)\n\n def test_compare_7(self):\n result = self.expression_calculator.compare(\"+\", \"%\")\n self.assertTrue(result)\n\n\nclass ExpressionCalculatorTestCalculateMethod(unittest.TestCase):\n def setUp(self):\n self.expression_calculator = ExpressionCalculator()\n\n def test_calculate_method_1(self):\n result = self.expression_calculator._calculate(\"2\", \"3\", \"+\")\n self.assertEqual(result, Decimal(5.0))\n\n def test_calculate_method_2(self):\n result = self.expression_calculator._calculate(\"3\", \"2\", \"-\")\n self.assertEqual(result, Decimal(1.0))\n\n def test_calculate_method_3(self):\n result = self.expression_calculator._calculate(\"2\", \"3\", \"*\")\n self.assertEqual(result, Decimal(6.0))\n\n def test_calculate_method_4(self):\n result = self.expression_calculator._calculate(\"3\", \"3\", \"/\")\n self.assertEqual(result, Decimal(1.0))\n\n def test_calculate_method_5(self):\n result = self.expression_calculator._calculate(\"6\", \"2\", \"/\")\n self.assertEqual(result, Decimal(3.0))\n\n def test_calculate_method_6(self):\n result = self.expression_calculator._calculate(\"6\", \"2\", \"%\")\n self.assertEqual(result, Decimal(0.0))\n\n def test_calculate_method_7(self):\n try:\n self.expression_calculator._calculate(\"6\", \"2\", \"??\")\n except:\n pass\n\n\nclass ExpressionCalculatorTestTransform(unittest.TestCase):\n def setUp(self):\n self.expression_calculator = ExpressionCalculator()\n\n def test_transform_1(self):\n result = self.expression_calculator.transform(\"2 + 3 * 4\")\n self.assertEqual(result, \"2+3*4\")\n\n def test_transform_2(self):\n result = self.expression_calculator.transform(\"2 + 3 / 4\")\n self.assertEqual(result, \"2+3/4\")\n\n def test_transform_3(self):\n result = self.expression_calculator.transform(\"2 - 3 * 4\")\n self.assertEqual(result, \"2-3*4\")\n\n def test_transform_4(self):\n result = self.expression_calculator.transform(\"1 + 3 * 4\")\n self.assertEqual(result, \"1+3*4\")\n\n def test_transform_5(self):\n result = self.expression_calculator.transform(\"-2 + (-3) * 4\")\n self.assertEqual(result, \"~2+(~3)*4\")\n\n def test_transform_6(self):\n result = self.expression_calculator.transform(\"~(1 + 1)\")\n self.assertEqual(result, \"0-(1+1)\")\n\n\nclass ExpressionCalculatorTest(unittest.TestCase):\n def setUp(self):\n self.expression_calculator = ExpressionCalculator()\n\n def test_ExpressionCalculator(self):\n result = self.expression_calculator.calculate(\"2 + 3 * 4\")\n self.assertEqual(result, 14.0)\n\n self.expression_calculator.prepare(\"2+3*4\")\n self.assertEqual(self.expression_calculator.postfix_stack, deque(['2', '3', '4', '*', '+']))\n\n self.assertTrue(self.expression_calculator.is_operator(\"+\"))\n\n result = self.expression_calculator.compare(\"+\", \"-\")\n self.assertTrue(result)\n\n result = self.expression_calculator._calculate(\"2\", \"3\", \"+\")\n self.assertEqual(result, Decimal(5.0))\n\n result = self.expression_calculator.transform(\"2 + 3 * 4\")\n self.assertEqual(result, \"2+3*4\")", "solution_code": "import re\nfrom collections import deque\nfrom decimal import Decimal\n\n\nclass ExpressionCalculator:\n def __init__(self):\n self.postfix_stack = deque()\n self.operat_priority = [0, 3, 2, 1, -1, 1, 0, 2]\n\n def calculate(self, expression):\n self.prepare(self.transform(expression))\n\n result_stack = deque()\n self.postfix_stack.reverse()\n\n while self.postfix_stack:\n current_op = self.postfix_stack.pop()\n if not self.is_operator(current_op):\n current_op = current_op.replace(\"~\", \"-\")\n result_stack.append(current_op)\n else:\n second_value = result_stack.pop()\n first_value = result_stack.pop()\n\n first_value = first_value.replace(\"~\", \"-\")\n second_value = second_value.replace(\"~\", \"-\")\n\n temp_result = self._calculate(first_value, second_value, current_op)\n result_stack.append(str(temp_result))\n\n return float(eval(\"*\".join(result_stack)))\n\n def prepare(self, expression):\n op_stack = deque([','])\n arr = list(expression)\n current_index = 0\n count = 0\n\n for i, current_op in enumerate(arr):\n if self.is_operator(current_op):\n if count > 0:\n self.postfix_stack.append(\"\".join(arr[current_index: current_index + count]))\n peek_op = op_stack[-1]\n if current_op == ')':\n while op_stack[-1] != '(':\n self.postfix_stack.append(str(op_stack.pop()))\n op_stack.pop()\n else:\n while current_op != '(' and peek_op != ',' and self.compare(current_op, peek_op):\n self.postfix_stack.append(str(op_stack.pop()))\n peek_op = op_stack[-1]\n op_stack.append(current_op)\n\n count = 0\n current_index = i + 1\n else:\n count += 1\n\n if count > 1 or (count == 1 and not self.is_operator(arr[current_index])):\n self.postfix_stack.append(\"\".join(arr[current_index: current_index + count]))\n\n while op_stack[-1] != ',':\n self.postfix_stack.append(str(op_stack.pop()))\n\n @staticmethod\n def is_operator(c):\n return c in {'+', '-', '*', '/', '(', ')', '%'}\n\n def compare(self, cur, peek):\n if cur == '%':\n cur = '/'\n if peek == '%':\n peek = '/'\n return self.operat_priority[ord(peek) - 40] >= self.operat_priority[ord(cur) - 40]\n\n @staticmethod\n def _calculate(first_value, second_value, current_op):\n if current_op == '+':\n return Decimal(first_value) + Decimal(second_value)\n elif current_op == '-':\n return Decimal(first_value) - Decimal(second_value)\n elif current_op == '*':\n return Decimal(first_value) * Decimal(second_value)\n elif current_op == '/':\n return Decimal(first_value) / Decimal(second_value)\n elif current_op == '%':\n return Decimal(first_value) % Decimal(second_value)\n else:\n raise ValueError(\"Unexpected operator: {}\".format(current_op))\n\n @staticmethod\n def transform(expression):\n expression = re.sub(r\"\\s+\", \"\", expression)\n expression = re.sub(r\"=$\", \"\", expression)\n arr = list(expression)\n\n for i, c in enumerate(arr):\n if c == '-':\n if i == 0:\n arr[i] = '~'\n else:\n prev_c = arr[i - 1]\n if prev_c in {'+', '-', '*', '/', '(', 'E', 'e'}:\n arr[i] = '~'\n\n if arr[0] == '~' and (len(arr) > 1 and arr[1] == '('):\n arr[0] = '-'\n return \"0\" + \"\".join(arr)\n else:\n return \"\".join(arr)", "import_statement": [ "import re", "from collections import deque", "from decimal import Decimal" ], "class_description": " \"\"\"\n This is a class in Python that can perform calculations with basic arithmetic operations, including addition, subtraction, multiplication, division, and modulo.\n \"\"\"\n", "class_name": "ExpressionCalculator", "test_classes": [ "ExpressionCalculatorTestCalculate", "ExpressionCalculatorTestPrepare", "ExpressionCalculatorTestIsOperator", "ExpressionCalculatorTestCompare", "ExpressionCalculatorTestCalculateMethod", "ExpressionCalculatorTestTransform", "ExpressionCalculatorTest" ], "class_constructor": "class ExpressionCalculator: \n def __init__(self):\n \"\"\"\n Initialize the expression calculator\n \"\"\"\n self.postfix_stack = deque()\n self.operat_priority = [0, 3, 2, 1, -1, 1, 0, 2]\n\n", "fields": [ "self.operat_priority", "self.postfix_stack" ], "methods_info": [ { "method_name": "calculate", "method_description": "def calculate(self, expression):\n \"\"\"\n Calculate the result of the given postfix expression\n :param expression: string, the postfix expression to be calculated\n :return: float, the calculated result\n >>> expression_calculator = ExpressionCalculator()\n >>> expression_calculator.calculate(\"2 + 3 * 4\")\n 14.0\n\n \"\"\"", "test_class": "ExpressionCalculatorTestCalculate", "test_code": "class ExpressionCalculatorTestCalculate(unittest.TestCase):\n def setUp(self):\n self.expression_calculator = ExpressionCalculator()\n\n def test_calculate_1(self):\n result = self.expression_calculator.calculate(\"2 + 3 * 4\")\n self.assertEqual(result, 14.0)\n\n def test_calculate_2(self):\n result = self.expression_calculator.calculate(\"2 + 3 + 4\")\n self.assertEqual(result, 9.0)\n\n def test_calculate_3(self):\n result = self.expression_calculator.calculate(\"2 * 3 * 4\")\n self.assertEqual(result, 24.0)\n\n def test_calculate_4(self):\n result = self.expression_calculator.calculate(\"2 + 4 / 4\")\n self.assertEqual(result, 3.0)\n\n def test_calculate_5(self):\n result = self.expression_calculator.calculate(\"(2 + 3) * 4\")\n self.assertEqual(result, 20.0)", "solution_code": "def calculate(self, expression):\n self.prepare(self.transform(expression))\n\n result_stack = deque()\n self.postfix_stack.reverse()\n\n while self.postfix_stack:\n current_op = self.postfix_stack.pop()\n if not self.is_operator(current_op):\n current_op = current_op.replace(\"~\", \"-\")\n result_stack.append(current_op)\n else:\n second_value = result_stack.pop()\n first_value = result_stack.pop()\n\n first_value = first_value.replace(\"~\", \"-\")\n second_value = second_value.replace(\"~\", \"-\")\n\n temp_result = self._calculate(first_value, second_value, current_op)\n result_stack.append(str(temp_result))\n\n return float(eval(\"*\".join(result_stack)))", "dependencies": { "Standalone": false, "lib_dependencies": [ "re", "deque" ], "field_dependencies": [ "self.postfix_stack" ], "method_dependencies": [ "prepare", "is_operator", "_calculate", "transform" ] } }, { "method_name": "prepare", "method_description": "def prepare(self, expression):\n \"\"\"\n Prepare the infix expression for conversion to postfix notation\n :param expression: string, the infix expression to be prepared\n >>> expression_calculator = ExpressionCalculator()\n >>> expression_calculator.prepare(\"2+3*4\")\n\n expression_calculator.postfix_stack = ['2', '3', '4', '*', '+']\n \"\"\"", "test_class": "ExpressionCalculatorTestPrepare", "test_code": "class ExpressionCalculatorTestPrepare(unittest.TestCase):\n def setUp(self):\n self.expression_calculator = ExpressionCalculator()\n\n def test_prepare_1(self):\n self.expression_calculator.prepare(\"2+3*4\")\n self.assertEqual(self.expression_calculator.postfix_stack, deque(['2', '3', '4', '*', '+']))\n\n def test_prepare_2(self):\n self.expression_calculator.prepare(\"2+3/4\")\n self.assertEqual(self.expression_calculator.postfix_stack, deque(['2', '3', '4', '/', '+']))\n\n def test_prepare_3(self):\n self.expression_calculator.prepare(\"2-3*4\")\n self.assertEqual(self.expression_calculator.postfix_stack, deque(['2', '3', '4', '*', '-']))\n\n def test_prepare_4(self):\n self.expression_calculator.prepare(\"1+3*4\")\n self.assertEqual(self.expression_calculator.postfix_stack, deque(['1', '3', '4', '*', '+']))\n\n def test_prepare_5(self):\n self.expression_calculator.prepare(\"(2+3)*4\")\n self.assertEqual(self.expression_calculator.postfix_stack, deque(['2', '3', '+', '4', '*']))\n\n def test_prepare_6(self):\n self.expression_calculator.prepare(\"\")\n self.assertEqual(self.expression_calculator.postfix_stack, deque([]))", "solution_code": "def prepare(self, expression):\n op_stack = deque([','])\n arr = list(expression)\n current_index = 0\n count = 0\n\n for i, current_op in enumerate(arr):\n if self.is_operator(current_op):\n if count > 0:\n self.postfix_stack.append(\"\".join(arr[current_index: current_index + count]))\n peek_op = op_stack[-1]\n if current_op == ')':\n while op_stack[-1] != '(':\n self.postfix_stack.append(str(op_stack.pop()))\n op_stack.pop()\n else:\n while current_op != '(' and peek_op != ',' and self.compare(current_op, peek_op):\n self.postfix_stack.append(str(op_stack.pop()))\n peek_op = op_stack[-1]\n op_stack.append(current_op)\n\n count = 0\n current_index = i + 1\n else:\n count += 1\n\n if count > 1 or (count == 1 and not self.is_operator(arr[current_index])):\n self.postfix_stack.append(\"\".join(arr[current_index: current_index + count]))\n\n while op_stack[-1] != ',':\n self.postfix_stack.append(str(op_stack.pop()))", "dependencies": { "Standalone": false, "lib_dependencies": [ "re", "deque" ], "field_dependencies": [ "self.postfix_stack" ], "method_dependencies": [ "is_operator", "compare" ] } }, { "method_name": "is_operator", "method_description": "@staticmethod\n def is_operator(c):\n \"\"\"\n Check if a character is an operator in {'+', '-', '*', '/', '(', ')', '%'}\n :param c: string, the character to be checked\n :return: bool, True if the character is an operator, False otherwise\n >>> expression_calculator = ExpressionCalculator()\n >>> expression_calculator.is_operator(\"+\")\n True\n\n \"\"\"", "test_class": "ExpressionCalculatorTestIsOperator", "test_code": "class ExpressionCalculatorTestIsOperator(unittest.TestCase):\n def setUp(self):\n self.expression_calculator = ExpressionCalculator()\n\n def test_is_operator_1(self):\n self.assertTrue(self.expression_calculator.is_operator(\"+\"))\n\n def test_is_operator_2(self):\n self.assertTrue(self.expression_calculator.is_operator(\"-\"))\n\n def test_is_operator_3(self):\n self.assertTrue(self.expression_calculator.is_operator(\"*\"))\n\n def test_is_operator_4(self):\n self.assertTrue(self.expression_calculator.is_operator(\"/\"))\n\n def test_is_operator_5(self):\n self.assertFalse(self.expression_calculator.is_operator(\"5\"))", "solution_code": "@staticmethod\n def is_operator(c):\n return c in {'+', '-', '*', '/', '(', ')', '%'}", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "compare", "method_description": "def compare(self, cur, peek):\n \"\"\"\n Compare the precedence of two operators\n :param cur: string, the current operator\n :param peek: string, the operator at the top of the operator stack\n :return: bool, True if the current operator has higher or equal precedence, False otherwise\n >>> expression_calculator = ExpressionCalculator()\n >>> expression_calculator.compare(\"+\", \"-\")\n True\n\n \"\"\"", "test_class": "ExpressionCalculatorTestCompare", "test_code": "class ExpressionCalculatorTestCompare(unittest.TestCase):\n def setUp(self):\n self.expression_calculator = ExpressionCalculator()\n\n def test_compare_1(self):\n result = self.expression_calculator.compare(\"+\", \"-\")\n self.assertTrue(result)\n\n def test_compare_2(self):\n result = self.expression_calculator.compare(\"*\", \"/\")\n self.assertTrue(result)\n\n def test_compare_3(self):\n result = self.expression_calculator.compare(\"+\", \"*\")\n self.assertTrue(result)\n\n def test_compare_4(self):\n result = self.expression_calculator.compare(\"*\", \"+\")\n self.assertFalse(result)\n\n def test_compare_5(self):\n result = self.expression_calculator.compare(\"/\", \"+\")\n self.assertFalse(result)\n\n def test_compare_6(self):\n result = self.expression_calculator.compare(\"%\", \"+\")\n self.assertFalse(result)\n\n def test_compare_7(self):\n result = self.expression_calculator.compare(\"+\", \"%\")\n self.assertTrue(result)", "solution_code": "def compare(self, cur, peek):\n if cur == '%':\n cur = '/'\n if peek == '%':\n peek = '/'\n return self.operat_priority[ord(peek) - 40] >= self.operat_priority[ord(cur) - 40]", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.operat_priority" ], "method_dependencies": [] } }, { "method_name": "_calculate", "method_description": "@staticmethod\n def _calculate(first_value, second_value, current_op):\n \"\"\"\n Perform the mathematical calculation based on the given operands and operator\n :param first_value: string, the first operand\n :param second_value: string, the second operand\n :param current_op: string, the operator\n :return: decimal.Decimal, the calculated result\n >>> expression_calculator = ExpressionCalculator()\n >>> expression_calculator._calculate(\"2\", \"3\", \"+\")\n 5.0\n\n \"\"\"", "test_class": "ExpressionCalculatorTestCalculateMethod", "test_code": "class ExpressionCalculatorTestCalculateMethod(unittest.TestCase):\n def setUp(self):\n self.expression_calculator = ExpressionCalculator()\n\n def test_calculate_method_1(self):\n result = self.expression_calculator._calculate(\"2\", \"3\", \"+\")\n self.assertEqual(result, Decimal(5.0))\n\n def test_calculate_method_2(self):\n result = self.expression_calculator._calculate(\"3\", \"2\", \"-\")\n self.assertEqual(result, Decimal(1.0))\n\n def test_calculate_method_3(self):\n result = self.expression_calculator._calculate(\"2\", \"3\", \"*\")\n self.assertEqual(result, Decimal(6.0))\n\n def test_calculate_method_4(self):\n result = self.expression_calculator._calculate(\"3\", \"3\", \"/\")\n self.assertEqual(result, Decimal(1.0))\n\n def test_calculate_method_5(self):\n result = self.expression_calculator._calculate(\"6\", \"2\", \"/\")\n self.assertEqual(result, Decimal(3.0))\n\n def test_calculate_method_6(self):\n result = self.expression_calculator._calculate(\"6\", \"2\", \"%\")\n self.assertEqual(result, Decimal(0.0))\n\n def test_calculate_method_7(self):\n try:\n self.expression_calculator._calculate(\"6\", \"2\", \"??\")\n except:\n pass", "solution_code": "@staticmethod\n def _calculate(first_value, second_value, current_op):\n if current_op == '+':\n return Decimal(first_value) + Decimal(second_value)\n elif current_op == '-':\n return Decimal(first_value) - Decimal(second_value)\n elif current_op == '*':\n return Decimal(first_value) * Decimal(second_value)\n elif current_op == '/':\n return Decimal(first_value) / Decimal(second_value)\n elif current_op == '%':\n return Decimal(first_value) % Decimal(second_value)\n else:\n raise ValueError(\"Unexpected operator: {}\".format(current_op))", "dependencies": { "Standalone": false, "lib_dependencies": [ "Decimal" ], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "transform", "method_description": "@staticmethod\n def transform(expression):\n \"\"\"\n Transform the infix expression to a format suitable for conversion\n :param expression: string, the infix expression to be transformed\n :return: string, the transformed expression\n >>> expression_calculator = ExpressionCalculator()\n >>> expression_calculator.transform(\"2 + 3 * 4\")\n \"2+3*4\"\n\n \"\"\"", "test_class": "ExpressionCalculatorTestTransform", "test_code": "class ExpressionCalculatorTestTransform(unittest.TestCase):\n def setUp(self):\n self.expression_calculator = ExpressionCalculator()\n\n def test_transform_1(self):\n result = self.expression_calculator.transform(\"2 + 3 * 4\")\n self.assertEqual(result, \"2+3*4\")\n\n def test_transform_2(self):\n result = self.expression_calculator.transform(\"2 + 3 / 4\")\n self.assertEqual(result, \"2+3/4\")\n\n def test_transform_3(self):\n result = self.expression_calculator.transform(\"2 - 3 * 4\")\n self.assertEqual(result, \"2-3*4\")\n\n def test_transform_4(self):\n result = self.expression_calculator.transform(\"1 + 3 * 4\")\n self.assertEqual(result, \"1+3*4\")\n\n def test_transform_5(self):\n result = self.expression_calculator.transform(\"-2 + (-3) * 4\")\n self.assertEqual(result, \"~2+(~3)*4\")\n\n def test_transform_6(self):\n result = self.expression_calculator.transform(\"~(1 + 1)\")\n self.assertEqual(result, \"0-(1+1)\")", "solution_code": "@staticmethod\n def transform(expression):\n expression = re.sub(r\"\\s+\", \"\", expression)\n expression = re.sub(r\"=$\", \"\", expression)\n arr = list(expression)\n\n for i, c in enumerate(arr):\n if c == '-':\n if i == 0:\n arr[i] = '~'\n else:\n prev_c = arr[i - 1]\n if prev_c in {'+', '-', '*', '/', '(', 'E', 'e'}:\n arr[i] = '~'\n\n if arr[0] == '~' and (len(arr) > 1 and arr[1] == '('):\n arr[0] = '-'\n return \"0\" + \"\".join(arr)\n else:\n return \"\".join(arr)", "dependencies": { "Standalone": false, "lib_dependencies": [ "re" ], "field_dependencies": [], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_40", "skeleton": "\nclass FitnessTracker:\n \"\"\"\n This is a class as fitness tracker that implements to calculate BMI (Body Mass Index) and calorie intake based on the user's height, weight, age, and sex.\n \"\"\"\n\n def __init__(self, height, weight, age, sex) -> None:\n \"\"\"\n Initialize the class with height, weight, age, and sex, and calculate the BMI standard based on sex, and male is 20-25, female is 19-24.\n \"\"\"\n self.height = height\n self.weight = weight\n self.age = age\n self.sex = sex\n self.BMI_std = [\n {\"male\": [20, 25]},\n {\"female\": [19, 24]}\n ]\n\n def get_BMI(self):\n \"\"\"\n Calculate the BMI based on the height and weight.\n :return: BMI,which is the weight divide by the square of height, float.\n >>> fitnessTracker = FitnessTracker(1.8, 70, 20, \"male\")\n >>> fitnessTracker.get_BMI()\n 21.604938271604937\n\n \"\"\"\n\n def condition_judge(self):\n \"\"\"\n Judge the condition of the user based on the BMI standard.\n :return: 1 if the user is too fat, -1 if the user is too thin, 0 if the user is normal, int.\n >>> fitnessTracker = FitnessTracker(1.8, 70, 20, \"male\")\n >>> fitnessTracker.condition_judge()\n -1\n\n \"\"\"\n\n def calculate_calorie_intake(self):\n \"\"\"\n Calculate the calorie intake based on the user's condition and BMR (Basal Metabolic Rate),BMR is calculated based on the user's height, weight, age, and sex,male is10 * self.weight + 6.25 * self.height - 5 * self.age + 5,female is 10 * self.weight + 6.25 * self.height - 5 * self.age - 161, and the calorie intake is calculated based on the BMR and the user's condition,if the user is too fat, the calorie intake is BMR * 1.2, if the user is too thin, the calorie intake is BMR * 1.6, if the user is normal, the calorie intake is BMR * 1.4.\n :return: calorie intake, float.\n >>> fitnessTracker = FitnessTracker(1.8, 70, 20, \"male\")\n >>> fitnessTracker.calculate_calorie_intake()\n 986.0\n\n \"\"\"", "test": "import unittest\n\n\nclass FitnessTrackerTestGetBMI(unittest.TestCase):\n def test_get_BMI(self):\n fitnessTracker = FitnessTracker(1.8, 70, 20, \"male\")\n self.assertEqual(fitnessTracker.get_BMI(), 21.604938271604937)\n\n def test_get_BMI_2(self):\n fitnessTracker = FitnessTracker(1.8, 50, 20, \"male\")\n self.assertEqual(fitnessTracker.get_BMI(), 15.432098765432098)\n\n def test_get_BMI_3(self):\n fitnessTracker = FitnessTracker(1.72, 53, 20, \"male\")\n self.assertEqual(fitnessTracker.get_BMI(), 17.915089237425637)\n\n def test_get_BMI_4(self):\n fitnessTracker = FitnessTracker(1.72, 60, 20, \"male\")\n self.assertEqual(fitnessTracker.get_BMI(), 20.281233098972418)\n\n def test_get_BMI_5(self):\n fitnessTracker = FitnessTracker(1.72, 65, 20, \"male\")\n self.assertEqual(fitnessTracker.get_BMI(), 21.971335857220122)\n\n\nclass FitnessTrackerTestConditionJudge(unittest.TestCase):\n def test_condition_judge(self):\n fitnessTracker = FitnessTracker(1.8, 45, 20, \"female\")\n self.assertEqual(fitnessTracker.condition_judge(), -1)\n\n def test_condition_judge_2(self):\n fitnessTracker = FitnessTracker(1.72, 80, 22, \"female\")\n self.assertEqual(fitnessTracker.condition_judge(), 1)\n\n def test_condition_judge_3(self):\n fitnessTracker = FitnessTracker(1.72, 53, 22, \"male\")\n self.assertEqual(fitnessTracker.condition_judge(), -1)\n\n def test_condition_judge_4(self):\n fitnessTracker = FitnessTracker(1.72, 60, 22, \"male\")\n self.assertEqual(fitnessTracker.condition_judge(), 0)\n\n def test_condition_judge_5(self):\n fitnessTracker = FitnessTracker(1.72, 75, 22, \"male\")\n self.assertEqual(fitnessTracker.condition_judge(), 1)\n\n\nclass FitnessTrackerTestCaculateCalorieIntake(unittest.TestCase):\n def test_calculate_calorie_intake(self):\n fitnessTracker = FitnessTracker(1.8, 70, 20, \"female\")\n self.assertEqual(fitnessTracker.calculate_calorie_intake(), 630.3499999999999)\n\n def test_calculate_calorie_intake_2(self):\n fitnessTracker = FitnessTracker(1.72, 80, 22, \"female\")\n self.assertEqual(fitnessTracker.calculate_calorie_intake(), 647.6999999999999)\n\n def test_calculate_calorie_intake_3(self):\n fitnessTracker = FitnessTracker(1.72, 53, 22, \"male\")\n self.assertEqual(fitnessTracker.calculate_calorie_intake(), 697.2)\n\n def test_calculate_calorie_intake_4(self):\n fitnessTracker = FitnessTracker(1.72, 60, 22, \"male\")\n self.assertEqual(fitnessTracker.calculate_calorie_intake(), 708.05)\n\n def test_calculate_calorie_intake_5(self):\n fitnessTracker = FitnessTracker(1.72, 75, 22, \"male\")\n self.assertEqual(fitnessTracker.calculate_calorie_intake(), 786.9)\n\n\nclass FitnessTrackerTestMain(unittest.TestCase):\n def test_main(self):\n fitnessTracker = FitnessTracker(1.8, 70, 20, \"male\")\n self.assertEqual(fitnessTracker.get_BMI(), 21.604938271604937)\n self.assertEqual(fitnessTracker.condition_judge(), 0)\n self.assertEqual(fitnessTracker.calculate_calorie_intake(), 862.75)", "solution_code": "class FitnessTracker:\n def __init__(self, height, weight, age, sex) -> None:\n self.height = height\n self.weight = weight\n self.age = age\n self.sex = sex\n self.BMI_std = [\n {\"male\": [20, 25]},\n {\"female\": [19, 24]}\n ]\n\n def get_BMI(self):\n return self.weight / self.height ** 2\n\n def condition_judge(self):\n BMI = self.get_BMI()\n if self.sex == \"male\":\n BMI_range = self.BMI_std[0][\"male\"]\n else:\n BMI_range = self.BMI_std[1][\"female\"]\n if BMI > BMI_range[1]:\n # too fat\n return 1\n elif BMI < BMI_range[0]:\n # too thin\n return -1\n else:\n # normal\n return 0\n\n def calculate_calorie_intake(self):\n if self.sex == \"male\":\n BMR = 10 * self.weight + 6.25 * self.height - 5 * self.age + 5\n else:\n BMR = 10 * self.weight + 6.25 * self.height - 5 * self.age - 161\n if self.condition_judge() == 1:\n calorie_intake = BMR * 1.2 # Sedentary lifestyle\n elif self.condition_judge() == -1:\n calorie_intake = BMR * 1.6 # Active lifestyle\n else:\n calorie_intake = BMR * 1.4 # Moderate lifestyle\n return calorie_intake", "import_statement": [], "class_description": " \"\"\"\n This is a class as fitness tracker that implements to calculate BMI (Body Mass Index) and calorie intake based on the user's height, weight, age, and sex.\n \"\"\"\n", "class_name": "FitnessTracker", "test_classes": [ "FitnessTrackerTestGetBMI", "FitnessTrackerTestConditionJudge", "FitnessTrackerTestCaculateCalorieIntake", "FitnessTrackerTestMain" ], "class_constructor": "class FitnessTracker: \n def __init__(self, height, weight, age, sex) -> None:\n \"\"\"\n Initialize the class with height, weight, age, and sex, and calculate the BMI standard based on sex, and male is 20-25, female is 19-24.\n \"\"\"\n self.height = height\n self.weight = weight\n self.age = age\n self.sex = sex\n self.BMI_std = [\n {\"male\": [20, 25]},\n {\"female\": [19, 24]}\n ]\n\n", "fields": [ "self.BMI_std", "self.age", "self.height", "self.sex", "self.weight" ], "methods_info": [ { "method_name": "get_BMI", "method_description": "def get_BMI(self):\n \"\"\"\n Calculate the BMI based on the height and weight.\n :return: BMI,which is the weight divide by the square of height, float.\n >>> fitnessTracker = FitnessTracker(1.8, 70, 20, \"male\")\n >>> fitnessTracker.get_BMI()\n 21.604938271604937\n\n \"\"\"", "test_class": "FitnessTrackerTestGetBMI", "test_code": "class FitnessTrackerTestGetBMI(unittest.TestCase):\n def test_get_BMI(self):\n fitnessTracker = FitnessTracker(1.8, 70, 20, \"male\")\n self.assertEqual(fitnessTracker.get_BMI(), 21.604938271604937)\n\n def test_get_BMI_2(self):\n fitnessTracker = FitnessTracker(1.8, 50, 20, \"male\")\n self.assertEqual(fitnessTracker.get_BMI(), 15.432098765432098)\n\n def test_get_BMI_3(self):\n fitnessTracker = FitnessTracker(1.72, 53, 20, \"male\")\n self.assertEqual(fitnessTracker.get_BMI(), 17.915089237425637)\n\n def test_get_BMI_4(self):\n fitnessTracker = FitnessTracker(1.72, 60, 20, \"male\")\n self.assertEqual(fitnessTracker.get_BMI(), 20.281233098972418)\n\n def test_get_BMI_5(self):\n fitnessTracker = FitnessTracker(1.72, 65, 20, \"male\")\n self.assertEqual(fitnessTracker.get_BMI(), 21.971335857220122)", "solution_code": "def get_BMI(self):\n return self.weight / self.height ** 2", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.height", "self.weight" ], "method_dependencies": [] } }, { "method_name": "condition_judge", "method_description": "def condition_judge(self):\n \"\"\"\n Judge the condition of the user based on the BMI standard.\n :return: 1 if the user is too fat, -1 if the user is too thin, 0 if the user is normal, int.\n >>> fitnessTracker = FitnessTracker(1.8, 70, 20, \"male\")\n >>> fitnessTracker.condition_judge()\n -1\n\n \"\"\"", "test_class": "FitnessTrackerTestConditionJudge", "test_code": "class FitnessTrackerTestConditionJudge(unittest.TestCase):\n def test_condition_judge(self):\n fitnessTracker = FitnessTracker(1.8, 45, 20, \"female\")\n self.assertEqual(fitnessTracker.condition_judge(), -1)\n\n def test_condition_judge_2(self):\n fitnessTracker = FitnessTracker(1.72, 80, 22, \"female\")\n self.assertEqual(fitnessTracker.condition_judge(), 1)\n\n def test_condition_judge_3(self):\n fitnessTracker = FitnessTracker(1.72, 53, 22, \"male\")\n self.assertEqual(fitnessTracker.condition_judge(), -1)\n\n def test_condition_judge_4(self):\n fitnessTracker = FitnessTracker(1.72, 60, 22, \"male\")\n self.assertEqual(fitnessTracker.condition_judge(), 0)\n\n def test_condition_judge_5(self):\n fitnessTracker = FitnessTracker(1.72, 75, 22, \"male\")\n self.assertEqual(fitnessTracker.condition_judge(), 1)", "solution_code": "def condition_judge(self):\n BMI = self.get_BMI()\n if self.sex == \"male\":\n BMI_range = self.BMI_std[0][\"male\"]\n else:\n BMI_range = self.BMI_std[1][\"female\"]\n if BMI > BMI_range[1]:\n # too fat\n return 1\n elif BMI < BMI_range[0]:\n # too thin\n return -1\n else:\n # normal\n return 0", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.BMI_std", "self.sex" ], "method_dependencies": [ "get_BMI" ] } }, { "method_name": "calculate_calorie_intake", "method_description": "def calculate_calorie_intake(self):\n \"\"\"\n Calculate the calorie intake based on the user's condition and BMR (Basal Metabolic Rate),BMR is calculated based on the user's height, weight, age, and sex,male is10 * self.weight + 6.25 * self.height - 5 * self.age + 5,female is 10 * self.weight + 6.25 * self.height - 5 * self.age - 161, and the calorie intake is calculated based on the BMR and the user's condition,if the user is too fat, the calorie intake is BMR * 1.2, if the user is too thin, the calorie intake is BMR * 1.6, if the user is normal, the calorie intake is BMR * 1.4.\n :return: calorie intake, float.\n >>> fitnessTracker = FitnessTracker(1.8, 70, 20, \"male\")\n >>> fitnessTracker.calculate_calorie_intake()\n 986.0\n\n \"\"\"", "test_class": "FitnessTrackerTestCaculateCalorieIntake", "test_code": "class FitnessTrackerTestCaculateCalorieIntake(unittest.TestCase):\n def test_calculate_calorie_intake(self):\n fitnessTracker = FitnessTracker(1.8, 70, 20, \"female\")\n self.assertEqual(fitnessTracker.calculate_calorie_intake(), 630.3499999999999)\n\n def test_calculate_calorie_intake_2(self):\n fitnessTracker = FitnessTracker(1.72, 80, 22, \"female\")\n self.assertEqual(fitnessTracker.calculate_calorie_intake(), 647.6999999999999)\n\n def test_calculate_calorie_intake_3(self):\n fitnessTracker = FitnessTracker(1.72, 53, 22, \"male\")\n self.assertEqual(fitnessTracker.calculate_calorie_intake(), 697.2)\n\n def test_calculate_calorie_intake_4(self):\n fitnessTracker = FitnessTracker(1.72, 60, 22, \"male\")\n self.assertEqual(fitnessTracker.calculate_calorie_intake(), 708.05)\n\n def test_calculate_calorie_intake_5(self):\n fitnessTracker = FitnessTracker(1.72, 75, 22, \"male\")\n self.assertEqual(fitnessTracker.calculate_calorie_intake(), 786.9)", "solution_code": "def calculate_calorie_intake(self):\n if self.sex == \"male\":\n BMR = 10 * self.weight + 6.25 * self.height - 5 * self.age + 5\n else:\n BMR = 10 * self.weight + 6.25 * self.height - 5 * self.age - 161\n if self.condition_judge() == 1:\n calorie_intake = BMR * 1.2 # Sedentary lifestyle\n elif self.condition_judge() == -1:\n calorie_intake = BMR * 1.6 # Active lifestyle\n else:\n calorie_intake = BMR * 1.4 # Moderate lifestyle\n return calorie_intake", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.age", "self.height", "self.sex", "self.weight" ], "method_dependencies": [ "condition_judge" ] } } ] }, { "task_id": "ClassEval_41", "skeleton": "\nclass GomokuGame:\n \"\"\"\n This class is an implementation of a Gomoku game, supporting for making moves, checking for a winner, and checking if there are five consecutive symbols on the game board.\n \"\"\"\n\n def __init__(self, board_size):\n \"\"\"\n Initializes the game with a given board size.\n It initializes the board with empty spaces and sets the current player symble as 'X'.\n \"\"\"\n self.board_size = board_size\n self.board = [[' ' for _ in range(board_size)] for _ in range(board_size)]\n self.current_player = 'X'\n\n def make_move(self, row, col):\n \"\"\"\n Makes a move at the given row and column.\n If the move is valid, it places the current player's symbol on the board\n and changes the current player to the other player (if the current player is 'X', then it becomes 'O' and vice versa).\n :param row: int, the row index of this move\n :param col: int, the column index\n return: True if the move is valid, or False otherwise.\n >>> gomokuGame = GomokuGame(10)\n >>> gomokuGame.make_move(5, 5)\n True\n >>> gomokuGame.make_move(5, 5)\n False\n \"\"\"\n\n def check_winner(self):\n \"\"\"\n Checks if there is a winner by looking for five in a row in all directions (horizontal, vertical, diagonal).\n return: the symbol of the winning player (either 'X' or 'O') if there is a winner, or None otherwise.\n >>> gomokuGame = GomokuGame(10)\n >>> moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1)]\n >>> for move in moves:\n ... gomokuGame.make_move(move[0], move[1])\n >>> gomokuGame.check_winner()\n 'X'\n \"\"\"\n\n def _check_five_in_a_row(self, row, col, direction):\n \"\"\"\n checks if there are five consecutive symbols of the same player in a row starting from a given cell in a given direction (horizontal, vertical, diagonal).\n Counts the number of consecutive symbols in that direction starting from the given cell,\n :param row: int, row of the given cell\n :param col: int, column of the given cell\n :param direction: tuple, (int, int), named as (dx, dy). Row and col will plus several dx and dy repectively.\n :return: True if there are five consecutive symbols of the same player, and False otherwise.\n >>> gomokuGame = GomokuGame(10)\n >>> moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1)]\n >>> for move in moves:\n ... gomokuGame.make_move(move[0], move[1])\n >>> gomokuGame._check_five_in_a_row(5, 1, (0, 1))\n True\n >>> gomokuGame._check_five_in_a_row(5, 1, (1, 1))\n False\n \"\"\"", "test": "import unittest\n\nclass GomokuGameTestMakeMove(unittest.TestCase):\n def setUp(self) -> None:\n self.board_size = 10\n self.gomokuGame = GomokuGame(self.board_size)\n\n def test_make_move_1(self):\n board = [[' ' for _ in range(self.board_size)] for _ in range(self.board_size)]\n self.assertEqual(True, self.gomokuGame.make_move(0, 0))\n board[0][0] = 'X'\n self.assertEqual(board, self.gomokuGame.board)\n\n # same position\n def test_make_move_2(self):\n board = [[' ' for _ in range(self.board_size)] for _ in range(self.board_size)]\n self.assertEqual(True, self.gomokuGame.make_move(0, 0))\n self.assertEqual(False, self.gomokuGame.make_move(0, 0))\n board[0][0] = 'X'\n self.assertEqual(board, self.gomokuGame.board)\n\n def test_make_move_3(self):\n board = [[' ' for _ in range(self.board_size)] for _ in range(self.board_size)]\n self.assertEqual(True, self.gomokuGame.make_move(0, 0))\n self.assertEqual(True, self.gomokuGame.make_move(0, 1))\n board[0][0] = 'X'\n board[0][1] = 'O'\n self.assertEqual(board, self.gomokuGame.board)\n\n def test_make_move_4(self):\n board = [[' ' for _ in range(self.board_size)] for _ in range(self.board_size)]\n self.assertEqual(True, self.gomokuGame.make_move(0, 0))\n self.assertEqual(True, self.gomokuGame.make_move(0, 1))\n self.assertEqual(False, self.gomokuGame.make_move(0, 0))\n board[0][0] = 'X'\n board[0][1] = 'O'\n self.assertEqual(board, self.gomokuGame.board)\n\n def test_make_move_5(self):\n board = [[' ' for _ in range(self.board_size)] for _ in range(self.board_size)]\n self.assertEqual(True, self.gomokuGame.make_move(0, 0))\n self.assertEqual(True, self.gomokuGame.make_move(0, 1))\n self.assertEqual(False, self.gomokuGame.make_move(0, 1))\n board[0][0] = 'X'\n board[0][1] = 'O'\n self.assertEqual(board, self.gomokuGame.board)\n\n\nclass GomokuGameTestCheckWinner(unittest.TestCase):\n def test_check_winner_1(self):\n gomokuGame = GomokuGame(10)\n self.assertEqual(None, gomokuGame.check_winner())\n\n def test_check_winner_2(self):\n gomokuGame = GomokuGame(10)\n moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1)]\n for move in moves:\n gomokuGame.make_move(move[0], move[1])\n self.assertEqual('X', gomokuGame.check_winner())\n\n def test_check_winner_3(self):\n gomokuGame = GomokuGame(10)\n moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 0), (0, 4)]\n for move in moves:\n gomokuGame.make_move(move[0], move[1])\n self.assertEqual('O', gomokuGame.check_winner())\n\n def test_check_winner_4(self):\n gomokuGame = GomokuGame(10)\n moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1), (0, 4)]\n for move in moves:\n gomokuGame.make_move(move[0], move[1])\n self.assertEqual(gomokuGame.check_winner(), 'O')\n\n def test_check_winner_5(self):\n gomokuGame = GomokuGame(10)\n moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1), (0, 4), (5, 0)]\n for move in moves:\n gomokuGame.make_move(move[0], move[1])\n self.assertEqual('O', gomokuGame.check_winner())\n\n\nclass GomokuGameTestCheckFiveInARow(unittest.TestCase):\n def setUp(self) -> None:\n self.gomokuGame = GomokuGame(10)\n moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1)]\n for move in moves:\n self.gomokuGame.make_move(move[0], move[1])\n\n def test_check_five_in_a_row_1(self):\n self.assertEqual(True, self.gomokuGame._check_five_in_a_row(5, 5, (0, -1)))\n\n def test_check_five_in_a_row_2(self):\n self.assertEqual(True, self.gomokuGame._check_five_in_a_row(5, 1, (0, 1)))\n\n def test_check_five_in_a_row_3(self):\n self.assertEqual(False, self.gomokuGame._check_five_in_a_row(0, 0, (0, 1)))\n\n def test_check_five_in_a_row_4(self):\n self.assertEqual(False, self.gomokuGame._check_five_in_a_row(0, 0, (1, 0)))\n\n def test_check_five_in_a_row_5(self):\n self.assertEqual(False, self.gomokuGame._check_five_in_a_row(5, 5, (1, 0)))\n\nclass GomokuGameTestMain(unittest.TestCase):\n def test_main(self):\n gomokuGame = GomokuGame(10)\n moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1)]\n self.assertEqual(None, gomokuGame.check_winner())\n for move in moves:\n self.assertEqual(True, gomokuGame.make_move(move[0], move[1]))\n self.assertEqual(False, gomokuGame.make_move(0, 0))\n self.assertEqual(True, gomokuGame._check_five_in_a_row(5, 5, (0, -1)))\n self.assertEqual('X', gomokuGame.check_winner())", "solution_code": "class GomokuGame:\n def __init__(self, board_size):\n self.board_size = board_size\n self.board = [[' ' for _ in range(board_size)] for _ in range(board_size)]\n self.current_player = 'X'\n\n def make_move(self, row, col):\n if self.board[row][col] == ' ':\n self.board[row][col] = self.current_player\n self.current_player = 'O' if self.current_player == 'X' else 'X'\n return True\n return False\n\n def check_winner(self):\n directions = [(0, 1), (1, 0), (1, 1), (1, -1)]\n for row in range(self.board_size):\n for col in range(self.board_size):\n if self.board[row][col] != ' ':\n for direction in directions:\n if self._check_five_in_a_row(row, col, direction):\n return self.board[row][col]\n return None\n\n def _check_five_in_a_row(self, row, col, direction):\n dx, dy = direction\n count = 1\n symbol = self.board[row][col]\n for i in range(1, 5):\n new_row = row + dx * i\n new_col = col + dy * i\n if not (0 <= new_row < self.board_size and 0 <= new_col < self.board_size):\n return False\n if self.board[new_row][new_col] != symbol:\n return False\n count += 1\n return count == 5", "import_statement": [], "class_description": " \"\"\"\n This class is an implementation of a Gomoku game, supporting for making moves, checking for a winner, and checking if there are five consecutive symbols on the game board.\n \"\"\"\n", "class_name": "GomokuGame", "test_classes": [ "GomokuGameTestMakeMove", "GomokuGameTestCheckWinner", "GomokuGameTestCheckFiveInARow", "GomokuGameTestMain" ], "class_constructor": "class GomokuGame: \n def __init__(self, board_size):\n \"\"\"\n Initializes the game with a given board size.\n It initializes the board with empty spaces and sets the current player symble as 'X'.\n \"\"\"\n self.board_size = board_size\n self.board = [[' ' for _ in range(board_size)] for _ in range(board_size)]\n self.current_player = 'X'\n\n", "fields": [ "self.board", "self.board_size", "self.current_player" ], "methods_info": [ { "method_name": "make_move", "method_description": "def make_move(self, row, col):\n \"\"\"\n Makes a move at the given row and column.\n If the move is valid, it places the current player's symbol on the board\n and changes the current player to the other player (if the current player is 'X', then it becomes 'O' and vice versa).\n :param row: int, the row index of this move\n :param col: int, the column index\n return: True if the move is valid, or False otherwise.\n >>> gomokuGame = GomokuGame(10)\n >>> gomokuGame.make_move(5, 5)\n True\n >>> gomokuGame.make_move(5, 5)\n False\n \"\"\"", "test_class": "GomokuGameTestMakeMove", "test_code": "class GomokuGameTestMakeMove(unittest.TestCase):\n def setUp(self) -> None:\n self.board_size = 10\n self.gomokuGame = GomokuGame(self.board_size)\n\n def test_make_move_1(self):\n board = [[' ' for _ in range(self.board_size)] for _ in range(self.board_size)]\n self.assertEqual(True, self.gomokuGame.make_move(0, 0))\n board[0][0] = 'X'\n self.assertEqual(board, self.gomokuGame.board)\n\n # same position\n def test_make_move_2(self):\n board = [[' ' for _ in range(self.board_size)] for _ in range(self.board_size)]\n self.assertEqual(True, self.gomokuGame.make_move(0, 0))\n self.assertEqual(False, self.gomokuGame.make_move(0, 0))\n board[0][0] = 'X'\n self.assertEqual(board, self.gomokuGame.board)\n\n def test_make_move_3(self):\n board = [[' ' for _ in range(self.board_size)] for _ in range(self.board_size)]\n self.assertEqual(True, self.gomokuGame.make_move(0, 0))\n self.assertEqual(True, self.gomokuGame.make_move(0, 1))\n board[0][0] = 'X'\n board[0][1] = 'O'\n self.assertEqual(board, self.gomokuGame.board)\n\n def test_make_move_4(self):\n board = [[' ' for _ in range(self.board_size)] for _ in range(self.board_size)]\n self.assertEqual(True, self.gomokuGame.make_move(0, 0))\n self.assertEqual(True, self.gomokuGame.make_move(0, 1))\n self.assertEqual(False, self.gomokuGame.make_move(0, 0))\n board[0][0] = 'X'\n board[0][1] = 'O'\n self.assertEqual(board, self.gomokuGame.board)\n\n def test_make_move_5(self):\n board = [[' ' for _ in range(self.board_size)] for _ in range(self.board_size)]\n self.assertEqual(True, self.gomokuGame.make_move(0, 0))\n self.assertEqual(True, self.gomokuGame.make_move(0, 1))\n self.assertEqual(False, self.gomokuGame.make_move(0, 1))\n board[0][0] = 'X'\n board[0][1] = 'O'\n self.assertEqual(board, self.gomokuGame.board)", "solution_code": "def make_move(self, row, col):\n if self.board[row][col] == ' ':\n self.board[row][col] = self.current_player\n self.current_player = 'O' if self.current_player == 'X' else 'X'\n return True\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.board", "self.current_player" ], "method_dependencies": [] } }, { "method_name": "check_winner", "method_description": "def check_winner(self):\n \"\"\"\n Checks if there is a winner by looking for five in a row in all directions (horizontal, vertical, diagonal).\n return: the symbol of the winning player (either 'X' or 'O') if there is a winner, or None otherwise.\n >>> gomokuGame = GomokuGame(10)\n >>> moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1)]\n >>> for move in moves:\n ... gomokuGame.make_move(move[0], move[1])\n >>> gomokuGame.check_winner()\n 'X'\n \"\"\"", "test_class": "GomokuGameTestCheckWinner", "test_code": "class GomokuGameTestCheckWinner(unittest.TestCase):\n def test_check_winner_1(self):\n gomokuGame = GomokuGame(10)\n self.assertEqual(None, gomokuGame.check_winner())\n\n def test_check_winner_2(self):\n gomokuGame = GomokuGame(10)\n moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1)]\n for move in moves:\n gomokuGame.make_move(move[0], move[1])\n self.assertEqual('X', gomokuGame.check_winner())\n\n def test_check_winner_3(self):\n gomokuGame = GomokuGame(10)\n moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 0), (0, 4)]\n for move in moves:\n gomokuGame.make_move(move[0], move[1])\n self.assertEqual('O', gomokuGame.check_winner())\n\n def test_check_winner_4(self):\n gomokuGame = GomokuGame(10)\n moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1), (0, 4)]\n for move in moves:\n gomokuGame.make_move(move[0], move[1])\n self.assertEqual(gomokuGame.check_winner(), 'O')\n\n def test_check_winner_5(self):\n gomokuGame = GomokuGame(10)\n moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1), (0, 4), (5, 0)]\n for move in moves:\n gomokuGame.make_move(move[0], move[1])\n self.assertEqual('O', gomokuGame.check_winner())", "solution_code": "def check_winner(self):\n directions = [(0, 1), (1, 0), (1, 1), (1, -1)]\n for row in range(self.board_size):\n for col in range(self.board_size):\n if self.board[row][col] != ' ':\n for direction in directions:\n if self._check_five_in_a_row(row, col, direction):\n return self.board[row][col]\n return None", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.board", "self.board_size" ], "method_dependencies": [ "_check_five_in_a_row" ] } }, { "method_name": "_check_five_in_a_row", "method_description": "def _check_five_in_a_row(self, row, col, direction):\n \"\"\"\n checks if there are five consecutive symbols of the same player in a row starting from a given cell in a given direction (horizontal, vertical, diagonal).\n Counts the number of consecutive symbols in that direction starting from the given cell,\n :param row: int, row of the given cell\n :param col: int, column of the given cell\n :param direction: tuple, (int, int), named as (dx, dy). Row and col will plus several dx and dy repectively.\n :return: True if there are five consecutive symbols of the same player, and False otherwise.\n >>> gomokuGame = GomokuGame(10)\n >>> moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1)]\n >>> for move in moves:\n ... gomokuGame.make_move(move[0], move[1])\n >>> gomokuGame._check_five_in_a_row(5, 1, (0, 1))\n True\n >>> gomokuGame._check_five_in_a_row(5, 1, (1, 1))\n False\n \"\"\"", "test_class": "GomokuGameTestCheckFiveInARow", "test_code": "class GomokuGameTestCheckFiveInARow(unittest.TestCase):\n def setUp(self) -> None:\n self.gomokuGame = GomokuGame(10)\n moves = [(5, 5), (0, 0), (5, 4), (0, 1), (5, 3), (0, 2), (5, 2), (0, 3), (5, 1)]\n for move in moves:\n self.gomokuGame.make_move(move[0], move[1])\n\n def test_check_five_in_a_row_1(self):\n self.assertEqual(True, self.gomokuGame._check_five_in_a_row(5, 5, (0, -1)))\n\n def test_check_five_in_a_row_2(self):\n self.assertEqual(True, self.gomokuGame._check_five_in_a_row(5, 1, (0, 1)))\n\n def test_check_five_in_a_row_3(self):\n self.assertEqual(False, self.gomokuGame._check_five_in_a_row(0, 0, (0, 1)))\n\n def test_check_five_in_a_row_4(self):\n self.assertEqual(False, self.gomokuGame._check_five_in_a_row(0, 0, (1, 0)))\n\n def test_check_five_in_a_row_5(self):\n self.assertEqual(False, self.gomokuGame._check_five_in_a_row(5, 5, (1, 0)))", "solution_code": "def _check_five_in_a_row(self, row, col, direction):\n dx, dy = direction\n count = 1\n symbol = self.board[row][col]\n for i in range(1, 5):\n new_row = row + dx * i\n new_col = col + dy * i\n if not (0 <= new_row < self.board_size and 0 <= new_col < self.board_size):\n return False\n if self.board[new_row][new_col] != symbol:\n return False\n count += 1\n return count == 5", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.board", "self.board_size" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_42", "skeleton": "\nclass Hotel:\n \"\"\"\n This is a class as hotel management system, managing the booking, check-in, check-out, and availability of rooms in a hotel with different room types.\n \"\"\"\n\n def __init__(self, name, rooms):\n \"\"\"\n Initialize the three fields in Hotel System.\n name is the hotel name.\n available_rooms stores the remaining rooms in the hotel\n booked_rooms stores the rooms that have been booked and the person's name who booked rooms.\n >>> hotel.name\n 'peace hotel'\n >>> hotel.available_rooms\n available_rooms = {'single': 5, 'double': 3}\n >>> hotel.booked_rooms\n {'single': {'guest 1': 2, 'guest 2':1}, 'double': {'guest1': 1}}\n \"\"\"\n self.name = name\n self.available_rooms = rooms\n self.booked_rooms = {}\n\n def book_room(self, room_type, room_number, name):\n \"\"\"\n Check if there are any rooms of the specified type available.\n if rooms are adequate, modify available_rooms and booked_rooms and finish booking, or fail to book otherwise.\n :param room_type: str\n :param room_number: int, the expected number of specified type rooms to be booked\n :param name: str, guest name\n :return: if number of rooms about to be booked doesn't exceed the remaining rooms, return str 'Success!'\n if exceeds but quantity of available rooms is not equal to zero, return int(the remaining quantity of this room type).\n if exceeds and quantity is zero or the room_type isn't in available_room, return False.\n >>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})\n >>> hotel.book_room('single', 1, 'guest 1')\n 'Success!'\n >>> hotel.book_room('single', 5, 'guest 1')\n 4\n >>> hotel.book_room('single', 4, 'guest 1')\n 'Success!'\n >>> hotel.book_room('single', 1, 'guest 1')\n False\n >>> hotel.book_room('triple', 1, 'guest 1')\n False\n \"\"\"\n \n def check_in(self, room_type, room_number, name):\n \"\"\"\n Check if the room of the specified type and number is booked by the person named name.\n Remove this name when check in successfuly(room_number is equal to specific person's booked_rooms. When the actual check in quantity (room_number) is less than the booked quantity, number in booked_rooms will be booked quantity minus actual quantity\n :param room_type: str, check in room type\n :param room_number: int, check in room number\n :param name: str, person name\n :return False: only if the room_type is not in the booked_rooms or room_number is higher than quantity in booked rooms.\n >>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})\n >>> hotel.book_room('single', 1, 'guest 1')\n 'Success!'\n >>> hotel.check_in('single', 2, 'guest 1')\n False\n >>> hotel.check_in('single', 1, 'guest 1')\n >>> hotel.booked_rooms\n {'single': {}}\n \"\"\"\n\n def check_out(self, room_type, room_number):\n \"\"\"\n Check out rooms, add number for specific type in available_rooms.\n If room_type is new, add new type in available_rooms.\n :param room_type: str, check out room type\n :param room_number: int, check out room number\n >>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})\n >>> hotel.check_out('single', 2)\n >>> hotel.available_rooms\n {'single': 7, 'double': 3}\n >>> hotel.check_out('triple', 2)\n >>> hotel.available_rooms\n {'single': 7, 'double': 3, 'triple': 2}\n \"\"\"\n\n def get_available_rooms(self, room_type):\n \"\"\"\n Get the number of specific type of available rooms.\n :param room_type: str, the room type that want to know\n :return: int, the remaining number of this type rooms.\n >>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})\n >>> hotel.get_available_rooms('single')\n 5\n \"\"\"", "test": "import unittest\n\n\nclass HotelTestBookRoom(unittest.TestCase):\n def setUp(self):\n self.hotel = Hotel('peace hotel', {'single': 3, 'double': 2})\n\n def test_book_room_1(self):\n result = self.hotel.book_room('single', 2, 'guest 1')\n self.assertEqual(result, 'Success!')\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}})\n self.assertEqual(self.hotel.available_rooms, {'single': 1, 'double': 2})\n\n def test_book_room_2(self):\n result = self.hotel.book_room('triple', 2, 'guest 1')\n self.assertFalse(result)\n self.assertEqual(self.hotel.booked_rooms, {})\n self.assertEqual(self.hotel.available_rooms, {'single': 3, 'double': 2})\n\n def test_book_room_3(self):\n self.hotel.book_room('single', 2, 'guest 1')\n result = self.hotel.book_room('single', 2, 'guest 2')\n self.assertEqual(result, 1)\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}})\n self.assertEqual(self.hotel.available_rooms, {'single': 1, 'double': 2})\n\n def test_book_room_4(self):\n self.hotel.book_room('single', 2, 'guest 1')\n result = self.hotel.book_room('single', 1, 'guest 2')\n self.assertEqual(result, 'Success!')\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2, 'guest 2': 1}})\n self.assertEqual(self.hotel.available_rooms, {'double': 2, 'single': 0})\n\n def test_book_room_5(self):\n self.hotel.book_room('single', 2, 'guest 1')\n result = self.hotel.book_room('single', 3, 'guest 2')\n self.assertEqual(result, 1)\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}})\n self.assertEqual(self.hotel.available_rooms, {'single': 1, 'double': 2})\n\n def test_book_room_6(self):\n self.hotel.book_room('single', 3, 'guest 1')\n result = self.hotel.book_room('single', 100, 'guest 1')\n self.assertFalse(result)\n\n\nclass HotelTestCheckIn(unittest.TestCase):\n def setUp(self):\n self.hotel = Hotel('Test Hotel', {'single': 3, 'double': 2})\n self.hotel.booked_rooms = {'single': {'guest 1': 2}, 'double': {'guest 2': 1}}\n\n def test_check_in_1(self):\n self.hotel.check_in('single', 1, 'guest 1')\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 1}, 'double': {'guest 2': 1}})\n\n def test_check_in_2(self):\n self.assertFalse(self.hotel.check_in('single', 3, 'guest 1'))\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}, 'double': {'guest 2': 1}})\n\n def test_check_in_3(self):\n self.assertFalse(self.hotel.check_in('double', 1, 'guest 1'))\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}, 'double': {'guest 2': 1}})\n\n def test_check_in_4(self):\n self.hotel.check_in('double', 1, 'guest 2')\n self.assertEqual(self.hotel.booked_rooms, {'double': {}, 'single': {'guest 1': 2}})\n\n def test_check_in_5(self):\n self.hotel.check_in('double', 2, 'guest 2')\n self.assertEqual(self.hotel.booked_rooms, {'double': {'guest 2': 1}, 'single': {'guest 1': 2}})\n\n def test_check_in_6(self):\n res = self.hotel.check_in('abc', 1, 'guest 1')\n self.assertFalse(res)\n\n\nclass HotelTestCheckOut(unittest.TestCase):\n def setUp(self):\n self.hotel = Hotel('Test Hotel', {'single': 3, 'double': 2})\n self.hotel.booked_rooms = {'single': {'guest 1': 2}, 'double': {'guest 2': 1}}\n\n def test_check_out_1(self):\n self.hotel.check_out('single', 1)\n self.assertEqual(self.hotel.available_rooms, {'single': 4, 'double': 2})\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}, 'double': {'guest 2': 1}})\n\n def test_check_out_2(self):\n self.hotel.check_out('single', 3)\n self.assertEqual(self.hotel.available_rooms, {'single': 6, 'double': 2})\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}, 'double': {'guest 2': 1}})\n\n def test_check_out_3(self):\n self.hotel.check_out('triple', 2)\n self.assertEqual(self.hotel.available_rooms, {'single': 3, 'double': 2, 'triple': 2})\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}, 'double': {'guest 2': 1}})\n\n def test_check_out_4(self):\n self.hotel.check_out('double', 1)\n self.assertEqual(self.hotel.available_rooms, {'single': 3, 'double': 3})\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}, 'double': {'guest 2': 1}})\n\n def test_check_out_5(self):\n self.hotel.check_out('double', 2)\n self.assertEqual(self.hotel.available_rooms, {'single': 3, 'double': 4})\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}, 'double': {'guest 2': 1}})\n\n\nclass HotelTestAvailableRooms(unittest.TestCase):\n def setUp(self):\n self.hotel = Hotel('Test Hotel', {'single': 3, 'double': 2, 'triple': 2})\n\n def test_get_available_rooms(self):\n result = self.hotel.get_available_rooms('single')\n self.assertEqual(result, 3)\n\n def test_get_available_rooms_2(self):\n self.hotel.book_room('single', 2, 'guest 1')\n result = self.hotel.get_available_rooms('single')\n self.assertEqual(result, 1)\n\n def test_get_available_rooms_3(self):\n self.hotel.book_room('single', 3, 'guest 1')\n result = self.hotel.get_available_rooms('single')\n self.assertEqual(result, 0)\n\n def test_get_available_rooms_4(self):\n self.hotel.book_room('single', 3, 'guest 1')\n result = self.hotel.get_available_rooms('double')\n self.assertEqual(result, 2)\n\n def test_get_available_rooms_5(self):\n self.hotel.book_room('single', 3, 'guest 1')\n result = self.hotel.get_available_rooms('triple')\n self.assertEqual(result, 2)\n\n\nclass HotelTestMain(unittest.TestCase):\n def setUp(self) -> None:\n self.hotel = Hotel('Test Hotel', {'single': 3, 'double': 2})\n\n def test_main(self):\n result = self.hotel.book_room('single', 2, 'guest 1')\n self.assertEqual(result, 'Success!')\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}})\n self.assertEqual(self.hotel.available_rooms, {'single': 1, 'double': 2})\n\n self.hotel.check_in('single', 2, 'guest 1')\n self.assertEqual(self.hotel.booked_rooms, {'single': {}})\n self.assertEqual(self.hotel.available_rooms, {'single': 1, 'double': 2})\n\n self.hotel.check_out('single', 2)\n self.assertEqual(self.hotel.available_rooms, {'single': 3, 'double': 2})\n\n self.assertEqual(self.hotel.get_available_rooms('single'), 3)", "solution_code": "class Hotel:\n def __init__(self, name, rooms):\n self.name = name\n self.available_rooms = rooms\n # available_rooms = {room_type1: room_number1, room_type2: room_number2, ...}\n # available_rooms = {'single': 5, 'double': 3}\n self.booked_rooms = {}\n # booked_rooms = {room_type1: {name1: room_number1, name2: room_number2, ...}, room_type2: {...}, ...}\n # booked_rooms = {'single': {'name1': 2, 'name2':1}, 'double': {}}\n\n def book_room(self, room_type, room_number, name):\n # Check if there are any rooms of the specified type available\n if room_type not in self.available_rooms.keys():\n return False\n\n if room_number <= self.available_rooms[room_type]:\n # Book the room by adding it to the booked_rooms dictionary\n if room_type not in self.booked_rooms.keys():\n self.booked_rooms[room_type] = {}\n self.booked_rooms[room_type][name] = room_number\n self.available_rooms[room_type] -= room_number\n return \"Success!\"\n elif self.available_rooms[room_type] != 0:\n return self.available_rooms[room_type]\n else:\n return False\n\n def check_in(self, room_type, room_number, name):\n # Check if the room of the specified type and number is booked\n if room_type not in self.booked_rooms.keys():\n return False\n if name in self.booked_rooms[room_type]:\n if room_number > self.booked_rooms[room_type][name]:\n return False\n elif room_number == self.booked_rooms[room_type][name]:\n # Check in the room by removing it from the booked_rooms dictionary\n self.booked_rooms[room_type].pop(name)\n else:\n self.booked_rooms[room_type][name] -= room_number\n\n\n def check_out(self, room_type, room_number):\n if room_type in self.available_rooms:\n self.available_rooms[room_type] += room_number\n else:\n self.available_rooms[room_type] = room_number\n\n def get_available_rooms(self, room_type):\n return self.available_rooms[room_type]", "import_statement": [], "class_description": " \"\"\"\n This is a class as hotel management system, managing the booking, check-in, check-out, and availability of rooms in a hotel with different room types.\n \"\"\"\n", "class_name": "Hotel", "test_classes": [ "HotelTestBookRoom", "HotelTestCheckIn", "HotelTestCheckOut", "HotelTestAvailableRooms", "HotelTestMain" ], "class_constructor": "class Hotel: \n def __init__(self, name, rooms):\n \"\"\"\n Initialize the three fields in Hotel System.\n name is the hotel name.\n available_rooms stores the remaining rooms in the hotel\n booked_rooms stores the rooms that have been booked and the person's name who booked rooms.\n >>> hotel.name\n 'peace hotel'\n >>> hotel.available_rooms\n available_rooms = {'single': 5, 'double': 3}\n >>> hotel.booked_rooms\n {'single': {'guest 1': 2, 'guest 2':1}, 'double': {'guest1': 1}}\n \"\"\"\n self.name = name\n self.available_rooms = rooms\n self.booked_rooms = {}\n\n", "fields": [ "self.available_rooms", "self.booked_rooms", "self.name" ], "methods_info": [ { "method_name": "book_room", "method_description": "def book_room(self, room_type, room_number, name):\n \"\"\"\n Check if there are any rooms of the specified type available.\n if rooms are adequate, modify available_rooms and booked_rooms and finish booking, or fail to book otherwise.\n :param room_type: str\n :param room_number: int, the expected number of specified type rooms to be booked\n :param name: str, guest name\n :return: if number of rooms about to be booked doesn't exceed the remaining rooms, return str 'Success!'\n if exceeds but quantity of available rooms is not equal to zero, return int(the remaining quantity of this room type).\n if exceeds and quantity is zero or the room_type isn't in available_room, return False.\n >>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})\n >>> hotel.book_room('single', 1, 'guest 1')\n 'Success!'\n >>> hotel.book_room('single', 5, 'guest 1')\n 4\n >>> hotel.book_room('single', 4, 'guest 1')\n 'Success!'\n >>> hotel.book_room('single', 1, 'guest 1')\n False\n >>> hotel.book_room('triple', 1, 'guest 1')\n False\n \"\"\"", "test_class": "HotelTestBookRoom", "test_code": "class HotelTestBookRoom(unittest.TestCase):\n def setUp(self):\n self.hotel = Hotel('peace hotel', {'single': 3, 'double': 2})\n\n def test_book_room_1(self):\n result = self.hotel.book_room('single', 2, 'guest 1')\n self.assertEqual(result, 'Success!')\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}})\n self.assertEqual(self.hotel.available_rooms, {'single': 1, 'double': 2})\n\n def test_book_room_2(self):\n result = self.hotel.book_room('triple', 2, 'guest 1')\n self.assertFalse(result)\n self.assertEqual(self.hotel.booked_rooms, {})\n self.assertEqual(self.hotel.available_rooms, {'single': 3, 'double': 2})\n\n def test_book_room_3(self):\n self.hotel.book_room('single', 2, 'guest 1')\n result = self.hotel.book_room('single', 2, 'guest 2')\n self.assertEqual(result, 1)\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}})\n self.assertEqual(self.hotel.available_rooms, {'single': 1, 'double': 2})\n\n def test_book_room_4(self):\n self.hotel.book_room('single', 2, 'guest 1')\n result = self.hotel.book_room('single', 1, 'guest 2')\n self.assertEqual(result, 'Success!')\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2, 'guest 2': 1}})\n self.assertEqual(self.hotel.available_rooms, {'double': 2, 'single': 0})\n\n def test_book_room_5(self):\n self.hotel.book_room('single', 2, 'guest 1')\n result = self.hotel.book_room('single', 3, 'guest 2')\n self.assertEqual(result, 1)\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}})\n self.assertEqual(self.hotel.available_rooms, {'single': 1, 'double': 2})\n\n def test_book_room_6(self):\n self.hotel.book_room('single', 3, 'guest 1')\n result = self.hotel.book_room('single', 100, 'guest 1')\n self.assertFalse(result)", "solution_code": "def book_room(self, room_type, room_number, name):\n # Check if there are any rooms of the specified type available\n if room_type not in self.available_rooms.keys():\n return False\n\n if room_number <= self.available_rooms[room_type]:\n # Book the room by adding it to the booked_rooms dictionary\n if room_type not in self.booked_rooms.keys():\n self.booked_rooms[room_type] = {}\n self.booked_rooms[room_type][name] = room_number\n self.available_rooms[room_type] -= room_number\n return \"Success!\"\n elif self.available_rooms[room_type] != 0:\n return self.available_rooms[room_type]\n else:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.available_rooms", "self.booked_rooms" ], "method_dependencies": [] } }, { "method_name": "check_in", "method_description": "def check_in(self, room_type, room_number, name):\n \"\"\"\n Check if the room of the specified type and number is booked by the person named name.\n Remove this name when check in successfuly(room_number is equal to specific person's booked_rooms. When the actual check in quantity (room_number) is less than the booked quantity, number in booked_rooms will be booked quantity minus actual quantity\n :param room_type: str, check in room type\n :param room_number: int, check in room number\n :param name: str, person name\n :return False: only if the room_type is not in the booked_rooms or room_number is higher than quantity in booked rooms.\n >>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})\n >>> hotel.book_room('single', 1, 'guest 1')\n 'Success!'\n >>> hotel.check_in('single', 2, 'guest 1')\n False\n >>> hotel.check_in('single', 1, 'guest 1')\n >>> hotel.booked_rooms\n {'single': {}}\n \"\"\"", "test_class": "HotelTestCheckIn", "test_code": "class HotelTestCheckIn(unittest.TestCase):\n def setUp(self):\n self.hotel = Hotel('Test Hotel', {'single': 3, 'double': 2})\n self.hotel.booked_rooms = {'single': {'guest 1': 2}, 'double': {'guest 2': 1}}\n\n def test_check_in_1(self):\n self.hotel.check_in('single', 1, 'guest 1')\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 1}, 'double': {'guest 2': 1}})\n\n def test_check_in_2(self):\n self.assertFalse(self.hotel.check_in('single', 3, 'guest 1'))\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}, 'double': {'guest 2': 1}})\n\n def test_check_in_3(self):\n self.assertFalse(self.hotel.check_in('double', 1, 'guest 1'))\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}, 'double': {'guest 2': 1}})\n\n def test_check_in_4(self):\n self.hotel.check_in('double', 1, 'guest 2')\n self.assertEqual(self.hotel.booked_rooms, {'double': {}, 'single': {'guest 1': 2}})\n\n def test_check_in_5(self):\n self.hotel.check_in('double', 2, 'guest 2')\n self.assertEqual(self.hotel.booked_rooms, {'double': {'guest 2': 1}, 'single': {'guest 1': 2}})\n\n def test_check_in_6(self):\n res = self.hotel.check_in('abc', 1, 'guest 1')\n self.assertFalse(res)", "solution_code": "def check_in(self, room_type, room_number, name):\n # Check if the room of the specified type and number is booked\n if room_type not in self.booked_rooms.keys():\n return False\n if name in self.booked_rooms[room_type]:\n if room_number > self.booked_rooms[room_type][name]:\n return False\n elif room_number == self.booked_rooms[room_type][name]:\n # Check in the room by removing it from the booked_rooms dictionary\n self.booked_rooms[room_type].pop(name)\n else:\n self.booked_rooms[room_type][name] -= room_number", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.booked_rooms" ], "method_dependencies": [] } }, { "method_name": "check_out", "method_description": "def check_out(self, room_type, room_number):\n \"\"\"\n Check out rooms, add number for specific type in available_rooms.\n If room_type is new, add new type in available_rooms.\n :param room_type: str, check out room type\n :param room_number: int, check out room number\n >>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})\n >>> hotel.check_out('single', 2)\n >>> hotel.available_rooms\n {'single': 7, 'double': 3}\n >>> hotel.check_out('triple', 2)\n >>> hotel.available_rooms\n {'single': 7, 'double': 3, 'triple': 2}\n \"\"\"", "test_class": "HotelTestCheckOut", "test_code": "class HotelTestCheckOut(unittest.TestCase):\n def setUp(self):\n self.hotel = Hotel('Test Hotel', {'single': 3, 'double': 2})\n self.hotel.booked_rooms = {'single': {'guest 1': 2}, 'double': {'guest 2': 1}}\n\n def test_check_out_1(self):\n self.hotel.check_out('single', 1)\n self.assertEqual(self.hotel.available_rooms, {'single': 4, 'double': 2})\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}, 'double': {'guest 2': 1}})\n\n def test_check_out_2(self):\n self.hotel.check_out('single', 3)\n self.assertEqual(self.hotel.available_rooms, {'single': 6, 'double': 2})\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}, 'double': {'guest 2': 1}})\n\n def test_check_out_3(self):\n self.hotel.check_out('triple', 2)\n self.assertEqual(self.hotel.available_rooms, {'single': 3, 'double': 2, 'triple': 2})\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}, 'double': {'guest 2': 1}})\n\n def test_check_out_4(self):\n self.hotel.check_out('double', 1)\n self.assertEqual(self.hotel.available_rooms, {'single': 3, 'double': 3})\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}, 'double': {'guest 2': 1}})\n\n def test_check_out_5(self):\n self.hotel.check_out('double', 2)\n self.assertEqual(self.hotel.available_rooms, {'single': 3, 'double': 4})\n self.assertEqual(self.hotel.booked_rooms, {'single': {'guest 1': 2}, 'double': {'guest 2': 1}})", "solution_code": "def check_out(self, room_type, room_number):\n if room_type in self.available_rooms:\n self.available_rooms[room_type] += room_number\n else:\n self.available_rooms[room_type] = room_number", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.available_rooms" ], "method_dependencies": [] } }, { "method_name": "get_available_rooms", "method_description": "def get_available_rooms(self, room_type):\n \"\"\"\n Get the number of specific type of available rooms.\n :param room_type: str, the room type that want to know\n :return: int, the remaining number of this type rooms.\n >>> hotel = Hotel('peace hotel', {'single': 5, 'double': 3})\n >>> hotel.get_available_rooms('single')\n 5\n \"\"\"", "test_class": "HotelTestAvailableRooms", "test_code": "class HotelTestAvailableRooms(unittest.TestCase):\n def setUp(self):\n self.hotel = Hotel('Test Hotel', {'single': 3, 'double': 2, 'triple': 2})\n\n def test_get_available_rooms(self):\n result = self.hotel.get_available_rooms('single')\n self.assertEqual(result, 3)\n\n def test_get_available_rooms_2(self):\n self.hotel.book_room('single', 2, 'guest 1')\n result = self.hotel.get_available_rooms('single')\n self.assertEqual(result, 1)\n\n def test_get_available_rooms_3(self):\n self.hotel.book_room('single', 3, 'guest 1')\n result = self.hotel.get_available_rooms('single')\n self.assertEqual(result, 0)\n\n def test_get_available_rooms_4(self):\n self.hotel.book_room('single', 3, 'guest 1')\n result = self.hotel.get_available_rooms('double')\n self.assertEqual(result, 2)\n\n def test_get_available_rooms_5(self):\n self.hotel.book_room('single', 3, 'guest 1')\n result = self.hotel.get_available_rooms('triple')\n self.assertEqual(result, 2)", "solution_code": "def get_available_rooms(self, room_type):\n return self.available_rooms[room_type]", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.available_rooms" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_43", "skeleton": "\nclass HRManagementSystem:\n \"\"\"\n This is a class as personnel management system that implements functions such as adding, deleting, querying, and updating employees\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialize the HRManagementSystem withan attribute employees, which is an empty dictionary.\n \"\"\"\n self.employees = {}\n\n def add_employee(self, employee_id, name, position, department, salary):\n \"\"\"\n Add a new employee to the HRManagementSystem.\n :param employee_id: The employee's id, int.\n :param name: The employee's name, str.\n :param position: The employee's position, str.\n :param department: The employee's department, str.\n :param salary: The employee's salary, int.\n :return: If the employee is already in the HRManagementSystem, returns False, otherwise, returns True.\n >>> hrManagementSystem = HRManagementSystem()\n >>> hrManagementSystem.add_employee(1, 'John', 'Manager', 'Sales', 100000)\n True\n >>> hrManagementSystem.add_employee(1, 'John', 'Manager', 'Sales', 100000)\n False\n\n \"\"\"\n\n def remove_employee(self, employee_id):\n \"\"\"\n Remove an employee from the HRManagementSystem.\n :param employee_id: The employee's id, int.\n :return: If the employee is already in the HRManagementSystem, returns True, otherwise, returns False.\n >>> hrManagementSystem = HRManagementSystem()\n >>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n >>> hrManagementSystem.remove_employee(1)\n True\n >>> hrManagementSystem.remove_employee(2)\n False\n\n \"\"\"\n\n def update_employee(self, employee_id: int, employee_info: dict):\n \"\"\"\n Update an employee's information in the HRManagementSystem.\n :param employee_id: The employee's id, int.\n :param employee_info: The employee's information, dict.\n :return: If the employee is already in the HRManagementSystem, returns True, otherwise, returns False.\n >>> hrManagementSystem = HRManagementSystem()\n >>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n >>> hrManagementSystem.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000})\n True\n >>> hrManagementSystem.update_employee(2, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000})\n False\n\n \"\"\"\n\n def get_employee(self, employee_id):\n \"\"\"\n Get an employee's information from the HRManagementSystem.\n :param employee_id: The employee's id, int.\n :return: If the employee is already in the HRManagementSystem, returns the employee's information, otherwise, returns False.\n >>> hrManagementSystem = HRManagementSystem()\n >>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n >>> hrManagementSystem.get_employee(1)\n {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}\n >>> hrManagementSystem.get_employee(2)\n False\n\n \"\"\"\n\n def list_employees(self):\n “”“\n List all employees' information in the HRManagementSystem.\n :return: A list of all employees' information,dict.\n >>> hrManagementSystem = HRManagementSystem()\n >>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n >>> hrManagementSystem.list_employees()\n {1: {'employee_ID': 1, 'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n\n \"\"\"", "test": "import unittest\n\nclass HRManagementSystemTestAddEmployee(unittest.TestCase):\n def test_add_employee(self):\n hr_system = HRManagementSystem()\n self.assertEqual(hr_system.add_employee(1, \"John Doe\", \"Manager\", \"HR\", 5000), True)\n self.assertEqual(hr_system.employees[1], {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000})\n\n def test_add_employee_2(self):\n hr_system = HRManagementSystem()\n self.assertEqual(hr_system.add_employee(1, \"John Doe\", \"Manager\", \"HR\", 5000), True)\n self.assertEqual(hr_system.add_employee(1, \"John Doe\", \"Manager\", \"HR\", 5000), False)\n self.assertEqual(hr_system.employees[1], {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000})\n\n def test_add_employee_3(self):\n hr_system = HRManagementSystem()\n self.assertEqual(hr_system.add_employee(1, \"John Doe\", \"Manager\", \"HR\", 5000), True)\n self.assertEqual(hr_system.add_employee(2, \"John Doe\", \"Manager\", \"HR\", 5000), True)\n self.assertEqual(hr_system.employees,{1: {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000}, 2: {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000}})\n\n def test_add_employee_4(self):\n hr_system = HRManagementSystem()\n self.assertEqual(hr_system.add_employee(1, \"John Doe\", \"Manager\", \"HR\", 5000), True)\n self.assertEqual(hr_system.add_employee(2, \"John Doe\", \"Manager\", \"HR\", 5000), True)\n self.assertEqual(hr_system.add_employee(1, \"John Doe\", \"Manager\", \"HR\", 5000), False)\n self.assertEqual(hr_system.employees,{1: {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000}, 2: {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000}})\n\n def test_add_employee_5(self):\n hr_system = HRManagementSystem()\n self.assertEqual(hr_system.add_employee(1, \"John Doe\", \"Manager\", \"HR\", 5000), True)\n self.assertEqual(hr_system.add_employee(2, \"John Doe\", \"Manager\", \"HR\", 5000), True)\n self.assertEqual(hr_system.add_employee(1, \"John Doe\", \"Manager\", \"HR\", 5000), False)\n self.assertEqual(hr_system.add_employee(2, \"John Doe\", \"Manager\", \"HR\", 5000), False)\n self.assertEqual(hr_system.employees,{1: {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000}, 2: {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000}})\n\nclass HRManagementSystemTestRemoveEmployee(unittest.TestCase):\n def test_remove_employee(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.remove_employee(1), True)\n self.assertEqual(hr_system.employees, {})\n\n def test_remove_employee_2(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.remove_employee(1), True)\n self.assertEqual(hr_system.remove_employee(1), False)\n self.assertEqual(hr_system.employees, {})\n\n def test_remove_employee_3(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.remove_employee(1), True)\n self.assertEqual(hr_system.employees, {2: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}})\n\n def test_remove_employee_4(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.remove_employee(1), True)\n self.assertEqual(hr_system.remove_employee(2), True)\n self.assertEqual(hr_system.employees, {})\n\n def test_remove_employee_5(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.remove_employee(1), True)\n self.assertEqual(hr_system.remove_employee(2), True)\n self.assertEqual(hr_system.remove_employee(1), False)\n self.assertEqual(hr_system.remove_employee(2), False)\n self.assertEqual(hr_system.employees, {})\n\nclass HRManagementSystemTestUpdateEmployee(unittest.TestCase):\n def test_update_employee(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000}), True)\n self.assertEqual(hr_system.employees[1], {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000})\n\n def test_update_employee_2(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {}\n self.assertEqual(hr_system.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000}), False)\n self.assertEqual(hr_system.employees, {})\n\n def test_update_employee_3(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.update_employee(2, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000}), False)\n self.assertEqual(hr_system.employees, {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}})\n\n def test_update_employee_4(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000}), True)\n self.assertEqual(hr_system.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000}), True)\n self.assertEqual(hr_system.employees[1], {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000})\n\n def test_update_employee_5(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000}), True)\n self.assertEqual(hr_system.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000}), True)\n self.assertEqual(hr_system.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}), True)\n self.assertEqual(hr_system.employees[1], {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000})\n\n def test_update_employee_6(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.update_employee(1, {'Name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000}), False)\n\n\nclass HRManagementSystemTestGetEmployee(unittest.TestCase):\n def test_get_employee(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.get_employee(1), {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000})\n\n def test_get_employee_2(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {}\n self.assertEqual(hr_system.get_employee(1), False)\n\n def test_get_employee_3(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.get_employee(2), False)\n\n def test_get_employee_4(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.get_employee(1), {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000})\n self.assertEqual(hr_system.get_employee(1), {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000})\n\n def test_get_employee_5(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'name': 'Jane', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.get_employee(1), {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000})\n self.assertEqual(hr_system.get_employee(2), {'name': 'Jane', 'position': 'Manager', 'department': 'Sales', 'salary': 100000})\n\nclass HRManagementSystemTestListEmployees(unittest.TestCase):\n def test_list_employees(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.list_employees(), {1: {'employee_ID':1,'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}})\n\n def test_list_employees_2(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {}\n self.assertEqual(hr_system.list_employees(), {})\n\n def test_list_employees_3(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'name': 'Jane', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.list_employees(), {1: {'employee_ID':1,'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'employee_ID':2,'name': 'Jane', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}})\n\n def test_list_employees_4(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'name': 'Jane', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.list_employees(), {1: {'employee_ID':1,'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'employee_ID':2,'name': 'Jane', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}})\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.list_employees(), {1: {'employee_ID':1,'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}})\n\n def test_list_employees_5(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'name': 'Jane', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.list_employees(), {1: {'employee_ID':1,'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'employee_ID':2,'name': 'Jane', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}})\n hr_system.employees = {}\n self.assertEqual(hr_system.list_employees(), {})\nclass HRManagementSystemTestMain(unittest.TestCase):\n def test_main(self):\n hr_system = HRManagementSystem()\n hr_system.add_employee(1, \"John Doe\", \"Manager\", \"HR\", 5000)\n hr_system.add_employee(2, \"Jane Smith\", \"Developer\", \"IT\", 4000)\n self.assertEqual(hr_system.list_employees(), {1: {'employee_ID': 1, 'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000}, 2: {'employee_ID': 2, 'name': 'Jane Smith', 'position': 'Developer', 'department': 'IT', 'salary': 4000}})\n hr_system.remove_employee(2)\n self.assertEqual(hr_system.list_employees(), {1: {'employee_ID': 1, 'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000}})\n self.assertEqual(hr_system.remove_employee(2), False)\n self.assertEqual(hr_system.update_employee(1, {'name': 'John Doe Jr.', 'salary': 5500}), True)\n self.assertEqual(hr_system.employees[1], {'name': 'John Doe Jr.', 'position': 'Manager', 'department': 'HR', 'salary': 5500})\n self.assertEqual(hr_system.update_employee(3, {'name': 'Invalid Employee'}), False)\n self.assertEqual(hr_system.get_employee(1), {'name': 'John Doe Jr.', 'position': 'Manager', 'department': 'HR', 'salary': 5500})\n self.assertEqual(hr_system.get_employee(2), False)\n self.assertEqual(hr_system.list_employees(), {1: {'employee_ID': 1, 'name': 'John Doe Jr.', 'position': 'Manager', 'department': 'HR', 'salary': 5500}})\n\n def test_main_2(self):\n hr_system = HRManagementSystem()\n self.assertEqual(hr_system.remove_employee(2), False)\n self.assertEqual(hr_system.update_employee(1, {'name': 'John Doe Jr.', 'salary': 5500}), False)\n hr_system.add_employee(1, \"John Doe\", \"Manager\", \"HR\", 5000)\n hr_system.add_employee(2, \"Jane Smith\", \"Developer\", \"IT\", 4000)\n self.assertEqual(hr_system.list_employees(), {\n 1: {'employee_ID': 1, 'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000},\n 2: {'employee_ID': 2, 'name': 'Jane Smith', 'position': 'Developer', 'department': 'IT', 'salary': 4000}})\n self.assertEqual(hr_system.remove_employee(2), True)\n self.assertEqual(hr_system.employees, {1: {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000}})\n self.assertEqual(hr_system.list_employees(), {1: {'employee_ID': 1, 'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000}})\n self.assertEqual(hr_system.update_employee(1, {'name': 'John Doe Jr.', 'salary': 5500}), True)\n self.assertEqual(hr_system.employees[1], {'name': 'John Doe Jr.', 'position': 'Manager', 'department': 'HR', 'salary': 5500})\n self.assertEqual(hr_system.get_employee(1), {'name': 'John Doe Jr.', 'position': 'Manager', 'department': 'HR', 'salary': 5500})\n self.assertEqual(hr_system.get_employee(2), False)", "solution_code": "class HRManagementSystem:\n def __init__(self):\n self.employees = {}\n\n def add_employee(self, employee_id, name, position, department, salary):\n if employee_id in self.employees:\n return False\n else:\n self.employees[employee_id] = {\n 'name': name,\n 'position': position,\n 'department': department,\n 'salary': salary\n }\n return True\n\n def remove_employee(self, employee_id):\n if employee_id in self.employees:\n del self.employees[employee_id]\n return True\n else:\n return False\n\n def update_employee(self, employee_id: int, employee_info: dict):\n employee = self.get_employee(employee_id)\n if employee == False:\n return False\n else:\n for key, value in employee_info.items():\n if key not in employee:\n return False\n for key, value in employee_info.items():\n employee[key] = value\n return True\n\n def get_employee(self, employee_id):\n if employee_id in self.employees:\n return self.employees[employee_id]\n else:\n return False\n\n def list_employees(self):\n employee_data = {}\n if self.employees:\n for employee_id, employee_info in self.employees.items():\n employee_details = {}\n employee_details[\"employee_ID\"] = employee_id\n for key, value in employee_info.items():\n employee_details[key] = value\n employee_data[employee_id] = employee_details\n return employee_data", "import_statement": [], "class_description": " \"\"\"\n This is a class as personnel management system that implements functions such as adding, deleting, querying, and updating employees\n \"\"\"\n", "class_name": "HRManagementSystem", "test_classes": [ "HRManagementSystemTestAddEmployee", "HRManagementSystemTestRemoveEmployee", "HRManagementSystemTestUpdateEmployee", "HRManagementSystemTestGetEmployee", "HRManagementSystemTestListEmployees", "HRManagementSystemTestMain" ], "class_constructor": "class HRManagementSystem: \n def __init__(self):\n \"\"\"\n Initialize the HRManagementSystem withan attribute employees, which is an empty dictionary.\n \"\"\"\n self.employees = {}\n\n", "fields": [ "self.employees" ], "methods_info": [ { "method_name": "add_employee", "method_description": "def add_employee(self, employee_id, name, position, department, salary):\n \"\"\"\n Add a new employee to the HRManagementSystem.\n :param employee_id: The employee's id, int.\n :param name: The employee's name, str.\n :param position: The employee's position, str.\n :param department: The employee's department, str.\n :param salary: The employee's salary, int.\n :return: If the employee is already in the HRManagementSystem, returns False, otherwise, returns True.\n >>> hrManagementSystem = HRManagementSystem()\n >>> hrManagementSystem.add_employee(1, 'John', 'Manager', 'Sales', 100000)\n True\n >>> hrManagementSystem.add_employee(1, 'John', 'Manager', 'Sales', 100000)\n False\n\n \"\"\"", "test_class": "HRManagementSystemTestAddEmployee", "test_code": "class HRManagementSystemTestAddEmployee(unittest.TestCase):\n def test_add_employee(self):\n hr_system = HRManagementSystem()\n self.assertEqual(hr_system.add_employee(1, \"John Doe\", \"Manager\", \"HR\", 5000), True)\n self.assertEqual(hr_system.employees[1], {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000})\n\n def test_add_employee_2(self):\n hr_system = HRManagementSystem()\n self.assertEqual(hr_system.add_employee(1, \"John Doe\", \"Manager\", \"HR\", 5000), True)\n self.assertEqual(hr_system.add_employee(1, \"John Doe\", \"Manager\", \"HR\", 5000), False)\n self.assertEqual(hr_system.employees[1], {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000})\n\n def test_add_employee_3(self):\n hr_system = HRManagementSystem()\n self.assertEqual(hr_system.add_employee(1, \"John Doe\", \"Manager\", \"HR\", 5000), True)\n self.assertEqual(hr_system.add_employee(2, \"John Doe\", \"Manager\", \"HR\", 5000), True)\n self.assertEqual(hr_system.employees,{1: {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000}, 2: {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000}})\n\n def test_add_employee_4(self):\n hr_system = HRManagementSystem()\n self.assertEqual(hr_system.add_employee(1, \"John Doe\", \"Manager\", \"HR\", 5000), True)\n self.assertEqual(hr_system.add_employee(2, \"John Doe\", \"Manager\", \"HR\", 5000), True)\n self.assertEqual(hr_system.add_employee(1, \"John Doe\", \"Manager\", \"HR\", 5000), False)\n self.assertEqual(hr_system.employees,{1: {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000}, 2: {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000}})\n\n def test_add_employee_5(self):\n hr_system = HRManagementSystem()\n self.assertEqual(hr_system.add_employee(1, \"John Doe\", \"Manager\", \"HR\", 5000), True)\n self.assertEqual(hr_system.add_employee(2, \"John Doe\", \"Manager\", \"HR\", 5000), True)\n self.assertEqual(hr_system.add_employee(1, \"John Doe\", \"Manager\", \"HR\", 5000), False)\n self.assertEqual(hr_system.add_employee(2, \"John Doe\", \"Manager\", \"HR\", 5000), False)\n self.assertEqual(hr_system.employees,{1: {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000}, 2: {'name': 'John Doe', 'position': 'Manager', 'department': 'HR', 'salary': 5000}})", "solution_code": "def add_employee(self, employee_id, name, position, department, salary):\n if employee_id in self.employees:\n return False\n else:\n self.employees[employee_id] = {\n 'name': name,\n 'position': position,\n 'department': department,\n 'salary': salary\n }\n return True", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.employees" ], "method_dependencies": [] } }, { "method_name": "remove_employee", "method_description": "def remove_employee(self, employee_id):\n \"\"\"\n Remove an employee from the HRManagementSystem.\n :param employee_id: The employee's id, int.\n :return: If the employee is already in the HRManagementSystem, returns True, otherwise, returns False.\n >>> hrManagementSystem = HRManagementSystem()\n >>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n >>> hrManagementSystem.remove_employee(1)\n True\n >>> hrManagementSystem.remove_employee(2)\n False\n\n \"\"\"", "test_class": "HRManagementSystemTestRemoveEmployee", "test_code": "class HRManagementSystemTestRemoveEmployee(unittest.TestCase):\n def test_remove_employee(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.remove_employee(1), True)\n self.assertEqual(hr_system.employees, {})\n\n def test_remove_employee_2(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.remove_employee(1), True)\n self.assertEqual(hr_system.remove_employee(1), False)\n self.assertEqual(hr_system.employees, {})\n\n def test_remove_employee_3(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.remove_employee(1), True)\n self.assertEqual(hr_system.employees, {2: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}})\n\n def test_remove_employee_4(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.remove_employee(1), True)\n self.assertEqual(hr_system.remove_employee(2), True)\n self.assertEqual(hr_system.employees, {})\n\n def test_remove_employee_5(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.remove_employee(1), True)\n self.assertEqual(hr_system.remove_employee(2), True)\n self.assertEqual(hr_system.remove_employee(1), False)\n self.assertEqual(hr_system.remove_employee(2), False)\n self.assertEqual(hr_system.employees, {})", "solution_code": "def remove_employee(self, employee_id):\n if employee_id in self.employees:\n del self.employees[employee_id]\n return True\n else:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.employees" ], "method_dependencies": [] } }, { "method_name": "update_employee", "method_description": "def update_employee(self, employee_id: int, employee_info: dict):\n \"\"\"\n Update an employee's information in the HRManagementSystem.\n :param employee_id: The employee's id, int.\n :param employee_info: The employee's information, dict.\n :return: If the employee is already in the HRManagementSystem, returns True, otherwise, returns False.\n >>> hrManagementSystem = HRManagementSystem()\n >>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n >>> hrManagementSystem.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000})\n True\n >>> hrManagementSystem.update_employee(2, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000})\n False\n\n \"\"\"", "test_class": "HRManagementSystemTestUpdateEmployee", "test_code": "class HRManagementSystemTestUpdateEmployee(unittest.TestCase):\n def test_update_employee(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000}), True)\n self.assertEqual(hr_system.employees[1], {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000})\n\n def test_update_employee_2(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {}\n self.assertEqual(hr_system.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000}), False)\n self.assertEqual(hr_system.employees, {})\n\n def test_update_employee_3(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.update_employee(2, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000}), False)\n self.assertEqual(hr_system.employees, {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}})\n\n def test_update_employee_4(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000}), True)\n self.assertEqual(hr_system.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000}), True)\n self.assertEqual(hr_system.employees[1], {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000})\n\n def test_update_employee_5(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000}), True)\n self.assertEqual(hr_system.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000}), True)\n self.assertEqual(hr_system.update_employee(1, {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}), True)\n self.assertEqual(hr_system.employees[1], {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000})\n\n def test_update_employee_6(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.update_employee(1, {'Name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 20000}), False)", "solution_code": "def update_employee(self, employee_id: int, employee_info: dict):\n employee = self.get_employee(employee_id)\n if employee == False:\n return False\n else:\n for key, value in employee_info.items():\n if key not in employee:\n return False\n for key, value in employee_info.items():\n employee[key] = value\n return True", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "get_employee" ] } }, { "method_name": "get_employee", "method_description": "def get_employee(self, employee_id):\n \"\"\"\n Get an employee's information from the HRManagementSystem.\n :param employee_id: The employee's id, int.\n :return: If the employee is already in the HRManagementSystem, returns the employee's information, otherwise, returns False.\n >>> hrManagementSystem = HRManagementSystem()\n >>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n >>> hrManagementSystem.get_employee(1)\n {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}\n >>> hrManagementSystem.get_employee(2)\n False\n\n \"\"\"", "test_class": "HRManagementSystemTestGetEmployee", "test_code": "class HRManagementSystemTestGetEmployee(unittest.TestCase):\n def test_get_employee(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.get_employee(1), {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000})\n\n def test_get_employee_2(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {}\n self.assertEqual(hr_system.get_employee(1), False)\n\n def test_get_employee_3(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.get_employee(2), False)\n\n def test_get_employee_4(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.get_employee(1), {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000})\n self.assertEqual(hr_system.get_employee(1), {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000})\n\n def test_get_employee_5(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'name': 'Jane', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.get_employee(1), {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000})\n self.assertEqual(hr_system.get_employee(2), {'name': 'Jane', 'position': 'Manager', 'department': 'Sales', 'salary': 100000})", "solution_code": "def get_employee(self, employee_id):\n if employee_id in self.employees:\n return self.employees[employee_id]\n else:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.employees" ], "method_dependencies": [] } }, { "method_name": "list_employees", "method_description": "def list_employees(self):\n “”“\n List all employees' information in the HRManagementSystem.\n :return: A list of all employees' information,dict.\n >>> hrManagementSystem = HRManagementSystem()\n >>> hrManagementSystem.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n >>> hrManagementSystem.list_employees()\n {1: {'employee_ID': 1, 'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n\n \"\"\"", "test_class": "HRManagementSystemTestListEmployees", "test_code": "class HRManagementSystemTestListEmployees(unittest.TestCase):\n def test_list_employees(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.list_employees(), {1: {'employee_ID':1,'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}})\n\n def test_list_employees_2(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {}\n self.assertEqual(hr_system.list_employees(), {})\n\n def test_list_employees_3(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'name': 'Jane', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.list_employees(), {1: {'employee_ID':1,'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'employee_ID':2,'name': 'Jane', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}})\n\n def test_list_employees_4(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'name': 'Jane', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.list_employees(), {1: {'employee_ID':1,'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'employee_ID':2,'name': 'Jane', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}})\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.list_employees(), {1: {'employee_ID':1,'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}})\n\n def test_list_employees_5(self):\n hr_system = HRManagementSystem()\n hr_system.employees = {1: {'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'name': 'Jane', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}}\n self.assertEqual(hr_system.list_employees(), {1: {'employee_ID':1,'name': 'John', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}, 2: {'employee_ID':2,'name': 'Jane', 'position': 'Manager', 'department': 'Sales', 'salary': 100000}})\n hr_system.employees = {}\n self.assertEqual(hr_system.list_employees(), {})", "solution_code": "def list_employees(self):\n employee_data = {}\n if self.employees:\n for employee_id, employee_info in self.employees.items():\n employee_details = {}\n employee_details[\"employee_ID\"] = employee_id\n for key, value in employee_info.items():\n employee_details[key] = value\n employee_data[employee_id] = employee_details\n return employee_data", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.employees" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_44", "skeleton": "\nimport re\nimport string\nimport gensim\nfrom bs4 import BeautifulSoup\n\nclass HtmlUtil:\n \"\"\"\n This is a class as util for html, supporting for formatting and extracting code from HTML text, including cleaning up the text and converting certain elements into specific marks.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialize a series of labels\n \"\"\"\n self.SPACE_MARK = '-SPACE-'\n self.JSON_MARK = '-JSON-'\n self.MARKUP_LANGUAGE_MARK = '-MARKUP_LANGUAGE-'\n self.URL_MARK = '-URL-'\n self.NUMBER_MARK = '-NUMBER-'\n self.TRACE_MARK = '-TRACE-'\n self.COMMAND_MARK = '-COMMAND-'\n self.COMMENT_MARK = '-COMMENT-'\n self.CODE_MARK = '-CODE-'\n\n @staticmethod\n def __format_line_feed(text):\n \"\"\"\n Replace consecutive line breaks with a single line break\n :param text: string with consecutive line breaks\n :return:string, replaced text with single line break\n \"\"\"\n\n def format_line_html_text(self, html_text):\n \"\"\"\n get the html text without the code, and add the code tag -CODE- where the code is\n :param html_text:string\n :return:string\n >>>htmlutil = HtmlUtil()\n >>>htmlutil.format_line_html_text(\n >>> \n >>>

Title

\n >>>

This is a paragraph.

\n >>>
print('Hello, world!')
\n >>>

Another paragraph.

\n >>>
for i in range(5):\n        >>>    print(i)
\n >>> \n >>> )\n Title\n This is a paragraph.\n -CODE-\n Another paragraph.\n -CODE-\n \"\"\"\n\n def extract_code_from_html_text(self, html_text):\n \"\"\"\n extract codes from the html body\n :param html_text: string, html text\n :return: the list of code\n >>>htmlutil = HtmlUtil()\n >>>htmlutil.extract_code_from_html_text(\n >>> \n >>>

Title

\n >>>

This is a paragraph.

\n >>>
print('Hello, world!')
\n >>>

Another paragraph.

\n >>>
for i in range(5):\n        >>>    print(i)
\n >>> \n >>> )\n [\"print('Hello, world!')\", 'for i in range(5):\\n print(i)']\n \"\"\"", "test": "import unittest\nimport sys\nsys.path.append(r'C:\\Users\\86181\\Desktop\\forgit\\SE-Eval-Benchmark')\nfrom benchmark_code.HtmlUtil import HtmlUtil\n\nclass HtmlUtilTestFormatLineFeed(unittest.TestCase):\n def test_format_line_feed_1(self):\n self.assertEqual(HtmlUtil._HtmlUtil__format_line_feed('aaa\\n\\n\\n'), 'aaa\\n')\n\n def test_format_line_feed_2(self):\n self.assertEqual(HtmlUtil._HtmlUtil__format_line_feed('aaa\\n\\n\\n\\n'), 'aaa\\n')\n\n def test_format_line_feed_3(self):\n self.assertEqual(HtmlUtil._HtmlUtil__format_line_feed('aaa\\n\\n\\nbbb\\n\\n'), 'aaa\\nbbb\\n')\n\n def test_format_line_feed_4(self):\n self.assertEqual(HtmlUtil._HtmlUtil__format_line_feed('ccc\\n\\n\\n'), 'ccc\\n')\n\n def test_format_line_feed_5(self):\n self.assertEqual(HtmlUtil._HtmlUtil__format_line_feed(''), '')\n\n\nclass HtmlUtilTestFormatLineHtmlText(unittest.TestCase):\n def test_format_line_html_text_1(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''\n \n \n

Title

\n

This is a paragraph.

\n
print('Hello, world!')
\n

Another paragraph.

\n
for i in range(5):\n        print(i)
\n \n \n ''')\n self.assertEqual(res, '''\nTitle\nThis is a paragraph.\n-CODE-\nAnother paragraph.\n-CODE-\n''')\n\n def test_format_line_html_text_2(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''\n \n \n

Title2

\n

This is a paragraph.

\n
print('Hello, world!')
\n

Another paragraph.

\n
for i in range(5):\n        print(i)
\n \n \n ''')\n self.assertEqual(res, '''\nTitle2\nThis is a paragraph.\n-CODE-\nAnother paragraph.\n-CODE-\n''')\n\n def test_format_line_html_text_3(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''\n \n \n

Title3

\n

This is a paragraph.

\n
print('Hello, world!')
\n

Another paragraph.

\n
for i in range(5):\n        print(i)
\n \n \n ''')\n self.assertEqual(res, '''\nTitle3\nThis is a paragraph.\n-CODE-\nAnother paragraph.\n-CODE-\n''')\n\n def test_format_line_html_text_4(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''\n \n \n

Title4

\n

This is a paragraph.

\n
print('Hello, world!')
\n

Another paragraph.

\n
for i in range(5):\n        print(i)
\n \n \n ''')\n self.assertEqual(res, '''\nTitle4\nThis is a paragraph.\n-CODE-\nAnother paragraph.\n-CODE-\n''')\n\n def test_format_line_html_text_5(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''\n \n \n

Title5

\n

This is a paragraph.

\n
print('Hello, world!')
\n

Another paragraph.

\n
for i in range(5):\n        print(i)
\n \n \n ''')\n self.assertEqual(res, '''\nTitle5\nThis is a paragraph.\n-CODE-\nAnother paragraph.\n-CODE-\n''')\n def test_format_line_html_text_6(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('')\n self.assertEqual(res, '')\n\n def test_format_line_html_text_7(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''''')\n self.assertEqual(res, '''[-]Item 1!''')\n\n def test_format_line_html_text_8(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''''')\n self.assertEqual(res, '')\n\n def test_format_line_html_text_9(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''

Some sentence here.

''')\n self.assertEqual(res, 'Some sentence here.')\n\n def test_format_line_html_text_10(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''

Some paragraph here

Code block''')\n self.assertEqual(res, '''Some paragraph here.Code block''')\n\n def test_format_line_html_text_11(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''

Some paragraph here

Some text here
''')\n self.assertEqual(res, '''Some paragraph here.Some text here''')\n\n def test_format_line_html_text_12(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''''')\n self.assertEqual(res, '''[-]Item 1.''')\n\n\nclass HtmlUtilTestExtractCodeFromHtmlText(unittest.TestCase):\n def test_extract_code_from_html_text_1(self):\n htmlutil = HtmlUtil()\n res = htmlutil.extract_code_from_html_text('''\n \n \n

Title

\n

This is a paragraph.

\n
print('Hello, world!')
\n

Another paragraph.

\n
for i in range(5):\n                print(i)
\n \n \n ''')\n self.assertEqual(res, [\"print('Hello, world!')\", 'for i in range(5):\\n print(i)'])\n\n def test_extract_code_from_html_text_2(self):\n htmlutil = HtmlUtil()\n res = htmlutil.extract_code_from_html_text('''\n \n \n

Title

\n

This is a paragraph.

\n
print('Hello, world!')
\n

Another paragraph.

\n
for i in range(4):\n                print(i)
\n \n \n ''')\n self.assertEqual(res, [\"print('Hello, world!')\", 'for i in range(4):\\n print(i)'])\n\n def test_extract_code_from_html_text_3(self):\n htmlutil = HtmlUtil()\n res = htmlutil.extract_code_from_html_text('''\n \n \n

Title

\n

This is a paragraph.

\n
print('Hello, world!')
\n

Another paragraph.

\n
for i in range(3):\n                print(i)
\n \n \n ''')\n self.assertEqual(res, [\"print('Hello, world!')\", 'for i in range(3):\\n print(i)'])\n\n def test_extract_code_from_html_text_4(self):\n htmlutil = HtmlUtil()\n res = htmlutil.extract_code_from_html_text('''\n \n \n

Title

\n

This is a paragraph.

\n
print('Hello, world!')
\n

Another paragraph.

\n
for i in range(2):\n                print(i)
\n \n \n ''')\n self.assertEqual(res, [\"print('Hello, world!')\", 'for i in range(2):\\n print(i)'])\n\n def test_extract_code_from_html_text_5(self):\n htmlutil = HtmlUtil()\n htmlutil.CODE_MARK = 'abcdefg'\n res = htmlutil.extract_code_from_html_text(\"\")\n self.assertEqual(res, [])\n\n\nclass HtmlUtilTest(unittest.TestCase):\n def test_htmlutil(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''\n \n \n

Title

\n

This is a paragraph.

\n
print('Hello, world!')
\n

Another paragraph.

\n
for i in range(5):\n        print(i)
\n \n \n ''')\n self.assertEqual(res, '''\nTitle\nThis is a paragraph.\n-CODE-\nAnother paragraph.\n-CODE-\n''')\n res = htmlutil.extract_code_from_html_text('''\n \n \n

Title

\n

This is a paragraph.

\n
print('Hello, world!')
\n

Another paragraph.

\n
for i in range(5):\n                print(i)
\n \n \n ''')\n self.assertEqual(res, [\"print('Hello, world!')\", 'for i in range(5):\\n print(i)'])\n\nif __name__ == '__main__':\n unittest.main()", "solution_code": "import re\nimport string\nimport gensim\nfrom bs4 import BeautifulSoup\n\n\nclass HtmlUtil:\n\n def __init__(self):\n self.SPACE_MARK = '-SPACE-'\n self.JSON_MARK = '-JSON-'\n self.MARKUP_LANGUAGE_MARK = '-MARKUP_LANGUAGE-'\n self.URL_MARK = '-URL-'\n self.NUMBER_MARK = '-NUMBER-'\n self.TRACE_MARK = '-TRACE-'\n self.COMMAND_MARK = '-COMMAND-'\n self.COMMENT_MARK = '-COMMENT-'\n self.CODE_MARK = '-CODE-'\n\n @staticmethod\n def __format_line_feed(text):\n return re.sub(re.compile(r'\\n+'), '\\n', text)\n\n def format_line_html_text(self, html_text):\n if html_text is None or len(html_text) == 0:\n return ''\n soup = BeautifulSoup(html_text, 'lxml')\n\n code_tag = soup.find_all(name=['pre', 'blockquote'])\n for tag in code_tag:\n tag.string = self.CODE_MARK\n\n ul_ol_group = soup.find_all(name=['ul', 'ol'])\n for ul_ol_item in ul_ol_group:\n li_group = ul_ol_item.find_all('li')\n for li_item in li_group:\n li_item_text = li_item.get_text().strip()\n if len(li_item_text) == 0:\n continue\n if li_item_text[-1] in string.punctuation:\n li_item.string = '[{0}]{1}'.format('-', li_item_text)\n continue\n li_item.string = '[{0}]{1}.'.format('-', li_item_text)\n\n p_group = soup.find_all(name=['p'])\n for p_item in p_group:\n p_item_text = p_item.get_text().strip()\n if p_item_text:\n if p_item_text[-1] in string.punctuation:\n p_item.string = p_item_text\n continue\n next_sibling = p_item.find_next_sibling()\n if next_sibling and self.CODE_MARK in next_sibling.get_text():\n p_item.string = p_item_text + ':'\n continue\n p_item.string = p_item_text + '.'\n\n clean_text = gensim.utils.decode_htmlentities(soup.get_text())\n return self.__format_line_feed(clean_text)\n\n def extract_code_from_html_text(self, html_text):\n text_with_code_tag = self.format_line_html_text(html_text)\n\n if self.CODE_MARK not in text_with_code_tag:\n return []\n\n code_index_start = 0\n soup = BeautifulSoup(html_text, 'lxml')\n code_tag = soup.find_all(name=['pre', 'blockquote'])\n code_count = text_with_code_tag.count(self.CODE_MARK)\n code_list = []\n for code_index in range(code_index_start, code_index_start + code_count):\n code = code_tag[code_index].get_text()\n if code:\n code_list.append(code)\n return code_list", "import_statement": [ "import re", "import string", "import gensim", "from bs4 import BeautifulSoup" ], "class_description": " \"\"\"\n This is a class as util for html, supporting for formatting and extracting code from HTML text, including cleaning up the text and converting certain elements into specific marks.\n \"\"\"\n", "class_name": "HtmlUtil", "test_classes": [ "HtmlUtilTestFormatLineFeed", "HtmlUtilTestFormatLineHtmlText", "HtmlUtilTestExtractCodeFromHtmlText", "HtmlUtilTest" ], "class_constructor": "class HtmlUtil: \n def __init__(self):\n \"\"\"\n Initialize a series of labels\n \"\"\"\n self.SPACE_MARK = '-SPACE-'\n self.JSON_MARK = '-JSON-'\n self.MARKUP_LANGUAGE_MARK = '-MARKUP_LANGUAGE-'\n self.URL_MARK = '-URL-'\n self.NUMBER_MARK = '-NUMBER-'\n self.TRACE_MARK = '-TRACE-'\n self.COMMAND_MARK = '-COMMAND-'\n self.COMMENT_MARK = '-COMMENT-'\n self.CODE_MARK = '-CODE-'\n\n @staticmethod\n", "fields": [ "self.CODE_MARK", "self.COMMAND_MARK", "self.COMMENT_MARK", "self.JSON_MARK", "self.MARKUP_LANGUAGE_MARK", "self.NUMBER_MARK", "self.SPACE_MARK", "self.TRACE_MARK", "self.URL_MARK" ], "methods_info": [ { "method_name": "__format_line_feed", "method_description": "def __format_line_feed(text):\n \"\"\"\n Replace consecutive line breaks with a single line break\n :param text: string with consecutive line breaks\n :return:string, replaced text with single line break\n \"\"\"", "test_class": "HtmlUtilTestFormatLineFeed", "test_code": "class HtmlUtilTestFormatLineFeed(unittest.TestCase):\n def test_format_line_feed_1(self):\n self.assertEqual(HtmlUtil._HtmlUtil__format_line_feed('aaa\\n\\n\\n'), 'aaa\\n')\n\n def test_format_line_feed_2(self):\n self.assertEqual(HtmlUtil._HtmlUtil__format_line_feed('aaa\\n\\n\\n\\n'), 'aaa\\n')\n\n def test_format_line_feed_3(self):\n self.assertEqual(HtmlUtil._HtmlUtil__format_line_feed('aaa\\n\\n\\nbbb\\n\\n'), 'aaa\\nbbb\\n')\n\n def test_format_line_feed_4(self):\n self.assertEqual(HtmlUtil._HtmlUtil__format_line_feed('ccc\\n\\n\\n'), 'ccc\\n')\n\n def test_format_line_feed_5(self):\n self.assertEqual(HtmlUtil._HtmlUtil__format_line_feed(''), '')", "solution_code": "def __format_line_feed(text):\n return re.sub(re.compile(r'\\n+'), '\\n', text)", "dependencies": { "Standalone": false, "lib_dependencies": [ "re" ], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "format_line_html_text", "method_description": "def format_line_html_text(self, html_text):\n \"\"\"\n get the html text without the code, and add the code tag -CODE- where the code is\n :param html_text:string\n :return:string\n >>>htmlutil = HtmlUtil()\n >>>htmlutil.format_line_html_text(\n >>> \n >>>

Title

\n >>>

This is a paragraph.

\n >>>
print('Hello, world!')
\n >>>

Another paragraph.

\n >>>
for i in range(5):\n        >>>    print(i)
\n >>> \n >>> )\n Title\n This is a paragraph.\n -CODE-\n Another paragraph.\n -CODE-\n \"\"\"", "test_class": "HtmlUtilTestFormatLineHtmlText", "test_code": "class HtmlUtilTestFormatLineHtmlText(unittest.TestCase):\n def test_format_line_html_text_1(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''\n \n \n

Title

\n

This is a paragraph.

\n
print('Hello, world!')
\n

Another paragraph.

\n
for i in range(5):\n        print(i)
\n \n \n ''')\n self.assertEqual(res, '''\nTitle\nThis is a paragraph.\n-CODE-\nAnother paragraph.\n-CODE-\n''')\n\n def test_format_line_html_text_2(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''\n \n \n

Title2

\n

This is a paragraph.

\n
print('Hello, world!')
\n

Another paragraph.

\n
for i in range(5):\n        print(i)
\n \n \n ''')\n self.assertEqual(res, '''\nTitle2\nThis is a paragraph.\n-CODE-\nAnother paragraph.\n-CODE-\n''')\n\n def test_format_line_html_text_3(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''\n \n \n

Title3

\n

This is a paragraph.

\n
print('Hello, world!')
\n

Another paragraph.

\n
for i in range(5):\n        print(i)
\n \n \n ''')\n self.assertEqual(res, '''\nTitle3\nThis is a paragraph.\n-CODE-\nAnother paragraph.\n-CODE-\n''')\n\n def test_format_line_html_text_4(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''\n \n \n

Title4

\n

This is a paragraph.

\n
print('Hello, world!')
\n

Another paragraph.

\n
for i in range(5):\n        print(i)
\n \n \n ''')\n self.assertEqual(res, '''\nTitle4\nThis is a paragraph.\n-CODE-\nAnother paragraph.\n-CODE-\n''')\n\n def test_format_line_html_text_5(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''\n \n \n

Title5

\n

This is a paragraph.

\n
print('Hello, world!')
\n

Another paragraph.

\n
for i in range(5):\n        print(i)
\n \n \n ''')\n self.assertEqual(res, '''\nTitle5\nThis is a paragraph.\n-CODE-\nAnother paragraph.\n-CODE-\n''')\n def test_format_line_html_text_6(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('')\n self.assertEqual(res, '')\n\n def test_format_line_html_text_7(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''''')\n self.assertEqual(res, '''[-]Item 1!''')\n\n def test_format_line_html_text_8(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''''')\n self.assertEqual(res, '')\n\n def test_format_line_html_text_9(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''

Some sentence here.

''')\n self.assertEqual(res, 'Some sentence here.')\n\n def test_format_line_html_text_10(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''

Some paragraph here

Code block''')\n self.assertEqual(res, '''Some paragraph here.Code block''')\n\n def test_format_line_html_text_11(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''

Some paragraph here

Some text here
''')\n self.assertEqual(res, '''Some paragraph here.Some text here''')\n\n def test_format_line_html_text_12(self):\n htmlutil = HtmlUtil()\n res = htmlutil.format_line_html_text('''''')\n self.assertEqual(res, '''[-]Item 1.''')", "solution_code": "def format_line_html_text(self, html_text):\n if html_text is None or len(html_text) == 0:\n return ''\n soup = BeautifulSoup(html_text, 'lxml')\n\n code_tag = soup.find_all(name=['pre', 'blockquote'])\n for tag in code_tag:\n tag.string = self.CODE_MARK\n\n ul_ol_group = soup.find_all(name=['ul', 'ol'])\n for ul_ol_item in ul_ol_group:\n li_group = ul_ol_item.find_all('li')\n for li_item in li_group:\n li_item_text = li_item.get_text().strip()\n if len(li_item_text) == 0:\n continue\n if li_item_text[-1] in string.punctuation:\n li_item.string = '[{0}]{1}'.format('-', li_item_text)\n continue\n li_item.string = '[{0}]{1}.'.format('-', li_item_text)\n\n p_group = soup.find_all(name=['p'])\n for p_item in p_group:\n p_item_text = p_item.get_text().strip()\n if p_item_text:\n if p_item_text[-1] in string.punctuation:\n p_item.string = p_item_text\n continue\n next_sibling = p_item.find_next_sibling()\n if next_sibling and self.CODE_MARK in next_sibling.get_text():\n p_item.string = p_item_text + ':'\n continue\n p_item.string = p_item_text + '.'\n\n clean_text = gensim.utils.decode_htmlentities(soup.get_text())\n return self.__format_line_feed(clean_text)", "dependencies": { "Standalone": false, "lib_dependencies": [ "string", "gensim", "BeautifulSoup" ], "field_dependencies": [ "self.CODE_MARK" ], "method_dependencies": [ "__format_line_feed" ] } }, { "method_name": "extract_code_from_html_text", "method_description": "def extract_code_from_html_text(self, html_text):\n \"\"\"\n extract codes from the html body\n :param html_text: string, html text\n :return: the list of code\n >>>htmlutil = HtmlUtil()\n >>>htmlutil.extract_code_from_html_text(\n >>> \n >>>

Title

\n >>>

This is a paragraph.

\n >>>
print('Hello, world!')
\n >>>

Another paragraph.

\n >>>
for i in range(5):\n        >>>    print(i)
\n >>> \n >>> )\n [\"print('Hello, world!')\", 'for i in range(5):\\n print(i)']\n \"\"\"", "test_class": "HtmlUtilTestExtractCodeFromHtmlText", "test_code": "class HtmlUtilTestExtractCodeFromHtmlText(unittest.TestCase):\n def test_extract_code_from_html_text_1(self):\n htmlutil = HtmlUtil()\n res = htmlutil.extract_code_from_html_text('''\n \n \n

Title

\n

This is a paragraph.

\n
print('Hello, world!')
\n

Another paragraph.

\n
for i in range(5):\n                print(i)
\n \n \n ''')\n self.assertEqual(res, [\"print('Hello, world!')\", 'for i in range(5):\\n print(i)'])\n\n def test_extract_code_from_html_text_2(self):\n htmlutil = HtmlUtil()\n res = htmlutil.extract_code_from_html_text('''\n \n \n

Title

\n

This is a paragraph.

\n
print('Hello, world!')
\n

Another paragraph.

\n
for i in range(4):\n                print(i)
\n \n \n ''')\n self.assertEqual(res, [\"print('Hello, world!')\", 'for i in range(4):\\n print(i)'])\n\n def test_extract_code_from_html_text_3(self):\n htmlutil = HtmlUtil()\n res = htmlutil.extract_code_from_html_text('''\n \n \n

Title

\n

This is a paragraph.

\n
print('Hello, world!')
\n

Another paragraph.

\n
for i in range(3):\n                print(i)
\n \n \n ''')\n self.assertEqual(res, [\"print('Hello, world!')\", 'for i in range(3):\\n print(i)'])\n\n def test_extract_code_from_html_text_4(self):\n htmlutil = HtmlUtil()\n res = htmlutil.extract_code_from_html_text('''\n \n \n

Title

\n

This is a paragraph.

\n
print('Hello, world!')
\n

Another paragraph.

\n
for i in range(2):\n                print(i)
\n \n \n ''')\n self.assertEqual(res, [\"print('Hello, world!')\", 'for i in range(2):\\n print(i)'])\n\n def test_extract_code_from_html_text_5(self):\n htmlutil = HtmlUtil()\n htmlutil.CODE_MARK = 'abcdefg'\n res = htmlutil.extract_code_from_html_text(\"\")\n self.assertEqual(res, [])", "solution_code": "def extract_code_from_html_text(self, html_text):\n text_with_code_tag = self.format_line_html_text(html_text)\n\n if self.CODE_MARK not in text_with_code_tag:\n return []\n\n code_index_start = 0\n soup = BeautifulSoup(html_text, 'lxml')\n code_tag = soup.find_all(name=['pre', 'blockquote'])\n code_count = text_with_code_tag.count(self.CODE_MARK)\n code_list = []\n for code_index in range(code_index_start, code_index_start + code_count):\n code = code_tag[code_index].get_text()\n if code:\n code_list.append(code)\n return code_list", "dependencies": { "Standalone": false, "lib_dependencies": [ "BeautifulSoup" ], "field_dependencies": [ "self.CODE_MARK" ], "method_dependencies": [ "format_line_html_text" ] } } ] }, { "task_id": "ClassEval_45", "skeleton": "\nfrom PIL import Image, ImageEnhance\n\nclass ImageProcessor:\n \"\"\"\n This is a class to process image, including loading, saving, resizing, rotating, and adjusting the brightness of images.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialize self.image\n \"\"\"\n self.image = None\n\n def load_image(self, image_path):\n \"\"\"\n Use Image util in PIL to open a image\n :param image_path: str, path of image that is to be\n >>> processor.load_image('test.jpg')\n >>> processor.image\n \n \"\"\"\n\n def save_image(self, save_path):\n \"\"\"\n Save image to a path if image has opened\n :param save_path: str, the path that the image will be saved\n >>> processor.load_image('test.jpg')\n >>> processor.save_image('test2.jpg')\n \"\"\"\n\n def resize_image(self, width, height):\n \"\"\"\n Risize the image if image has opened.\n :param width: int, the target width of image\n :param height: int, the target height of image\n >>> processor.load_image('test.jpg')\n >>> processor.resize_image(300, 300)\n >>> processor.image.width\n 300\n >>> processor.image.height\n 300\n \"\"\"\n\n def rotate_image(self, degrees):\n \"\"\"\n rotate image if image has opened\n :param degrees: float, the degrees that the image will be rotated\n >>> processor.load_image('test.jpg')\n >>> processor.resize_image(90)\n \"\"\"\n\n def adjust_brightness(self, factor):\n \"\"\"\n Adjust the brightness of image if image has opened.\n :param factor: float, brightness of an image. A factor of 0.0 gives a black image. A factor of 1.0 gives the original image.\n >>> processor.load_image('test.jpg')\n >>> processor.adjust_brightness(0.5)\n \"\"\"", "test": "import unittest\nimport os\n\n\nclass ImageProcessorTestLoadImage(unittest.TestCase):\n def setUp(self):\n self.processor = ImageProcessor()\n self.image_path = os.path.join(os.path.dirname(__file__), \"test.png\")\n image = Image.new(\"RGB\", (100, 100), (255, 255, 255))\n image.save(self.image_path)\n\n def tearDown(self):\n self.processor.image.close()\n # if os.path.exists(self.image_path):\n # os.remove(self.image_path)\n\n def test_load_image(self):\n self.processor.load_image(self.image_path)\n self.assertIsNotNone(self.processor.image)\n\n def test_load_image_2(self):\n self.processor.load_image(self.image_path)\n self.assertEqual(self.processor.image.size, (100, 100))\n\n def test_load_image_3(self):\n self.processor.load_image(self.image_path)\n self.assertEqual(self.processor.image.mode, \"RGB\")\n\n def test_load_image_4(self):\n self.processor.load_image(self.image_path)\n self.assertEqual(self.processor.image.format, \"PNG\")\n\n def test_load_image_5(self):\n self.processor.load_image(self.image_path)\n self.assertEqual(self.processor.image.filename, self.image_path)\n\n\nclass ImageProcessorTestSaveImage(unittest.TestCase):\n def setUp(self):\n self.processor = ImageProcessor()\n self.image_path = os.path.join(os.path.dirname(__file__), \"test.png\")\n image = Image.new(\"RGB\", (100, 100), (255, 255, 255))\n image.save(self.image_path)\n\n def tearDown(self):\n self.processor.image.close()\n\n def test_save_image(self):\n save_path = os.path.join(os.path.dirname(__file__), \"test_save.png\")\n self.processor.load_image(self.image_path)\n self.processor.save_image(save_path)\n saved_image = Image.open(save_path)\n self.assertIsNotNone(saved_image)\n\n def test_save_image_2(self):\n save_path = os.path.join(os.path.dirname(__file__), \"test_save.png\")\n self.processor.load_image(self.image_path)\n self.processor.save_image(save_path)\n saved_image = Image.open(save_path)\n self.assertEqual(saved_image.size, (100, 100))\n\n def test_save_image_3(self):\n save_path = os.path.join(os.path.dirname(__file__), \"test_save.png\")\n self.processor.load_image(self.image_path)\n self.processor.save_image(save_path)\n saved_image = Image.open(save_path)\n self.assertEqual(saved_image.mode, \"RGB\")\n\n def test_save_image_4(self):\n save_path = os.path.join(os.path.dirname(__file__), \"test_save.png\")\n self.processor.load_image(self.image_path)\n self.processor.save_image(save_path)\n saved_image = Image.open(save_path)\n self.assertEqual(saved_image.format, \"PNG\")\n\n def test_save_image_5(self):\n save_path = os.path.join(os.path.dirname(__file__), \"test_save.png\")\n self.processor.load_image(self.image_path)\n self.processor.save_image(save_path)\n saved_image = Image.open(save_path)\n self.assertEqual(saved_image.filename, save_path)\n\n\nclass ImageProcessorTestResizeImage(unittest.TestCase):\n def setUp(self):\n self.processor = ImageProcessor()\n self.image_path = os.path.join(os.path.dirname(__file__), \"test.png\")\n image = Image.new(\"RGB\", (100, 100), (255, 255, 255))\n image.save(self.image_path)\n\n def tearDown(self):\n self.processor.image.close()\n\n def test_resize_image(self):\n self.processor.load_image(self.image_path)\n self.processor.resize_image(30, 15)\n self.assertEqual(self.processor.image.size, (30, 15))\n\n def test_resize_image_2(self):\n self.processor.load_image(self.image_path)\n self.processor.resize_image(30, 15)\n self.assertEqual(self.processor.image.mode, \"RGB\")\n\n def test_resize_image_3(self):\n self.processor.load_image(self.image_path)\n self.processor.resize_image(30, 15)\n self.assertEqual(self.processor.image.format, None)\n\n def test_resize_image_4(self):\n self.processor.load_image(self.image_path)\n self.processor.resize_image(40, 20)\n self.assertEqual(self.processor.image.mode, \"RGB\")\n\n def test_resize_image_5(self):\n self.processor.load_image(self.image_path)\n self.processor.resize_image(50, 25)\n self.assertEqual(self.processor.image.format, None)\n\n\nclass ImageProcessorTestRotateImage(unittest.TestCase):\n def setUp(self):\n self.processor = ImageProcessor()\n self.image_path = os.path.join(os.path.dirname(__file__), \"test.png\")\n image = Image.new(\"RGB\", (100, 100), (255, 255, 255))\n image.save(self.image_path)\n\n def tearDown(self):\n self.processor.image.close()\n\n def test_rotate_image(self):\n self.processor.load_image(self.image_path)\n original_image = self.processor.image\n self.processor.rotate_image(90)\n self.assertTrue(ImageChops.difference(original_image.rotate(90), self.processor.image).getbbox() is None)\n\n def test_rotate_image_2(self):\n self.processor.load_image(self.image_path)\n original_image = self.processor.image\n self.processor.rotate_image(180)\n self.assertTrue(ImageChops.difference(original_image.rotate(180), self.processor.image).getbbox() is None)\n\n def test_rotate_image_3(self):\n self.processor.load_image(self.image_path)\n original_image = self.processor.image\n self.processor.rotate_image(270)\n self.assertTrue(ImageChops.difference(original_image.rotate(270), self.processor.image).getbbox() is None)\n\n def test_rotate_image_4(self):\n self.processor.load_image(self.image_path)\n original_image = self.processor.image\n self.processor.rotate_image(360)\n self.assertTrue(ImageChops.difference(original_image.rotate(360), self.processor.image).getbbox() is None)\n\n def test_rotate_image_5(self):\n self.processor.load_image(self.image_path)\n original_image = self.processor.image\n self.processor.rotate_image(45)\n self.assertTrue(ImageChops.difference(original_image.rotate(45), self.processor.image).getbbox() is None)\n\n\nclass ImageProcessorTestAdjustBrightness(unittest.TestCase):\n def setUp(self):\n self.processor = ImageProcessor()\n self.image_path = os.path.join(os.path.dirname(__file__), \"test.png\")\n image = Image.new(\"RGB\", (100, 100), (255, 255, 255))\n image.save(self.image_path)\n\n def tearDown(self):\n self.processor.image.close()\n\n def test_adjust_brightness(self):\n self.processor.load_image(self.image_path)\n enhancer = ImageEnhance.Brightness(Image.open(self.image_path))\n expected_image = enhancer.enhance(0.3)\n self.processor.adjust_brightness(0.3)\n self.assertTrue(ImageChops.difference(expected_image, self.processor.image).getbbox() is None)\n\n def test_adjust_brightness_2(self):\n self.processor.load_image(self.image_path)\n enhancer = ImageEnhance.Brightness(Image.open(self.image_path))\n expected_image = enhancer.enhance(0.5)\n self.processor.adjust_brightness(0.5)\n self.assertTrue(ImageChops.difference(expected_image, self.processor.image).getbbox() is None)\n\n def test_adjust_brightness_3(self):\n self.processor.load_image(self.image_path)\n enhancer = ImageEnhance.Brightness(Image.open(self.image_path))\n expected_image = enhancer.enhance(0.7)\n self.processor.adjust_brightness(0.7)\n self.assertTrue(ImageChops.difference(expected_image, self.processor.image).getbbox() is None)\n\n def test_adjust_brightness_4(self):\n self.processor.load_image(self.image_path)\n enhancer = ImageEnhance.Brightness(Image.open(self.image_path))\n expected_image = enhancer.enhance(1.0)\n self.processor.adjust_brightness(1.0)\n self.assertTrue(ImageChops.difference(expected_image, self.processor.image).getbbox() is None)\n\n def test_adjust_brightness_5(self):\n self.processor.load_image(self.image_path)\n enhancer = ImageEnhance.Brightness(Image.open(self.image_path))\n expected_image = enhancer.enhance(1.5)\n self.processor.adjust_brightness(1.5)\n self.assertTrue(ImageChops.difference(expected_image, self.processor.image).getbbox() is None)\n\n\nclass ImageProcessorTestMain(unittest.TestCase):\n def setUp(self):\n self.processor = ImageProcessor()\n self.image_path = os.path.join(os.path.dirname(__file__), \"test.png\")\n image = Image.new(\"RGB\", (100, 100), (255, 255, 255))\n image.save(self.image_path)\n\n def tearDown(self):\n self.processor.image.close()\n\n def test_main(self):\n self.processor.load_image(self.image_path)\n self.assertIsNotNone(self.processor.image)\n\n enhancer = ImageEnhance.Brightness(Image.open(self.image_path))\n expected_image = enhancer.enhance(0.4)\n self.processor.adjust_brightness(0.4)\n self.assertTrue(ImageChops.difference(expected_image, self.processor.image).getbbox() is None)\n\n self.processor.resize_image(30, 15)\n self.assertEqual(self.processor.image.size, (30, 15))\n\n original_image = self.processor.image\n self.processor.rotate_image(90)\n self.assertTrue(ImageChops.difference(original_image.rotate(90), self.processor.image).getbbox() is None)\n\n save_path = os.path.join(os.path.dirname(__file__), \"test_save.png\")\n self.processor.save_image(save_path)\n saved_image = Image.open(save_path)\n self.assertIsNotNone(saved_image)\n saved_image.close()", "solution_code": "from PIL import Image, ImageEnhance, ImageChops\n\n\nclass ImageProcessor:\n def __init__(self):\n self.image = None\n\n def load_image(self, image_path):\n self.image = Image.open(image_path)\n\n def save_image(self, save_path):\n if self.image:\n self.image.save(save_path)\n\n def resize_image(self, width, height):\n if self.image:\n self.image = self.image.resize((width, height))\n\n def rotate_image(self, degrees):\n if self.image:\n self.image = self.image.rotate(degrees)\n\n def adjust_brightness(self, factor):\n if self.image:\n enhancer = ImageEnhance.Brightness(self.image)\n self.image = enhancer.enhance(factor)", "import_statement": [ "from PIL import Image, ImageEnhance, ImageChops" ], "class_description": " \"\"\"\n This is a class to process image, including loading, saving, resizing, rotating, and adjusting the brightness of images.\n \"\"\"\n", "class_name": "ImageProcessor", "test_classes": [ "ImageProcessorTestLoadImage", "ImageProcessorTestSaveImage", "ImageProcessorTestResizeImage", "ImageProcessorTestRotateImage", "ImageProcessorTestAdjustBrightness", "ImageProcessorTestMain" ], "class_constructor": "class ImageProcessor: \n def __init__(self):\n \"\"\"\n Initialize self.image\n \"\"\"\n self.image = None\n\n", "fields": [ "self.image" ], "methods_info": [ { "method_name": "load_image", "method_description": "def load_image(self, image_path):\n \"\"\"\n Use Image util in PIL to open a image\n :param image_path: str, path of image that is to be\n >>> processor.load_image('test.jpg')\n >>> processor.image\n \n \"\"\"", "test_class": "ImageProcessorTestLoadImage", "test_code": "class ImageProcessorTestLoadImage(unittest.TestCase):\n def setUp(self):\n self.processor = ImageProcessor()\n self.image_path = os.path.join(os.path.dirname(__file__), \"test.png\")\n image = Image.new(\"RGB\", (100, 100), (255, 255, 255))\n image.save(self.image_path)\n\n def tearDown(self):\n self.processor.image.close()\n # if os.path.exists(self.image_path):\n # os.remove(self.image_path)\n\n def test_load_image(self):\n self.processor.load_image(self.image_path)\n self.assertIsNotNone(self.processor.image)\n\n def test_load_image_2(self):\n self.processor.load_image(self.image_path)\n self.assertEqual(self.processor.image.size, (100, 100))\n\n def test_load_image_3(self):\n self.processor.load_image(self.image_path)\n self.assertEqual(self.processor.image.mode, \"RGB\")\n\n def test_load_image_4(self):\n self.processor.load_image(self.image_path)\n self.assertEqual(self.processor.image.format, \"PNG\")\n\n def test_load_image_5(self):\n self.processor.load_image(self.image_path)\n self.assertEqual(self.processor.image.filename, self.image_path)", "solution_code": "def load_image(self, image_path):\n self.image = Image.open(image_path)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.image" ], "method_dependencies": [] } }, { "method_name": "save_image", "method_description": "def save_image(self, save_path):\n \"\"\"\n Save image to a path if image has opened\n :param save_path: str, the path that the image will be saved\n >>> processor.load_image('test.jpg')\n >>> processor.save_image('test2.jpg')\n \"\"\"", "test_class": "ImageProcessorTestSaveImage", "test_code": "class ImageProcessorTestSaveImage(unittest.TestCase):\n def setUp(self):\n self.processor = ImageProcessor()\n self.image_path = os.path.join(os.path.dirname(__file__), \"test.png\")\n image = Image.new(\"RGB\", (100, 100), (255, 255, 255))\n image.save(self.image_path)\n\n def tearDown(self):\n self.processor.image.close()\n\n def test_save_image(self):\n save_path = os.path.join(os.path.dirname(__file__), \"test_save.png\")\n self.processor.load_image(self.image_path)\n self.processor.save_image(save_path)\n saved_image = Image.open(save_path)\n self.assertIsNotNone(saved_image)\n\n def test_save_image_2(self):\n save_path = os.path.join(os.path.dirname(__file__), \"test_save.png\")\n self.processor.load_image(self.image_path)\n self.processor.save_image(save_path)\n saved_image = Image.open(save_path)\n self.assertEqual(saved_image.size, (100, 100))\n\n def test_save_image_3(self):\n save_path = os.path.join(os.path.dirname(__file__), \"test_save.png\")\n self.processor.load_image(self.image_path)\n self.processor.save_image(save_path)\n saved_image = Image.open(save_path)\n self.assertEqual(saved_image.mode, \"RGB\")\n\n def test_save_image_4(self):\n save_path = os.path.join(os.path.dirname(__file__), \"test_save.png\")\n self.processor.load_image(self.image_path)\n self.processor.save_image(save_path)\n saved_image = Image.open(save_path)\n self.assertEqual(saved_image.format, \"PNG\")\n\n def test_save_image_5(self):\n save_path = os.path.join(os.path.dirname(__file__), \"test_save.png\")\n self.processor.load_image(self.image_path)\n self.processor.save_image(save_path)\n saved_image = Image.open(save_path)\n self.assertEqual(saved_image.filename, save_path)", "solution_code": "def save_image(self, save_path):\n if self.image:\n self.image.save(save_path)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.image" ], "method_dependencies": [] } }, { "method_name": "resize_image", "method_description": "def resize_image(self, width, height):\n \"\"\"\n Risize the image if image has opened.\n :param width: int, the target width of image\n :param height: int, the target height of image\n >>> processor.load_image('test.jpg')\n >>> processor.resize_image(300, 300)\n >>> processor.image.width\n 300\n >>> processor.image.height\n 300\n \"\"\"", "test_class": "ImageProcessorTestResizeImage", "test_code": "class ImageProcessorTestResizeImage(unittest.TestCase):\n def setUp(self):\n self.processor = ImageProcessor()\n self.image_path = os.path.join(os.path.dirname(__file__), \"test.png\")\n image = Image.new(\"RGB\", (100, 100), (255, 255, 255))\n image.save(self.image_path)\n\n def tearDown(self):\n self.processor.image.close()\n\n def test_resize_image(self):\n self.processor.load_image(self.image_path)\n self.processor.resize_image(30, 15)\n self.assertEqual(self.processor.image.size, (30, 15))\n\n def test_resize_image_2(self):\n self.processor.load_image(self.image_path)\n self.processor.resize_image(30, 15)\n self.assertEqual(self.processor.image.mode, \"RGB\")\n\n def test_resize_image_3(self):\n self.processor.load_image(self.image_path)\n self.processor.resize_image(30, 15)\n self.assertEqual(self.processor.image.format, None)\n\n def test_resize_image_4(self):\n self.processor.load_image(self.image_path)\n self.processor.resize_image(40, 20)\n self.assertEqual(self.processor.image.mode, \"RGB\")\n\n def test_resize_image_5(self):\n self.processor.load_image(self.image_path)\n self.processor.resize_image(50, 25)\n self.assertEqual(self.processor.image.format, None)", "solution_code": "def resize_image(self, width, height):\n if self.image:\n self.image = self.image.resize((width, height))", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.image" ], "method_dependencies": [] } }, { "method_name": "rotate_image", "method_description": "def rotate_image(self, degrees):\n \"\"\"\n rotate image if image has opened\n :param degrees: float, the degrees that the image will be rotated\n >>> processor.load_image('test.jpg')\n >>> processor.resize_image(90)\n \"\"\"", "test_class": "ImageProcessorTestRotateImage", "test_code": "class ImageProcessorTestRotateImage(unittest.TestCase):\n def setUp(self):\n self.processor = ImageProcessor()\n self.image_path = os.path.join(os.path.dirname(__file__), \"test.png\")\n image = Image.new(\"RGB\", (100, 100), (255, 255, 255))\n image.save(self.image_path)\n\n def tearDown(self):\n self.processor.image.close()\n\n def test_rotate_image(self):\n self.processor.load_image(self.image_path)\n original_image = self.processor.image\n self.processor.rotate_image(90)\n self.assertTrue(ImageChops.difference(original_image.rotate(90), self.processor.image).getbbox() is None)\n\n def test_rotate_image_2(self):\n self.processor.load_image(self.image_path)\n original_image = self.processor.image\n self.processor.rotate_image(180)\n self.assertTrue(ImageChops.difference(original_image.rotate(180), self.processor.image).getbbox() is None)\n\n def test_rotate_image_3(self):\n self.processor.load_image(self.image_path)\n original_image = self.processor.image\n self.processor.rotate_image(270)\n self.assertTrue(ImageChops.difference(original_image.rotate(270), self.processor.image).getbbox() is None)\n\n def test_rotate_image_4(self):\n self.processor.load_image(self.image_path)\n original_image = self.processor.image\n self.processor.rotate_image(360)\n self.assertTrue(ImageChops.difference(original_image.rotate(360), self.processor.image).getbbox() is None)\n\n def test_rotate_image_5(self):\n self.processor.load_image(self.image_path)\n original_image = self.processor.image\n self.processor.rotate_image(45)\n self.assertTrue(ImageChops.difference(original_image.rotate(45), self.processor.image).getbbox() is None)", "solution_code": "def rotate_image(self, degrees):\n if self.image:\n self.image = self.image.rotate(degrees)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.image" ], "method_dependencies": [] } }, { "method_name": "adjust_brightness", "method_description": "def adjust_brightness(self, factor):\n \"\"\"\n Adjust the brightness of image if image has opened.\n :param factor: float, brightness of an image. A factor of 0.0 gives a black image. A factor of 1.0 gives the original image.\n >>> processor.load_image('test.jpg')\n >>> processor.adjust_brightness(0.5)\n \"\"\"", "test_class": "ImageProcessorTestAdjustBrightness", "test_code": "class ImageProcessorTestAdjustBrightness(unittest.TestCase):\n def setUp(self):\n self.processor = ImageProcessor()\n self.image_path = os.path.join(os.path.dirname(__file__), \"test.png\")\n image = Image.new(\"RGB\", (100, 100), (255, 255, 255))\n image.save(self.image_path)\n\n def tearDown(self):\n self.processor.image.close()\n\n def test_adjust_brightness(self):\n self.processor.load_image(self.image_path)\n enhancer = ImageEnhance.Brightness(Image.open(self.image_path))\n expected_image = enhancer.enhance(0.3)\n self.processor.adjust_brightness(0.3)\n self.assertTrue(ImageChops.difference(expected_image, self.processor.image).getbbox() is None)\n\n def test_adjust_brightness_2(self):\n self.processor.load_image(self.image_path)\n enhancer = ImageEnhance.Brightness(Image.open(self.image_path))\n expected_image = enhancer.enhance(0.5)\n self.processor.adjust_brightness(0.5)\n self.assertTrue(ImageChops.difference(expected_image, self.processor.image).getbbox() is None)\n\n def test_adjust_brightness_3(self):\n self.processor.load_image(self.image_path)\n enhancer = ImageEnhance.Brightness(Image.open(self.image_path))\n expected_image = enhancer.enhance(0.7)\n self.processor.adjust_brightness(0.7)\n self.assertTrue(ImageChops.difference(expected_image, self.processor.image).getbbox() is None)\n\n def test_adjust_brightness_4(self):\n self.processor.load_image(self.image_path)\n enhancer = ImageEnhance.Brightness(Image.open(self.image_path))\n expected_image = enhancer.enhance(1.0)\n self.processor.adjust_brightness(1.0)\n self.assertTrue(ImageChops.difference(expected_image, self.processor.image).getbbox() is None)\n\n def test_adjust_brightness_5(self):\n self.processor.load_image(self.image_path)\n enhancer = ImageEnhance.Brightness(Image.open(self.image_path))\n expected_image = enhancer.enhance(1.5)\n self.processor.adjust_brightness(1.5)\n self.assertTrue(ImageChops.difference(expected_image, self.processor.image).getbbox() is None)", "solution_code": "def adjust_brightness(self, factor):\n if self.image:\n enhancer = ImageEnhance.Brightness(self.image)\n self.image = enhancer.enhance(factor)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.image" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_46", "skeleton": "\nclass Interpolation:\n \"\"\"\n This is a class that implements the Linear interpolation operation of one-dimensional and two-dimensional data\n \"\"\"\n\n def __init__(self):\n pass\n\n @staticmethod\n def interpolate_1d(x, y, x_interp):\n \"\"\"\n Linear interpolation of one-dimensional data\n :param x: The x-coordinate of the data point, list.\n :param y: The y-coordinate of the data point, list.\n :param x_interp: The x-coordinate of the interpolation point, list.\n :return: The y-coordinate of the interpolation point, list.\n >>> interpolation = Interpolation()\n >>> interpolation.interpolate_1d([1, 2, 3], [1, 2, 3], [1.5, 2.5])\n [1.5, 2.5]\n\n \"\"\"\n\n @staticmethod\n def interpolate_2d(x, y, z, x_interp, y_interp):\n ”“”\n Linear interpolation of two-dimensional data\n :param x: The x-coordinate of the data point, list.\n :param y: The y-coordinate of the data point, list.\n :param z: The z-coordinate of the data point, list.\n :param x_interp: The x-coordinate of the interpolation point, list.\n :param y_interp: The y-coordinate of the interpolation point, list.\n :return: The z-coordinate of the interpolation point, list.\n >>> interpolation = Interpolation()\n >>> interpolation.interpolate_2d([1, 2, 3], [1, 2, 3], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [1.5, 2.5], [1.5, 2.5])\n [3.0, 7.0]\n\n ”“”", "test": "import unittest\n\n\nclass InterpolationTestInterpolate1d(unittest.TestCase):\n def test_interpolate_1d(self):\n interpolation = Interpolation()\n self.assertEqual(interpolation.interpolate_1d([1, 2, 3], [1, 2, 3], [1.5, 2.5]), [1.5, 2.5])\n\n def test_interpolate_1d_2(self):\n interpolation = Interpolation()\n self.assertEqual(interpolation.interpolate_1d([1, 6, 4], [1, 2, 5], [1.5, 2.5]), [1.1, 1.3])\n\n def test_interpolate_1d_3(self):\n interpolation = Interpolation()\n self.assertEqual(interpolation.interpolate_1d([1, 6, 4], [1, 7, 5], [1.5, 2.5]), [1.6, 2.8])\n\n def test_interpolate_1d_4(self):\n interpolation = Interpolation()\n self.assertEqual(interpolation.interpolate_1d([1, 6, 4], [1, 2, 5], [2, 3]), [1.2, 1.4])\n\n def test_interpolate_1d_5(self):\n interpolation = Interpolation()\n self.assertEqual(interpolation.interpolate_1d([1, 6, 4], [1, 7, 5], [2, 3]), [2.2, 3.4])\n\n def test_interpolate_1d_6(self):\n interpolation = Interpolation()\n self.assertEqual(interpolation.interpolate_1d([1, 6, 4], [1, 7, 5], []), [])\n\n def test_interpolate_1d_7(self):\n interpolation = Interpolation()\n self.assertEqual(interpolation.interpolate_1d([], [], [[], []]), [])\n\n\nclass InterpolationTestInterpolate2d(unittest.TestCase):\n def test_interpolate_2d(self):\n interpolation = Interpolation()\n self.assertEqual(\n interpolation.interpolate_2d([1, 2, 3], [1, 2, 3], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [1.5, 2.5],\n [1.5, 2.5]), [3.0, 7.0])\n\n def test_interpolate_2d_2(self):\n interpolation = Interpolation()\n self.assertEqual(\n interpolation.interpolate_2d([1, 2, 3], [1, 2, 3], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [1.5, 2.5], [3, 4]),\n [4.5])\n\n def test_interpolate_2d_3(self):\n interpolation = Interpolation()\n self.assertEqual(\n interpolation.interpolate_2d([1, 2, 3], [1, 2, 3], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [3, 4], [1.5, 2.5]),\n [7.5])\n\n def test_interpolate_2d_4(self):\n interpolation = Interpolation()\n self.assertEqual(\n interpolation.interpolate_2d([1, 2, 3], [1, 2, 3], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [3, 4], [3, 4]),\n [9.0])\n\n def test_interpolate_2d_5(self):\n interpolation = Interpolation()\n self.assertEqual(\n interpolation.interpolate_2d([1, 2, 3], [1, 2, 3], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [1.5, 2.5],\n [1.5, 2.5]), [3.0, 7.0])\n\n\nclass InterpolationTestMain(unittest.TestCase):\n def test_main(self):\n interpolation = Interpolation()\n self.assertEqual(interpolation.interpolate_1d([1, 2, 3], [1, 2, 3], [1.5, 2.5]), [1.5, 2.5])\n self.assertEqual(\n interpolation.interpolate_2d([1, 2, 3], [1, 2, 3], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [1.5, 2.5],\n [1.5, 2.5]), [3.0, 7.0])", "solution_code": "class Interpolation:\n def __init__(self):\n pass\n\n @staticmethod\n def interpolate_1d(x, y, x_interp):\n y_interp = []\n for xi in x_interp:\n for i in range(len(x) - 1):\n if x[i] <= xi <= x[i+1]:\n yi = y[i] + (y[i+1] - y[i]) * (xi - x[i]) / (x[i+1] - x[i])\n y_interp.append(yi)\n break\n return y_interp\n \n @staticmethod\n def interpolate_2d(x, y, z, x_interp, y_interp):\n z_interp = []\n for xi, yi in zip(x_interp, y_interp):\n for i in range(len(x) - 1):\n if x[i] <= xi <= x[i+1]:\n for j in range(len(y) - 1):\n if y[j] <= yi <= y[j+1]:\n z00 = z[i][j]\n z01 = z[i][j+1]\n z10 = z[i+1][j]\n z11 = z[i+1][j+1]\n zi = (z00 * (x[i+1] - xi) * (y[j+1] - yi) +\n z10 * (xi - x[i]) * (y[j+1] - yi) +\n z01 * (x[i+1] - xi) * (yi - y[j]) +\n z11 * (xi - x[i]) * (yi - y[j])) / ((x[i+1] - x[i]) * (y[j+1] - y[j]))\n z_interp.append(zi)\n break\n break\n return z_interp", "import_statement": [], "class_description": " \"\"\"\n This is a class that implements the Linear interpolation operation of one-dimensional and two-dimensional data\n \"\"\"\n", "class_name": "Interpolation", "test_classes": [ "InterpolationTestInterpolate1d", "InterpolationTestInterpolate2d", "InterpolationTestMain" ], "class_constructor": "class Interpolation: \n def __init__(self):\n pass\n\n @staticmethod\n", "fields": [], "methods_info": [ { "method_name": "interpolate_1d", "method_description": "def interpolate_1d(x, y, x_interp):\n \"\"\"\n Linear interpolation of one-dimensional data\n :param x: The x-coordinate of the data point, list.\n :param y: The y-coordinate of the data point, list.\n :param x_interp: The x-coordinate of the interpolation point, list.\n :return: The y-coordinate of the interpolation point, list.\n >>> interpolation = Interpolation()\n >>> interpolation.interpolate_1d([1, 2, 3], [1, 2, 3], [1.5, 2.5])\n [1.5, 2.5]\n\n \"\"\"", "test_class": "InterpolationTestInterpolate1d", "test_code": "class InterpolationTestInterpolate1d(unittest.TestCase):\n def test_interpolate_1d(self):\n interpolation = Interpolation()\n self.assertEqual(interpolation.interpolate_1d([1, 2, 3], [1, 2, 3], [1.5, 2.5]), [1.5, 2.5])\n\n def test_interpolate_1d_2(self):\n interpolation = Interpolation()\n self.assertEqual(interpolation.interpolate_1d([1, 6, 4], [1, 2, 5], [1.5, 2.5]), [1.1, 1.3])\n\n def test_interpolate_1d_3(self):\n interpolation = Interpolation()\n self.assertEqual(interpolation.interpolate_1d([1, 6, 4], [1, 7, 5], [1.5, 2.5]), [1.6, 2.8])\n\n def test_interpolate_1d_4(self):\n interpolation = Interpolation()\n self.assertEqual(interpolation.interpolate_1d([1, 6, 4], [1, 2, 5], [2, 3]), [1.2, 1.4])\n\n def test_interpolate_1d_5(self):\n interpolation = Interpolation()\n self.assertEqual(interpolation.interpolate_1d([1, 6, 4], [1, 7, 5], [2, 3]), [2.2, 3.4])\n\n def test_interpolate_1d_6(self):\n interpolation = Interpolation()\n self.assertEqual(interpolation.interpolate_1d([1, 6, 4], [1, 7, 5], []), [])\n\n def test_interpolate_1d_7(self):\n interpolation = Interpolation()\n self.assertEqual(interpolation.interpolate_1d([], [], [[], []]), [])", "solution_code": "def interpolate_1d(x, y, x_interp):\n y_interp = []\n for xi in x_interp:\n for i in range(len(x) - 1):\n if x[i] <= xi <= x[i+1]:\n yi = y[i] + (y[i+1] - y[i]) * (xi - x[i]) / (x[i+1] - x[i])\n y_interp.append(yi)\n break\n return y_interp", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "interpolate_2d", "method_description": "@staticmethod\n def interpolate_2d(x, y, z, x_interp, y_interp):\n ”“”\n Linear interpolation of two-dimensional data\n :param x: The x-coordinate of the data point, list.\n :param y: The y-coordinate of the data point, list.\n :param z: The z-coordinate of the data point, list.\n :param x_interp: The x-coordinate of the interpolation point, list.\n :param y_interp: The y-coordinate of the interpolation point, list.\n :return: The z-coordinate of the interpolation point, list.\n >>> interpolation = Interpolation()\n >>> interpolation.interpolate_2d([1, 2, 3], [1, 2, 3], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [1.5, 2.5], [1.5, 2.5])\n [3.0, 7.0]\n\n ”“”", "test_class": "InterpolationTestInterpolate2d", "test_code": "class InterpolationTestInterpolate2d(unittest.TestCase):\n def test_interpolate_2d(self):\n interpolation = Interpolation()\n self.assertEqual(\n interpolation.interpolate_2d([1, 2, 3], [1, 2, 3], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [1.5, 2.5],\n [1.5, 2.5]), [3.0, 7.0])\n\n def test_interpolate_2d_2(self):\n interpolation = Interpolation()\n self.assertEqual(\n interpolation.interpolate_2d([1, 2, 3], [1, 2, 3], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [1.5, 2.5], [3, 4]),\n [4.5])\n\n def test_interpolate_2d_3(self):\n interpolation = Interpolation()\n self.assertEqual(\n interpolation.interpolate_2d([1, 2, 3], [1, 2, 3], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [3, 4], [1.5, 2.5]),\n [7.5])\n\n def test_interpolate_2d_4(self):\n interpolation = Interpolation()\n self.assertEqual(\n interpolation.interpolate_2d([1, 2, 3], [1, 2, 3], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [3, 4], [3, 4]),\n [9.0])\n\n def test_interpolate_2d_5(self):\n interpolation = Interpolation()\n self.assertEqual(\n interpolation.interpolate_2d([1, 2, 3], [1, 2, 3], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [1.5, 2.5],\n [1.5, 2.5]), [3.0, 7.0])", "solution_code": "@staticmethod\n def interpolate_2d(x, y, z, x_interp, y_interp):\n z_interp = []\n for xi, yi in zip(x_interp, y_interp):\n for i in range(len(x) - 1):\n if x[i] <= xi <= x[i+1]:\n for j in range(len(y) - 1):\n if y[j] <= yi <= y[j+1]:\n z00 = z[i][j]\n z01 = z[i][j+1]\n z10 = z[i+1][j]\n z11 = z[i+1][j+1]\n zi = (z00 * (x[i+1] - xi) * (y[j+1] - yi) +\n z10 * (xi - x[i]) * (y[j+1] - yi) +\n z01 * (x[i+1] - xi) * (yi - y[j]) +\n z11 * (xi - x[i]) * (yi - y[j])) / ((x[i+1] - x[i]) * (y[j+1] - y[j]))\n z_interp.append(zi)\n break\n break\n return z_interp", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_47", "skeleton": "\nclass IPAddress:\n \"\"\"\n This is a class to process IP Address, including validating, getting the octets and obtaining the binary representation of a valid IP address.\n \"\"\"\n\n def __init__(self, ip_address):\n \"\"\"\n Initialize the IP address to the specified address\n :param ip_address:string\n \"\"\"\n self.ip_address = ip_address\n\n\n def is_valid(self):\n \"\"\"\n Judge whether the IP address is valid, that is, whether the IP address is composed of four Decimal digits separated by '.'. Each digit is greater than or equal to 0 and less than or equal to 255\n :return: bool\n >>> ipaddress = IPAddress(\"10.10.10.10\")\n >>> ipaddress.is_valid()\n True\n \"\"\"\n\n\n def get_octets(self):\n \"\"\"\n If the IP address is valid, the list of four decimal numbers separated by \".\" constituting the IP address is returned; otherwise, an empty list is returned\n :return: list\n >>> ipaddress = IPAddress(\"10.10.10.10\")\n >>> ipaddress.get_octets()\n [\"10\", \"10\", \"10\", \"10\"]\n \"\"\"\n\n\n def get_binary(self):\n \"\"\"\n If the IP address is valid, return the binary form of the IP address; otherwise, return ''\n :return: string\n >>> ipaddress = IPAddress(\"10.10.10.10\")\n >>> ipaddress.get_binary()\n \"00001010.00001010.00001010.00001010\"\n \"\"\"", "test": "import unittest\n\n\nclass IPAddressTestIsValid(unittest.TestCase):\n def test_is_valid_1(self):\n ipaddress = IPAddress(\"10.10.10.10\")\n self.assertEqual(ipaddress.is_valid(), True)\n\n def test_is_valid_2(self):\n ipaddress = IPAddress(\"-1.10.10.10\")\n self.assertEqual(ipaddress.is_valid(), False)\n\n def test_is_valid_3(self):\n ipaddress = IPAddress(\"10.10.10\")\n self.assertEqual(ipaddress.is_valid(), False)\n\n def test_is_valid_4(self):\n ipaddress = IPAddress(\"a.10.10.10\")\n self.assertEqual(ipaddress.is_valid(), False)\n\n def test_is_valid_5(self):\n ipaddress = IPAddress(\"300.10.10.10\")\n self.assertEqual(ipaddress.is_valid(), False)\n\n\nclass IPAddressTestGetOctets(unittest.TestCase):\n def test_get_octets_1(self):\n ipaddress = IPAddress(\"10.10.10.10\")\n self.assertEqual(ipaddress.get_octets(), [\"10\", \"10\", \"10\", \"10\"])\n\n def test_get_octets_2(self):\n ipaddress = IPAddress(\"a.10.10.10\")\n self.assertEqual(ipaddress.get_octets(), [])\n\n def test_get_octets_3(self):\n ipaddress = IPAddress(\"-1.10.10.10\")\n self.assertEqual(ipaddress.get_octets(), [])\n\n def test_get_octets_4(self):\n ipaddress = IPAddress(\"300.10.10.10\")\n self.assertEqual(ipaddress.get_octets(), [])\n\n def test_get_octets_5(self):\n ipaddress = IPAddress(\".10.10.10\")\n self.assertEqual(ipaddress.get_octets(), [])\n\n\nclass IPAddressTestGetBinary(unittest.TestCase):\n def test_get_binary_1(self):\n ipaddress = IPAddress(\"10.10.10.10\")\n self.assertEqual(ipaddress.get_binary(), \"00001010.00001010.00001010.00001010\")\n\n def test_get_binary_2(self):\n ipaddress = IPAddress(\"a.10.10.10\")\n self.assertEqual(ipaddress.get_binary(), '')\n\n def test_get_binary_3(self):\n ipaddress = IPAddress(\"-1.10.10.10\")\n self.assertEqual(ipaddress.get_binary(), '')\n\n def test_get_binary_4(self):\n ipaddress = IPAddress(\"300.10.10.10\")\n self.assertEqual(ipaddress.get_binary(), '')\n\n def test_get_binary_5(self):\n ipaddress = IPAddress(\".10.10.10\")\n self.assertEqual(ipaddress.get_binary(), '')\n\n\nclass IPAddressTest(unittest.TestCase):\n def test_IPAddress(self):\n ipaddress = IPAddress(\"10.10.10.10\")\n self.assertEqual(ipaddress.is_valid(), True)\n self.assertEqual(ipaddress.get_octets(), [\"10\", \"10\", \"10\", \"10\"])\n self.assertEqual(ipaddress.get_binary(), \"00001010.00001010.00001010.00001010\")", "solution_code": "class IPAddress:\n def __init__(self, ip_address):\n self.ip_address = ip_address\n\n def is_valid(self):\n octets = self.ip_address.split('.')\n if len(octets) != 4:\n return False\n for octet in octets:\n if not octet.isdigit() or int(octet) < 0 or int(octet) > 255:\n return False\n return True\n\n def get_octets(self):\n if self.is_valid():\n return self.ip_address.split('.')\n else:\n return []\n\n def get_binary(self):\n if self.is_valid():\n binary_octets = []\n for octet in self.get_octets():\n binary_octets.append(format(int(octet), '08b'))\n return '.'.join(binary_octets)\n else:\n return ''", "import_statement": [], "class_description": " \"\"\"\n This is a class to process IP Address, including validating, getting the octets and obtaining the binary representation of a valid IP address.\n \"\"\"\n", "class_name": "IPAddress", "test_classes": [ "IPAddressTestIsValid", "IPAddressTestGetOctets", "IPAddressTestGetBinary", "IPAddressTest" ], "class_constructor": "class IPAddress: \n def __init__(self, ip_address):\n \"\"\"\n Initialize the IP address to the specified address\n :param ip_address:string\n \"\"\"\n self.ip_address = ip_address\n\n\n", "fields": [ "self.ip_address" ], "methods_info": [ { "method_name": "is_valid", "method_description": "def is_valid(self):\n \"\"\"\n Judge whether the IP address is valid, that is, whether the IP address is composed of four Decimal digits separated by '.'. Each digit is greater than or equal to 0 and less than or equal to 255\n :return: bool\n >>> ipaddress = IPAddress(\"10.10.10.10\")\n >>> ipaddress.is_valid()\n True\n \"\"\"", "test_class": "IPAddressTestIsValid", "test_code": "class IPAddressTestIsValid(unittest.TestCase):\n def test_is_valid_1(self):\n ipaddress = IPAddress(\"10.10.10.10\")\n self.assertEqual(ipaddress.is_valid(), True)\n\n def test_is_valid_2(self):\n ipaddress = IPAddress(\"-1.10.10.10\")\n self.assertEqual(ipaddress.is_valid(), False)\n\n def test_is_valid_3(self):\n ipaddress = IPAddress(\"10.10.10\")\n self.assertEqual(ipaddress.is_valid(), False)\n\n def test_is_valid_4(self):\n ipaddress = IPAddress(\"a.10.10.10\")\n self.assertEqual(ipaddress.is_valid(), False)\n\n def test_is_valid_5(self):\n ipaddress = IPAddress(\"300.10.10.10\")\n self.assertEqual(ipaddress.is_valid(), False)", "solution_code": "def is_valid(self):\n octets = self.ip_address.split('.')\n if len(octets) != 4:\n return False\n for octet in octets:\n if not octet.isdigit() or int(octet) < 0 or int(octet) > 255:\n return False\n return True", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.ip_address" ], "method_dependencies": [] } }, { "method_name": "get_octets", "method_description": "def get_octets(self):\n \"\"\"\n If the IP address is valid, the list of four decimal numbers separated by \".\" constituting the IP address is returned; otherwise, an empty list is returned\n :return: list\n >>> ipaddress = IPAddress(\"10.10.10.10\")\n >>> ipaddress.get_octets()\n [\"10\", \"10\", \"10\", \"10\"]\n \"\"\"", "test_class": "IPAddressTestGetOctets", "test_code": "class IPAddressTestGetOctets(unittest.TestCase):\n def test_get_octets_1(self):\n ipaddress = IPAddress(\"10.10.10.10\")\n self.assertEqual(ipaddress.get_octets(), [\"10\", \"10\", \"10\", \"10\"])\n\n def test_get_octets_2(self):\n ipaddress = IPAddress(\"a.10.10.10\")\n self.assertEqual(ipaddress.get_octets(), [])\n\n def test_get_octets_3(self):\n ipaddress = IPAddress(\"-1.10.10.10\")\n self.assertEqual(ipaddress.get_octets(), [])\n\n def test_get_octets_4(self):\n ipaddress = IPAddress(\"300.10.10.10\")\n self.assertEqual(ipaddress.get_octets(), [])\n\n def test_get_octets_5(self):\n ipaddress = IPAddress(\".10.10.10\")\n self.assertEqual(ipaddress.get_octets(), [])", "solution_code": "def get_octets(self):\n if self.is_valid():\n return self.ip_address.split('.')\n else:\n return []", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.ip_address" ], "method_dependencies": [ "is_valid" ] } }, { "method_name": "get_binary", "method_description": "def get_binary(self):\n \"\"\"\n If the IP address is valid, return the binary form of the IP address; otherwise, return ''\n :return: string\n >>> ipaddress = IPAddress(\"10.10.10.10\")\n >>> ipaddress.get_binary()\n \"00001010.00001010.00001010.00001010\"\n \"\"\"", "test_class": "IPAddressTestGetBinary", "test_code": "class IPAddressTestGetBinary(unittest.TestCase):\n def test_get_binary_1(self):\n ipaddress = IPAddress(\"10.10.10.10\")\n self.assertEqual(ipaddress.get_binary(), \"00001010.00001010.00001010.00001010\")\n\n def test_get_binary_2(self):\n ipaddress = IPAddress(\"a.10.10.10\")\n self.assertEqual(ipaddress.get_binary(), '')\n\n def test_get_binary_3(self):\n ipaddress = IPAddress(\"-1.10.10.10\")\n self.assertEqual(ipaddress.get_binary(), '')\n\n def test_get_binary_4(self):\n ipaddress = IPAddress(\"300.10.10.10\")\n self.assertEqual(ipaddress.get_binary(), '')\n\n def test_get_binary_5(self):\n ipaddress = IPAddress(\".10.10.10\")\n self.assertEqual(ipaddress.get_binary(), '')", "solution_code": "def get_binary(self):\n if self.is_valid():\n binary_octets = []\n for octet in self.get_octets():\n binary_octets.append(format(int(octet), '08b'))\n return '.'.join(binary_octets)\n else:\n return ''", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "is_valid", "get_octets" ] } } ] }, { "task_id": "ClassEval_48", "skeleton": "\nimport socket\nimport netifaces\n\n\nclass IpUtil:\n \"\"\"\n This is a class as tool for ip that can be used to obtain the local IP address, validate its validity, and also provides the functionality to retrieve the corresponding hostname.\n \"\"\"\n\n\n @staticmethod\n def is_valid_ipv4(ip_address):\n \"\"\"\n Check if the given IP address is a valid IPv4 address.\n :param ip_address: string, the IP address to check\n :return: bool, True if the IP address is valid, False otherwise\n >>> IpUtil.is_valid_ipv4('192.168.0.123')\n True\n >>> IpUtil.is_valid_ipv4('256.0.0.0')\n False\n\n \"\"\"\n\n @staticmethod\n def is_valid_ipv6(ip_address):\n \"\"\"\n Check if the given IP address is a valid IPv6 address.\n :param ip_address:string, the IP address to check\n :return:bool, True if the IP address is valid, False otherwise\n >>> IpUtil.is_valid_ipv6('2001:0db8:85a3:0000:0000:8a2e:0370:7334')\n True\n >>> IpUtil.is_valid_ipv6('2001:0db8:85a3:::8a2e:0370:7334')\n False\n\n \"\"\"\n\n\n @staticmethod\n def get_hostname(ip_address):\n \"\"\"\n Get the hostname associated with the given IP address.\n :param ip_address:string, the IP address to get the hostname for\n :return: string, the hostname associated with the IP address\n >>> IpUtil.get_hostname('110.242.68.3')\n 'www.baidu.com'\n >>> IpUtil.get_hostname('10.0.0.1')\n\n \"\"\"", "test": "import unittest\n\n\nclass IpUtilTestIsValidIpv4(unittest.TestCase):\n def test_is_valid_ipv4_1(self):\n result = IpUtil.is_valid_ipv4('192.168.0.123')\n self.assertEqual(result, True)\n\n def test_is_valid_ipv4_2(self):\n result = IpUtil.is_valid_ipv4('10.10.10.10')\n self.assertEqual(result, True)\n\n def test_is_valid_ipv4_3(self):\n result = IpUtil.is_valid_ipv4('0.0.0.0')\n self.assertEqual(result, True)\n\n def test_is_valid_ipv4_4(self):\n result = IpUtil.is_valid_ipv4('abc.168.0.123')\n self.assertEqual(result, False)\n\n def test_is_valid_ipv4_5(self):\n result = IpUtil.is_valid_ipv4('256.0.0.0')\n self.assertEqual(result, False)\n\n\nclass IpUtilTestIsValidIpv6(unittest.TestCase):\n def test_is_valid_ipv6_1(self):\n result = IpUtil.is_valid_ipv6('2001:0db8:85a3:0000:0000:8a2e:0370:7334')\n self.assertEqual(result, True)\n\n def test_is_valid_ipv6_2(self):\n result = IpUtil.is_valid_ipv6('2001:0db8:85a3:::8a2e:0370:7334')\n self.assertEqual(result, False)\n\n def test_is_valid_ipv6_3(self):\n result = IpUtil.is_valid_ipv6('2001:0db8:85a3:2001:llll:8a2e:0370:7334')\n self.assertEqual(result, False)\n\n def test_is_valid_ipv6_4(self):\n result = IpUtil.is_valid_ipv6('2001:0db8:85a3:llll:llll:8a2e:0370:7334')\n self.assertEqual(result, False)\n\n def test_is_valid_ipv6_5(self):\n result = IpUtil.is_valid_ipv6('2001:0db8:85a3::llll:8a2e:0370:7334')\n self.assertEqual(result, False)\n\n\nclass IpUtilTestGetHostname(unittest.TestCase):\n def test_get_hostname_1(self):\n result = IpUtil.get_hostname('110.242.68.3')\n self.assertEqual(result, None)\n\n def test_get_hostname_2(self):\n result = IpUtil.get_hostname('10.0.0.1')\n self.assertEqual(result, None)\n\n def test_get_hostname_3(self):\n result = IpUtil.get_hostname('0.0.0.0')\n self.assertEqual(result, 'LAPTOP-2CS86KUM')\n\n def test_get_hostname_4(self):\n result = IpUtil.get_hostname('0.0.0.1')\n self.assertEqual(result, None)\n\n def test_get_hostname_5(self):\n result = IpUtil.get_hostname('0.0.0.2')\n self.assertEqual(result, None)\n\n\nclass IpUtilTest(unittest.TestCase):\n def test_IpUtil(self):\n result = IpUtil.is_valid_ipv4('192.168.0.123')\n self.assertEqual(result, True)\n\n result = IpUtil.is_valid_ipv6('2001:0db8:85a3:0000:0000:8a2e:0370:7334')\n self.assertEqual(result, True)\n\n result = IpUtil.get_hostname('110.242.68.3')\n self.assertEqual(result, None)", "solution_code": "import socket\n\n\nclass IpUtil:\n\n @staticmethod\n def is_valid_ipv4(ip_address):\n try:\n socket.inet_pton(socket.AF_INET, ip_address)\n return True\n except socket.error:\n return False\n\n @staticmethod\n def is_valid_ipv6(ip_address):\n try:\n socket.inet_pton(socket.AF_INET6, ip_address)\n return True\n except socket.error:\n return False\n\n @staticmethod\n def get_hostname(ip_address):\n try:\n hostname = socket.gethostbyaddr(ip_address)[0]\n return hostname\n except socket.herror:\n return None", "import_statement": [ "import socket" ], "class_description": " \"\"\"\n This is a class as tool for ip that can be used to obtain the local IP address, validate its validity, and also provides the functionality to retrieve the corresponding hostname.\n \"\"\"\n", "class_name": "IpUtil", "test_classes": [ "IpUtilTestIsValidIpv4", "IpUtilTestIsValidIpv6", "IpUtilTestGetHostname", "IpUtilTest" ], "class_constructor": "class IpUtil: \n", "fields": [], "methods_info": [ { "method_name": "is_valid_ipv4", "method_description": "def is_valid_ipv4(ip_address):\n \"\"\"\n Check if the given IP address is a valid IPv4 address.\n :param ip_address: string, the IP address to check\n :return: bool, True if the IP address is valid, False otherwise\n >>> IpUtil.is_valid_ipv4('192.168.0.123')\n True\n >>> IpUtil.is_valid_ipv4('256.0.0.0')\n False\n\n \"\"\"", "test_class": "IpUtilTestIsValidIpv4", "test_code": "class IpUtilTestIsValidIpv4(unittest.TestCase):\n def test_is_valid_ipv4_1(self):\n result = IpUtil.is_valid_ipv4('192.168.0.123')\n self.assertEqual(result, True)\n\n def test_is_valid_ipv4_2(self):\n result = IpUtil.is_valid_ipv4('10.10.10.10')\n self.assertEqual(result, True)\n\n def test_is_valid_ipv4_3(self):\n result = IpUtil.is_valid_ipv4('0.0.0.0')\n self.assertEqual(result, True)\n\n def test_is_valid_ipv4_4(self):\n result = IpUtil.is_valid_ipv4('abc.168.0.123')\n self.assertEqual(result, False)\n\n def test_is_valid_ipv4_5(self):\n result = IpUtil.is_valid_ipv4('256.0.0.0')\n self.assertEqual(result, False)", "solution_code": "def is_valid_ipv4(ip_address):\n try:\n socket.inet_pton(socket.AF_INET, ip_address)\n return True\n except socket.error:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [ "socket" ], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "is_valid_ipv6", "method_description": "@staticmethod\n def is_valid_ipv6(ip_address):\n \"\"\"\n Check if the given IP address is a valid IPv6 address.\n :param ip_address:string, the IP address to check\n :return:bool, True if the IP address is valid, False otherwise\n >>> IpUtil.is_valid_ipv6('2001:0db8:85a3:0000:0000:8a2e:0370:7334')\n True\n >>> IpUtil.is_valid_ipv6('2001:0db8:85a3:::8a2e:0370:7334')\n False\n\n \"\"\"", "test_class": "IpUtilTestIsValidIpv6", "test_code": "class IpUtilTestIsValidIpv6(unittest.TestCase):\n def test_is_valid_ipv6_1(self):\n result = IpUtil.is_valid_ipv6('2001:0db8:85a3:0000:0000:8a2e:0370:7334')\n self.assertEqual(result, True)\n\n def test_is_valid_ipv6_2(self):\n result = IpUtil.is_valid_ipv6('2001:0db8:85a3:::8a2e:0370:7334')\n self.assertEqual(result, False)\n\n def test_is_valid_ipv6_3(self):\n result = IpUtil.is_valid_ipv6('2001:0db8:85a3:2001:llll:8a2e:0370:7334')\n self.assertEqual(result, False)\n\n def test_is_valid_ipv6_4(self):\n result = IpUtil.is_valid_ipv6('2001:0db8:85a3:llll:llll:8a2e:0370:7334')\n self.assertEqual(result, False)\n\n def test_is_valid_ipv6_5(self):\n result = IpUtil.is_valid_ipv6('2001:0db8:85a3::llll:8a2e:0370:7334')\n self.assertEqual(result, False)", "solution_code": "@staticmethod\n def is_valid_ipv6(ip_address):\n try:\n socket.inet_pton(socket.AF_INET6, ip_address)\n return True\n except socket.error:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [ "socket" ], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "get_hostname", "method_description": "@staticmethod\n def get_hostname(ip_address):\n \"\"\"\n Get the hostname associated with the given IP address.\n :param ip_address:string, the IP address to get the hostname for\n :return: string, the hostname associated with the IP address\n >>> IpUtil.get_hostname('110.242.68.3')\n 'www.baidu.com'\n >>> IpUtil.get_hostname('10.0.0.1')\n\n \"\"\"", "test_class": "IpUtilTestGetHostname", "test_code": "class IpUtilTestGetHostname(unittest.TestCase):\n def test_get_hostname_1(self):\n result = IpUtil.get_hostname('110.242.68.3')\n self.assertEqual(result, None)\n\n def test_get_hostname_2(self):\n result = IpUtil.get_hostname('10.0.0.1')\n self.assertEqual(result, None)\n\n def test_get_hostname_3(self):\n result = IpUtil.get_hostname('0.0.0.0')\n self.assertEqual(result, 'LAPTOP-2CS86KUM')\n\n def test_get_hostname_4(self):\n result = IpUtil.get_hostname('0.0.0.1')\n self.assertEqual(result, None)\n\n def test_get_hostname_5(self):\n result = IpUtil.get_hostname('0.0.0.2')\n self.assertEqual(result, None)", "solution_code": "@staticmethod\n def get_hostname(ip_address):\n try:\n hostname = socket.gethostbyaddr(ip_address)[0]\n return hostname\n except socket.herror:\n return None", "dependencies": { "Standalone": false, "lib_dependencies": [ "socket" ], "field_dependencies": [], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_49", "skeleton": "\nclass JobMarketplace:\n \"\"\"\n This is a class that provides functionalities to publish positions, remove positions, submit resumes, withdraw resumes, search for positions, and obtain candidate information.\n \"\"\"\n\n def __init__(self):\n self.job_listings = []\n self.resumes = []\n\n def post_job(self, job_title, company, requirements):\n \"\"\"\n This function is used to publish positions,and add the position information to the job_listings list.\n :param job_title: The title of the position,str.\n :param company: The company of the position,str.\n :param requirements: The requirements of the position,list.\n :return: None\n >>> jobMarketplace = JobMarketplace()\n >>> jobMarketplace.post_job(\"Software Engineer\", \"ABC Company\", ['requirement1', 'requirement2'])\n >>> jobMarketplace.job_listings\n [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}]\n\n \"\"\"\n\n def remove_job(self, job):\n \"\"\"\n This function is used to remove positions,and remove the position information from the job_listings list.\n :param job: The position information to be removed,dict.\n :return: None\n >>> jobMarketplace = JobMarketplace()\n >>> jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['requirement1', 'requirement2']}]\n >>> jobMarketplace.remove_job(jobMarketplace.job_listings[0])\n >>> jobMarketplace.job_listings\n []\n\n \"\"\"\n\n def submit_resume(self, name, skills, experience):\n \"\"\"\n This function is used to submit resumes,and add the resume information to the resumes list.\n :param name: The name of the resume,str.\n :param skills: The skills of the resume,list.\n :param experience: The experience of the resume,str.\n :return: None\n >>> jobMarketplace = JobMarketplace()\n >>> jobMarketplace.submit_resume(\"Tom\", ['skill1', 'skill2'], \"experience\")\n >>> jobMarketplace.resumes\n [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}]\n\n \"\"\"\n\n def withdraw_resume(self, resume):\n \"\"\"\n This function is used to withdraw resumes,and remove the resume information from the resumes list.\n :param resume: The resume information to be removed,dict.\n :return: None\n >>> jobMarketplace = JobMarketplace()\n >>> jobMarketplace.resumes = [{\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}]\n >>> jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])\n >>> jobMarketplace.resumes\n []\n\n \"\"\"\n\n def search_jobs(self, criteria):\n \"\"\"\n This function is used to search for positions,and return the position information that meets the requirements.\n :param criteria: The requirements of the position,list.\n :return: The position information that meets the requirements,list.\n >>> jobMarketplace = JobMarketplace()\n >>> jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill1', 'skill2']}]\n >>> jobMarketplace.search_jobs(\"skill1\")\n [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['skill1', 'skill2']}]\n\n \"\"\"\n\n def get_job_applicants(self, job):\n \"\"\"\n This function is used to obtain candidate information,and return the candidate information that meets the requirements by calling the matches_requirements function.\n :param job: The position information,dict.\n :return: The candidate information that meets the requirements,list.\n >>> jobMarketplace = JobMarketplace()\n >>> jobMarketplace.resumes = [{\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}]\n >>> jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill1', 'skill2']}]\n >>> jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0])\n [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}]\n\n \"\"\"", "test": "import unittest\nclass JobMarketplaceTestPostJob(unittest.TestCase):\n def test_post_job(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.post_job(\"Software Engineer\", \"ABC Company\", ['requirement1', 'requirement2'])\n self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}])\n\n def test_post_job_2(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.post_job(\"Mechanical Engineer\", \"XYZ Company\", ['requirement3', 'requirement4'])\n self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Mechanical Engineer', 'company': 'XYZ Company', 'requirements': ['requirement3', 'requirement4']}])\n\n def test_post_job_3(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.post_job(\"Software Engineer\", \"ABC Company\", ['requirement1', 'requirement2'])\n jobMarketplace.post_job(\"Mechanical Engineer\", \"XYZ Company\", ['requirement3', 'requirement4'])\n self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}, {'job_title': 'Mechanical Engineer', 'company': 'XYZ Company', 'requirements': ['requirement3', 'requirement4']}])\n\n def test_post_job_4(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.post_job(\"Software Engineer\", \"ABC Company\", ['requirement1', 'requirement2'])\n jobMarketplace.post_job(\"Mechanical Engineer\", \"XYZ Company\", ['requirement3', 'requirement4'])\n jobMarketplace.post_job(\"Software Engineer\", \"ABC Company\", ['requirement1', 'requirement2'])\n self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}, {'job_title': 'Mechanical Engineer', 'company': 'XYZ Company', 'requirements': ['requirement3', 'requirement4']}, {'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}])\n\n def test_post_job_5(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.post_job(\"Software Engineer\", \"ABC Company\", ['requirement1', 'requirement2'])\n jobMarketplace.post_job(\"Mechanical Engineer\", \"XYZ Company\", ['requirement3', 'requirement4'])\n jobMarketplace.post_job(\"Software Engineer\", \"ABC Company\", ['requirement1', 'requirement2'])\n jobMarketplace.post_job(\"Mechanical Engineer\", \"XYZ Company\", ['requirement3', 'requirement4'])\n self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}, {'job_title': 'Mechanical Engineer', 'company': 'XYZ Company', 'requirements': ['requirement3', 'requirement4']}, {'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}, {'job_title': 'Mechanical Engineer', 'company': 'XYZ Company', 'requirements': ['requirement3', 'requirement4']}])\n\nclass JobMarketplaceTestRemoveJob(unittest.TestCase):\n def test_remove_job(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['requirement1', 'requirement2']}]\n jobMarketplace.remove_job(jobMarketplace.job_listings[0])\n self.assertEqual(jobMarketplace.job_listings, [])\n\n def test_remove_job_2(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['requirement1', 'requirement2']}, {\"job_title\": \"Mechanical Engineer\", \"company\": \"XYZ Company\", \"requirements\": ['requirement3', 'requirement4']}]\n jobMarketplace.remove_job(jobMarketplace.job_listings[0])\n self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Mechanical Engineer', 'company': 'XYZ Company', 'requirements': ['requirement3', 'requirement4']}])\n\n def test_remove_job_3(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['requirement1', 'requirement2']}, {\"job_title\": \"Mechanical Engineer\", \"company\": \"XYZ Company\", \"requirements\": ['requirement3', 'requirement4']}]\n jobMarketplace.remove_job(jobMarketplace.job_listings[0])\n jobMarketplace.remove_job(jobMarketplace.job_listings[0])\n self.assertEqual(jobMarketplace.job_listings, [])\n\n def test_remove_job_4(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['requirement1', 'requirement2']}, {\"job_title\": \"Mechanical Engineer\", \"company\": \"XYZ Company\", \"requirements\": ['requirement3', 'requirement4']}, {\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['requirement1', 'requirement2']}]\n jobMarketplace.remove_job(jobMarketplace.job_listings[0])\n jobMarketplace.remove_job(jobMarketplace.job_listings[0])\n self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}])\n\n def test_remove_job_5(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\",\n \"requirements\": ['requirement1', 'requirement2']},\n {\"job_title\": \"Mechanical Engineer\", \"company\": \"XYZ Company\",\n \"requirements\": ['requirement3', 'requirement4']},\n {\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\",\n \"requirements\": ['requirement1', 'requirement2']}]\n jobMarketplace.remove_job(jobMarketplace.job_listings[0])\n self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Mechanical Engineer', 'company': 'XYZ Company', 'requirements': ['requirement3', 'requirement4']}, {'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}])\n\nclass JobMarketplaceTestSubmitResume(unittest.TestCase):\n def test_submit_resume(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.submit_resume(\"Tom\", ['skill1', 'skill2'], \"experience\")\n self.assertEqual(jobMarketplace.resumes, [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}])\n\n def test_submit_resume_2(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.submit_resume(\"Tom\", ['skill1', 'skill2'], \"experience\")\n jobMarketplace.submit_resume(\"John\", ['skill3', 'skill4'], \"experience\")\n self.assertEqual(jobMarketplace.resumes, [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}, {'name': 'John', 'skills': ['skill3', 'skill4'], 'experience': 'experience'}])\n\n def test_submit_resume_3(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.submit_resume(\"Tom\", ['skill1', 'skill2'], \"experience\")\n jobMarketplace.submit_resume(\"John\", ['skill3', 'skill4'], \"experience\")\n jobMarketplace.submit_resume(\"Tom\", ['skill1', 'skill2'], \"experience\")\n self.assertEqual(jobMarketplace.resumes, [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}, {'name': 'John', 'skills': ['skill3', 'skill4'], 'experience': 'experience'}, {'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}])\n\n def test_submit_resume_4(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.submit_resume(\"Tom\", ['skill1', 'skill2'], \"experience\")\n jobMarketplace.submit_resume(\"John\", ['skill3', 'skill4'], \"experience\")\n jobMarketplace.submit_resume(\"Tom\", ['skill1', 'skill2'], \"experience\")\n jobMarketplace.submit_resume(\"John\", ['skill3', 'skill4'], \"experience\")\n self.assertEqual(jobMarketplace.resumes, [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}, {'name': 'John', 'skills': ['skill3', 'skill4'], 'experience': 'experience'}, {'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}, {'name': 'John', 'skills': ['skill3', 'skill4'], 'experience': 'experience'}])\n\n def test_submit_resume_5(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.submit_resume(\"Tom\", ['skill1', 'skill2'], \"experience\")\n jobMarketplace.submit_resume(\"John\", ['skill3', 'skill4'], \"experience\")\n jobMarketplace.submit_resume(\"Tom\", ['skill1', 'skill2'], \"experience\")\n jobMarketplace.submit_resume(\"John\", ['skill3', 'skill4'], \"experience\")\n jobMarketplace.submit_resume(\"Tom\", ['skill1', 'skill2'], \"experience\")\n self.assertEqual(jobMarketplace.resumes, [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}, {'name': 'John', 'skills': ['skill3', 'skill4'], 'experience': 'experience'}, {'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}, {'name': 'John', 'skills': ['skill3', 'skill4'], 'experience': 'experience'}, {'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}])\n\n\nclass JobMarketplaceTestWithdrawResume(unittest.TestCase):\n def test_withdraw_resume(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.resumes = [{\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}]\n jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])\n self.assertEqual(jobMarketplace.resumes, [])\n\n def test_withdraw_resume_2(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.resumes = [{\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}, {\"name\": \"John\", \"skills\": ['skill3', 'skill4'], \"experience\": \"experience\"}]\n jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])\n self.assertEqual(jobMarketplace.resumes, [{'name': 'John', 'skills': ['skill3', 'skill4'], 'experience': 'experience'}])\n\n def test_withdraw_resume_3(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.resumes = [{\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}, {\"name\": \"John\", \"skills\": ['skill3', 'skill4'], \"experience\": \"experience\"}]\n jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])\n jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])\n self.assertEqual(jobMarketplace.resumes, [])\n \n def test_withdraw_resume_4(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.resumes = [{\"name\": \"Amy\", \"skills\": ['skill3', 'skill2'], \"experience\": \"experience\"}, {\"name\": \"John\", \"skills\": ['skill3', 'skill4'], \"experience\": \"experience\"}]\n jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])\n jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])\n self.assertEqual(jobMarketplace.resumes, [])\n\n def test_withdraw_resume_5(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.resumes = [{\"name\": \"Amy\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}, {\"name\": \"John\", \"skills\": ['skill3', 'skill4'], \"experience\": \"experience\"}]\n jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])\n self.assertEqual(jobMarketplace.resumes, [{'experience': 'experience', 'name': 'John', 'skills': ['skill3', 'skill4']}])\n\nclass JobMarketplaceTestSearchJobs(unittest.TestCase):\n def test_search_jobs(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill1', 'skill2']}]\n self.assertEqual(jobMarketplace.search_jobs(\"skill1\"), [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['skill1', 'skill2']}])\n\n def test_search_jobs_2(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill1', 'skill2']}, {\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill3', 'skill4']}]\n self.assertEqual(jobMarketplace.search_jobs(\"skill1\"), [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['skill1', 'skill2']}])\n\n def test_search_jobs_3(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill1', 'skill2']}, {\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill3', 'skill4']}]\n self.assertEqual(jobMarketplace.search_jobs(\"skill3\"), [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['skill3', 'skill4']}])\n\n def test_search_jobs_4(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill1', 'skill2']}, {\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill3', 'skill4']}]\n self.assertEqual(jobMarketplace.search_jobs(\"skill5\"), [])\n\n def test_search_jobs_5(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill1', 'skill2']}, {\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill3', 'skill4']}]\n self.assertEqual(jobMarketplace.search_jobs(\"skill6\"), [])\n\nclass JobMarketplaceTestGetJobApplicants(unittest.TestCase):\n def test_get_job_applicants(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.resumes = [{\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}]\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill1', 'skill2']}]\n self.assertEqual(jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0]), [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}])\n\n def test_get_job_applicants_2(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.resumes = [{\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}, {\"name\": \"John\", \"skills\": ['skill3', 'skill4'], \"experience\": \"experience\"}]\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill1', 'skill2']}]\n self.assertEqual(jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0]), [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}])\n\n def test_get_job_applicants_3(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.resumes = [{\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}, {\"name\": \"John\", \"skills\": ['skill3', 'skill4'], \"experience\": \"experience\"}]\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill3', 'skill4']}]\n self.assertEqual(jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0]), [{'name': 'John', 'skills': ['skill3', 'skill4'], 'experience': 'experience'}])\n\n def test_get_job_applicants_4(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.resumes = [{\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}, {\"name\": \"John\", \"skills\": ['skill3', 'skill4'], \"experience\": \"experience\"}]\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill5', 'skill6']}]\n self.assertEqual(jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0]), [])\n\n def test_get_job_applicants_5(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.resumes = [{\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}, {\"name\": \"John\", \"skills\": ['skill3', 'skill4'], \"experience\": \"experience\"}]\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill6', 'skill7']}]\n self.assertEqual(jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0]), [])\n\nclass JobMarketplaceTestMatchesRequirements(unittest.TestCase):\n def test_matches_requirements(self):\n jobMarketplace = JobMarketplace()\n self.assertEqual(jobMarketplace.matches_requirements({\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}, ['skill1', 'skill2']), True)\n\n def test_matches_requirements_2(self):\n jobMarketplace = JobMarketplace()\n self.assertEqual(jobMarketplace.matches_requirements({\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}, ['skill3', 'skill4']), False)\n\n def test_matches_requirements_3(self):\n jobMarketplace = JobMarketplace()\n self.assertEqual(jobMarketplace.matches_requirements({\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}, ['skill5', 'skill6']), False)\n\n def test_matches_requirements_4(self):\n jobMarketplace = JobMarketplace()\n self.assertEqual(jobMarketplace.matches_requirements({\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}, ['skill1', 'skill3']), False)\n\n def test_matches_requirements_5(self):\n jobMarketplace = JobMarketplace()\n self.assertEqual(jobMarketplace.matches_requirements({\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}, ['skill1']), False)\n\nclass JobMarketplaceTestMain(unittest.TestCase):\n def test_main(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.post_job(\"Software Engineer\", \"ABC Company\", ['skill1', 'skill2'])\n jobMarketplace.post_job(\"Mechanical Engineer\", \"XYZ Company\", ['skill3', 'skill4'])\n self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['skill1', 'skill2']}, {'job_title': 'Mechanical Engineer', 'company': 'XYZ Company', 'requirements': ['skill3', 'skill4']}])\n jobMarketplace.remove_job(jobMarketplace.job_listings[1])\n self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['skill1', 'skill2']}])\n jobMarketplace.submit_resume(\"Tom\", ['skill1', 'skill2'], \"experience\")\n self.assertEqual(jobMarketplace.resumes, [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}])\n jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])\n self.assertEqual(jobMarketplace.resumes, [])\n self.assertEqual(jobMarketplace.search_jobs(\"skill1\"), [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['skill1', 'skill2']}])\n jobMarketplace.resumes = [{\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}]\n self.assertEqual(jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0]), [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}])\n self.assertEqual(jobMarketplace.matches_requirements({\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}, ['skill1', 'skill2']), True)", "solution_code": "class JobMarketplace:\n def __init__(self):\n self.job_listings = []\n self.resumes = []\n\n def post_job(self, job_title, company, requirements):\n # requirements = ['requirement1', 'requirement2']\n job = {\"job_title\": job_title, \"company\": company, \"requirements\": requirements}\n self.job_listings.append(job)\n\n def remove_job(self, job):\n self.job_listings.remove(job)\n\n def submit_resume(self, name, skills, experience):\n resume = {\"name\": name, \"skills\": skills, \"experience\": experience}\n self.resumes.append(resume)\n\n def withdraw_resume(self, resume):\n self.resumes.remove(resume)\n\n def search_jobs(self, criteria):\n matching_jobs = []\n for job_listing in self.job_listings:\n if criteria.lower() in job_listing[\"job_title\"].lower() or criteria.lower() in [r.lower() for r in job_listing[\"requirements\"]]:\n matching_jobs.append(job_listing)\n return matching_jobs\n\n def get_job_applicants(self, job):\n applicants = []\n for resume in self.resumes:\n if self.matches_requirements(resume, job[\"requirements\"]):\n applicants.append(resume)\n return applicants\n\n @staticmethod\n def matches_requirements(resume, requirements):\n for skill in resume[\"skills\"]:\n if skill not in requirements:\n return False\n return True", "import_statement": [], "class_description": " \"\"\"\n This is a class that provides functionalities to publish positions, remove positions, submit resumes, withdraw resumes, search for positions, and obtain candidate information.\n \"\"\"\n", "class_name": "JobMarketplace", "test_classes": [ "JobMarketplaceTestPostJob", "JobMarketplaceTestRemoveJob", "JobMarketplaceTestSubmitResume", "JobMarketplaceTestWithdrawResume", "JobMarketplaceTestSearchJobs", "JobMarketplaceTestGetJobApplicants", "JobMarketplaceTestMatchesRequirements", "JobMarketplaceTestMain" ], "class_constructor": "class JobMarketplace: \n def __init__(self):\n self.job_listings = []\n self.resumes = []\n\n", "fields": [ "self.job_listings", "self.resumes" ], "methods_info": [ { "method_name": "post_job", "method_description": "def post_job(self, job_title, company, requirements):\n \"\"\"\n This function is used to publish positions,and add the position information to the job_listings list.\n :param job_title: The title of the position,str.\n :param company: The company of the position,str.\n :param requirements: The requirements of the position,list.\n :return: None\n >>> jobMarketplace = JobMarketplace()\n >>> jobMarketplace.post_job(\"Software Engineer\", \"ABC Company\", ['requirement1', 'requirement2'])\n >>> jobMarketplace.job_listings\n [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}]\n\n \"\"\"", "test_class": "JobMarketplaceTestPostJob", "test_code": "class JobMarketplaceTestPostJob(unittest.TestCase):\n def test_post_job(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.post_job(\"Software Engineer\", \"ABC Company\", ['requirement1', 'requirement2'])\n self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}])\n\n def test_post_job_2(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.post_job(\"Mechanical Engineer\", \"XYZ Company\", ['requirement3', 'requirement4'])\n self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Mechanical Engineer', 'company': 'XYZ Company', 'requirements': ['requirement3', 'requirement4']}])\n\n def test_post_job_3(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.post_job(\"Software Engineer\", \"ABC Company\", ['requirement1', 'requirement2'])\n jobMarketplace.post_job(\"Mechanical Engineer\", \"XYZ Company\", ['requirement3', 'requirement4'])\n self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}, {'job_title': 'Mechanical Engineer', 'company': 'XYZ Company', 'requirements': ['requirement3', 'requirement4']}])\n\n def test_post_job_4(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.post_job(\"Software Engineer\", \"ABC Company\", ['requirement1', 'requirement2'])\n jobMarketplace.post_job(\"Mechanical Engineer\", \"XYZ Company\", ['requirement3', 'requirement4'])\n jobMarketplace.post_job(\"Software Engineer\", \"ABC Company\", ['requirement1', 'requirement2'])\n self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}, {'job_title': 'Mechanical Engineer', 'company': 'XYZ Company', 'requirements': ['requirement3', 'requirement4']}, {'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}])\n\n def test_post_job_5(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.post_job(\"Software Engineer\", \"ABC Company\", ['requirement1', 'requirement2'])\n jobMarketplace.post_job(\"Mechanical Engineer\", \"XYZ Company\", ['requirement3', 'requirement4'])\n jobMarketplace.post_job(\"Software Engineer\", \"ABC Company\", ['requirement1', 'requirement2'])\n jobMarketplace.post_job(\"Mechanical Engineer\", \"XYZ Company\", ['requirement3', 'requirement4'])\n self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}, {'job_title': 'Mechanical Engineer', 'company': 'XYZ Company', 'requirements': ['requirement3', 'requirement4']}, {'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}, {'job_title': 'Mechanical Engineer', 'company': 'XYZ Company', 'requirements': ['requirement3', 'requirement4']}])", "solution_code": "def post_job(self, job_title, company, requirements):\n # requirements = ['requirement1', 'requirement2']\n job = {\"job_title\": job_title, \"company\": company, \"requirements\": requirements}\n self.job_listings.append(job)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.job_listings" ], "method_dependencies": [] } }, { "method_name": "remove_job", "method_description": "def remove_job(self, job):\n \"\"\"\n This function is used to remove positions,and remove the position information from the job_listings list.\n :param job: The position information to be removed,dict.\n :return: None\n >>> jobMarketplace = JobMarketplace()\n >>> jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['requirement1', 'requirement2']}]\n >>> jobMarketplace.remove_job(jobMarketplace.job_listings[0])\n >>> jobMarketplace.job_listings\n []\n\n \"\"\"", "test_class": "JobMarketplaceTestRemoveJob", "test_code": "class JobMarketplaceTestRemoveJob(unittest.TestCase):\n def test_remove_job(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['requirement1', 'requirement2']}]\n jobMarketplace.remove_job(jobMarketplace.job_listings[0])\n self.assertEqual(jobMarketplace.job_listings, [])\n\n def test_remove_job_2(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['requirement1', 'requirement2']}, {\"job_title\": \"Mechanical Engineer\", \"company\": \"XYZ Company\", \"requirements\": ['requirement3', 'requirement4']}]\n jobMarketplace.remove_job(jobMarketplace.job_listings[0])\n self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Mechanical Engineer', 'company': 'XYZ Company', 'requirements': ['requirement3', 'requirement4']}])\n\n def test_remove_job_3(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['requirement1', 'requirement2']}, {\"job_title\": \"Mechanical Engineer\", \"company\": \"XYZ Company\", \"requirements\": ['requirement3', 'requirement4']}]\n jobMarketplace.remove_job(jobMarketplace.job_listings[0])\n jobMarketplace.remove_job(jobMarketplace.job_listings[0])\n self.assertEqual(jobMarketplace.job_listings, [])\n\n def test_remove_job_4(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['requirement1', 'requirement2']}, {\"job_title\": \"Mechanical Engineer\", \"company\": \"XYZ Company\", \"requirements\": ['requirement3', 'requirement4']}, {\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['requirement1', 'requirement2']}]\n jobMarketplace.remove_job(jobMarketplace.job_listings[0])\n jobMarketplace.remove_job(jobMarketplace.job_listings[0])\n self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}])\n\n def test_remove_job_5(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\",\n \"requirements\": ['requirement1', 'requirement2']},\n {\"job_title\": \"Mechanical Engineer\", \"company\": \"XYZ Company\",\n \"requirements\": ['requirement3', 'requirement4']},\n {\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\",\n \"requirements\": ['requirement1', 'requirement2']}]\n jobMarketplace.remove_job(jobMarketplace.job_listings[0])\n self.assertEqual(jobMarketplace.job_listings, [{'job_title': 'Mechanical Engineer', 'company': 'XYZ Company', 'requirements': ['requirement3', 'requirement4']}, {'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['requirement1', 'requirement2']}])", "solution_code": "def remove_job(self, job):\n self.job_listings.remove(job)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.job_listings" ], "method_dependencies": [] } }, { "method_name": "submit_resume", "method_description": "def submit_resume(self, name, skills, experience):\n \"\"\"\n This function is used to submit resumes,and add the resume information to the resumes list.\n :param name: The name of the resume,str.\n :param skills: The skills of the resume,list.\n :param experience: The experience of the resume,str.\n :return: None\n >>> jobMarketplace = JobMarketplace()\n >>> jobMarketplace.submit_resume(\"Tom\", ['skill1', 'skill2'], \"experience\")\n >>> jobMarketplace.resumes\n [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}]\n\n \"\"\"", "test_class": "JobMarketplaceTestSubmitResume", "test_code": "class JobMarketplaceTestSubmitResume(unittest.TestCase):\n def test_submit_resume(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.submit_resume(\"Tom\", ['skill1', 'skill2'], \"experience\")\n self.assertEqual(jobMarketplace.resumes, [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}])\n\n def test_submit_resume_2(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.submit_resume(\"Tom\", ['skill1', 'skill2'], \"experience\")\n jobMarketplace.submit_resume(\"John\", ['skill3', 'skill4'], \"experience\")\n self.assertEqual(jobMarketplace.resumes, [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}, {'name': 'John', 'skills': ['skill3', 'skill4'], 'experience': 'experience'}])\n\n def test_submit_resume_3(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.submit_resume(\"Tom\", ['skill1', 'skill2'], \"experience\")\n jobMarketplace.submit_resume(\"John\", ['skill3', 'skill4'], \"experience\")\n jobMarketplace.submit_resume(\"Tom\", ['skill1', 'skill2'], \"experience\")\n self.assertEqual(jobMarketplace.resumes, [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}, {'name': 'John', 'skills': ['skill3', 'skill4'], 'experience': 'experience'}, {'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}])\n\n def test_submit_resume_4(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.submit_resume(\"Tom\", ['skill1', 'skill2'], \"experience\")\n jobMarketplace.submit_resume(\"John\", ['skill3', 'skill4'], \"experience\")\n jobMarketplace.submit_resume(\"Tom\", ['skill1', 'skill2'], \"experience\")\n jobMarketplace.submit_resume(\"John\", ['skill3', 'skill4'], \"experience\")\n self.assertEqual(jobMarketplace.resumes, [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}, {'name': 'John', 'skills': ['skill3', 'skill4'], 'experience': 'experience'}, {'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}, {'name': 'John', 'skills': ['skill3', 'skill4'], 'experience': 'experience'}])\n\n def test_submit_resume_5(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.submit_resume(\"Tom\", ['skill1', 'skill2'], \"experience\")\n jobMarketplace.submit_resume(\"John\", ['skill3', 'skill4'], \"experience\")\n jobMarketplace.submit_resume(\"Tom\", ['skill1', 'skill2'], \"experience\")\n jobMarketplace.submit_resume(\"John\", ['skill3', 'skill4'], \"experience\")\n jobMarketplace.submit_resume(\"Tom\", ['skill1', 'skill2'], \"experience\")\n self.assertEqual(jobMarketplace.resumes, [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}, {'name': 'John', 'skills': ['skill3', 'skill4'], 'experience': 'experience'}, {'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}, {'name': 'John', 'skills': ['skill3', 'skill4'], 'experience': 'experience'}, {'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}])", "solution_code": "def submit_resume(self, name, skills, experience):\n resume = {\"name\": name, \"skills\": skills, \"experience\": experience}\n self.resumes.append(resume)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.resumes" ], "method_dependencies": [] } }, { "method_name": "withdraw_resume", "method_description": "def withdraw_resume(self, resume):\n \"\"\"\n This function is used to withdraw resumes,and remove the resume information from the resumes list.\n :param resume: The resume information to be removed,dict.\n :return: None\n >>> jobMarketplace = JobMarketplace()\n >>> jobMarketplace.resumes = [{\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}]\n >>> jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])\n >>> jobMarketplace.resumes\n []\n\n \"\"\"", "test_class": "JobMarketplaceTestWithdrawResume", "test_code": "class JobMarketplaceTestWithdrawResume(unittest.TestCase):\n def test_withdraw_resume(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.resumes = [{\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}]\n jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])\n self.assertEqual(jobMarketplace.resumes, [])\n\n def test_withdraw_resume_2(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.resumes = [{\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}, {\"name\": \"John\", \"skills\": ['skill3', 'skill4'], \"experience\": \"experience\"}]\n jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])\n self.assertEqual(jobMarketplace.resumes, [{'name': 'John', 'skills': ['skill3', 'skill4'], 'experience': 'experience'}])\n\n def test_withdraw_resume_3(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.resumes = [{\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}, {\"name\": \"John\", \"skills\": ['skill3', 'skill4'], \"experience\": \"experience\"}]\n jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])\n jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])\n self.assertEqual(jobMarketplace.resumes, [])\n \n def test_withdraw_resume_4(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.resumes = [{\"name\": \"Amy\", \"skills\": ['skill3', 'skill2'], \"experience\": \"experience\"}, {\"name\": \"John\", \"skills\": ['skill3', 'skill4'], \"experience\": \"experience\"}]\n jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])\n jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])\n self.assertEqual(jobMarketplace.resumes, [])\n\n def test_withdraw_resume_5(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.resumes = [{\"name\": \"Amy\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}, {\"name\": \"John\", \"skills\": ['skill3', 'skill4'], \"experience\": \"experience\"}]\n jobMarketplace.withdraw_resume(jobMarketplace.resumes[0])\n self.assertEqual(jobMarketplace.resumes, [{'experience': 'experience', 'name': 'John', 'skills': ['skill3', 'skill4']}])", "solution_code": "def withdraw_resume(self, resume):\n self.resumes.remove(resume)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.resumes" ], "method_dependencies": [] } }, { "method_name": "search_jobs", "method_description": "def search_jobs(self, criteria):\n \"\"\"\n This function is used to search for positions,and return the position information that meets the requirements.\n :param criteria: The requirements of the position,list.\n :return: The position information that meets the requirements,list.\n >>> jobMarketplace = JobMarketplace()\n >>> jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill1', 'skill2']}]\n >>> jobMarketplace.search_jobs(\"skill1\")\n [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['skill1', 'skill2']}]\n\n \"\"\"", "test_class": "JobMarketplaceTestSearchJobs", "test_code": "class JobMarketplaceTestSearchJobs(unittest.TestCase):\n def test_search_jobs(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill1', 'skill2']}]\n self.assertEqual(jobMarketplace.search_jobs(\"skill1\"), [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['skill1', 'skill2']}])\n\n def test_search_jobs_2(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill1', 'skill2']}, {\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill3', 'skill4']}]\n self.assertEqual(jobMarketplace.search_jobs(\"skill1\"), [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['skill1', 'skill2']}])\n\n def test_search_jobs_3(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill1', 'skill2']}, {\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill3', 'skill4']}]\n self.assertEqual(jobMarketplace.search_jobs(\"skill3\"), [{'job_title': 'Software Engineer', 'company': 'ABC Company', 'requirements': ['skill3', 'skill4']}])\n\n def test_search_jobs_4(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill1', 'skill2']}, {\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill3', 'skill4']}]\n self.assertEqual(jobMarketplace.search_jobs(\"skill5\"), [])\n\n def test_search_jobs_5(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill1', 'skill2']}, {\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill3', 'skill4']}]\n self.assertEqual(jobMarketplace.search_jobs(\"skill6\"), [])", "solution_code": "def search_jobs(self, criteria):\n matching_jobs = []\n for job_listing in self.job_listings:\n if criteria.lower() in job_listing[\"job_title\"].lower() or criteria.lower() in [r.lower() for r in job_listing[\"requirements\"]]:\n matching_jobs.append(job_listing)\n return matching_jobs", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.job_listings" ], "method_dependencies": [] } }, { "method_name": "get_job_applicants", "method_description": "def get_job_applicants(self, job):\n \"\"\"\n This function is used to obtain candidate information,and return the candidate information that meets the requirements by calling the matches_requirements function.\n :param job: The position information,dict.\n :return: The candidate information that meets the requirements,list.\n >>> jobMarketplace = JobMarketplace()\n >>> jobMarketplace.resumes = [{\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}]\n >>> jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill1', 'skill2']}]\n >>> jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0])\n [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}]\n\n \"\"\"", "test_class": "JobMarketplaceTestGetJobApplicants", "test_code": "class JobMarketplaceTestGetJobApplicants(unittest.TestCase):\n def test_get_job_applicants(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.resumes = [{\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}]\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill1', 'skill2']}]\n self.assertEqual(jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0]), [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}])\n\n def test_get_job_applicants_2(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.resumes = [{\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}, {\"name\": \"John\", \"skills\": ['skill3', 'skill4'], \"experience\": \"experience\"}]\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill1', 'skill2']}]\n self.assertEqual(jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0]), [{'name': 'Tom', 'skills': ['skill1', 'skill2'], 'experience': 'experience'}])\n\n def test_get_job_applicants_3(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.resumes = [{\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}, {\"name\": \"John\", \"skills\": ['skill3', 'skill4'], \"experience\": \"experience\"}]\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill3', 'skill4']}]\n self.assertEqual(jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0]), [{'name': 'John', 'skills': ['skill3', 'skill4'], 'experience': 'experience'}])\n\n def test_get_job_applicants_4(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.resumes = [{\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}, {\"name\": \"John\", \"skills\": ['skill3', 'skill4'], \"experience\": \"experience\"}]\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill5', 'skill6']}]\n self.assertEqual(jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0]), [])\n\n def test_get_job_applicants_5(self):\n jobMarketplace = JobMarketplace()\n jobMarketplace.resumes = [{\"name\": \"Tom\", \"skills\": ['skill1', 'skill2'], \"experience\": \"experience\"}, {\"name\": \"John\", \"skills\": ['skill3', 'skill4'], \"experience\": \"experience\"}]\n jobMarketplace.job_listings = [{\"job_title\": \"Software Engineer\", \"company\": \"ABC Company\", \"requirements\": ['skill6', 'skill7']}]\n self.assertEqual(jobMarketplace.get_job_applicants(jobMarketplace.job_listings[0]), [])", "solution_code": "def get_job_applicants(self, job):\n applicants = []\n for resume in self.resumes:\n if self.matches_requirements(resume, job[\"requirements\"]):\n applicants.append(resume)\n return applicants", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.resumes" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_50", "skeleton": "\nimport json\nimport os\n\nclass JSONProcessor:\n \"\"\"\n This is a class to process JSON file, including reading and writing JSON files, as well as processing JSON data by removing a specified key from the JSON object.\n \"\"\"\n\n def read_json(self, file_path):\n \"\"\"\n Read a JSON file and return the data.\n :param file_path: str, the path of the JSON file.\n :return: dict, the data from the JSON file if read successfully, or return -1 if an error occurs during the reading process.\n return 0 if the file does not exist.\n >>> json.read_json('test.json')\n {'name': 'test', 'age': 14}\n \"\"\"\n\n def write_json(self, data, file_path):\n \"\"\"\n Write data to a JSON file and save it to the given path.\n\n :param data: dict, the data to be written to the JSON file.\n :param file_path: str, the path of the JSON file.\n :return: 1 if the writing process is successful, or -1, if an error occurs during the writing process.\n >>> json.write_json({'key1': 'value1', 'key2': 'value2'}, 'test.json')\n 1\n >>> json.read_json('test.json')\n {'key1': 'value1', 'key2': 'value2'}\n \"\"\"\n\n def process_json(self, file_path, remove_key):\n \"\"\"\n read a JSON file and process the data by removing a specified key and rewrite the modified data back to the file.\n\n :param file_path: str, the path of the JSON file.\n :param remove_key: str, the key to be removed.\n :return: 1, if the specified key is successfully removed and the data is written back.\n 0, if the file does not exist or the specified key does not exist in the data.\n >>> json.read_json('test.json')\n {'key1': 'value1', 'key2': 'value2'}\n >>> json.process_json('test.json', 'key1')\n 1\n >>> json.read_json('test.json')\n {'key2': 'value2'}\n \"\"\"", "test": "import os\nimport stat\nimport json\nimport unittest\n\n\nclass JSONProcessorTestReadJson(unittest.TestCase):\n def setUp(self):\n self.processor = JSONProcessor()\n self.test_data = {\n \"key1\": \"value1\",\n \"key2\": \"value2\",\n \"key3\": \"value3\"\n }\n self.file_path = \"test.json\"\n\n def tearDown(self):\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n\n # file exists\n def test_read_json_1(self):\n with open(self.file_path, 'w') as file:\n json.dump(self.test_data, file)\n result = self.processor.read_json(self.file_path)\n self.assertEqual(result, self.test_data)\n\n # file not exists\n def test_read_json_2(self):\n result = self.processor.read_json(self.file_path)\n self.assertEqual(result, 0)\n\n # invalid json file\n def test_read_json_3(self):\n with open(self.file_path, 'w') as file:\n file.write(\"Invalid JSON\")\n result = self.processor.read_json(self.file_path)\n self.assertEqual(result, -1)\n\n def test_read_json_4(self):\n result = self.processor.read_json('wrong')\n self.assertEqual(result, 0)\n\n def test_read_json_5(self):\n result = self.processor.read_json('abcd')\n self.assertEqual(result, 0)\n\n\nclass JSONProcessorTestWriteJson(unittest.TestCase):\n def setUp(self):\n self.processor = JSONProcessor()\n self.test_data = {\n \"key1\": \"value1\",\n \"key2\": \"value2\",\n \"key3\": \"value3\"\n }\n self.file_path = \"test.json\"\n\n # create a read only file\n self.file_path_only_read = 'test_only_read.json'\n with open(self.file_path_only_read, 'w') as f:\n f.write('{\"key1\": \"value1\"}')\n\n # set file only read mode\n os.chmod(self.file_path_only_read, stat.S_IRUSR + stat.S_IRGRP + stat.S_IROTH)\n\n def tearDown(self):\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n if os.path.exists(self.file_path_only_read):\n # unset file only read mode and remove the file\n os.chmod(self.file_path_only_read,\n stat.S_IWUSR + stat.S_IRUSR + stat.S_IWGRP + stat.S_IRGRP + stat.S_IWOTH + stat.S_IROTH)\n os.remove(self.file_path_only_read)\n\n def test_write_json_1(self):\n result = self.processor.write_json(self.test_data, self.file_path)\n self.assertEqual(result, 1)\n with open(self.file_path, 'r') as file:\n written_data = json.load(file)\n self.assertEqual(written_data, self.test_data)\n\n def test_write_json_2(self):\n # Provide a read-only file path to simulate an exception\n result = self.processor.write_json(self.test_data, self.file_path_only_read)\n self.assertEqual(result, -1)\n\n def test_write_json_3(self):\n result = self.processor.write_json([], self.file_path_only_read)\n self.assertEqual(result, -1)\n\n def test_write_json_4(self):\n result = self.processor.write_json(self.test_data, '')\n self.assertEqual(result, -1)\n\n def test_write_json_5(self):\n result = self.processor.write_json([], '')\n self.assertEqual(result, -1)\n\n\nclass JSONProcessorTestProcessJsonExistingKey(unittest.TestCase):\n def setUp(self):\n self.processor = JSONProcessor()\n self.test_data = {\n \"key1\": \"value1\",\n \"key2\": \"value2\",\n \"key3\": \"value3\"\n }\n self.file_path = \"test.json\"\n\n def tearDown(self):\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n\n # key exists\n def test_process_json_1(self):\n with open(self.file_path, 'w') as file:\n json.dump(self.test_data, file)\n remove_key = \"key2\"\n self.processor.process_json(self.file_path, remove_key)\n with open(self.file_path, 'r') as file:\n processed_data = json.load(file)\n expected_data = {\n \"key1\": \"value1\",\n \"key3\": \"value3\"\n }\n self.assertEqual(processed_data, expected_data)\n\n # key not exists\n def test_process_json_2(self):\n with open(self.file_path, 'w') as file:\n json.dump(self.test_data, file)\n remove_key = \"nonexistent_key\"\n self.processor.process_json(self.file_path, remove_key)\n with open(self.file_path, 'r') as file:\n processed_data = json.load(file)\n self.assertEqual(processed_data, self.test_data)\n\n # file is empty\n def test_process_json_3(self):\n # Create an empty JSON file\n with open(self.file_path, 'w') as file:\n pass\n remove_key = \"key1\"\n self.assertEqual(self.processor.process_json(self.file_path, remove_key), 0)\n\n def test_process_json_4(self):\n with open(self.file_path, 'w') as file:\n json.dump(self.test_data, file)\n remove_key = \"aaa\"\n self.processor.process_json(self.file_path, remove_key)\n with open(self.file_path, 'r') as file:\n processed_data = json.load(file)\n self.assertEqual(processed_data, self.test_data)\n\n def test_process_json_5(self):\n with open(self.file_path, 'w') as file:\n json.dump(self.test_data, file)\n remove_key = \"bbb\"\n self.processor.process_json(self.file_path, remove_key)\n with open(self.file_path, 'r') as file:\n processed_data = json.load(file)\n self.assertEqual(processed_data, self.test_data)\n\n\nclass JSONProcessorTestMain(unittest.TestCase):\n def setUp(self):\n self.processor = JSONProcessor()\n self.test_data = {\n \"key1\": \"value1\",\n \"key2\": \"value2\",\n \"key3\": \"value3\"\n }\n self.file_path = \"test.json\"\n\n def tearDown(self):\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n\n def test_main(self):\n # write first\n result = self.processor.write_json(self.test_data, self.file_path)\n self.assertEqual(result, 1)\n with open(self.file_path, 'r') as file:\n written_data = json.load(file)\n self.assertEqual(written_data, self.test_data)\n\n # read\n result = self.processor.read_json(self.file_path)\n self.assertEqual(result, self.test_data)\n\n # process\n remove_key = \"key2\"\n self.processor.process_json(self.file_path, remove_key)\n with open(self.file_path, 'r') as file:\n processed_data = json.load(file)\n expected_data = {\n \"key1\": \"value1\",\n \"key3\": \"value3\"\n }\n self.assertEqual(processed_data, expected_data)", "solution_code": "import json\nimport os\n\n\nclass JSONProcessor:\n def read_json(self, file_path):\n if not os.path.exists(file_path):\n return 0\n try:\n with open(file_path, 'r') as file:\n data = json.load(file)\n return data\n except:\n return -1\n\n def write_json(self, data, file_path):\n try:\n with open(file_path, 'w') as file:\n json.dump(data, file)\n return 1\n except:\n return -1\n\n def process_json(self, file_path, remove_key):\n data = self.read_json(file_path)\n if data == 0 or data == -1:\n return 0\n if remove_key in data:\n del data[remove_key]\n self.write_json(data, file_path)\n return 1\n else:\n return 0", "import_statement": [ "import json", "import os" ], "class_description": " \"\"\"\n This is a class to process JSON file, including reading and writing JSON files, as well as processing JSON data by removing a specified key from the JSON object.\n \"\"\"\n", "class_name": "JSONProcessor", "test_classes": [ "JSONProcessorTestReadJson", "JSONProcessorTestWriteJson", "JSONProcessorTestProcessJsonExistingKey", "JSONProcessorTestMain" ], "class_constructor": "class JSONProcessor: \n", "fields": [], "methods_info": [ { "method_name": "read_json", "method_description": "def read_json(self, file_path):\n \"\"\"\n Read a JSON file and return the data.\n :param file_path: str, the path of the JSON file.\n :return: dict, the data from the JSON file if read successfully, or return -1 if an error occurs during the reading process.\n return 0 if the file does not exist.\n >>> json.read_json('test.json')\n {'name': 'test', 'age': 14}\n \"\"\"", "test_class": "JSONProcessorTestReadJson", "test_code": "class JSONProcessorTestReadJson(unittest.TestCase):\n def setUp(self):\n self.processor = JSONProcessor()\n self.test_data = {\n \"key1\": \"value1\",\n \"key2\": \"value2\",\n \"key3\": \"value3\"\n }\n self.file_path = \"test.json\"\n\n def tearDown(self):\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n\n # file exists\n def test_read_json_1(self):\n with open(self.file_path, 'w') as file:\n json.dump(self.test_data, file)\n result = self.processor.read_json(self.file_path)\n self.assertEqual(result, self.test_data)\n\n # file not exists\n def test_read_json_2(self):\n result = self.processor.read_json(self.file_path)\n self.assertEqual(result, 0)\n\n # invalid json file\n def test_read_json_3(self):\n with open(self.file_path, 'w') as file:\n file.write(\"Invalid JSON\")\n result = self.processor.read_json(self.file_path)\n self.assertEqual(result, -1)\n\n def test_read_json_4(self):\n result = self.processor.read_json('wrong')\n self.assertEqual(result, 0)\n\n def test_read_json_5(self):\n result = self.processor.read_json('abcd')\n self.assertEqual(result, 0)", "solution_code": "def read_json(self, file_path):\n if not os.path.exists(file_path):\n return 0\n try:\n with open(file_path, 'r') as file:\n data = json.load(file)\n return data\n except:\n return -1", "dependencies": { "Standalone": false, "lib_dependencies": [ "json", "os" ], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "write_json", "method_description": "def write_json(self, data, file_path):\n \"\"\"\n Write data to a JSON file and save it to the given path.\n\n :param data: dict, the data to be written to the JSON file.\n :param file_path: str, the path of the JSON file.\n :return: 1 if the writing process is successful, or -1, if an error occurs during the writing process.\n >>> json.write_json({'key1': 'value1', 'key2': 'value2'}, 'test.json')\n 1\n >>> json.read_json('test.json')\n {'key1': 'value1', 'key2': 'value2'}\n \"\"\"", "test_class": "JSONProcessorTestWriteJson", "test_code": "class JSONProcessorTestWriteJson(unittest.TestCase):\n def setUp(self):\n self.processor = JSONProcessor()\n self.test_data = {\n \"key1\": \"value1\",\n \"key2\": \"value2\",\n \"key3\": \"value3\"\n }\n self.file_path = \"test.json\"\n\n # create a read only file\n self.file_path_only_read = 'test_only_read.json'\n with open(self.file_path_only_read, 'w') as f:\n f.write('{\"key1\": \"value1\"}')\n\n # set file only read mode\n os.chmod(self.file_path_only_read, stat.S_IRUSR + stat.S_IRGRP + stat.S_IROTH)\n\n def tearDown(self):\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n if os.path.exists(self.file_path_only_read):\n # unset file only read mode and remove the file\n os.chmod(self.file_path_only_read,\n stat.S_IWUSR + stat.S_IRUSR + stat.S_IWGRP + stat.S_IRGRP + stat.S_IWOTH + stat.S_IROTH)\n os.remove(self.file_path_only_read)\n\n def test_write_json_1(self):\n result = self.processor.write_json(self.test_data, self.file_path)\n self.assertEqual(result, 1)\n with open(self.file_path, 'r') as file:\n written_data = json.load(file)\n self.assertEqual(written_data, self.test_data)\n\n def test_write_json_2(self):\n # Provide a read-only file path to simulate an exception\n result = self.processor.write_json(self.test_data, self.file_path_only_read)\n self.assertEqual(result, -1)\n\n def test_write_json_3(self):\n result = self.processor.write_json([], self.file_path_only_read)\n self.assertEqual(result, -1)\n\n def test_write_json_4(self):\n result = self.processor.write_json(self.test_data, '')\n self.assertEqual(result, -1)\n\n def test_write_json_5(self):\n result = self.processor.write_json([], '')\n self.assertEqual(result, -1)", "solution_code": "def write_json(self, data, file_path):\n try:\n with open(file_path, 'w') as file:\n json.dump(data, file)\n return 1\n except:\n return -1", "dependencies": { "Standalone": false, "lib_dependencies": [ "json" ], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "process_json", "method_description": "def process_json(self, file_path, remove_key):\n \"\"\"\n read a JSON file and process the data by removing a specified key and rewrite the modified data back to the file.\n\n :param file_path: str, the path of the JSON file.\n :param remove_key: str, the key to be removed.\n :return: 1, if the specified key is successfully removed and the data is written back.\n 0, if the file does not exist or the specified key does not exist in the data.\n >>> json.read_json('test.json')\n {'key1': 'value1', 'key2': 'value2'}\n >>> json.process_json('test.json', 'key1')\n 1\n >>> json.read_json('test.json')\n {'key2': 'value2'}\n \"\"\"", "test_class": "JSONProcessorTestProcessJsonExistingKey", "test_code": "class JSONProcessorTestProcessJsonExistingKey(unittest.TestCase):\n def setUp(self):\n self.processor = JSONProcessor()\n self.test_data = {\n \"key1\": \"value1\",\n \"key2\": \"value2\",\n \"key3\": \"value3\"\n }\n self.file_path = \"test.json\"\n\n def tearDown(self):\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n\n # key exists\n def test_process_json_1(self):\n with open(self.file_path, 'w') as file:\n json.dump(self.test_data, file)\n remove_key = \"key2\"\n self.processor.process_json(self.file_path, remove_key)\n with open(self.file_path, 'r') as file:\n processed_data = json.load(file)\n expected_data = {\n \"key1\": \"value1\",\n \"key3\": \"value3\"\n }\n self.assertEqual(processed_data, expected_data)\n\n # key not exists\n def test_process_json_2(self):\n with open(self.file_path, 'w') as file:\n json.dump(self.test_data, file)\n remove_key = \"nonexistent_key\"\n self.processor.process_json(self.file_path, remove_key)\n with open(self.file_path, 'r') as file:\n processed_data = json.load(file)\n self.assertEqual(processed_data, self.test_data)\n\n # file is empty\n def test_process_json_3(self):\n # Create an empty JSON file\n with open(self.file_path, 'w') as file:\n pass\n remove_key = \"key1\"\n self.assertEqual(self.processor.process_json(self.file_path, remove_key), 0)\n\n def test_process_json_4(self):\n with open(self.file_path, 'w') as file:\n json.dump(self.test_data, file)\n remove_key = \"aaa\"\n self.processor.process_json(self.file_path, remove_key)\n with open(self.file_path, 'r') as file:\n processed_data = json.load(file)\n self.assertEqual(processed_data, self.test_data)\n\n def test_process_json_5(self):\n with open(self.file_path, 'w') as file:\n json.dump(self.test_data, file)\n remove_key = \"bbb\"\n self.processor.process_json(self.file_path, remove_key)\n with open(self.file_path, 'r') as file:\n processed_data = json.load(file)\n self.assertEqual(processed_data, self.test_data)", "solution_code": "def process_json(self, file_path, remove_key):\n data = self.read_json(file_path)\n if data == 0 or data == -1:\n return 0\n if remove_key in data:\n del data[remove_key]\n self.write_json(data, file_path)\n return 1\n else:\n return 0", "dependencies": { "Standalone": false, "lib_dependencies": [ "json" ], "field_dependencies": [], "method_dependencies": [ "read_json", "write_json" ] } } ] }, { "task_id": "ClassEval_51", "skeleton": "\nimport numpy as np\n\nclass KappaCalculator:\n \"\"\"\n This is a class as KappaCalculator, supporting to calculate Cohen's and Fleiss' kappa coefficient.\n \"\"\"\n\n\n @staticmethod\n def kappa(testData, k):\n \"\"\"\n Calculate the cohens kappa value of a k-dimensional matrix\n :param testData: The k-dimensional matrix that needs to calculate the cohens kappa value\n :param k: int, Matrix dimension\n :return:float, the cohens kappa value of the matrix\n >>> KappaCalculator.kappa([[2, 1, 1], [1, 2, 1], [1, 1, 2]], 3)\n 0.25\n \"\"\"\n\n @staticmethod\n def fleiss_kappa(testData, N, k, n):\n \"\"\"\n Calculate the fliss kappa value of an N * k matrix\n :param testData: Input data matrix, N * k\n :param N: int, Number of samples\n :param k: int, Number of categories\n :param n: int, Number of raters\n :return: float, fleiss kappa value\n >>> KappaCalculator.fleiss_kappa([[0, 0, 0, 0, 14],\n >>> [0, 2, 6, 4, 2],\n >>> [0, 0, 3, 5, 6],\n >>> [0, 3, 9, 2, 0],\n >>> [2, 2, 8, 1, 1],\n >>> [7, 7, 0, 0, 0],\n >>> [3, 2, 6, 3, 0],\n >>> [2, 5, 3, 2, 2],\n >>> [6, 5, 2, 1, 0],\n >>> [0, 2, 2, 3, 7]], 10, 5, 14)\n 0.20993070442195522\n \"\"\"", "test": "import unittest\n\n\nclass KappaCalculatorTestKappa(unittest.TestCase):\n def test_kappa_1(self):\n self.assertEqual(KappaCalculator.kappa([[2, 1, 1], [1, 2, 1], [1, 1, 2]], 3), 0.25)\n\n def test_kappa_2(self):\n self.assertAlmostEqual(KappaCalculator.kappa([[2, 2, 1], [1, 2, 1], [1, 1, 2]], 3), 0.19469026548672572)\n\n def test_kappa_3(self):\n self.assertAlmostEqual(KappaCalculator.kappa([[2, 1, 2], [1, 2, 1], [1, 1, 2]], 3), 0.19469026548672572)\n\n def test_kappa_4(self):\n self.assertAlmostEqual(KappaCalculator.kappa([[2, 1, 1], [2, 2, 1], [1, 1, 2]], 3), 0.19469026548672572)\n\n def test_kappa_5(self):\n self.assertAlmostEqual(KappaCalculator.kappa([[2, 1, 1], [1, 2, 2], [1, 1, 2]], 3), 0.19469026548672572)\n\n\nclass KappaCalculatorTestFleissKappa(unittest.TestCase):\n def test_fleiss_kappa_1(self):\n self.assertEqual(KappaCalculator.fleiss_kappa([[0, 0, 0, 0, 14],\n [0, 2, 6, 4, 2],\n [0, 0, 3, 5, 6],\n [0, 3, 9, 2, 0],\n [2, 2, 8, 1, 1],\n [7, 7, 0, 0, 0],\n [3, 2, 6, 3, 0],\n [2, 5, 3, 2, 2],\n [6, 5, 2, 1, 0],\n [0, 2, 2, 3, 7]], 10, 5, 14), 0.20993070442195522)\n\n def test_fleiss_kappa_2(self):\n self.assertEqual(KappaCalculator.fleiss_kappa([[1, 0, 0, 0, 14],\n [0, 2, 6, 4, 2],\n [0, 0, 3, 5, 6],\n [0, 3, 9, 2, 0],\n [2, 2, 8, 1, 1],\n [7, 7, 0, 0, 0],\n [3, 2, 6, 3, 0],\n [2, 5, 3, 2, 2],\n [6, 5, 2, 1, 0],\n [0, 2, 2, 3, 7]], 10, 5, 14), 0.2115748928799344)\n\n def test_fleiss_kappa_3(self):\n self.assertEqual(KappaCalculator.fleiss_kappa([[0, 1, 0, 0, 14],\n [0, 2, 6, 4, 2],\n [0, 0, 3, 5, 6],\n [0, 3, 9, 2, 0],\n [2, 2, 8, 1, 1],\n [7, 7, 0, 0, 0],\n [3, 2, 6, 3, 0],\n [2, 5, 3, 2, 2],\n [6, 5, 2, 1, 0],\n [0, 2, 2, 3, 7]], 10, 5, 14), 0.21076904123090398)\n\n def test_fleiss_kappa_4(self):\n self.assertEqual(KappaCalculator.fleiss_kappa([[0, 0, 1, 0, 14],\n [0, 2, 6, 4, 2],\n [0, 0, 3, 5, 6],\n [0, 3, 9, 2, 0],\n [2, 2, 8, 1, 1],\n [7, 7, 0, 0, 0],\n [3, 2, 6, 3, 0],\n [2, 5, 3, 2, 2],\n [6, 5, 2, 1, 0],\n [0, 2, 2, 3, 7]], 10, 5, 14), 0.2096583016522883)\n\n def test_fleiss_kappa_5(self):\n self.assertEqual(KappaCalculator.fleiss_kappa([[0, 0, 0, 1, 14],\n [0, 2, 6, 4, 2],\n [0, 0, 3, 5, 6],\n [0, 3, 9, 2, 0],\n [2, 2, 8, 1, 1],\n [7, 7, 0, 0, 0],\n [3, 2, 6, 3, 0],\n [2, 5, 3, 2, 2],\n [6, 5, 2, 1, 0],\n [0, 2, 2, 3, 7]], 10, 5, 14), 0.21147425143148907)\n\n\nclass KappaCalculatorTest(unittest.TestCase):\n def test_kappacalculator(self):\n self.assertEqual(KappaCalculator.kappa([[2, 1, 1], [1, 2, 1], [1, 1, 2]], 3), 0.25)\n self.assertEqual(KappaCalculator.fleiss_kappa([[0, 0, 0, 0, 14],\n [0, 2, 6, 4, 2],\n [0, 0, 3, 5, 6],\n [0, 3, 9, 2, 0],\n [2, 2, 8, 1, 1],\n [7, 7, 0, 0, 0],\n [3, 2, 6, 3, 0],\n [2, 5, 3, 2, 2],\n [6, 5, 2, 1, 0],\n [0, 2, 2, 3, 7]], 10, 5, 14), 0.20993070442195522)", "solution_code": "import numpy as np\n\n\nclass KappaCalculator:\n\n @staticmethod\n def kappa(testData, k):\n dataMat = np.mat(testData)\n P0 = 0.0\n for i in range(k):\n P0 += dataMat[i, i] * 1.0\n xsum = np.sum(dataMat, axis=1)\n ysum = np.sum(dataMat, axis=0)\n sum = np.sum(dataMat)\n Pe = float(ysum * xsum) / sum / sum\n P0 = float(P0 / sum * 1.0)\n cohens_coefficient = float((P0 - Pe) / (1 - Pe))\n return cohens_coefficient\n\n @staticmethod\n def fleiss_kappa(testData, N, k, n):\n dataMat = np.mat(testData, float)\n oneMat = np.ones((k, 1))\n sum = 0.0\n P0 = 0.0\n for i in range(N):\n temp = 0.0\n for j in range(k):\n sum += dataMat[i, j]\n temp += 1.0 * dataMat[i, j] ** 2\n temp -= n\n temp /= (n - 1) * n\n P0 += temp\n P0 = 1.0 * P0 / N\n ysum = np.sum(dataMat, axis=0)\n for i in range(k):\n ysum[0, i] = (ysum[0, i] / sum) ** 2\n Pe = ysum * oneMat * 1.0\n ans = (P0 - Pe) / (1 - Pe)\n return ans[0, 0]", "import_statement": [ "import numpy as np" ], "class_description": " \"\"\"\n This is a class as KappaCalculator, supporting to calculate Cohen's and Fleiss' kappa coefficient.\n \"\"\"\n", "class_name": "KappaCalculator", "test_classes": [ "KappaCalculatorTestKappa", "KappaCalculatorTestFleissKappa", "KappaCalculatorTest" ], "class_constructor": "class KappaCalculator: \n", "fields": [], "methods_info": [ { "method_name": "kappa", "method_description": "def kappa(testData, k):\n \"\"\"\n Calculate the cohens kappa value of a k-dimensional matrix\n :param testData: The k-dimensional matrix that needs to calculate the cohens kappa value\n :param k: int, Matrix dimension\n :return:float, the cohens kappa value of the matrix\n >>> KappaCalculator.kappa([[2, 1, 1], [1, 2, 1], [1, 1, 2]], 3)\n 0.25\n \"\"\"", "test_class": "KappaCalculatorTestKappa", "test_code": "class KappaCalculatorTestKappa(unittest.TestCase):\n def test_kappa_1(self):\n self.assertEqual(KappaCalculator.kappa([[2, 1, 1], [1, 2, 1], [1, 1, 2]], 3), 0.25)\n\n def test_kappa_2(self):\n self.assertAlmostEqual(KappaCalculator.kappa([[2, 2, 1], [1, 2, 1], [1, 1, 2]], 3), 0.19469026548672572)\n\n def test_kappa_3(self):\n self.assertAlmostEqual(KappaCalculator.kappa([[2, 1, 2], [1, 2, 1], [1, 1, 2]], 3), 0.19469026548672572)\n\n def test_kappa_4(self):\n self.assertAlmostEqual(KappaCalculator.kappa([[2, 1, 1], [2, 2, 1], [1, 1, 2]], 3), 0.19469026548672572)\n\n def test_kappa_5(self):\n self.assertAlmostEqual(KappaCalculator.kappa([[2, 1, 1], [1, 2, 2], [1, 1, 2]], 3), 0.19469026548672572)", "solution_code": "def kappa(testData, k):\n dataMat = np.mat(testData)\n P0 = 0.0\n for i in range(k):\n P0 += dataMat[i, i] * 1.0\n xsum = np.sum(dataMat, axis=1)\n ysum = np.sum(dataMat, axis=0)\n sum = np.sum(dataMat)\n Pe = float(ysum * xsum) / sum / sum\n P0 = float(P0 / sum * 1.0)\n cohens_coefficient = float((P0 - Pe) / (1 - Pe))\n return cohens_coefficient", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "fleiss_kappa", "method_description": "@staticmethod\n def fleiss_kappa(testData, N, k, n):\n \"\"\"\n Calculate the fliss kappa value of an N * k matrix\n :param testData: Input data matrix, N * k\n :param N: int, Number of samples\n :param k: int, Number of categories\n :param n: int, Number of raters\n :return: float, fleiss kappa value\n >>> KappaCalculator.fleiss_kappa([[0, 0, 0, 0, 14],\n >>> [0, 2, 6, 4, 2],\n >>> [0, 0, 3, 5, 6],\n >>> [0, 3, 9, 2, 0],\n >>> [2, 2, 8, 1, 1],\n >>> [7, 7, 0, 0, 0],\n >>> [3, 2, 6, 3, 0],\n >>> [2, 5, 3, 2, 2],\n >>> [6, 5, 2, 1, 0],\n >>> [0, 2, 2, 3, 7]], 10, 5, 14)\n 0.20993070442195522\n \"\"\"", "test_class": "KappaCalculatorTestFleissKappa", "test_code": "class KappaCalculatorTestFleissKappa(unittest.TestCase):\n def test_fleiss_kappa_1(self):\n self.assertEqual(KappaCalculator.fleiss_kappa([[0, 0, 0, 0, 14],\n [0, 2, 6, 4, 2],\n [0, 0, 3, 5, 6],\n [0, 3, 9, 2, 0],\n [2, 2, 8, 1, 1],\n [7, 7, 0, 0, 0],\n [3, 2, 6, 3, 0],\n [2, 5, 3, 2, 2],\n [6, 5, 2, 1, 0],\n [0, 2, 2, 3, 7]], 10, 5, 14), 0.20993070442195522)\n\n def test_fleiss_kappa_2(self):\n self.assertEqual(KappaCalculator.fleiss_kappa([[1, 0, 0, 0, 14],\n [0, 2, 6, 4, 2],\n [0, 0, 3, 5, 6],\n [0, 3, 9, 2, 0],\n [2, 2, 8, 1, 1],\n [7, 7, 0, 0, 0],\n [3, 2, 6, 3, 0],\n [2, 5, 3, 2, 2],\n [6, 5, 2, 1, 0],\n [0, 2, 2, 3, 7]], 10, 5, 14), 0.2115748928799344)\n\n def test_fleiss_kappa_3(self):\n self.assertEqual(KappaCalculator.fleiss_kappa([[0, 1, 0, 0, 14],\n [0, 2, 6, 4, 2],\n [0, 0, 3, 5, 6],\n [0, 3, 9, 2, 0],\n [2, 2, 8, 1, 1],\n [7, 7, 0, 0, 0],\n [3, 2, 6, 3, 0],\n [2, 5, 3, 2, 2],\n [6, 5, 2, 1, 0],\n [0, 2, 2, 3, 7]], 10, 5, 14), 0.21076904123090398)\n\n def test_fleiss_kappa_4(self):\n self.assertEqual(KappaCalculator.fleiss_kappa([[0, 0, 1, 0, 14],\n [0, 2, 6, 4, 2],\n [0, 0, 3, 5, 6],\n [0, 3, 9, 2, 0],\n [2, 2, 8, 1, 1],\n [7, 7, 0, 0, 0],\n [3, 2, 6, 3, 0],\n [2, 5, 3, 2, 2],\n [6, 5, 2, 1, 0],\n [0, 2, 2, 3, 7]], 10, 5, 14), 0.2096583016522883)\n\n def test_fleiss_kappa_5(self):\n self.assertEqual(KappaCalculator.fleiss_kappa([[0, 0, 0, 1, 14],\n [0, 2, 6, 4, 2],\n [0, 0, 3, 5, 6],\n [0, 3, 9, 2, 0],\n [2, 2, 8, 1, 1],\n [7, 7, 0, 0, 0],\n [3, 2, 6, 3, 0],\n [2, 5, 3, 2, 2],\n [6, 5, 2, 1, 0],\n [0, 2, 2, 3, 7]], 10, 5, 14), 0.21147425143148907)", "solution_code": "@staticmethod\n def fleiss_kappa(testData, N, k, n):\n dataMat = np.mat(testData, float)\n oneMat = np.ones((k, 1))\n sum = 0.0\n P0 = 0.0\n for i in range(N):\n temp = 0.0\n for j in range(k):\n sum += dataMat[i, j]\n temp += 1.0 * dataMat[i, j] ** 2\n temp -= n\n temp /= (n - 1) * n\n P0 += temp\n P0 = 1.0 * P0 / N\n ysum = np.sum(dataMat, axis=0)\n for i in range(k):\n ysum[0, i] = (ysum[0, i] / sum) ** 2\n Pe = ysum * oneMat * 1.0\n ans = (P0 - Pe) / (1 - Pe)\n return ans[0, 0]", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_52", "skeleton": "\nimport nltk\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk import pos_tag, word_tokenize\nimport string\n\nnltk.download('averaged_perceptron_tagger')\nnltk.download('punkt')\n\n\nclass Lemmatization:\n \"\"\"\n This is a class about Lemmatization, which utilizes the nltk library to perform lemmatization and part-of-speech tagging on sentences, as well as remove punctuation.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n creates a WordNetLemmatizer object and stores it in the self.lemmatizer member variable.\n \"\"\"\n self.lemmatizer = WordNetLemmatizer()\n\n def lemmatize_sentence(self, sentence):\n \"\"\"\n Remove punctuations of the sentence and tokenizes the input sentence, mark the part of speech tag of each word,\n lemmatizes the words with different parameters based on their parts of speech, and stores in a list.\n :param sentence: a sentence str\n :return: a list of words which have been lemmatized.\n >>> lemmatization = Lemmatization()\n >>> lemmatization.lemmatize_sentence(\"I am running in a race.\")\n ['I', 'be', 'run', 'in', 'a', 'race']\n \"\"\"\n\n def get_pos_tag(self, sentence):\n \"\"\"\n Remove punctuations of the sentence and tokenizes the input sentence, mark the part of speech tag of each word.\n :param sentence: a sentence str\n :return: list, part of speech tag of each word in the sentence.\n >>> lemmatization = Lemmatization()\n >>> lemmatization.get_pos_tag(\"I am running in a race.\")\n ['PRP', 'VBP', 'VBG', 'IN', 'DT', 'NN']\n \"\"\"\n\n def remove_punctuation(self, sentence):\n \"\"\"\n Removes punctuation from the input text.\n :param sentence: a sentence str\n :return: str, sentence without any punctuation\n >>> lemmatization = Lemmatization()\n >>> lemmatization.remove_punctuation(\"I am running in a race.\")\n 'I am running in a race'\n \"\"\"", "test": "import unittest\n\n\nclass LemmatizationTestLemmatizeSentence(unittest.TestCase):\n def test_lemmatize_sentence_1(self):\n lemmatization = Lemmatization()\n result = lemmatization.lemmatize_sentence(\"I am running in a race.\")\n expected = ['I', 'be', 'run', 'in', 'a', 'race']\n self.assertEqual(result, expected)\n\n def test_lemmatize_sentence_2(self):\n lemmatization = Lemmatization()\n result = lemmatization.lemmatize_sentence(\"Until the beating, Cantanco's eyesight had been weak, but adequate.\")\n expected = ['Until', 'the', 'beating', 'Cantancos', 'eyesight', 'have', 'be', 'weak', 'but', 'adequate']\n self.assertEqual(result, expected)\n\n def test_lammatize_sentence_3(self):\n lemmatization = Lemmatization()\n result = lemmatization.lemmatize_sentence(\"The dog's barked at the mailman.\")\n expected = ['The', 'dog', 'bark', 'at', 'the', 'mailman']\n self.assertEqual(result, expected)\n\n def test_lemmatize_sentence_4(self):\n lemmatization = Lemmatization()\n result = lemmatization.lemmatize_sentence(\"He was running and eating at same time. \")\n expected = ['He', 'be', 'run', 'and', 'eat', 'at', 'same', 'time']\n self.assertEqual(result, expected)\n\n def test_lemmatize_sentence_5(self):\n lemmatization = Lemmatization()\n result = lemmatization.lemmatize_sentence(\"I was taking a ride in the car.\")\n expected = ['I', 'be', 'take', 'a', 'ride', 'in', 'the', 'car']\n self.assertEqual(result, expected)\n\nclass LemmatizationTestGetPosTag(unittest.TestCase):\n def test_get_pos_tag_1(self):\n lemmatization = Lemmatization()\n result = lemmatization.get_pos_tag(\"I am running in a race.\")\n expected = ['PRP', 'VBP', 'VBG', 'IN', 'DT', 'NN']\n self.assertEqual(result, expected)\n\n def test_get_pos_tag_2(self):\n lemmatization = Lemmatization()\n result = lemmatization.get_pos_tag(\"Cantanco's eyesight had been weak, but adequate.\")\n expected = ['NNP', 'NN', 'VBD', 'VBN', 'JJ', 'CC', 'JJ']\n self.assertEqual(result, expected)\n\n def test_get_pos_tag_3(self):\n lemmatization = Lemmatization()\n result = lemmatization.get_pos_tag(\"The dog's barked at the mailman.\")\n expected = ['DT', 'NNS', 'VBD', 'IN', 'DT', 'NN']\n self.assertEqual(result, expected)\n\n def test_get_pos_tag_4(self):\n lemmatization = Lemmatization()\n result = lemmatization.get_pos_tag(\"He was running and eating at same time. \")\n expected = ['PRP', 'VBD', 'VBG', 'CC', 'VBG', 'IN', 'JJ', 'NN']\n self.assertEqual(result, expected)\n\n def test_get_pos_tag_5(self):\n lemmatization = Lemmatization()\n result = lemmatization.get_pos_tag(\"I was taking a ride in the car.\")\n expected = ['PRP', 'VBD', 'VBG', 'DT', 'NN', 'IN', 'DT', 'NN']\n self.assertEqual(result, expected)\n\n\nclass LemmatizationTestRemovePunctuation(unittest.TestCase):\n def test_remove_punctuation_1(self):\n lemmatization = Lemmatization()\n result = lemmatization.remove_punctuation(\"I am running in a race.\")\n expected = \"I am running in a race\"\n self.assertEqual(result, expected)\n\n def test_remove_punctuation_2(self):\n lemmatization = Lemmatization()\n result = lemmatization.remove_punctuation(\"Until the beating, Cantanco's eyesight had been weak, but adequate.\")\n expected = 'Until the beating Cantancos eyesight had been weak but adequate'\n self.assertEqual(result, expected)\n\n def test_remove_punctuation_3(self):\n lemmatization = Lemmatization()\n result = lemmatization.remove_punctuation(\"The dog's barked at the mailman!!!\")\n expected = 'The dogs barked at the mailman'\n self.assertEqual(result, expected)\n\n def test_remove_punctuation_4(self):\n lemmatization = Lemmatization()\n result = lemmatization.remove_punctuation(\"He was running and eating at same time... \")\n expected = 'He was running and eating at same time '\n self.assertEqual(result, expected)\n\n def test_remove_punctuation_5(self):\n lemmatization = Lemmatization()\n result = lemmatization.remove_punctuation(\"Is this a test? I hope it is...\")\n expected = 'Is this a test I hope it is'\n self.assertEqual(result, expected)\n\nclass LemmatizationTestMain(unittest.TestCase):\n def test_main(self):\n lemmatization = Lemmatization()\n result = lemmatization.lemmatize_sentence(\"Until the beating, Cantanco's eyesight had been weak, but adequate.\")\n expected = ['Until', 'the', 'beating', 'Cantancos', 'eyesight', 'have', 'be', 'weak', 'but', 'adequate']\n self.assertEqual(result, expected)\n\n result = lemmatization.get_pos_tag(\"Cantanco's eyesight had been weak, but adequate.\")\n expected = ['NNP', 'NN', 'VBD', 'VBN', 'JJ', 'CC', 'JJ']\n self.assertEqual(result, expected)", "solution_code": "import nltk\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk import pos_tag, word_tokenize\nimport string\n\nnltk.download('averaged_perceptron_tagger')\nnltk.download('punkt')\n\n\nclass Lemmatization:\n def __init__(self):\n self.lemmatizer = WordNetLemmatizer()\n\n def lemmatize_sentence(self, sentence):\n lemmatized_words = []\n sentence = self.remove_punctuation(sentence)\n words = word_tokenize(sentence)\n tagged_words = pos_tag(words)\n for word, tag in tagged_words:\n if tag.startswith('V'):\n lemmatized_word = self.lemmatizer.lemmatize(word, pos='v')\n elif tag.startswith('J'):\n lemmatized_word = self.lemmatizer.lemmatize(word, pos='a')\n elif tag.startswith('R'):\n lemmatized_word = self.lemmatizer.lemmatize(word, pos='r')\n else:\n lemmatized_word = self.lemmatizer.lemmatize(word)\n lemmatized_words.append(lemmatized_word)\n return lemmatized_words\n\n def get_pos_tag(self, sentence):\n pos_tags = []\n sentence = self.remove_punctuation(sentence)\n words = word_tokenize(sentence)\n tagged_words = pos_tag(words)\n for tagged_word in tagged_words:\n pos_tags.append(tagged_word[1])\n return pos_tags\n\n def remove_punctuation(self, sentence):\n return sentence.translate(str.maketrans('', '', string.punctuation))", "import_statement": [ "import nltk", "from nltk.stem import WordNetLemmatizer", "from nltk import pos_tag, word_tokenize", "import string" ], "class_description": " \"\"\"\n This is a class about Lemmatization, which utilizes the nltk library to perform lemmatization and part-of-speech tagging on sentences, as well as remove punctuation.\n \"\"\"\n", "class_name": "Lemmatization", "test_classes": [ "LemmatizationTestLemmatizeSentence", "LemmatizationTestGetPosTag", "LemmatizationTestRemovePunctuation", "LemmatizationTestMain" ], "class_constructor": "class Lemmatization: \n def __init__(self):\n \"\"\"\n creates a WordNetLemmatizer object and stores it in the self.lemmatizer member variable.\n \"\"\"\n self.lemmatizer = WordNetLemmatizer()\n\n", "fields": [ "self.lemmatizer" ], "methods_info": [ { "method_name": "lemmatize_sentence", "method_description": "def lemmatize_sentence(self, sentence):\n \"\"\"\n Remove punctuations of the sentence and tokenizes the input sentence, mark the part of speech tag of each word,\n lemmatizes the words with different parameters based on their parts of speech, and stores in a list.\n :param sentence: a sentence str\n :return: a list of words which have been lemmatized.\n >>> lemmatization = Lemmatization()\n >>> lemmatization.lemmatize_sentence(\"I am running in a race.\")\n ['I', 'be', 'run', 'in', 'a', 'race']\n \"\"\"", "test_class": "LemmatizationTestLemmatizeSentence", "test_code": "class LemmatizationTestLemmatizeSentence(unittest.TestCase):\n def test_lemmatize_sentence_1(self):\n lemmatization = Lemmatization()\n result = lemmatization.lemmatize_sentence(\"I am running in a race.\")\n expected = ['I', 'be', 'run', 'in', 'a', 'race']\n self.assertEqual(result, expected)\n\n def test_lemmatize_sentence_2(self):\n lemmatization = Lemmatization()\n result = lemmatization.lemmatize_sentence(\"Until the beating, Cantanco's eyesight had been weak, but adequate.\")\n expected = ['Until', 'the', 'beating', 'Cantancos', 'eyesight', 'have', 'be', 'weak', 'but', 'adequate']\n self.assertEqual(result, expected)\n\n def test_lammatize_sentence_3(self):\n lemmatization = Lemmatization()\n result = lemmatization.lemmatize_sentence(\"The dog's barked at the mailman.\")\n expected = ['The', 'dog', 'bark', 'at', 'the', 'mailman']\n self.assertEqual(result, expected)\n\n def test_lemmatize_sentence_4(self):\n lemmatization = Lemmatization()\n result = lemmatization.lemmatize_sentence(\"He was running and eating at same time. \")\n expected = ['He', 'be', 'run', 'and', 'eat', 'at', 'same', 'time']\n self.assertEqual(result, expected)\n\n def test_lemmatize_sentence_5(self):\n lemmatization = Lemmatization()\n result = lemmatization.lemmatize_sentence(\"I was taking a ride in the car.\")\n expected = ['I', 'be', 'take', 'a', 'ride', 'in', 'the', 'car']\n self.assertEqual(result, expected)", "solution_code": "def lemmatize_sentence(self, sentence):\n lemmatized_words = []\n sentence = self.remove_punctuation(sentence)\n words = word_tokenize(sentence)\n tagged_words = pos_tag(words)\n for word, tag in tagged_words:\n if tag.startswith('V'):\n lemmatized_word = self.lemmatizer.lemmatize(word, pos='v')\n elif tag.startswith('J'):\n lemmatized_word = self.lemmatizer.lemmatize(word, pos='a')\n elif tag.startswith('R'):\n lemmatized_word = self.lemmatizer.lemmatize(word, pos='r')\n else:\n lemmatized_word = self.lemmatizer.lemmatize(word)\n lemmatized_words.append(lemmatized_word)\n return lemmatized_words", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.lemmatizer" ], "method_dependencies": [ "remove_punctuation" ] } }, { "method_name": "get_pos_tag", "method_description": "def get_pos_tag(self, sentence):\n \"\"\"\n Remove punctuations of the sentence and tokenizes the input sentence, mark the part of speech tag of each word.\n :param sentence: a sentence str\n :return: list, part of speech tag of each word in the sentence.\n >>> lemmatization = Lemmatization()\n >>> lemmatization.get_pos_tag(\"I am running in a race.\")\n ['PRP', 'VBP', 'VBG', 'IN', 'DT', 'NN']\n \"\"\"", "test_class": "LemmatizationTestGetPosTag", "test_code": "class LemmatizationTestGetPosTag(unittest.TestCase):\n def test_get_pos_tag_1(self):\n lemmatization = Lemmatization()\n result = lemmatization.get_pos_tag(\"I am running in a race.\")\n expected = ['PRP', 'VBP', 'VBG', 'IN', 'DT', 'NN']\n self.assertEqual(result, expected)\n\n def test_get_pos_tag_2(self):\n lemmatization = Lemmatization()\n result = lemmatization.get_pos_tag(\"Cantanco's eyesight had been weak, but adequate.\")\n expected = ['NNP', 'NN', 'VBD', 'VBN', 'JJ', 'CC', 'JJ']\n self.assertEqual(result, expected)\n\n def test_get_pos_tag_3(self):\n lemmatization = Lemmatization()\n result = lemmatization.get_pos_tag(\"The dog's barked at the mailman.\")\n expected = ['DT', 'NNS', 'VBD', 'IN', 'DT', 'NN']\n self.assertEqual(result, expected)\n\n def test_get_pos_tag_4(self):\n lemmatization = Lemmatization()\n result = lemmatization.get_pos_tag(\"He was running and eating at same time. \")\n expected = ['PRP', 'VBD', 'VBG', 'CC', 'VBG', 'IN', 'JJ', 'NN']\n self.assertEqual(result, expected)\n\n def test_get_pos_tag_5(self):\n lemmatization = Lemmatization()\n result = lemmatization.get_pos_tag(\"I was taking a ride in the car.\")\n expected = ['PRP', 'VBD', 'VBG', 'DT', 'NN', 'IN', 'DT', 'NN']\n self.assertEqual(result, expected)", "solution_code": "def get_pos_tag(self, sentence):\n pos_tags = []\n sentence = self.remove_punctuation(sentence)\n words = word_tokenize(sentence)\n tagged_words = pos_tag(words)\n for tagged_word in tagged_words:\n pos_tags.append(tagged_word[1])\n return pos_tags", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "remove_punctuation" ] } }, { "method_name": "remove_punctuation", "method_description": "def remove_punctuation(self, sentence):\n \"\"\"\n Removes punctuation from the input text.\n :param sentence: a sentence str\n :return: str, sentence without any punctuation\n >>> lemmatization = Lemmatization()\n >>> lemmatization.remove_punctuation(\"I am running in a race.\")\n 'I am running in a race'\n \"\"\"", "test_class": "LemmatizationTestRemovePunctuation", "test_code": "class LemmatizationTestRemovePunctuation(unittest.TestCase):\n def test_remove_punctuation_1(self):\n lemmatization = Lemmatization()\n result = lemmatization.remove_punctuation(\"I am running in a race.\")\n expected = \"I am running in a race\"\n self.assertEqual(result, expected)\n\n def test_remove_punctuation_2(self):\n lemmatization = Lemmatization()\n result = lemmatization.remove_punctuation(\"Until the beating, Cantanco's eyesight had been weak, but adequate.\")\n expected = 'Until the beating Cantancos eyesight had been weak but adequate'\n self.assertEqual(result, expected)\n\n def test_remove_punctuation_3(self):\n lemmatization = Lemmatization()\n result = lemmatization.remove_punctuation(\"The dog's barked at the mailman!!!\")\n expected = 'The dogs barked at the mailman'\n self.assertEqual(result, expected)\n\n def test_remove_punctuation_4(self):\n lemmatization = Lemmatization()\n result = lemmatization.remove_punctuation(\"He was running and eating at same time... \")\n expected = 'He was running and eating at same time '\n self.assertEqual(result, expected)\n\n def test_remove_punctuation_5(self):\n lemmatization = Lemmatization()\n result = lemmatization.remove_punctuation(\"Is this a test? I hope it is...\")\n expected = 'Is this a test I hope it is'\n self.assertEqual(result, expected)", "solution_code": "def remove_punctuation(self, sentence):\n return sentence.translate(str.maketrans('', '', string.punctuation))", "dependencies": { "Standalone": false, "lib_dependencies": [ "string" ], "field_dependencies": [], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_53", "skeleton": "\nimport re\nimport string\n\nclass LongestWord:\n \"\"\"\n This is a class allows to add words to a list and find the longest word in a given sentence by comparing the words with the ones in the word list.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialize a list of word.\n \"\"\"\n self.word_list = []\n\n def add_word(self, word):\n \"\"\"\n append the input word into self.word_list\n :param word: str, input word\n \"\"\"\n\n def find_longest_word(self, sentence):\n \"\"\"\n Remove punctuation marks and split a sentence into a list of word. Find the longest splited word that is in the self.word_list.\n Words are strictly case sensitive.\n :param sentence: a sentence str\n :return str: longest splited word that is in the self.word_list. return '' if self.word_list is empty.\n >>> longestWord = LongestWord()\n >>> longestWord.add_word('A')\n >>> longestWord.add_word('aM')\n >>> longestWord.find_longest_word('I am a student.')\n 'a'\n \"\"\"", "test": "import unittest\n\nclass LongestWordTestAddWord(unittest.TestCase):\n def test_add_word_1(self):\n longestWord = LongestWord()\n longestWord.add_word(\"hello\")\n self.assertEqual(['hello'], longestWord.word_list)\n\n def test_add_word_2(self):\n longestWord = LongestWord()\n longestWord.add_word(\"hello\")\n longestWord.add_word(\"world\")\n self.assertEqual(['hello', 'world'], longestWord.word_list)\n\n def test_add_word_3(self):\n longestWord = LongestWord()\n longestWord.add_word(\"hello\")\n longestWord.add_word(\"world\")\n longestWord.add_word(\"!\")\n self.assertEqual(['hello', 'world', '!'], longestWord.word_list)\n\n def test_add_word_4(self):\n longestWord = LongestWord()\n longestWord.add_word(\"hello\")\n longestWord.add_word(\"world\")\n longestWord.add_word(\"!\")\n longestWord.add_word(\"!\")\n self.assertEqual(['hello', 'world', '!', '!'], longestWord.word_list)\n\n def test_add_word_5(self):\n longestWord = LongestWord()\n longestWord.add_word(\"hello\")\n longestWord.add_word(\"world\")\n longestWord.add_word(\"!\")\n longestWord.add_word(\"!\")\n longestWord.add_word(\"!\")\n self.assertEqual(['hello', 'world', '!', '!', '!'], longestWord.word_list)\n\n\nclass LongestWordTestFindLongestWord(unittest.TestCase):\n def test_find_longest_word_1(self):\n longestWord = LongestWord()\n longestWord.add_word(\"a\")\n sentence = 'I am a student.'\n self.assertEqual('a', longestWord.find_longest_word(sentence))\n\n def test_find_longest_word_2(self):\n longestWord = LongestWord()\n sentence = 'I am a student.'\n self.assertEqual('', longestWord.find_longest_word(sentence))\n\n def test_find_longest_word_3(self):\n longestWord = LongestWord()\n longestWord.add_word(\"student\")\n sentence = 'I am a student.'\n self.assertEqual('student', longestWord.find_longest_word(sentence))\n\n def test_find_longest_word_4(self):\n longestWord = LongestWord()\n longestWord.add_word(\"apple\")\n sentence = 'Apple is red.'\n self.assertEqual('apple', longestWord.find_longest_word(sentence))\n\n def test_find_longest_word_5(self):\n longestWord = LongestWord()\n longestWord.add_word(\"apple\")\n longestWord.add_word(\"red\")\n sentence = 'Apple is red.'\n self.assertEqual('apple', longestWord.find_longest_word(sentence))", "solution_code": "import re\nimport string\n\n\nclass LongestWord:\n\n def __init__(self):\n self.word_list = []\n\n def add_word(self, word):\n self.word_list.append(word)\n\n def find_longest_word(self, sentence):\n longest_word = \"\"\n sentence = sentence.lower()\n sentence = re.sub('[%s]' % re.escape(string.punctuation), '', sentence)\n sentence = re.split(' ', sentence)\n for word in sentence:\n if word in self.word_list and len(word) > len(longest_word):\n longest_word = word\n return longest_word", "import_statement": [ "import re", "import string" ], "class_description": " \"\"\"\n This is a class allows to add words to a list and find the longest word in a given sentence by comparing the words with the ones in the word list.\n \"\"\"\n", "class_name": "LongestWord", "test_classes": [ "LongestWordTestAddWord", "LongestWordTestFindLongestWord" ], "class_constructor": "class LongestWord: \n def __init__(self):\n \"\"\"\n Initialize a list of word.\n \"\"\"\n self.word_list = []\n\n", "fields": [ "self.word_list" ], "methods_info": [ { "method_name": "add_word", "method_description": "def add_word(self, word):\n \"\"\"\n append the input word into self.word_list\n :param word: str, input word\n \"\"\"", "test_class": "LongestWordTestAddWord", "test_code": "class LongestWordTestAddWord(unittest.TestCase):\n def test_add_word_1(self):\n longestWord = LongestWord()\n longestWord.add_word(\"hello\")\n self.assertEqual(['hello'], longestWord.word_list)\n\n def test_add_word_2(self):\n longestWord = LongestWord()\n longestWord.add_word(\"hello\")\n longestWord.add_word(\"world\")\n self.assertEqual(['hello', 'world'], longestWord.word_list)\n\n def test_add_word_3(self):\n longestWord = LongestWord()\n longestWord.add_word(\"hello\")\n longestWord.add_word(\"world\")\n longestWord.add_word(\"!\")\n self.assertEqual(['hello', 'world', '!'], longestWord.word_list)\n\n def test_add_word_4(self):\n longestWord = LongestWord()\n longestWord.add_word(\"hello\")\n longestWord.add_word(\"world\")\n longestWord.add_word(\"!\")\n longestWord.add_word(\"!\")\n self.assertEqual(['hello', 'world', '!', '!'], longestWord.word_list)\n\n def test_add_word_5(self):\n longestWord = LongestWord()\n longestWord.add_word(\"hello\")\n longestWord.add_word(\"world\")\n longestWord.add_word(\"!\")\n longestWord.add_word(\"!\")\n longestWord.add_word(\"!\")\n self.assertEqual(['hello', 'world', '!', '!', '!'], longestWord.word_list)", "solution_code": "def add_word(self, word):\n self.word_list.append(word)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.word_list" ], "method_dependencies": [] } }, { "method_name": "find_longest_word", "method_description": "def find_longest_word(self, sentence):\n \"\"\"\n Remove punctuation marks and split a sentence into a list of word. Find the longest splited word that is in the self.word_list.\n Words are strictly case sensitive.\n :param sentence: a sentence str\n :return str: longest splited word that is in the self.word_list. return '' if self.word_list is empty.\n >>> longestWord = LongestWord()\n >>> longestWord.add_word('A')\n >>> longestWord.add_word('aM')\n >>> longestWord.find_longest_word('I am a student.')\n 'a'\n \"\"\"", "test_class": "LongestWordTestFindLongestWord", "test_code": "class LongestWordTestFindLongestWord(unittest.TestCase):\n def test_find_longest_word_1(self):\n longestWord = LongestWord()\n longestWord.add_word(\"a\")\n sentence = 'I am a student.'\n self.assertEqual('a', longestWord.find_longest_word(sentence))\n\n def test_find_longest_word_2(self):\n longestWord = LongestWord()\n sentence = 'I am a student.'\n self.assertEqual('', longestWord.find_longest_word(sentence))\n\n def test_find_longest_word_3(self):\n longestWord = LongestWord()\n longestWord.add_word(\"student\")\n sentence = 'I am a student.'\n self.assertEqual('student', longestWord.find_longest_word(sentence))\n\n def test_find_longest_word_4(self):\n longestWord = LongestWord()\n longestWord.add_word(\"apple\")\n sentence = 'Apple is red.'\n self.assertEqual('apple', longestWord.find_longest_word(sentence))\n\n def test_find_longest_word_5(self):\n longestWord = LongestWord()\n longestWord.add_word(\"apple\")\n longestWord.add_word(\"red\")\n sentence = 'Apple is red.'\n self.assertEqual('apple', longestWord.find_longest_word(sentence))", "solution_code": "def find_longest_word(self, sentence):\n longest_word = \"\"\n sentence = sentence.lower()\n sentence = re.sub('[%s]' % re.escape(string.punctuation), '', sentence)\n sentence = re.split(' ', sentence)\n for word in sentence:\n if word in self.word_list and len(word) > len(longest_word):\n longest_word = word\n return longest_word", "dependencies": { "Standalone": false, "lib_dependencies": [ "re", "string" ], "field_dependencies": [ "self.word_list" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_54", "skeleton": "\nimport random\n\nclass MahjongConnect:\n \"\"\"\n MahjongConnect is a class representing a game board for Mahjong Connect with features like creating the board, checking valid moves, finding paths, removing icons, and checking if the game is over.\n \"\"\"\n\n def __init__(self, BOARD_SIZE, ICONS):\n \"\"\"\n initialize the board size and the icon list, create the game board\n :param BOARD_SIZE: list of two integer numbers, representing the number of rows and columns of the game board\n :param ICONS: list of string, representing the icons\n >>>mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.BOARD_SIZE = [4, 4]\n mc.ICONS = ['a', 'b', 'c']\n mc.board = mc.create_board()\n \"\"\"\n self.BOARD_SIZE = BOARD_SIZE\n self.ICONS = ICONS\n self.board = self.create_board()\n\n def create_board(self):\n \"\"\"\n create the game board with the given board size and icons\n :return: 2-dimensional list, the game board\n >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n >>> mc.create_board()\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n \"\"\"\n\n def is_valid_move(self, pos1, pos2):\n \"\"\"\n check if the move of two icons is valid (i.e. positions are within the game board range, the two positions are not the same, the two positions have the same icon, and there is a valid path between the two positions)\n :param pos1: position tuple(x, y) of the first icon\n :param pos2: position tuple(x, y) of the second icon\n :return:True or False ,representing whether the move of two icons is valid\n >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n >>> mc.is_valid_move((0, 0), (1, 0))\n True\n \"\"\"\n\n\n def has_path(self, pos1, pos2):\n \"\"\"\n check if there is a path between two icons\n :param pos1: position tuple(x, y) of the first icon\n :param pos2: position tuple(x, y) of the second icon\n :return: True or False ,representing whether there is a path between two icons\n >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n >>> mc.is_valid_move((0, 0), (1, 0))\n True\n \"\"\"\n\n\n def remove_icons(self, pos1, pos2):\n \"\"\"\n remove the connected icons on the game board\n :param pos1: position tuple(x, y) of the first icon to be removed\n :param pos2: position tuple(x, y) of the second icon to be removed\n :return: None\n >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n >>> mc.remove_icons((0, 0), (1, 0))\n mc.board = [[' ', 'b', 'c', 'a'],\n [' ', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n \"\"\"\n\n\n def is_game_over(self):\n \"\"\"\n Check if the game is over (i.e., if there are no more icons on the game board)\n :return: True or False ,representing whether the game is over\n >>> mc = MahjongConnect([4, 4] ['a', 'b', 'c'])\n >>> mc.board = [[' ', ' ', ' ', ' '],\n >>> [' ', ' ', ' ', ' '],\n >>> [' ', ' ', ' ', ' '],\n >>> [' ', ' ', ' ', ' ']]\n >>> mc.is_game_over()\n True\n \"\"\"", "test": "import unittest\n\n\nclass MahjongConnectTestCreateBoard(unittest.TestCase):\n def test_create_board_1(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n self.assertEqual(mc.BOARD_SIZE, [4, 4])\n self.assertEqual(mc.ICONS, ['a', 'b', 'c'])\n for row in mc.board:\n for icon in row:\n self.assertIn(icon, mc.ICONS)\n\n def test_create_board_2(self):\n mc = MahjongConnect([2, 2], ['a', 'b', 'c'])\n self.assertEqual(mc.BOARD_SIZE, [2, 2])\n self.assertEqual(mc.ICONS, ['a', 'b', 'c'])\n for row in mc.board:\n for icon in row:\n self.assertIn(icon, mc.ICONS)\n\n def test_create_board_3(self):\n mc = MahjongConnect([3, 3], ['a', 'b', 'c'])\n self.assertEqual(mc.BOARD_SIZE, [3, 3])\n self.assertEqual(mc.ICONS, ['a', 'b', 'c'])\n for row in mc.board:\n for icon in row:\n self.assertIn(icon, mc.ICONS)\n\n def test_create_board_4(self):\n mc = MahjongConnect([1, 1], ['a', 'b', 'c'])\n self.assertEqual(mc.BOARD_SIZE, [1, 1])\n self.assertEqual(mc.ICONS, ['a', 'b', 'c'])\n for row in mc.board:\n for icon in row:\n self.assertIn(icon, mc.ICONS)\n\n def test_create_board_5(self):\n mc = MahjongConnect([5, 5], ['a', 'b', 'c'])\n self.assertEqual(mc.BOARD_SIZE, [5, 5])\n self.assertEqual(mc.ICONS, ['a', 'b', 'c'])\n for row in mc.board:\n for icon in row:\n self.assertIn(icon, mc.ICONS)\n\n\nclass MahjongConnectTestIsValidMove(unittest.TestCase):\n def test_is_valid_move_1(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.is_valid_move((0, 0), (1, 0))\n self.assertEqual(res, True)\n\n def test_is_valid_move_2(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.is_valid_move((0, 0), (0, 1))\n self.assertEqual(res, False)\n\n def test_is_valid_move_3(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.is_valid_move((-1, 0), (0, 1))\n self.assertEqual(res, False)\n\n def test_is_valid_move_4(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.is_valid_move((0, 0), (0, 0))\n self.assertEqual(res, False)\n\n def test_is_valid_move_5(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.is_valid_move((300, 0), (0, 0))\n self.assertEqual(res, False)\n\n def test_is_valid_move_6(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'a', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.is_valid_move((0, 2), (0, 0))\n self.assertEqual(res, False)\n\n\nclass MahjongConnectTestHasPath(unittest.TestCase):\n def test_has_path_1(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.has_path((0, 0), (1, 0))\n self.assertEqual(res, True)\n\n def test_has_path_2(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.has_path((0, 0), (0, 0))\n self.assertEqual(res, True)\n\n def test_has_path_3(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.has_path((0, 0), (3, 0))\n self.assertEqual(res, True)\n\n def test_has_path_4(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.has_path((0, 0), (1, 1))\n self.assertEqual(res, False)\n\n def test_has_path_5(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.has_path((300, 0), (1, 1))\n self.assertEqual(res, False)\n\n def test_has_path_6(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'a', 'a', 'a'],\n ['a', 'a', 'a', 'a'],\n ['a', 'a', 'a', 'a'],\n ['a', 'a', 'a', 'a']]\n res = mc.has_path((0, 0), (3, 3))\n self.assertEqual(res, True)\n\n\nclass MahjongConnectTestRemoveIcons(unittest.TestCase):\n def test_remove_icons_1(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n mc.remove_icons((0, 0), (1, 0))\n self.assertEqual(mc.board, [[' ', 'b', 'c', 'a'],\n [' ', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']])\n\n def test_remove_icons_2(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n mc.remove_icons((2, 0), (1, 0))\n self.assertEqual(mc.board, [['a', 'b', 'c', 'a'],\n [' ', 'b', 'c', 'a'],\n [' ', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']])\n\n def test_remove_icons_3(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n mc.remove_icons((1, 1), (0, 1))\n self.assertEqual(mc.board, [['a', ' ', 'c', 'a'],\n ['a', ' ', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']])\n\n def test_remove_icons_4(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n mc.remove_icons((3, 0), (2, 0))\n self.assertEqual(mc.board, [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n [' ', 'b', 'c', 'a'],\n [' ', 'b', 'c', 'a']])\n\n def test_remove_icons_5(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n mc.remove_icons((3, 3), (2, 3))\n self.assertEqual(mc.board, [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', ' '],\n ['a', 'b', 'c', ' ']])\n\n\nclass MahjongConnectTestIsGameOver(unittest.TestCase):\n def test_is_game_over_1(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [[' ', ' ', ' ', ' '],\n [' ', ' ', ' ', ' '],\n [' ', ' ', ' ', ' '],\n [' ', ' ', ' ', ' ']]\n res = mc.is_game_over()\n self.assertEqual(res, True)\n\n def test_is_game_over_2(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', ' ', ' ', ' '],\n ['a', ' ', ' ', ' '],\n [' ', ' ', ' ', ' '],\n [' ', ' ', ' ', ' ']]\n res = mc.is_game_over()\n self.assertEqual(res, False)\n\n def test_is_game_over_3(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [[' ', ' ', ' ', ' '],\n ['a', ' ', ' ', ' '],\n [' ', ' ', ' ', ' '],\n [' ', ' ', ' ', ' ']]\n res = mc.is_game_over()\n self.assertEqual(res, False)\n\n def test_is_game_over_4(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['1', ' ', ' ', ' '],\n [' ', ' ', ' ', ' '],\n [' ', ' ', ' ', ' '],\n [' ', ' ', ' ', ' ']]\n res = mc.is_game_over()\n self.assertEqual(res, False)\n\n def test_is_game_over_5(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', ' ', ' ', ' '],\n [' ', ' ', ' ', ' '],\n [' ', ' ', ' ', ' '],\n [' ', ' ', ' ', ' ']]\n res = mc.is_game_over()\n self.assertEqual(res, False)\n\n\nclass MahjongConnectTest(unittest.TestCase):\n def test_mahjongconnect(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n self.assertEqual(mc.BOARD_SIZE, [4, 4])\n self.assertEqual(mc.ICONS, ['a', 'b', 'c'])\n for row in mc.board:\n for icon in row:\n self.assertIn(icon, mc.ICONS)\n\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.is_valid_move((0, 0), (1, 0))\n self.assertEqual(res, True)\n\n res = mc.has_path((0, 0), (1, 0))\n self.assertEqual(res, True)\n\n mc.remove_icons((0, 0), (1, 0))\n self.assertEqual(mc.board, [[' ', 'b', 'c', 'a'],\n [' ', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']])\n\n mc.board = [[' ', ' ', ' ', ' '],\n [' ', ' ', ' ', ' '],\n [' ', ' ', ' ', ' '],\n [' ', ' ', ' ', ' ']]\n res = mc.is_game_over()\n self.assertEqual(res, True)", "solution_code": "import random\n\n\nclass MahjongConnect:\n def __init__(self, BOARD_SIZE, ICONS):\n self.BOARD_SIZE = BOARD_SIZE\n self.ICONS = ICONS\n self.board = self.create_board()\n\n def create_board(self):\n board = [[random.choice(self.ICONS) for _ in range(self.BOARD_SIZE[1])] for _ in range(self.BOARD_SIZE[0])]\n return board\n\n def is_valid_move(self, pos1, pos2):\n x1, y1 = pos1\n x2, y2 = pos2\n\n # Check if positions are within the game board range\n if not (0 <= x1 < self.BOARD_SIZE[0] and 0 <= y1 < self.BOARD_SIZE[1] and 0 <= x2 < self.BOARD_SIZE[\n 0] and 0 <= y2 <\n self.BOARD_SIZE[1]):\n return False\n\n # Check if the two positions are the same\n if pos1 == pos2:\n return False\n\n # Check if the two positions have the same icon\n if self.board[x1][y1] != self.board[x2][y2]:\n return False\n\n # Check if there is a valid path between the two positions\n if not self.has_path(pos1, pos2):\n return False\n\n return True\n\n def has_path(self, pos1, pos2):\n visited = set()\n stack = [pos1]\n\n while stack:\n current_pos = stack.pop()\n if current_pos == pos2:\n return True\n\n if current_pos in visited:\n continue\n\n visited.add(current_pos)\n x, y = current_pos\n\n # Check adjacent positions (up, down, left, right)\n for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]:\n new_x, new_y = x + dx, y + dy\n if 0 <= new_x < self.BOARD_SIZE[0] and 0 <= new_y < self.BOARD_SIZE[1]:\n if (new_x, new_y) not in visited and self.board[new_x][new_y] == self.board[x][y]:\n stack.append((new_x, new_y))\n\n return False\n\n def remove_icons(self, pos1, pos2):\n x1, y1 = pos1\n x2, y2 = pos2\n self.board[x1][y1] = ' '\n self.board[x2][y2] = ' '\n\n def is_game_over(self):\n for row in self.board:\n if any(icon != ' ' for icon in row):\n return False\n return True", "import_statement": [ "import random" ], "class_description": " \"\"\"\n MahjongConnect is a class representing a game board for Mahjong Connect with features like creating the board, checking valid moves, finding paths, removing icons, and checking if the game is over.\n \"\"\"\n", "class_name": "MahjongConnect", "test_classes": [ "MahjongConnectTestCreateBoard", "MahjongConnectTestIsValidMove", "MahjongConnectTestHasPath", "MahjongConnectTestRemoveIcons", "MahjongConnectTestIsGameOver", "MahjongConnectTest" ], "class_constructor": "class MahjongConnect: \n def __init__(self, BOARD_SIZE, ICONS):\n \"\"\"\n initialize the board size and the icon list, create the game board\n :param BOARD_SIZE: list of two integer numbers, representing the number of rows and columns of the game board\n :param ICONS: list of string, representing the icons\n >>>mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.BOARD_SIZE = [4, 4]\n mc.ICONS = ['a', 'b', 'c']\n mc.board = mc.create_board()\n \"\"\"\n self.BOARD_SIZE = BOARD_SIZE\n self.ICONS = ICONS\n self.board = self.create_board()\n\n", "fields": [ "self.BOARD_SIZE", "self.ICONS", "self.board" ], "methods_info": [ { "method_name": "create_board", "method_description": "def create_board(self):\n \"\"\"\n create the game board with the given board size and icons\n :return: 2-dimensional list, the game board\n >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n >>> mc.create_board()\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n \"\"\"", "test_class": "MahjongConnectTestCreateBoard", "test_code": "class MahjongConnectTestCreateBoard(unittest.TestCase):\n def test_create_board_1(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n self.assertEqual(mc.BOARD_SIZE, [4, 4])\n self.assertEqual(mc.ICONS, ['a', 'b', 'c'])\n for row in mc.board:\n for icon in row:\n self.assertIn(icon, mc.ICONS)\n\n def test_create_board_2(self):\n mc = MahjongConnect([2, 2], ['a', 'b', 'c'])\n self.assertEqual(mc.BOARD_SIZE, [2, 2])\n self.assertEqual(mc.ICONS, ['a', 'b', 'c'])\n for row in mc.board:\n for icon in row:\n self.assertIn(icon, mc.ICONS)\n\n def test_create_board_3(self):\n mc = MahjongConnect([3, 3], ['a', 'b', 'c'])\n self.assertEqual(mc.BOARD_SIZE, [3, 3])\n self.assertEqual(mc.ICONS, ['a', 'b', 'c'])\n for row in mc.board:\n for icon in row:\n self.assertIn(icon, mc.ICONS)\n\n def test_create_board_4(self):\n mc = MahjongConnect([1, 1], ['a', 'b', 'c'])\n self.assertEqual(mc.BOARD_SIZE, [1, 1])\n self.assertEqual(mc.ICONS, ['a', 'b', 'c'])\n for row in mc.board:\n for icon in row:\n self.assertIn(icon, mc.ICONS)\n\n def test_create_board_5(self):\n mc = MahjongConnect([5, 5], ['a', 'b', 'c'])\n self.assertEqual(mc.BOARD_SIZE, [5, 5])\n self.assertEqual(mc.ICONS, ['a', 'b', 'c'])\n for row in mc.board:\n for icon in row:\n self.assertIn(icon, mc.ICONS)", "solution_code": "def create_board(self):\n board = [[random.choice(self.ICONS) for _ in range(self.BOARD_SIZE[1])] for _ in range(self.BOARD_SIZE[0])]\n return board", "dependencies": { "Standalone": false, "lib_dependencies": [ "random" ], "field_dependencies": [ "self.BOARD_SIZE", "self.ICONS" ], "method_dependencies": [] } }, { "method_name": "is_valid_move", "method_description": "def is_valid_move(self, pos1, pos2):\n \"\"\"\n check if the move of two icons is valid (i.e. positions are within the game board range, the two positions are not the same, the two positions have the same icon, and there is a valid path between the two positions)\n :param pos1: position tuple(x, y) of the first icon\n :param pos2: position tuple(x, y) of the second icon\n :return:True or False ,representing whether the move of two icons is valid\n >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n >>> mc.is_valid_move((0, 0), (1, 0))\n True\n \"\"\"", "test_class": "MahjongConnectTestIsValidMove", "test_code": "class MahjongConnectTestIsValidMove(unittest.TestCase):\n def test_is_valid_move_1(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.is_valid_move((0, 0), (1, 0))\n self.assertEqual(res, True)\n\n def test_is_valid_move_2(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.is_valid_move((0, 0), (0, 1))\n self.assertEqual(res, False)\n\n def test_is_valid_move_3(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.is_valid_move((-1, 0), (0, 1))\n self.assertEqual(res, False)\n\n def test_is_valid_move_4(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.is_valid_move((0, 0), (0, 0))\n self.assertEqual(res, False)\n\n def test_is_valid_move_5(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.is_valid_move((300, 0), (0, 0))\n self.assertEqual(res, False)\n\n def test_is_valid_move_6(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'a', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.is_valid_move((0, 2), (0, 0))\n self.assertEqual(res, False)", "solution_code": "def is_valid_move(self, pos1, pos2):\n x1, y1 = pos1\n x2, y2 = pos2\n\n # Check if positions are within the game board range\n if not (0 <= x1 < self.BOARD_SIZE[0] and 0 <= y1 < self.BOARD_SIZE[1] and 0 <= x2 < self.BOARD_SIZE[\n 0] and 0 <= y2 <\n self.BOARD_SIZE[1]):\n return False\n\n # Check if the two positions are the same\n if pos1 == pos2:\n return False\n\n # Check if the two positions have the same icon\n if self.board[x1][y1] != self.board[x2][y2]:\n return False\n\n # Check if there is a valid path between the two positions\n if not self.has_path(pos1, pos2):\n return False\n\n return True", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.BOARD_SIZE", "self.board" ], "method_dependencies": [ "has_path" ] } }, { "method_name": "has_path", "method_description": "def has_path(self, pos1, pos2):\n \"\"\"\n check if there is a path between two icons\n :param pos1: position tuple(x, y) of the first icon\n :param pos2: position tuple(x, y) of the second icon\n :return: True or False ,representing whether there is a path between two icons\n >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n >>> mc.is_valid_move((0, 0), (1, 0))\n True\n \"\"\"", "test_class": "MahjongConnectTestHasPath", "test_code": "class MahjongConnectTestHasPath(unittest.TestCase):\n def test_has_path_1(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.has_path((0, 0), (1, 0))\n self.assertEqual(res, True)\n\n def test_has_path_2(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.has_path((0, 0), (0, 0))\n self.assertEqual(res, True)\n\n def test_has_path_3(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.has_path((0, 0), (3, 0))\n self.assertEqual(res, True)\n\n def test_has_path_4(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.has_path((0, 0), (1, 1))\n self.assertEqual(res, False)\n\n def test_has_path_5(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n res = mc.has_path((300, 0), (1, 1))\n self.assertEqual(res, False)\n\n def test_has_path_6(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'a', 'a', 'a'],\n ['a', 'a', 'a', 'a'],\n ['a', 'a', 'a', 'a'],\n ['a', 'a', 'a', 'a']]\n res = mc.has_path((0, 0), (3, 3))\n self.assertEqual(res, True)", "solution_code": "def has_path(self, pos1, pos2):\n visited = set()\n stack = [pos1]\n\n while stack:\n current_pos = stack.pop()\n if current_pos == pos2:\n return True\n\n if current_pos in visited:\n continue\n\n visited.add(current_pos)\n x, y = current_pos\n\n # Check adjacent positions (up, down, left, right)\n for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]:\n new_x, new_y = x + dx, y + dy\n if 0 <= new_x < self.BOARD_SIZE[0] and 0 <= new_y < self.BOARD_SIZE[1]:\n if (new_x, new_y) not in visited and self.board[new_x][new_y] == self.board[x][y]:\n stack.append((new_x, new_y))\n\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.BOARD_SIZE", "self.board" ], "method_dependencies": [] } }, { "method_name": "remove_icons", "method_description": "def remove_icons(self, pos1, pos2):\n \"\"\"\n remove the connected icons on the game board\n :param pos1: position tuple(x, y) of the first icon to be removed\n :param pos2: position tuple(x, y) of the second icon to be removed\n :return: None\n >>> mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n >>> mc.remove_icons((0, 0), (1, 0))\n mc.board = [[' ', 'b', 'c', 'a'],\n [' ', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n \"\"\"", "test_class": "MahjongConnectTestRemoveIcons", "test_code": "class MahjongConnectTestRemoveIcons(unittest.TestCase):\n def test_remove_icons_1(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n mc.remove_icons((0, 0), (1, 0))\n self.assertEqual(mc.board, [[' ', 'b', 'c', 'a'],\n [' ', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']])\n\n def test_remove_icons_2(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n mc.remove_icons((2, 0), (1, 0))\n self.assertEqual(mc.board, [['a', 'b', 'c', 'a'],\n [' ', 'b', 'c', 'a'],\n [' ', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']])\n\n def test_remove_icons_3(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n mc.remove_icons((1, 1), (0, 1))\n self.assertEqual(mc.board, [['a', ' ', 'c', 'a'],\n ['a', ' ', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']])\n\n def test_remove_icons_4(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n mc.remove_icons((3, 0), (2, 0))\n self.assertEqual(mc.board, [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n [' ', 'b', 'c', 'a'],\n [' ', 'b', 'c', 'a']])\n\n def test_remove_icons_5(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a']]\n mc.remove_icons((3, 3), (2, 3))\n self.assertEqual(mc.board, [['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', 'a'],\n ['a', 'b', 'c', ' '],\n ['a', 'b', 'c', ' ']])", "solution_code": "def remove_icons(self, pos1, pos2):\n x1, y1 = pos1\n x2, y2 = pos2\n self.board[x1][y1] = ' '\n self.board[x2][y2] = ' '", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.board" ], "method_dependencies": [] } }, { "method_name": "is_game_over", "method_description": "def is_game_over(self):\n \"\"\"\n Check if the game is over (i.e., if there are no more icons on the game board)\n :return: True or False ,representing whether the game is over\n >>> mc = MahjongConnect([4, 4] ['a', 'b', 'c'])\n >>> mc.board = [[' ', ' ', ' ', ' '],\n >>> [' ', ' ', ' ', ' '],\n >>> [' ', ' ', ' ', ' '],\n >>> [' ', ' ', ' ', ' ']]\n >>> mc.is_game_over()\n True\n \"\"\"", "test_class": "MahjongConnectTestIsGameOver", "test_code": "class MahjongConnectTestIsGameOver(unittest.TestCase):\n def test_is_game_over_1(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [[' ', ' ', ' ', ' '],\n [' ', ' ', ' ', ' '],\n [' ', ' ', ' ', ' '],\n [' ', ' ', ' ', ' ']]\n res = mc.is_game_over()\n self.assertEqual(res, True)\n\n def test_is_game_over_2(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', ' ', ' ', ' '],\n ['a', ' ', ' ', ' '],\n [' ', ' ', ' ', ' '],\n [' ', ' ', ' ', ' ']]\n res = mc.is_game_over()\n self.assertEqual(res, False)\n\n def test_is_game_over_3(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [[' ', ' ', ' ', ' '],\n ['a', ' ', ' ', ' '],\n [' ', ' ', ' ', ' '],\n [' ', ' ', ' ', ' ']]\n res = mc.is_game_over()\n self.assertEqual(res, False)\n\n def test_is_game_over_4(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['1', ' ', ' ', ' '],\n [' ', ' ', ' ', ' '],\n [' ', ' ', ' ', ' '],\n [' ', ' ', ' ', ' ']]\n res = mc.is_game_over()\n self.assertEqual(res, False)\n\n def test_is_game_over_5(self):\n mc = MahjongConnect([4, 4], ['a', 'b', 'c'])\n mc.board = [['a', ' ', ' ', ' '],\n [' ', ' ', ' ', ' '],\n [' ', ' ', ' ', ' '],\n [' ', ' ', ' ', ' ']]\n res = mc.is_game_over()\n self.assertEqual(res, False)", "solution_code": "def is_game_over(self):\n for row in self.board:\n if any(icon != ' ' for icon in row):\n return False\n return True", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.board" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_55", "skeleton": "\nclass Manacher:\n \"\"\"\n his is a class that implements a manacher algorithm to find the Longest palindromic substring in a given string.\n \"\"\"\n\n def __init__(self, input_string) -> None:\n \"\"\"\n Initializes the Manacher class with the given input_string.\n :param input_string: The input_string to be searched, str.\n \"\"\"\n self.input_string = input_string\n\n def palindromic_length(self, center, diff, string):\n \"\"\"\n Recursively calculates the length of the palindromic substring based on a given center, difference value, and input string.\n :param center: The center of the palindromic substring, int.\n :param diff: The difference between the center and the current position, int.\n :param string: The string to be searched, str.\n :return: The length of the palindromic substring, int.\n >>> manacher = Manacher('ababa')\n >>> manacher.palindromic_length(2, 1, 'a|b|a|b|a')\n 2\n\n \"\"\"\n\n def palindromic_string(self):\n \"\"\"\n Finds the longest palindromic substring in the given string.\n :return: The longest palindromic substring, str.\n >>> manacher = Manacher('ababaxse')\n >>> manacher.palindromic_string()\n 'ababa'\n\n \"\"\"", "test": "import unittest\n\nclass ManacherTestPalindromicLength(unittest.TestCase):\n def test_palindromic_length(self):\n manacher = Manacher('ababa')\n self.assertEqual(manacher.palindromic_length(2, 1, 'a|b|a|b|a'), 2)\n def test_palindromic_length_2(self):\n manacher = Manacher('ababaxse')\n self.assertEqual(manacher.palindromic_length(2, 1, 'a|b|a|b|a|x|s|e'), 2)\n\n def test_palindromic_length_3(self):\n manacher = Manacher('ababax')\n self.assertEqual(manacher.palindromic_length(2, 3, 'a|b|a|b|a|x'), 0)\n\n def test_palindromic_length_4(self):\n manacher = Manacher('ababax')\n self.assertEqual(manacher.palindromic_length(9, 2, 'a|b|a|b|a|x'), 0)\n\n def test_palindromic_length_5(self):\n manacher = Manacher('ababax')\n self.assertEqual(manacher.palindromic_length(4, 1, 'a|b|a|b|a|x'), 4)\n\n\nclass ManacherTestPalindromicString(unittest.TestCase):\n def test_palindromic_string(self):\n manacher = Manacher('ababaxse')\n self.assertEqual(manacher.palindromic_string(), 'ababa')\n\n def test_palindromic_string_2(self):\n manacher = Manacher('ababax')\n self.assertEqual(manacher.palindromic_string(), 'ababa')\n\n def test_palindromic_string_3(self):\n manacher = Manacher('ababax')\n self.assertEqual(manacher.palindromic_string(), 'ababa')\n\n def test_palindromic_string_4(self):\n manacher = Manacher('ababaxssss')\n self.assertEqual(manacher.palindromic_string(), 'ababa')\n\n def test_palindromic_string_5(self):\n manacher = Manacher('abab')\n self.assertEqual(manacher.palindromic_string(), 'aba')\n\n\nclass ManacherTestMain(unittest.TestCase):\n def test_main(self):\n manacher = Manacher('ababa')\n self.assertEqual(manacher.palindromic_length(2, 1, 'a|b|a|b|a'), 2)\n self.assertEqual(manacher.palindromic_string(), 'ababa')", "solution_code": "class Manacher:\n def __init__(self, input_string) -> None:\n self.input_string = input_string\n\n def palindromic_length(self, center, diff, string):\n if (center - diff == -1 or center + diff == len(string)\n or string[center - diff] != string[center + diff]):\n return 0\n return 1 + self.palindromic_length(center, diff + 1, string)\n\n\n def palindromic_string(self):\n max_length = 0\n\n new_input_string = \"\"\n output_string = \"\"\n\n for i in self.input_string[:len(self.input_string) - 1]:\n new_input_string += i + \"|\"\n new_input_string += self.input_string[-1]\n\n for i in range(len(new_input_string)):\n\n length =self.palindromic_length(i, 1, new_input_string)\n\n if max_length < length:\n max_length = length\n start = i\n\n for i in new_input_string[start - max_length:start + max_length + 1]:\n if i != \"|\":\n output_string += i\n\n return output_string", "import_statement": [], "class_description": " \"\"\"\n his is a class that implements a manacher algorithm to find the Longest palindromic substring in a given string.\n \"\"\"\n", "class_name": "Manacher", "test_classes": [ "ManacherTestPalindromicLength", "ManacherTestPalindromicString", "ManacherTestMain" ], "class_constructor": "class Manacher: \n def __init__(self, input_string) -> None:\n \"\"\"\n Initializes the Manacher class with the given input_string.\n :param input_string: The input_string to be searched, str.\n \"\"\"\n self.input_string = input_string\n\n", "fields": [ "self.input_string" ], "methods_info": [ { "method_name": "palindromic_length", "method_description": "def palindromic_length(self, center, diff, string):\n \"\"\"\n Recursively calculates the length of the palindromic substring based on a given center, difference value, and input string.\n :param center: The center of the palindromic substring, int.\n :param diff: The difference between the center and the current position, int.\n :param string: The string to be searched, str.\n :return: The length of the palindromic substring, int.\n >>> manacher = Manacher('ababa')\n >>> manacher.palindromic_length(2, 1, 'a|b|a|b|a')\n 2\n\n \"\"\"", "test_class": "ManacherTestPalindromicLength", "test_code": "class ManacherTestPalindromicLength(unittest.TestCase):\n def test_palindromic_length(self):\n manacher = Manacher('ababa')\n self.assertEqual(manacher.palindromic_length(2, 1, 'a|b|a|b|a'), 2)\n def test_palindromic_length_2(self):\n manacher = Manacher('ababaxse')\n self.assertEqual(manacher.palindromic_length(2, 1, 'a|b|a|b|a|x|s|e'), 2)\n\n def test_palindromic_length_3(self):\n manacher = Manacher('ababax')\n self.assertEqual(manacher.palindromic_length(2, 3, 'a|b|a|b|a|x'), 0)\n\n def test_palindromic_length_4(self):\n manacher = Manacher('ababax')\n self.assertEqual(manacher.palindromic_length(9, 2, 'a|b|a|b|a|x'), 0)\n\n def test_palindromic_length_5(self):\n manacher = Manacher('ababax')\n self.assertEqual(manacher.palindromic_length(4, 1, 'a|b|a|b|a|x'), 4)", "solution_code": "def palindromic_length(self, center, diff, string):\n if (center - diff == -1 or center + diff == len(string)\n or string[center - diff] != string[center + diff]):\n return 0\n return 1 + self.palindromic_length(center, diff + 1, string)", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "palindromic_string", "method_description": "def palindromic_string(self):\n \"\"\"\n Finds the longest palindromic substring in the given string.\n :return: The longest palindromic substring, str.\n >>> manacher = Manacher('ababaxse')\n >>> manacher.palindromic_string()\n 'ababa'\n\n \"\"\"", "test_class": "ManacherTestPalindromicString", "test_code": "class ManacherTestPalindromicString(unittest.TestCase):\n def test_palindromic_string(self):\n manacher = Manacher('ababaxse')\n self.assertEqual(manacher.palindromic_string(), 'ababa')\n\n def test_palindromic_string_2(self):\n manacher = Manacher('ababax')\n self.assertEqual(manacher.palindromic_string(), 'ababa')\n\n def test_palindromic_string_3(self):\n manacher = Manacher('ababax')\n self.assertEqual(manacher.palindromic_string(), 'ababa')\n\n def test_palindromic_string_4(self):\n manacher = Manacher('ababaxssss')\n self.assertEqual(manacher.palindromic_string(), 'ababa')\n\n def test_palindromic_string_5(self):\n manacher = Manacher('abab')\n self.assertEqual(manacher.palindromic_string(), 'aba')", "solution_code": "def palindromic_string(self):\n max_length = 0\n\n new_input_string = \"\"\n output_string = \"\"\n\n for i in self.input_string[:len(self.input_string) - 1]:\n new_input_string += i + \"|\"\n new_input_string += self.input_string[-1]\n\n for i in range(len(new_input_string)):\n\n length =self.palindromic_length(i, 1, new_input_string)\n\n if max_length < length:\n max_length = length\n start = i\n\n for i in new_input_string[start - max_length:start + max_length + 1]:\n if i != \"|\":\n output_string += i\n\n return output_string", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.input_string" ], "method_dependencies": [ "palindromic_length" ] } } ] }, { "task_id": "ClassEval_56", "skeleton": "\nclass MetricsCalculator:\n \"\"\"\n The class calculates precision, recall, F1 score, and accuracy based on predicted and true labels.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialize the number of all four samples to 0\n \"\"\"\n self.true_positives = 0\n self.false_positives = 0\n self.false_negatives = 0\n self.true_negatives = 0\n\n\n def update(self, predicted_labels, true_labels):\n \"\"\"\n Update the number of all four samples(true_positives, false_positives, false_negatives, true_negatives)\n :param predicted_labels: list, predicted results\n :param true_labels: list, true labels\n :return: None, change the number of corresponding samples\n >>> mc = MetricsCalculator()\n >>> mc.update([1, 1, 0, 0], [1, 0, 0, 1])\n (self.true_positives, self.false_positives, self.false_negatives, self.true_negatives) = (1, 1, 1, 1)\n \"\"\"\n\n\n def precision(self, predicted_labels, true_labels):\n \"\"\"\n Calculate precision\n :param predicted_labels: list, predicted results\n :param true_labels: list, true labels\n :return: float\n >>> mc = MetricsCalculator()\n >>> mc.precision([1, 1, 0, 0], [1, 0, 0, 1])\n 0.5\n \"\"\"\n\n\n def recall(self, predicted_labels, true_labels):\n \"\"\"\n Calculate recall\n :param predicted_labels: list, predicted results\n :param true_labels: list, true labels\n :return: float\n >>> mc = MetricsCalculator()\n >>> mc.recall([1, 1, 0, 0], [1, 0, 0, 1])\n 0.5\n \"\"\"\n\n\n def f1_score(self, predicted_labels, true_labels):\n \"\"\"\n Calculate f1 score, which is the harmonic mean of precision and recall\n :param predicted_labels: list, predicted results\n :param true_labels: list, true labels\n :return: float\n >>> mc = MetricsCalculator()\n >>> mc.f1_score([1, 1, 0, 0], [1, 0, 0, 1])\n 0.5\n \"\"\"\n\n\n def accuracy(self, predicted_labels, true_labels):\n \"\"\"\n Calculate accuracy\n :param predicted_labels: list, predicted results\n :param true_labels: list, true labels\n :return: float\n >>> mc = MetricsCalculator()\n >>>mc.accuracy([1, 1, 0, 0], [1, 0, 0, 1])\n 0.5\n \"\"\"", "test": "import unittest\n\n\nclass MetricsCalculatorTestUpdate(unittest.TestCase):\n def test_update_1(self):\n mc = MetricsCalculator()\n self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (0, 0, 0, 0))\n mc.update([1, 1, 0, 0], [1, 0, 0, 1])\n self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (1, 1, 1, 1))\n\n def test_update_2(self):\n mc = MetricsCalculator()\n self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (0, 0, 0, 0))\n mc.update([1, 1, 1, 0], [1, 0, 0, 1])\n self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (1, 2, 1, 0))\n\n def test_update_3(self):\n mc = MetricsCalculator()\n self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (0, 0, 0, 0))\n mc.update([1, 1, 0, 1], [1, 0, 0, 1])\n self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (2, 1, 0, 1))\n\n def test_update_4(self):\n mc = MetricsCalculator()\n self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (0, 0, 0, 0))\n mc.update([1, 1, 0, 0], [1, 1, 0, 1])\n self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (2, 0, 1, 1))\n\n def test_update_5(self):\n mc = MetricsCalculator()\n self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (0, 0, 0, 0))\n mc.update([1, 1, 0, 0], [1, 0, 1, 1])\n self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (1, 1, 2, 0))\n\n\nclass MetricsCalculatorTestPrecision(unittest.TestCase):\n def test_precision_1(self):\n mc = MetricsCalculator()\n temp = mc.precision([1, 1, 0, 0], [1, 0, 0, 1])\n self.assertEqual(temp, 0.5)\n\n def test_precision_2(self):\n mc = MetricsCalculator()\n temp = mc.precision([1, 1, 1, 0], [1, 0, 0, 1])\n self.assertAlmostEqual(temp, 0.3333333333333333)\n\n def test_precision_3(self):\n mc = MetricsCalculator()\n temp = mc.precision([1, 1, 0, 1], [1, 0, 0, 1])\n self.assertAlmostEqual(temp, 0.6666666666666666)\n\n def test_precision_4(self):\n mc = MetricsCalculator()\n temp = mc.precision([1, 1, 0, 0], [1, 1, 0, 1])\n self.assertAlmostEqual(temp, 1.0)\n\n def test_precision_5(self):\n mc = MetricsCalculator()\n temp = mc.precision([1, 1, 0, 0], [1, 0, 1, 1])\n self.assertAlmostEqual(temp, 0.5)\n\n def test_precision_6(self):\n mc = MetricsCalculator()\n temp = mc.precision([0, 0, 0, 0], [1, 0, 1, 1])\n self.assertAlmostEqual(temp, 0.0)\n\n\nclass MetricsCalculatorTestRecall(unittest.TestCase):\n def test_recall_1(self):\n mc = MetricsCalculator()\n temp = mc.recall([1, 1, 0, 0], [1, 0, 0, 1])\n self.assertEqual(temp, 0.5)\n\n def test_recall_2(self):\n mc = MetricsCalculator()\n temp = mc.recall([1, 1, 1, 0], [1, 0, 0, 1])\n self.assertEqual(temp, 0.5)\n\n def test_recall_3(self):\n mc = MetricsCalculator()\n temp = mc.recall([1, 1, 0, 1], [1, 0, 0, 1])\n self.assertEqual(temp, 1.0)\n\n def test_recall_4(self):\n mc = MetricsCalculator()\n temp = mc.recall([1, 1, 0, 0], [1, 1, 0, 1])\n self.assertAlmostEqual(temp, 0.6666666666666666)\n\n def test_recall_5(self):\n mc = MetricsCalculator()\n temp = mc.recall([1, 1, 0, 0], [1, 0, 1, 1])\n self.assertAlmostEqual(temp, 0.3333333333333333)\n\n def test_recall_6(self):\n mc = MetricsCalculator()\n temp = mc.recall([1, 1, 0, 0], [0, 0, 0, 0])\n self.assertEqual(temp, 0.0)\n\n\nclass MetricsCalculatorTestF1Score(unittest.TestCase):\n def test_f1_score_1(self):\n mc = MetricsCalculator()\n temp = mc.f1_score([1, 1, 0, 0], [1, 0, 0, 1])\n self.assertEqual(temp, 0.5)\n\n def test_f1_score_2(self):\n mc = MetricsCalculator()\n temp = mc.f1_score([1, 1, 1, 0], [1, 0, 0, 1])\n self.assertEqual(temp, 0.4)\n\n def test_f1_score_3(self):\n mc = MetricsCalculator()\n temp = mc.f1_score([1, 1, 0, 1], [1, 0, 0, 1])\n self.assertEqual(temp, 0.8)\n\n def test_f1_score_4(self):\n mc = MetricsCalculator()\n temp = mc.f1_score([1, 1, 0, 0], [1, 1, 0, 1])\n self.assertEqual(temp, 0.8)\n\n def test_f1_score_5(self):\n mc = MetricsCalculator()\n temp = mc.f1_score([1, 1, 0, 0], [1, 0, 1, 1])\n self.assertEqual(temp, 0.4)\n\n def test_f1_score_6(self):\n mc = MetricsCalculator()\n temp = mc.f1_score([0, 0, 0, 0], [0, 0, 0, 0])\n self.assertEqual(temp, 0.0)\n\n\nclass MetricsCalculatorTestAccuracy(unittest.TestCase):\n def test_accuracy_1(self):\n mc = MetricsCalculator()\n temp = mc.accuracy([1, 1, 0, 0], [1, 0, 0, 1])\n self.assertEqual(temp, 0.5)\n\n def test_accuracy_2(self):\n mc = MetricsCalculator()\n temp = mc.accuracy([1, 1, 2, 0], [1, 0, 0, 1])\n self.assertAlmostEqual(temp, 0.3333333333333333)\n\n def test_accuracy_3(self):\n mc = MetricsCalculator()\n temp = mc.accuracy([1, 1, 0, 1], [1, 0, 0, 1])\n self.assertEqual(temp, 0.75)\n\n def test_accuracy_4(self):\n mc = MetricsCalculator()\n temp = mc.accuracy([1, 1, 0, 0], [1, 1, 0, 1])\n self.assertEqual(temp, 0.75)\n\n def test_accuracy_5(self):\n mc = MetricsCalculator()\n temp = mc.accuracy([1, 1, 0, 0], [1, 0, 1, 1])\n self.assertEqual(temp, 0.25)\n\n def test_accuracy_6(self):\n mc = MetricsCalculator()\n temp = mc.accuracy([], [])\n self.assertEqual(temp, 0.0)\n\n\nclass MetricsCalculatorTest(unittest.TestCase):\n def test_metricscalculator(self):\n mc = MetricsCalculator()\n self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (0, 0, 0, 0))\n mc.update([1, 1, 0, 0], [1, 0, 0, 1])\n self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (1, 1, 1, 1))\n temp = mc.precision([1, 1, 0, 0], [1, 0, 0, 1])\n self.assertEqual(temp, 0.5)\n temp = mc.recall([1, 1, 0, 0], [1, 0, 0, 1])\n self.assertEqual(temp, 0.5)\n temp = mc.f1_score([1, 1, 0, 0], [1, 0, 0, 1])\n self.assertEqual(temp, 0.5)\n temp = mc.accuracy([1, 1, 0, 0], [1, 0, 0, 1])\n self.assertEqual(temp, 0.5)", "solution_code": "class MetricsCalculator:\n def __init__(self):\n self.true_positives = 0\n self.false_positives = 0\n self.false_negatives = 0\n self.true_negatives = 0\n\n def update(self, predicted_labels, true_labels):\n for predicted, true in zip(predicted_labels, true_labels):\n if predicted == 1 and true == 1:\n self.true_positives += 1\n elif predicted == 1 and true == 0:\n self.false_positives += 1\n elif predicted == 0 and true == 1:\n self.false_negatives += 1\n elif predicted == 0 and true == 0:\n self.true_negatives += 1\n\n def precision(self, predicted_labels, true_labels):\n self.update(predicted_labels, true_labels)\n if self.true_positives + self.false_positives == 0:\n return 0.0\n return self.true_positives / (self.true_positives + self.false_positives)\n\n def recall(self, predicted_labels, true_labels):\n self.update(predicted_labels, true_labels)\n if self.true_positives + self.false_negatives == 0:\n return 0.0\n return self.true_positives / (self.true_positives + self.false_negatives)\n\n def f1_score(self, predicted_labels, true_labels):\n self.update(predicted_labels, true_labels)\n precision = self.precision(predicted_labels, true_labels)\n recall = self.recall(predicted_labels, true_labels)\n if precision + recall == 0.0:\n return 0.0\n return (2 * precision * recall) / (precision + recall)\n\n def accuracy(self, predicted_labels, true_labels):\n self.update(predicted_labels, true_labels)\n total = self.true_positives + self.true_negatives + self.false_positives + self.false_negatives\n if total == 0:\n return 0.0\n return (self.true_positives + self.true_negatives) / total", "import_statement": [], "class_description": " \"\"\"\n The class calculates precision, recall, F1 score, and accuracy based on predicted and true labels.\n \"\"\"\n", "class_name": "MetricsCalculator", "test_classes": [ "MetricsCalculatorTestUpdate", "MetricsCalculatorTestPrecision", "MetricsCalculatorTestRecall", "MetricsCalculatorTestF1Score", "MetricsCalculatorTestAccuracy", "MetricsCalculatorTest" ], "class_constructor": "class MetricsCalculator: \n def __init__(self):\n \"\"\"\n Initialize the number of all four samples to 0\n \"\"\"\n self.true_positives = 0\n self.false_positives = 0\n self.false_negatives = 0\n self.true_negatives = 0\n\n\n", "fields": [ "self.false_negatives", "self.false_positives", "self.true_negatives", "self.true_positives" ], "methods_info": [ { "method_name": "update", "method_description": "def update(self, predicted_labels, true_labels):\n \"\"\"\n Update the number of all four samples(true_positives, false_positives, false_negatives, true_negatives)\n :param predicted_labels: list, predicted results\n :param true_labels: list, true labels\n :return: None, change the number of corresponding samples\n >>> mc = MetricsCalculator()\n >>> mc.update([1, 1, 0, 0], [1, 0, 0, 1])\n (self.true_positives, self.false_positives, self.false_negatives, self.true_negatives) = (1, 1, 1, 1)\n \"\"\"", "test_class": "MetricsCalculatorTestUpdate", "test_code": "class MetricsCalculatorTestUpdate(unittest.TestCase):\n def test_update_1(self):\n mc = MetricsCalculator()\n self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (0, 0, 0, 0))\n mc.update([1, 1, 0, 0], [1, 0, 0, 1])\n self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (1, 1, 1, 1))\n\n def test_update_2(self):\n mc = MetricsCalculator()\n self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (0, 0, 0, 0))\n mc.update([1, 1, 1, 0], [1, 0, 0, 1])\n self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (1, 2, 1, 0))\n\n def test_update_3(self):\n mc = MetricsCalculator()\n self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (0, 0, 0, 0))\n mc.update([1, 1, 0, 1], [1, 0, 0, 1])\n self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (2, 1, 0, 1))\n\n def test_update_4(self):\n mc = MetricsCalculator()\n self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (0, 0, 0, 0))\n mc.update([1, 1, 0, 0], [1, 1, 0, 1])\n self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (2, 0, 1, 1))\n\n def test_update_5(self):\n mc = MetricsCalculator()\n self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (0, 0, 0, 0))\n mc.update([1, 1, 0, 0], [1, 0, 1, 1])\n self.assertEqual((mc.true_positives, mc.false_positives, mc.false_negatives, mc.true_negatives), (1, 1, 2, 0))", "solution_code": "def update(self, predicted_labels, true_labels):\n for predicted, true in zip(predicted_labels, true_labels):\n if predicted == 1 and true == 1:\n self.true_positives += 1\n elif predicted == 1 and true == 0:\n self.false_positives += 1\n elif predicted == 0 and true == 1:\n self.false_negatives += 1\n elif predicted == 0 and true == 0:\n self.true_negatives += 1", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.false_negatives", "self.false_positives", "self.true_negatives", "self.true_positives" ], "method_dependencies": [] } }, { "method_name": "precision", "method_description": "def precision(self, predicted_labels, true_labels):\n \"\"\"\n Calculate precision\n :param predicted_labels: list, predicted results\n :param true_labels: list, true labels\n :return: float\n >>> mc = MetricsCalculator()\n >>> mc.precision([1, 1, 0, 0], [1, 0, 0, 1])\n 0.5\n \"\"\"", "test_class": "MetricsCalculatorTestPrecision", "test_code": "class MetricsCalculatorTestPrecision(unittest.TestCase):\n def test_precision_1(self):\n mc = MetricsCalculator()\n temp = mc.precision([1, 1, 0, 0], [1, 0, 0, 1])\n self.assertEqual(temp, 0.5)\n\n def test_precision_2(self):\n mc = MetricsCalculator()\n temp = mc.precision([1, 1, 1, 0], [1, 0, 0, 1])\n self.assertAlmostEqual(temp, 0.3333333333333333)\n\n def test_precision_3(self):\n mc = MetricsCalculator()\n temp = mc.precision([1, 1, 0, 1], [1, 0, 0, 1])\n self.assertAlmostEqual(temp, 0.6666666666666666)\n\n def test_precision_4(self):\n mc = MetricsCalculator()\n temp = mc.precision([1, 1, 0, 0], [1, 1, 0, 1])\n self.assertAlmostEqual(temp, 1.0)\n\n def test_precision_5(self):\n mc = MetricsCalculator()\n temp = mc.precision([1, 1, 0, 0], [1, 0, 1, 1])\n self.assertAlmostEqual(temp, 0.5)\n\n def test_precision_6(self):\n mc = MetricsCalculator()\n temp = mc.precision([0, 0, 0, 0], [1, 0, 1, 1])\n self.assertAlmostEqual(temp, 0.0)", "solution_code": "def precision(self, predicted_labels, true_labels):\n self.update(predicted_labels, true_labels)\n if self.true_positives + self.false_positives == 0:\n return 0.0\n return self.true_positives / (self.true_positives + self.false_positives)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.false_positives", "self.true_positives" ], "method_dependencies": [ "update" ] } }, { "method_name": "recall", "method_description": "def recall(self, predicted_labels, true_labels):\n \"\"\"\n Calculate recall\n :param predicted_labels: list, predicted results\n :param true_labels: list, true labels\n :return: float\n >>> mc = MetricsCalculator()\n >>> mc.recall([1, 1, 0, 0], [1, 0, 0, 1])\n 0.5\n \"\"\"", "test_class": "MetricsCalculatorTestRecall", "test_code": "class MetricsCalculatorTestRecall(unittest.TestCase):\n def test_recall_1(self):\n mc = MetricsCalculator()\n temp = mc.recall([1, 1, 0, 0], [1, 0, 0, 1])\n self.assertEqual(temp, 0.5)\n\n def test_recall_2(self):\n mc = MetricsCalculator()\n temp = mc.recall([1, 1, 1, 0], [1, 0, 0, 1])\n self.assertEqual(temp, 0.5)\n\n def test_recall_3(self):\n mc = MetricsCalculator()\n temp = mc.recall([1, 1, 0, 1], [1, 0, 0, 1])\n self.assertEqual(temp, 1.0)\n\n def test_recall_4(self):\n mc = MetricsCalculator()\n temp = mc.recall([1, 1, 0, 0], [1, 1, 0, 1])\n self.assertAlmostEqual(temp, 0.6666666666666666)\n\n def test_recall_5(self):\n mc = MetricsCalculator()\n temp = mc.recall([1, 1, 0, 0], [1, 0, 1, 1])\n self.assertAlmostEqual(temp, 0.3333333333333333)\n\n def test_recall_6(self):\n mc = MetricsCalculator()\n temp = mc.recall([1, 1, 0, 0], [0, 0, 0, 0])\n self.assertEqual(temp, 0.0)", "solution_code": "def recall(self, predicted_labels, true_labels):\n self.update(predicted_labels, true_labels)\n if self.true_positives + self.false_negatives == 0:\n return 0.0\n return self.true_positives / (self.true_positives + self.false_negatives)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.false_negatives", "self.true_positives" ], "method_dependencies": [ "update" ] } }, { "method_name": "f1_score", "method_description": "def f1_score(self, predicted_labels, true_labels):\n \"\"\"\n Calculate f1 score, which is the harmonic mean of precision and recall\n :param predicted_labels: list, predicted results\n :param true_labels: list, true labels\n :return: float\n >>> mc = MetricsCalculator()\n >>> mc.f1_score([1, 1, 0, 0], [1, 0, 0, 1])\n 0.5\n \"\"\"", "test_class": "MetricsCalculatorTestF1Score", "test_code": "class MetricsCalculatorTestF1Score(unittest.TestCase):\n def test_f1_score_1(self):\n mc = MetricsCalculator()\n temp = mc.f1_score([1, 1, 0, 0], [1, 0, 0, 1])\n self.assertEqual(temp, 0.5)\n\n def test_f1_score_2(self):\n mc = MetricsCalculator()\n temp = mc.f1_score([1, 1, 1, 0], [1, 0, 0, 1])\n self.assertEqual(temp, 0.4)\n\n def test_f1_score_3(self):\n mc = MetricsCalculator()\n temp = mc.f1_score([1, 1, 0, 1], [1, 0, 0, 1])\n self.assertEqual(temp, 0.8)\n\n def test_f1_score_4(self):\n mc = MetricsCalculator()\n temp = mc.f1_score([1, 1, 0, 0], [1, 1, 0, 1])\n self.assertEqual(temp, 0.8)\n\n def test_f1_score_5(self):\n mc = MetricsCalculator()\n temp = mc.f1_score([1, 1, 0, 0], [1, 0, 1, 1])\n self.assertEqual(temp, 0.4)\n\n def test_f1_score_6(self):\n mc = MetricsCalculator()\n temp = mc.f1_score([0, 0, 0, 0], [0, 0, 0, 0])\n self.assertEqual(temp, 0.0)", "solution_code": "def f1_score(self, predicted_labels, true_labels):\n self.update(predicted_labels, true_labels)\n precision = self.precision(predicted_labels, true_labels)\n recall = self.recall(predicted_labels, true_labels)\n if precision + recall == 0.0:\n return 0.0\n return (2 * precision * recall) / (precision + recall)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "update", "precision", "recall" ] } }, { "method_name": "accuracy", "method_description": "def accuracy(self, predicted_labels, true_labels):\n \"\"\"\n Calculate accuracy\n :param predicted_labels: list, predicted results\n :param true_labels: list, true labels\n :return: float\n >>> mc = MetricsCalculator()\n >>>mc.accuracy([1, 1, 0, 0], [1, 0, 0, 1])\n 0.5\n \"\"\"", "test_class": "MetricsCalculatorTestAccuracy", "test_code": "class MetricsCalculatorTestAccuracy(unittest.TestCase):\n def test_accuracy_1(self):\n mc = MetricsCalculator()\n temp = mc.accuracy([1, 1, 0, 0], [1, 0, 0, 1])\n self.assertEqual(temp, 0.5)\n\n def test_accuracy_2(self):\n mc = MetricsCalculator()\n temp = mc.accuracy([1, 1, 2, 0], [1, 0, 0, 1])\n self.assertAlmostEqual(temp, 0.3333333333333333)\n\n def test_accuracy_3(self):\n mc = MetricsCalculator()\n temp = mc.accuracy([1, 1, 0, 1], [1, 0, 0, 1])\n self.assertEqual(temp, 0.75)\n\n def test_accuracy_4(self):\n mc = MetricsCalculator()\n temp = mc.accuracy([1, 1, 0, 0], [1, 1, 0, 1])\n self.assertEqual(temp, 0.75)\n\n def test_accuracy_5(self):\n mc = MetricsCalculator()\n temp = mc.accuracy([1, 1, 0, 0], [1, 0, 1, 1])\n self.assertEqual(temp, 0.25)\n\n def test_accuracy_6(self):\n mc = MetricsCalculator()\n temp = mc.accuracy([], [])\n self.assertEqual(temp, 0.0)", "solution_code": "def accuracy(self, predicted_labels, true_labels):\n self.update(predicted_labels, true_labels)\n total = self.true_positives + self.true_negatives + self.false_positives + self.false_negatives\n if total == 0:\n return 0.0\n return (self.true_positives + self.true_negatives) / total", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.false_negatives", "self.false_positives", "self.true_negatives", "self.true_positives" ], "method_dependencies": [ "update" ] } } ] }, { "task_id": "ClassEval_57", "skeleton": "\nimport numpy as np\n\n\nclass MetricsCalculator2:\n \"\"\"\n The class provides to calculate Mean Reciprocal Rank (MRR) and Mean Average Precision (MAP) based on input data, where MRR measures the ranking quality and MAP measures the average precision.\n \"\"\"\n\n def __init__(self):\n pass\n\n @staticmethod\n def mrr(data):\n \"\"\"\n compute the MRR of the input data. MRR is a widely used evaluation index. It is the mean of reciprocal rank.\n :param data: the data must be a tuple, list 0,1,eg.([1,0,...],5). In each tuple (actual result,ground truth num),ground truth num is the total ground num.\n ([1,0,...],5),\n or list of tuple eg. [([1,0,1,...],5),([1,0,...],6),([0,0,...],5)].\n 1 stands for a correct answer, 0 stands for a wrong answer.\n :return: if input data is list, return the recall of this list. if the input data is list of list, return the\n average recall on all list. The second return value is a list of precision for each input.\n >>> MetricsCalculator2.mrr(([1, 0, 1, 0], 4))\n >>> MetricsCalculator2.mrr([([1, 0, 1, 0], 4), ([0, 1, 0, 1], 4)])\n 1.0, [1.0]\n 0.75, [1.0, 0.5]\n \"\"\"\n\n\n @staticmethod\n def map(data):\n \"\"\"\n compute the MAP of the input data. MAP is a widely used evaluation index. It is the mean of AP (average precision).\n :param data: the data must be a tuple, list 0,1,eg.([1,0,...],5). In each tuple (actual result,ground truth num),ground truth num is the total ground num.\n ([1,0,...],5),\n or list of tuple eg. [([1,0,1,...],5),([1,0,...],6),([0,0,...],5)].\n 1 stands for a correct answer, 0 stands for a wrong answer.\n :return: if input data is list, return the recall of this list. if the input data is list of list, return the\n average recall on all list. The second return value is a list of precision for each input.\n >>> MetricsCalculator2.map(([1, 0, 1, 0], 4))\n >>> MetricsCalculator2.map([([1, 0, 1, 0], 4), ([0, 1, 0, 1], 4)])\n 0.41666666666666663, [0.41666666666666663]\n 0.3333333333333333, [0.41666666666666663, 0.25]\n \"\"\"", "test": "import unittest\n\n\nclass MetricsCalculator2TestMrr(unittest.TestCase):\n def test_mrr_1(self):\n mc2 = MetricsCalculator2()\n res1, res2 = MetricsCalculator2.mrr(([1, 0, 1, 0], 4))\n self.assertEqual(res1, 1.0)\n self.assertEqual(res2, [1.0])\n\n def test_mrr_2(self):\n res1, res2 = MetricsCalculator2.mrr(([0, 0, 0, 1], 4))\n self.assertEqual(res1, 0.25)\n self.assertEqual(res2, [0.25])\n\n def test_mrr_3(self):\n res1, res2 = MetricsCalculator2.mrr([([1, 0, 1, 0], 4), ([0, 1, 0, 1], 4)])\n self.assertEqual(res1, 0.75)\n self.assertEqual(res2, [1.0, 0.5])\n\n def test_mrr_4(self):\n res1, res2 = MetricsCalculator2.mrr([([1, 1, 1, 0], 4), ([0, 0, 0, 1], 4)])\n self.assertEqual(res1, 0.625)\n self.assertEqual(res2, [1.0, 0.25])\n\n def test_mrr_5(self):\n res1, res2 = MetricsCalculator2.mrr([([1, 0, 1, 1], 4), ([0, 1, 0, 0], 4)])\n self.assertEqual(res1, 0.75)\n self.assertEqual(res2, [1.0, 0.5])\n\n def test_mrr_6(self):\n try:\n MetricsCalculator2.mrr(1)\n except:\n pass\n\n def test_mrr_7(self):\n res1, res2 = MetricsCalculator2.mrr([])\n self.assertEqual(res1, 0.0)\n self.assertEqual(res2, [0.0])\n\n def test_mrr_8(self):\n res1, res2 = MetricsCalculator2.mrr([([1, 0, 1, 1], 0), ([0, 1, 0, 0], 0)])\n self.assertEqual(res1, 0.0)\n self.assertEqual(res2, [0.0, 0.0])\n\n\nclass MetricsCalculator2TestMap(unittest.TestCase):\n def test_map_1(self):\n res1, res2 = MetricsCalculator2.map(([1, 0, 1, 0], 4))\n self.assertEqual(res1, 0.41666666666666663)\n self.assertEqual(res2, [0.41666666666666663])\n\n def test_map_2(self):\n res1, res2 = MetricsCalculator2.map(([0, 0, 0, 1], 4))\n self.assertEqual(res1, 0.0625)\n self.assertEqual(res2, [0.0625])\n\n def test_map_3(self):\n res1, res2 = MetricsCalculator2.map([([1, 0, 1, 0], 4), ([0, 1, 0, 1], 4)])\n self.assertEqual(res1, 0.3333333333333333)\n self.assertEqual(res2, [0.41666666666666663, 0.25])\n\n def test_map_4(self):\n res1, res2 = MetricsCalculator2.map([([1, 1, 1, 0], 4), ([0, 0, 0, 1], 4)])\n self.assertEqual(res1, 0.40625)\n self.assertEqual(res2, [0.75, 0.0625])\n\n def test_map_5(self):\n res1, res2 = MetricsCalculator2.map([([1, 0, 1, 1], 4), ([0, 1, 0, 0], 4)])\n self.assertEqual(res1, 0.3645833333333333)\n self.assertEqual(res2, [0.6041666666666666, 0.125])\n\n def test_map_6(self):\n try:\n MetricsCalculator2.map(1)\n except:\n pass\n\n def test_map_7(self):\n res1, res2 = MetricsCalculator2.map([])\n self.assertEqual(res1, 0.0)\n self.assertEqual(res2, [0.0])\n\n def test_map_8(self):\n res1, res2 = MetricsCalculator2.map([([1, 0, 1, 1], 0), ([0, 1, 0, 0], 0)])\n self.assertEqual(res1, 0.0)\n self.assertEqual(res2, [0.0, 0.0])\n\n\nclass MetricsCalculator2Test(unittest.TestCase):\n def test_metricscalculator2_1(self):\n res1, res2 = MetricsCalculator2.mrr(([1, 0, 1, 0], 4))\n self.assertEqual(res1, 1.0)\n self.assertEqual(res2, [1.0])\n\n def test_metricscalculator2_2(self):\n res1, res2 = MetricsCalculator2.mrr([([1, 0, 1, 0], 4), ([0, 1, 0, 1], 4)])\n self.assertEqual(res1, 0.75)\n self.assertEqual(res2, [1.0, 0.5])\n\n def test_metricscalculator2_3(self):\n res1, res2 = MetricsCalculator2.map(([1, 0, 1, 0], 4))\n self.assertEqual(res1, 0.41666666666666663)\n self.assertEqual(res2, [0.41666666666666663])\n\n def test_metricscalculator2_4(self):\n res1, res2 = MetricsCalculator2.map([([1, 0, 1, 0], 4), ([0, 1, 0, 1], 4)])\n self.assertEqual(res1, 0.3333333333333333)\n self.assertEqual(res2, [0.41666666666666663, 0.25])", "solution_code": "import numpy as np\n\n\nclass MetricsCalculator2:\n def __init__(self):\n pass\n\n @staticmethod\n def mrr(data):\n if type(data) != list and type(data) != tuple:\n raise Exception(\"the input must be a tuple([0,...,1,...],int) or a iteration of list of tuple\")\n\n if len(data) == 0:\n return 0.0, [0.0]\n if type(data) == tuple:\n (sub_list, total_num) = data\n sub_list = np.array(sub_list)\n if total_num == 0:\n return 0.0, [0.0]\n else:\n ranking_array = 1.0 / (np.array(list(range(len(sub_list)))) + 1)\n mr_np = sub_list * ranking_array\n\n mr = 0.0\n for team in mr_np:\n if team > 0:\n mr = team\n break\n return mr, [mr]\n\n if type(data) == list:\n separate_result = []\n for (sub_list, total_num) in data:\n sub_list = np.array(sub_list)\n\n if total_num == 0:\n mr = 0.0\n else:\n ranking_array = 1.0 / (np.array(list(range(len(sub_list)))) + 1)\n mr_np = sub_list * ranking_array\n\n mr = 0.0\n for team in mr_np:\n if team > 0:\n mr = team\n break\n\n separate_result.append(mr)\n return np.mean(separate_result), separate_result\n\n @staticmethod\n def map(data):\n if type(data) != list and type(data) != tuple:\n raise Exception(\"the input must be a tuple([0,...,1,...],int) or a iteration of list of tuple\")\n\n if len(data) == 0:\n return 0.0, [0.0]\n if type(data) == tuple:\n (sub_list, total_num) = data\n sub_list = np.array(sub_list)\n if total_num == 0:\n return 0.0, [0.0]\n else:\n ranking_array = 1.0 / (np.array(list(range(len(sub_list)))) + 1)\n\n right_ranking_list = []\n count = 1\n for t in sub_list:\n if t == 0:\n right_ranking_list.append(0)\n else:\n right_ranking_list.append(count)\n count += 1\n\n ap = np.sum(np.array(right_ranking_list) * ranking_array) / total_num\n return ap, [ap]\n\n if type(data) == list:\n separate_result = []\n for (sub_list, total_num) in data:\n sub_list = np.array(sub_list)\n\n if total_num == 0:\n ap = 0.0\n else:\n ranking_array = 1.0 / (np.array(list(range(len(sub_list)))) + 1)\n\n right_ranking_list = []\n count = 1\n for t in sub_list:\n if t == 0:\n right_ranking_list.append(0)\n else:\n right_ranking_list.append(count)\n count += 1\n\n ap = np.sum(np.array(right_ranking_list) * ranking_array) / total_num\n\n separate_result.append(ap)\n return np.mean(separate_result), separate_result", "import_statement": [ "import numpy as np" ], "class_description": " \"\"\"\n The class provides to calculate Mean Reciprocal Rank (MRR) and Mean Average Precision (MAP) based on input data, where MRR measures the ranking quality and MAP measures the average precision.\n \"\"\"\n", "class_name": "MetricsCalculator2", "test_classes": [ "MetricsCalculator2TestMrr", "MetricsCalculator2TestMap", "MetricsCalculator2Test" ], "class_constructor": "class MetricsCalculator2: \n def __init__(self):\n pass\n\n @staticmethod\n", "fields": [], "methods_info": [ { "method_name": "mrr", "method_description": "def mrr(data):\n \"\"\"\n compute the MRR of the input data. MRR is a widely used evaluation index. It is the mean of reciprocal rank.\n :param data: the data must be a tuple, list 0,1,eg.([1,0,...],5). In each tuple (actual result,ground truth num),ground truth num is the total ground num.\n ([1,0,...],5),\n or list of tuple eg. [([1,0,1,...],5),([1,0,...],6),([0,0,...],5)].\n 1 stands for a correct answer, 0 stands for a wrong answer.\n :return: if input data is list, return the recall of this list. if the input data is list of list, return the\n average recall on all list. The second return value is a list of precision for each input.\n >>> MetricsCalculator2.mrr(([1, 0, 1, 0], 4))\n >>> MetricsCalculator2.mrr([([1, 0, 1, 0], 4), ([0, 1, 0, 1], 4)])\n 1.0, [1.0]\n 0.75, [1.0, 0.5]\n \"\"\"", "test_class": "MetricsCalculator2TestMrr", "test_code": "class MetricsCalculator2TestMrr(unittest.TestCase):\n def test_mrr_1(self):\n mc2 = MetricsCalculator2()\n res1, res2 = MetricsCalculator2.mrr(([1, 0, 1, 0], 4))\n self.assertEqual(res1, 1.0)\n self.assertEqual(res2, [1.0])\n\n def test_mrr_2(self):\n res1, res2 = MetricsCalculator2.mrr(([0, 0, 0, 1], 4))\n self.assertEqual(res1, 0.25)\n self.assertEqual(res2, [0.25])\n\n def test_mrr_3(self):\n res1, res2 = MetricsCalculator2.mrr([([1, 0, 1, 0], 4), ([0, 1, 0, 1], 4)])\n self.assertEqual(res1, 0.75)\n self.assertEqual(res2, [1.0, 0.5])\n\n def test_mrr_4(self):\n res1, res2 = MetricsCalculator2.mrr([([1, 1, 1, 0], 4), ([0, 0, 0, 1], 4)])\n self.assertEqual(res1, 0.625)\n self.assertEqual(res2, [1.0, 0.25])\n\n def test_mrr_5(self):\n res1, res2 = MetricsCalculator2.mrr([([1, 0, 1, 1], 4), ([0, 1, 0, 0], 4)])\n self.assertEqual(res1, 0.75)\n self.assertEqual(res2, [1.0, 0.5])\n\n def test_mrr_6(self):\n try:\n MetricsCalculator2.mrr(1)\n except:\n pass\n\n def test_mrr_7(self):\n res1, res2 = MetricsCalculator2.mrr([])\n self.assertEqual(res1, 0.0)\n self.assertEqual(res2, [0.0])\n\n def test_mrr_8(self):\n res1, res2 = MetricsCalculator2.mrr([([1, 0, 1, 1], 0), ([0, 1, 0, 0], 0)])\n self.assertEqual(res1, 0.0)\n self.assertEqual(res2, [0.0, 0.0])", "solution_code": "def mrr(data):\n if type(data) != list and type(data) != tuple:\n raise Exception(\"the input must be a tuple([0,...,1,...],int) or a iteration of list of tuple\")\n\n if len(data) == 0:\n return 0.0, [0.0]\n if type(data) == tuple:\n (sub_list, total_num) = data\n sub_list = np.array(sub_list)\n if total_num == 0:\n return 0.0, [0.0]\n else:\n ranking_array = 1.0 / (np.array(list(range(len(sub_list)))) + 1)\n mr_np = sub_list * ranking_array\n\n mr = 0.0\n for team in mr_np:\n if team > 0:\n mr = team\n break\n return mr, [mr]\n\n if type(data) == list:\n separate_result = []\n for (sub_list, total_num) in data:\n sub_list = np.array(sub_list)\n\n if total_num == 0:\n mr = 0.0\n else:\n ranking_array = 1.0 / (np.array(list(range(len(sub_list)))) + 1)\n mr_np = sub_list * ranking_array\n\n mr = 0.0\n for team in mr_np:\n if team > 0:\n mr = team\n break\n\n separate_result.append(mr)\n return np.mean(separate_result), separate_result", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "map", "method_description": "@staticmethod\n def map(data):\n \"\"\"\n compute the MAP of the input data. MAP is a widely used evaluation index. It is the mean of AP (average precision).\n :param data: the data must be a tuple, list 0,1,eg.([1,0,...],5). In each tuple (actual result,ground truth num),ground truth num is the total ground num.\n ([1,0,...],5),\n or list of tuple eg. [([1,0,1,...],5),([1,0,...],6),([0,0,...],5)].\n 1 stands for a correct answer, 0 stands for a wrong answer.\n :return: if input data is list, return the recall of this list. if the input data is list of list, return the\n average recall on all list. The second return value is a list of precision for each input.\n >>> MetricsCalculator2.map(([1, 0, 1, 0], 4))\n >>> MetricsCalculator2.map([([1, 0, 1, 0], 4), ([0, 1, 0, 1], 4)])\n 0.41666666666666663, [0.41666666666666663]\n 0.3333333333333333, [0.41666666666666663, 0.25]\n \"\"\"", "test_class": "MetricsCalculator2TestMap", "test_code": "class MetricsCalculator2TestMap(unittest.TestCase):\n def test_map_1(self):\n res1, res2 = MetricsCalculator2.map(([1, 0, 1, 0], 4))\n self.assertEqual(res1, 0.41666666666666663)\n self.assertEqual(res2, [0.41666666666666663])\n\n def test_map_2(self):\n res1, res2 = MetricsCalculator2.map(([0, 0, 0, 1], 4))\n self.assertEqual(res1, 0.0625)\n self.assertEqual(res2, [0.0625])\n\n def test_map_3(self):\n res1, res2 = MetricsCalculator2.map([([1, 0, 1, 0], 4), ([0, 1, 0, 1], 4)])\n self.assertEqual(res1, 0.3333333333333333)\n self.assertEqual(res2, [0.41666666666666663, 0.25])\n\n def test_map_4(self):\n res1, res2 = MetricsCalculator2.map([([1, 1, 1, 0], 4), ([0, 0, 0, 1], 4)])\n self.assertEqual(res1, 0.40625)\n self.assertEqual(res2, [0.75, 0.0625])\n\n def test_map_5(self):\n res1, res2 = MetricsCalculator2.map([([1, 0, 1, 1], 4), ([0, 1, 0, 0], 4)])\n self.assertEqual(res1, 0.3645833333333333)\n self.assertEqual(res2, [0.6041666666666666, 0.125])\n\n def test_map_6(self):\n try:\n MetricsCalculator2.map(1)\n except:\n pass\n\n def test_map_7(self):\n res1, res2 = MetricsCalculator2.map([])\n self.assertEqual(res1, 0.0)\n self.assertEqual(res2, [0.0])\n\n def test_map_8(self):\n res1, res2 = MetricsCalculator2.map([([1, 0, 1, 1], 0), ([0, 1, 0, 0], 0)])\n self.assertEqual(res1, 0.0)\n self.assertEqual(res2, [0.0, 0.0])", "solution_code": "@staticmethod\n def map(data):\n if type(data) != list and type(data) != tuple:\n raise Exception(\"the input must be a tuple([0,...,1,...],int) or a iteration of list of tuple\")\n\n if len(data) == 0:\n return 0.0, [0.0]\n if type(data) == tuple:\n (sub_list, total_num) = data\n sub_list = np.array(sub_list)\n if total_num == 0:\n return 0.0, [0.0]\n else:\n ranking_array = 1.0 / (np.array(list(range(len(sub_list)))) + 1)\n\n right_ranking_list = []\n count = 1\n for t in sub_list:\n if t == 0:\n right_ranking_list.append(0)\n else:\n right_ranking_list.append(count)\n count += 1\n\n ap = np.sum(np.array(right_ranking_list) * ranking_array) / total_num\n return ap, [ap]\n\n if type(data) == list:\n separate_result = []\n for (sub_list, total_num) in data:\n sub_list = np.array(sub_list)\n\n if total_num == 0:\n ap = 0.0\n else:\n ranking_array = 1.0 / (np.array(list(range(len(sub_list)))) + 1)\n\n right_ranking_list = []\n count = 1\n for t in sub_list:\n if t == 0:\n right_ranking_list.append(0)\n else:\n right_ranking_list.append(count)\n count += 1\n\n ap = np.sum(np.array(right_ranking_list) * ranking_array) / total_num\n\n separate_result.append(ap)\n return np.mean(separate_result), separate_result", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_58", "skeleton": "\nimport random\n\nclass MinesweeperGame:\n \"\"\"\n This is a class that implements mine sweeping games including minesweeping and winning judgment.\n \"\"\"\n\n def __init__(self, n, k) -> None:\n \"\"\"\n Initializes the MinesweeperGame class with the size of the board and the number of mines.\n :param n: The size of the board, int.\n :param k: The number of mines, int.\n \"\"\"\n self.n = n\n self.k = k\n self.minesweeper_map = self.generate_mine_sweeper_map()\n self.player_map = self.generate_playerMap()\n self.score = 0\n\n def generate_mine_sweeper_map(self):\n \"\"\"\n Generates a minesweeper map with the given size of the board and the number of mines,the given parameter n is the size of the board,the size of the board is n*n,the parameter k is the number of mines,'X' represents the mine,other numbers represent the number of mines around the position.\n :return: The minesweeper map, list.\n >>> minesweeper_game = MinesweeperGame(3, 1)\n >>> minesweeper_game.generate_mine_sweeper_map()\n [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n\n \"\"\"\n\n def generate_playerMap(self):\n \"\"\"\n Generates a player map with the given size of the board, the given parameter n is the size of the board,the size of the board is n*n,the parameter k is the number of mines,'-' represents the unknown position.\n :return: The player map, list.\n >>> minesweeper_game = MinesweeperGame(3, 1)\n >>> minesweeper_game.generate_playerMap()\n [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]\n\n \"\"\"\n\n def check_won(self,map):\n \"\"\"\n Checks whether the player has won the game,if there are just mines in the player map,return True,otherwise return False.\n :return: True if the player has won the game, False otherwise.\n >>> minesweeper_game = MinesweeperGame(3, 1)\n >>> minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n >>> minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]\n >>> minesweeper_game.check_won(minesweeper_game.player_map)\n False\n\n \"\"\"\n\n def sweep(self, x, y):\n \"\"\"\n Sweeps the given position.\n :param x: The x coordinate of the position, int.\n :param y: The y coordinate of the position, int.\n :return: True if the player has won the game, False otherwise,if the game still continues, return the player map, list.\n >>> minesweeper_game = MinesweeperGame(3, 1)\n >>> minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n >>> minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]\n >>> minesweeper_game.sweep(1, 1)\n [['-', '-', '-'], ['-', 1, '-'], ['-', '-', '-']]\n\n \"\"\"", "test": "import unittest\n\nclass MinesweeperGameTestGenerateMineSweeperMap(unittest.TestCase):\n def test_generate_mine_sweeper_map(self):\n minesweeper_game = MinesweeperGame(3, 2)\n length = len(minesweeper_game.minesweeper_map)\n mine_num = 0\n for row in minesweeper_game.minesweeper_map:\n for cell in row:\n if cell == 'X':\n mine_num += 1\n self.assertEqual(3, length)\n self.assertEqual(2, mine_num)\n\n def test_generate_mine_sweeper_map_2(self):\n minesweeper_game = MinesweeperGame(3, 1)\n length = len(minesweeper_game.minesweeper_map)\n mine_num = 0\n for row in minesweeper_game.minesweeper_map:\n for cell in row:\n if cell == 'X':\n mine_num += 1\n self.assertEqual(3, length)\n self.assertEqual(1, mine_num)\n\n def test_generate_mine_sweeper_map_3(self):\n minesweeper_game = MinesweeperGame(3, 0)\n length = len(minesweeper_game.minesweeper_map)\n mine_num = 0\n for row in minesweeper_game.minesweeper_map:\n for cell in row:\n if cell == 'X':\n mine_num += 1\n self.assertEqual(3, length)\n self.assertEqual(0, mine_num)\n\n def test_generate_mine_sweeper_map_4(self):\n minesweeper_game = MinesweeperGame(5, 1)\n length = len(minesweeper_game.minesweeper_map)\n mine_num = 0\n for row in minesweeper_game.minesweeper_map:\n for cell in row:\n if cell == 'X':\n mine_num += 1\n self.assertEqual(length,5)\n self.assertEqual(mine_num, 1)\n\n def test_generate_mine_sweeper_map_5(self):\n minesweeper_game = MinesweeperGame(4, 1)\n length = len(minesweeper_game.minesweeper_map)\n mine_num = 0\n for row in minesweeper_game.minesweeper_map:\n for cell in row:\n if cell == 'X':\n mine_num += 1\n self.assertEqual(length, 4)\n self.assertEqual(mine_num, 1)\n\nclass MinesweeperGameTestGeneratePlayerMap(unittest.TestCase):\n def test_generate_playerMap(self):\n minesweeper_game = MinesweeperGame(3, 2)\n self.assertEqual(minesweeper_game.generate_playerMap(), [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']])\n\n def test_generate_playerMap_2(self):\n minesweeper_game = MinesweeperGame(3, 1)\n self.assertEqual(minesweeper_game.generate_playerMap(), [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']])\n\n def test_generate_playerMap_3(self):\n minesweeper_game = MinesweeperGame(4, 2)\n self.assertEqual(minesweeper_game.generate_playerMap(),[['-', '-', '-', '-'],['-', '-', '-', '-'],['-', '-', '-', '-'],['-', '-', '-', '-']])\n\n def test_generate_playerMap_4(self):\n minesweeper_game = MinesweeperGame(1, 4)\n self.assertEqual(minesweeper_game.generate_playerMap(), [['-']])\n\n def test_generate_playerMap_5(self):\n minesweeper_game = MinesweeperGame(2, 5)\n self.assertEqual(minesweeper_game.generate_playerMap(), [['-', '-'], ['-', '-']])\n\nclass MinesweeperGameTestCheckWon(unittest.TestCase):\n def test_check_won(self):\n minesweeper_game = MinesweeperGame(3, 1)\n minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]\n self.assertEqual(minesweeper_game.check_won(minesweeper_game.player_map), False)\n\n def test_check_won_2(self):\n minesweeper_game = MinesweeperGame(3, 1)\n minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n minesweeper_game.player_map = [['-', '-', '-'], ['-', 1, '-'], ['-', '-', '-']]\n self.assertEqual(minesweeper_game.check_won(minesweeper_game.player_map), False)\n\n def test_check_won_3(self):\n minesweeper_game = MinesweeperGame(3, 0)\n minesweeper_game.minesweeper_map = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]\n minesweeper_game.player_map = [['-', '-', '-'], ['-', 1, '-'], ['-', '-', '-']]\n self.assertEqual(minesweeper_game.check_won(minesweeper_game.player_map), False)\n\n def test_check_won_4(self):\n minesweeper_game = MinesweeperGame(3, 1)\n minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n minesweeper_game.player_map = [['-', '1', '0'], ['1', 1, '0'], ['0', '0', '0']]\n self.assertEqual(minesweeper_game.check_won(minesweeper_game.player_map), True)\n\n def test_check_won_5(self):\n minesweeper_game = MinesweeperGame(3, 1)\n minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n minesweeper_game.player_map = [['X', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]\n self.assertEqual(minesweeper_game.check_won(minesweeper_game.player_map), False)\n\nclass MinesweeperGameTestSweep(unittest.TestCase):\n def test_sweep(self):\n minesweeper_game = MinesweeperGame(3, 1)\n minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]\n self.assertEqual(minesweeper_game.sweep(1,1), [['-', '-', '-'], ['-', 1, '-'], ['-', '-', '-']])\n self.assertEqual(minesweeper_game.score, 1)\n\n def test_sweep_2(self):\n minesweeper_game = MinesweeperGame(3, 1)\n minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]\n self.assertEqual(minesweeper_game.sweep(0,0), False)\n self.assertEqual(minesweeper_game.score, 0)\n\n def test_sweep_3(self):\n minesweeper_game = MinesweeperGame(3, 1)\n minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n minesweeper_game.player_map = [['-', '-', '0'], ['1', '1', '0'], ['0', '0', '0']]\n self.assertEqual(minesweeper_game.sweep(0,1), True)\n self.assertEqual(minesweeper_game.score, 1)\n\n def test_sweep_4(self):\n minesweeper_game = MinesweeperGame(3, 1)\n minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '0'], ['0', '0', '0']]\n self.assertEqual(minesweeper_game.sweep(0,2), [['-', '-', 0], ['-', '-', '0'], ['0', '0', '0']])\n self.assertEqual(minesweeper_game.score, 1)\n\n def test_sweep_5(self):\n minesweeper_game = MinesweeperGame(3, 1)\n minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n minesweeper_game.player_map = [['-', '-', '0'], ['-', '1', '0'], ['0', '0', '0']]\n self.assertEqual(minesweeper_game.sweep(1,0), [['-', '-', '0'], [1, '1', '0'], ['0', '0', '0']])\n self.assertEqual(minesweeper_game.score, 1)\n\nclass MinesweeperGameTestMain(unittest.TestCase):\n def test_minesweeper_main(self):\n minesweeper_game = MinesweeperGame(3, 1)\n length = len(minesweeper_game.minesweeper_map)\n mine_num = 0\n for row in minesweeper_game.minesweeper_map:\n for cell in row:\n if cell == 'X':\n mine_num += 1\n self.assertEqual(3, length)\n self.assertEqual(1, mine_num)\n self.assertEqual(minesweeper_game.generate_playerMap(), [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']])\n minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]\n self.assertEqual(minesweeper_game.check_won(minesweeper_game.player_map), False)\n self.assertEqual(minesweeper_game.sweep(1,1), [['-', '-', '-'], ['-', 1, '-'], ['-', '-', '-']])\n self.assertEqual(minesweeper_game.score, 1)\n\n def test_minesweeper_main_2(self):\n minesweeper_game = MinesweeperGame(3, 2)\n length = len(minesweeper_game.minesweeper_map)\n mine_num = 0\n for row in minesweeper_game.minesweeper_map:\n for cell in row:\n if cell == 'X':\n mine_num += 1\n self.assertEqual(3, length)\n self.assertEqual(2, mine_num)\n self.assertEqual(minesweeper_game.generate_playerMap(), [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']])\n minesweeper_game.minesweeper_map = [['X', 1, 1], [1, 'X', 1], [1, 1, 1]]\n self.assertEqual(minesweeper_game.check_won(minesweeper_game.player_map), False)\n self.assertEqual(minesweeper_game.sweep(0, 1), [['-', 1, '-'], ['-','-', '-'], ['-', '-', '-']])\n self.assertEqual(minesweeper_game.score, 1)\n self.assertEqual(minesweeper_game.sweep(0, 2), [['-', 1, 1], ['-', '-', '-'], ['-', '-', '-']])\n self.assertEqual(minesweeper_game.score, 2)", "solution_code": "import random\n\nclass MinesweeperGame:\n def __init__(self, n, k) -> None:\n self.n = n\n self.k = k\n self.minesweeper_map = self.generate_mine_sweeper_map()\n self.player_map = self.generate_playerMap()\n self.score = 0\n\n def generate_mine_sweeper_map(self):\n arr = [[0 for row in range(self.n)] for column in range(self.n)]\n for num in range(self.k):\n x = random.randint(0, self.n-1)\n y = random.randint(0, self.n-1)\n arr[y][x] = 'X'\n if (x >=0 and x <= self.n-2) and (y >= 0 and y <= self.n-1):\n if arr[y][x+1] != 'X':\n arr[y][x+1] += 1\n if (x >=1 and x <= self.n-1) and (y >= 0 and y <= self.n-1):\n if arr[y][x-1] != 'X':\n arr[y][x-1] += 1\n if (x >= 1 and x <= self.n-1) and (y >= 1 and y <= self.n-1):\n if arr[y-1][x-1] != 'X':\n arr[y-1][x-1] += 1\n \n if (x >= 0 and x <= self.n-2) and (y >= 1 and y <= self.n-1):\n if arr[y-1][x+1] != 'X':\n arr[y-1][x+1] += 1 \n if (x >= 0 and x <= self.n-1) and (y >= 1 and y <= self.n-1):\n if arr[y-1][x] != 'X':\n arr[y-1][x] += 1\n \n if (x >=0 and x <= self.n-2) and (y >= 0 and y <= self.n-2):\n if arr[y+1][x+1] != 'X':\n arr[y+1][x+1] += 1\n if (x >= 1 and x <= self.n-1) and (y >= 0 and y <= self.n-2):\n if arr[y+1][x-1] != 'X':\n arr[y+1][x-1] += 1\n if (x >= 0 and x <= self.n-1) and (y >= 0 and y <= self.n-2):\n if arr[y+1][x] != 'X':\n arr[y+1][x] += 1\n return arr\n \n def generate_playerMap(self):\n arr = [['-' for row in range(self.n)] for column in range(self.n)]\n return arr\n\n def check_won(self, map):\n for i in range(self.n):\n for j in range(self.n):\n if map[i][j] == '-' and self.minesweeper_map[i][j] != 'X':\n return False\n return True\n \n def sweep(self, x, y):\n\n if (self.minesweeper_map[x][y] == 'X'):\n return False\n else:\n self.player_map[x][y] = self.minesweeper_map[x][y]\n self.score += 1\n if self.check_won(self.player_map) == True:\n return True\n return self.player_map", "import_statement": [ "import random" ], "class_description": " \"\"\"\n This is a class that implements mine sweeping games including minesweeping and winning judgment.\n \"\"\"\n", "class_name": "MinesweeperGame", "test_classes": [ "MinesweeperGameTestGenerateMineSweeperMap", "MinesweeperGameTestGeneratePlayerMap", "MinesweeperGameTestCheckWon", "MinesweeperGameTestSweep", "MinesweeperGameTestMain" ], "class_constructor": "class MinesweeperGame: \n def __init__(self, n, k) -> None:\n \"\"\"\n Initializes the MinesweeperGame class with the size of the board and the number of mines.\n :param n: The size of the board, int.\n :param k: The number of mines, int.\n \"\"\"\n self.n = n\n self.k = k\n self.minesweeper_map = self.generate_mine_sweeper_map()\n self.player_map = self.generate_playerMap()\n self.score = 0\n\n", "fields": [ "self.k", "self.minesweeper_map", "self.n", "self.player_map", "self.score" ], "methods_info": [ { "method_name": "generate_mine_sweeper_map", "method_description": "def generate_mine_sweeper_map(self):\n \"\"\"\n Generates a minesweeper map with the given size of the board and the number of mines,the given parameter n is the size of the board,the size of the board is n*n,the parameter k is the number of mines,'X' represents the mine,other numbers represent the number of mines around the position.\n :return: The minesweeper map, list.\n >>> minesweeper_game = MinesweeperGame(3, 1)\n >>> minesweeper_game.generate_mine_sweeper_map()\n [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n\n \"\"\"", "test_class": "MinesweeperGameTestGenerateMineSweeperMap", "test_code": "class MinesweeperGameTestGenerateMineSweeperMap(unittest.TestCase):\n def test_generate_mine_sweeper_map(self):\n minesweeper_game = MinesweeperGame(3, 2)\n length = len(minesweeper_game.minesweeper_map)\n mine_num = 0\n for row in minesweeper_game.minesweeper_map:\n for cell in row:\n if cell == 'X':\n mine_num += 1\n self.assertEqual(3, length)\n self.assertEqual(2, mine_num)\n\n def test_generate_mine_sweeper_map_2(self):\n minesweeper_game = MinesweeperGame(3, 1)\n length = len(minesweeper_game.minesweeper_map)\n mine_num = 0\n for row in minesweeper_game.minesweeper_map:\n for cell in row:\n if cell == 'X':\n mine_num += 1\n self.assertEqual(3, length)\n self.assertEqual(1, mine_num)\n\n def test_generate_mine_sweeper_map_3(self):\n minesweeper_game = MinesweeperGame(3, 0)\n length = len(minesweeper_game.minesweeper_map)\n mine_num = 0\n for row in minesweeper_game.minesweeper_map:\n for cell in row:\n if cell == 'X':\n mine_num += 1\n self.assertEqual(3, length)\n self.assertEqual(0, mine_num)\n\n def test_generate_mine_sweeper_map_4(self):\n minesweeper_game = MinesweeperGame(5, 1)\n length = len(minesweeper_game.minesweeper_map)\n mine_num = 0\n for row in minesweeper_game.minesweeper_map:\n for cell in row:\n if cell == 'X':\n mine_num += 1\n self.assertEqual(length,5)\n self.assertEqual(mine_num, 1)\n\n def test_generate_mine_sweeper_map_5(self):\n minesweeper_game = MinesweeperGame(4, 1)\n length = len(minesweeper_game.minesweeper_map)\n mine_num = 0\n for row in minesweeper_game.minesweeper_map:\n for cell in row:\n if cell == 'X':\n mine_num += 1\n self.assertEqual(length, 4)\n self.assertEqual(mine_num, 1)", "solution_code": "def generate_mine_sweeper_map(self):\n arr = [[0 for row in range(self.n)] for column in range(self.n)]\n for num in range(self.k):\n x = random.randint(0, self.n-1)\n y = random.randint(0, self.n-1)\n arr[y][x] = 'X'\n if (x >=0 and x <= self.n-2) and (y >= 0 and y <= self.n-1):\n if arr[y][x+1] != 'X':\n arr[y][x+1] += 1\n if (x >=1 and x <= self.n-1) and (y >= 0 and y <= self.n-1):\n if arr[y][x-1] != 'X':\n arr[y][x-1] += 1\n if (x >= 1 and x <= self.n-1) and (y >= 1 and y <= self.n-1):\n if arr[y-1][x-1] != 'X':\n arr[y-1][x-1] += 1\n \n if (x >= 0 and x <= self.n-2) and (y >= 1 and y <= self.n-1):\n if arr[y-1][x+1] != 'X':\n arr[y-1][x+1] += 1 \n if (x >= 0 and x <= self.n-1) and (y >= 1 and y <= self.n-1):\n if arr[y-1][x] != 'X':\n arr[y-1][x] += 1\n \n if (x >=0 and x <= self.n-2) and (y >= 0 and y <= self.n-2):\n if arr[y+1][x+1] != 'X':\n arr[y+1][x+1] += 1\n if (x >= 1 and x <= self.n-1) and (y >= 0 and y <= self.n-2):\n if arr[y+1][x-1] != 'X':\n arr[y+1][x-1] += 1\n if (x >= 0 and x <= self.n-1) and (y >= 0 and y <= self.n-2):\n if arr[y+1][x] != 'X':\n arr[y+1][x] += 1\n return arr", "dependencies": { "Standalone": false, "lib_dependencies": [ "random" ], "field_dependencies": [ "self.k", "self.n" ], "method_dependencies": [] } }, { "method_name": "generate_playerMap", "method_description": "def generate_playerMap(self):\n \"\"\"\n Generates a player map with the given size of the board, the given parameter n is the size of the board,the size of the board is n*n,the parameter k is the number of mines,'-' represents the unknown position.\n :return: The player map, list.\n >>> minesweeper_game = MinesweeperGame(3, 1)\n >>> minesweeper_game.generate_playerMap()\n [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]\n\n \"\"\"", "test_class": "MinesweeperGameTestGeneratePlayerMap", "test_code": "class MinesweeperGameTestGeneratePlayerMap(unittest.TestCase):\n def test_generate_playerMap(self):\n minesweeper_game = MinesweeperGame(3, 2)\n self.assertEqual(minesweeper_game.generate_playerMap(), [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']])\n\n def test_generate_playerMap_2(self):\n minesweeper_game = MinesweeperGame(3, 1)\n self.assertEqual(minesweeper_game.generate_playerMap(), [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']])\n\n def test_generate_playerMap_3(self):\n minesweeper_game = MinesweeperGame(4, 2)\n self.assertEqual(minesweeper_game.generate_playerMap(),[['-', '-', '-', '-'],['-', '-', '-', '-'],['-', '-', '-', '-'],['-', '-', '-', '-']])\n\n def test_generate_playerMap_4(self):\n minesweeper_game = MinesweeperGame(1, 4)\n self.assertEqual(minesweeper_game.generate_playerMap(), [['-']])\n\n def test_generate_playerMap_5(self):\n minesweeper_game = MinesweeperGame(2, 5)\n self.assertEqual(minesweeper_game.generate_playerMap(), [['-', '-'], ['-', '-']])", "solution_code": "def generate_playerMap(self):\n arr = [['-' for row in range(self.n)] for column in range(self.n)]\n return arr", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.n" ], "method_dependencies": [] } }, { "method_name": "check_won", "method_description": "def check_won(self,map):\n \"\"\"\n Checks whether the player has won the game,if there are just mines in the player map,return True,otherwise return False.\n :return: True if the player has won the game, False otherwise.\n >>> minesweeper_game = MinesweeperGame(3, 1)\n >>> minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n >>> minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]\n >>> minesweeper_game.check_won(minesweeper_game.player_map)\n False\n\n \"\"\"", "test_class": "MinesweeperGameTestCheckWon", "test_code": "class MinesweeperGameTestCheckWon(unittest.TestCase):\n def test_check_won(self):\n minesweeper_game = MinesweeperGame(3, 1)\n minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]\n self.assertEqual(minesweeper_game.check_won(minesweeper_game.player_map), False)\n\n def test_check_won_2(self):\n minesweeper_game = MinesweeperGame(3, 1)\n minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n minesweeper_game.player_map = [['-', '-', '-'], ['-', 1, '-'], ['-', '-', '-']]\n self.assertEqual(minesweeper_game.check_won(minesweeper_game.player_map), False)\n\n def test_check_won_3(self):\n minesweeper_game = MinesweeperGame(3, 0)\n minesweeper_game.minesweeper_map = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]\n minesweeper_game.player_map = [['-', '-', '-'], ['-', 1, '-'], ['-', '-', '-']]\n self.assertEqual(minesweeper_game.check_won(minesweeper_game.player_map), False)\n\n def test_check_won_4(self):\n minesweeper_game = MinesweeperGame(3, 1)\n minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n minesweeper_game.player_map = [['-', '1', '0'], ['1', 1, '0'], ['0', '0', '0']]\n self.assertEqual(minesweeper_game.check_won(minesweeper_game.player_map), True)\n\n def test_check_won_5(self):\n minesweeper_game = MinesweeperGame(3, 1)\n minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n minesweeper_game.player_map = [['X', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]\n self.assertEqual(minesweeper_game.check_won(minesweeper_game.player_map), False)", "solution_code": "def check_won(self, map):\n for i in range(self.n):\n for j in range(self.n):\n if map[i][j] == '-' and self.minesweeper_map[i][j] != 'X':\n return False\n return True", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.minesweeper_map", "self.n" ], "method_dependencies": [ "sweep" ] } }, { "method_name": "sweep", "method_description": "def sweep(self, x, y):\n \"\"\"\n Sweeps the given position.\n :param x: The x coordinate of the position, int.\n :param y: The y coordinate of the position, int.\n :return: True if the player has won the game, False otherwise,if the game still continues, return the player map, list.\n >>> minesweeper_game = MinesweeperGame(3, 1)\n >>> minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n >>> minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]\n >>> minesweeper_game.sweep(1, 1)\n [['-', '-', '-'], ['-', 1, '-'], ['-', '-', '-']]\n\n \"\"\"", "test_class": "MinesweeperGameTestSweep", "test_code": "class MinesweeperGameTestSweep(unittest.TestCase):\n def test_sweep(self):\n minesweeper_game = MinesweeperGame(3, 1)\n minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]\n self.assertEqual(minesweeper_game.sweep(1,1), [['-', '-', '-'], ['-', 1, '-'], ['-', '-', '-']])\n self.assertEqual(minesweeper_game.score, 1)\n\n def test_sweep_2(self):\n minesweeper_game = MinesweeperGame(3, 1)\n minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]\n self.assertEqual(minesweeper_game.sweep(0,0), False)\n self.assertEqual(minesweeper_game.score, 0)\n\n def test_sweep_3(self):\n minesweeper_game = MinesweeperGame(3, 1)\n minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n minesweeper_game.player_map = [['-', '-', '0'], ['1', '1', '0'], ['0', '0', '0']]\n self.assertEqual(minesweeper_game.sweep(0,1), True)\n self.assertEqual(minesweeper_game.score, 1)\n\n def test_sweep_4(self):\n minesweeper_game = MinesweeperGame(3, 1)\n minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n minesweeper_game.player_map = [['-', '-', '-'], ['-', '-', '0'], ['0', '0', '0']]\n self.assertEqual(minesweeper_game.sweep(0,2), [['-', '-', 0], ['-', '-', '0'], ['0', '0', '0']])\n self.assertEqual(minesweeper_game.score, 1)\n\n def test_sweep_5(self):\n minesweeper_game = MinesweeperGame(3, 1)\n minesweeper_game.minesweeper_map = [['X', 1, 0], [1, 1, 0], [0, 0, 0]]\n minesweeper_game.player_map = [['-', '-', '0'], ['-', '1', '0'], ['0', '0', '0']]\n self.assertEqual(minesweeper_game.sweep(1,0), [['-', '-', '0'], [1, '1', '0'], ['0', '0', '0']])\n self.assertEqual(minesweeper_game.score, 1)", "solution_code": "def sweep(self, x, y):\n\n if (self.minesweeper_map[x][y] == 'X'):\n return False\n else:\n self.player_map[x][y] = self.minesweeper_map[x][y]\n self.score += 1\n if self.check_won(self.player_map) == True:\n return True\n return self.player_map", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.minesweeper_map", "self.player_map", "self.score" ], "method_dependencies": [ "check_won" ] } } ] }, { "task_id": "ClassEval_59", "skeleton": "\nfrom datetime import datetime\nimport numpy as np\n\nclass MovieBookingSystem:\n \"\"\"\n this is a class as movie booking system, which allows to add movies, book tickets and check the available movies within a given time range. \n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialize movies contains the information about movies\n >>> system.movies\n [{'name': 'Batman', 'price': 49.9, 'start_time': datetime.datetime(1900, 1, 1, 17, 5), 'end_time': datetime.datetime(1900, 1, 1, 19, 25),\n 'seats': array([[0., 0., 0.],\n [0., 0., 0.],\n [0., 0., 0.]])}]\n \"\"\"\n self.movies = []\n\n def add_movie(self, name, price, start_time, end_time, n):\n \"\"\"\n Add a new movie into self.movies\n :param name: str, movie name\n :param price: float, price for one ticket\n :param start_time: str\n :param end_time: str\n :param n: int, the size of seats(n*n)\n >>> system.add_movie('Batman', 49.9, '17:05', '19:25', 3)\n >>> system.movies\n [{'name': 'Batman', 'price': 49.9, 'start_time': datetime.datetime(1900, 1, 1, 17, 5), 'end_time': datetime.datetime(1900, 1, 1, 19, 25),\n 'seats': array([[0., 0., 0.],\n [0., 0., 0.],\n [0., 0., 0.]])}]\n \"\"\"\n\n def book_ticket(self, name, seats_to_book):\n \"\"\"\n Book tickets for a movie. Change the seats value in self.movies if book successfully.\n :param name: str, movie name\n :param seats_to_book: list of tuples, representing seats to book [(row1, col1), (row2, col2), ...]\n :return: str, booking status message. \"Movie not found.\" for no such movie.\n \"Booking success.\" for successfully booking, or \"Booking failed.\" otherwise\n >>> system.add_movie('Batman', 49.9, '17:05', '19:25', 3)\n >>> system.book_ticket('Batman', [(0, 0), (0, 1)])\n 'Booking success.'\n >>> system.book_ticket('Batman', [(0, 0)])\n 'Booking failed.'\n >>> system.book_ticket('batman', [(0, 0)])\n 'Movie not found.'\n \"\"\"\n\n def available_movies(self, start_time, end_time):\n \"\"\"\n Get a list of available movies within the specified time range\n :param start_time: str, start time in HH:MM format\n :param end_time: str, end time in HH:MM format\n :return: list of str, names of available movies\n >>> system.add_movie('Batman', 49.9, '17:05', '19:25', 3)\n >>> system.available_movies('12:00', '22:00')\n ['Batman']\n \"\"\"", "test": "import unittest\n\n\nclass MovieBookingSystemTestAddMovie(unittest.TestCase):\n def setUp(self):\n self.system = MovieBookingSystem()\n\n def tearDown(self):\n self.system = None\n\n def test_add_movie_1(self):\n self.system.add_movie('Batman', 49.9, '17:05', '19:25', 3)\n self.assertEqual(len(self.system.movies), 1)\n self.assertEqual(self.system.movies[0]['name'], 'Batman')\n self.assertEqual(self.system.movies[0]['price'], 49.9)\n self.assertEqual(self.system.movies[0]['start_time'], datetime.strptime('17:05', '%H:%M'))\n self.assertEqual(self.system.movies[0]['end_time'], datetime.strptime('19:25', '%H:%M'))\n self.assertEqual(self.system.movies[0]['seats'].shape, (3, 3))\n\n def test_add_movie_2(self):\n self.system.add_movie('Batman', 49.9, '17:05', '19:25', 3)\n self.system.add_movie('Superman', 49.9, '17:05', '19:25', 3)\n self.assertEqual(len(self.system.movies), 2)\n self.assertEqual(self.system.movies[0]['name'], 'Batman')\n self.assertEqual(self.system.movies[1]['name'], 'Superman')\n\n def test_add_movie_3(self):\n self.system.add_movie('Batman', 39.9, '17:05', '19:25', 3)\n self.assertEqual(len(self.system.movies), 1)\n self.assertEqual(self.system.movies[0]['name'], 'Batman')\n self.assertEqual(self.system.movies[0]['price'], 39.9)\n self.assertEqual(self.system.movies[0]['start_time'], datetime.strptime('17:05', '%H:%M'))\n self.assertEqual(self.system.movies[0]['end_time'], datetime.strptime('19:25', '%H:%M'))\n self.assertEqual(self.system.movies[0]['seats'].shape, (3, 3))\n\n def test_add_movie_4(self):\n self.system.add_movie('Batman', 29.9, '17:05', '19:25', 3)\n self.assertEqual(len(self.system.movies), 1)\n self.assertEqual(self.system.movies[0]['name'], 'Batman')\n self.assertEqual(self.system.movies[0]['price'], 29.9)\n self.assertEqual(self.system.movies[0]['start_time'], datetime.strptime('17:05', '%H:%M'))\n self.assertEqual(self.system.movies[0]['end_time'], datetime.strptime('19:25', '%H:%M'))\n self.assertEqual(self.system.movies[0]['seats'].shape, (3, 3))\n\n def test_add_movie_5(self):\n self.system.add_movie('Batman', 19.9, '17:05', '19:25', 3)\n self.assertEqual(len(self.system.movies), 1)\n self.assertEqual(self.system.movies[0]['name'], 'Batman')\n self.assertEqual(self.system.movies[0]['price'], 19.9)\n self.assertEqual(self.system.movies[0]['start_time'], datetime.strptime('17:05', '%H:%M'))\n self.assertEqual(self.system.movies[0]['end_time'], datetime.strptime('19:25', '%H:%M'))\n self.assertEqual(self.system.movies[0]['seats'].shape, (3, 3))\n\n\nclass MovieBookingSystemTestBookTicket(unittest.TestCase):\n def setUp(self):\n self.system = MovieBookingSystem()\n self.system.add_movie('Batman', 49.9, '17:05', '19:25', 3)\n\n # book successfully\n def test_book_ticket_1(self):\n result = self.system.book_ticket('Batman', [(0, 0), (1, 1), (2, 2)])\n self.assertEqual(result, 'Booking success.')\n self.assertEqual(self.system.movies[0]['seats'][0][0], 1)\n self.assertEqual(self.system.movies[0]['seats'][1][1], 1)\n self.assertEqual(self.system.movies[0]['seats'][2][2], 1)\n\n # seat is not available\n def test_book_ticket_2(self):\n self.system.book_ticket('Batman', [(0, 0)])\n result = self.system.book_ticket('Batman', [(0, 0)])\n self.assertEqual(result, 'Booking failed.')\n self.assertEqual(self.system.movies[0]['seats'][0][0], 1)\n\n def test_book_ticket_3(self):\n result = self.system.book_ticket('batman', [(0, 0)])\n self.assertEqual(result, 'Movie not found.')\n self.assertEqual(self.system.movies[0]['seats'][0][0], 0)\n\n def test_book_ticket_4(self):\n result = self.system.book_ticket('Batman', [(0, 0), (1, 1)])\n self.assertEqual(result, 'Booking success.')\n self.assertEqual(self.system.movies[0]['seats'][0][0], 1)\n self.assertEqual(self.system.movies[0]['seats'][1][1], 1)\n\n def test_book_ticket_5(self):\n result = self.system.book_ticket('Batman', [(0, 0)])\n self.assertEqual(result, 'Booking success.')\n self.assertEqual(self.system.movies[0]['seats'][0][0], 1)\n\n\nclass MovieBookingSystemTestAvailableMovies(unittest.TestCase):\n def setUp(self):\n self.system = MovieBookingSystem()\n self.system.add_movie('Batman', 49.9, '17:05', '19:25', 3)\n self.system.add_movie('Spiderman', 59.9, '20:00', '22:30', 4)\n\n def test_available_movies_1(self):\n result = self.system.available_movies('16:00', '23:00')\n self.assertEqual(result, ['Batman', 'Spiderman'])\n\n def test_available_movies_2(self):\n result = self.system.available_movies('23:00', '23:59')\n self.assertEqual(result, [])\n\n def test_available_movies_3(self):\n result = self.system.available_movies('17:00', '20:00')\n self.assertEqual(result, ['Batman'])\n\n def test_available_movies_4(self):\n result = self.system.available_movies('10:00', '23:00')\n self.assertEqual(result, ['Batman', 'Spiderman'])\n\n def test_available_movies_5(self):\n result = self.system.available_movies('20:00', '23:00')\n self.assertEqual(result, ['Spiderman'])\n\n\nclass MovieBookingSystemTestMain(unittest.TestCase):\n def test_main(self):\n system = MovieBookingSystem()\n system.add_movie('Batman', 49.9, '17:05', '19:25', 3)\n self.assertEqual(len(system.movies), 1)\n self.assertEqual(system.movies[0]['name'], 'Batman')\n self.assertEqual(system.movies[0]['price'], 49.9)\n self.assertEqual(system.movies[0]['start_time'], datetime.strptime('17:05', '%H:%M'))\n self.assertEqual(system.movies[0]['end_time'], datetime.strptime('19:25', '%H:%M'))\n self.assertEqual(system.movies[0]['seats'].shape, (3, 3))\n\n result = system.book_ticket('Batman', [(0, 0), (1, 1), (2, 2)])\n self.assertEqual(result, 'Booking success.')\n self.assertEqual(system.movies[0]['seats'][0][0], 1)\n self.assertEqual(system.movies[0]['seats'][1][1], 1)\n self.assertEqual(system.movies[0]['seats'][2][2], 1)\n\n result = system.available_movies('16:00', '23:00')\n self.assertEqual(result, ['Batman'])", "solution_code": "from datetime import datetime\nimport numpy as np\n\nclass MovieBookingSystem:\n def __init__(self):\n self.movies = []\n\n def add_movie(self, name, price, start_time, end_time, n):\n movie = {\n 'name': name,\n 'price': price,\n 'start_time': datetime.strptime(start_time, '%H:%M'),\n 'end_time': datetime.strptime(end_time, '%H:%M'),\n 'seats': np.zeros((n, n))\n }\n self.movies.append(movie)\n\n def book_ticket(self, name, seats_to_book):\n for movie in self.movies:\n if movie['name'] == name:\n for seat in seats_to_book:\n if movie['seats'][seat[0]][seat[1]] == 0:\n movie['seats'][seat[0]][seat[1]] = 1\n else:\n return \"Booking failed.\"\n return \"Booking success.\"\n return \"Movie not found.\"\n\n\n def available_movies(self, start_time, end_time):\n start_time = datetime.strptime(start_time, '%H:%M')\n end_time = datetime.strptime(end_time, '%H:%M')\n\n available_movies = []\n for movie in self.movies:\n if start_time <= movie['start_time'] and movie['end_time'] <= end_time:\n available_movies.append(movie['name'])\n\n return available_movies", "import_statement": [ "from datetime import datetime", "import numpy as np" ], "class_description": " \"\"\"\n this is a class as movie booking system, which allows to add movies, book tickets and check the available movies within a given time range. \n \"\"\"\n", "class_name": "MovieBookingSystem", "test_classes": [ "MovieBookingSystemTestAddMovie", "MovieBookingSystemTestBookTicket", "MovieBookingSystemTestAvailableMovies", "MovieBookingSystemTestMain" ], "class_constructor": "class MovieBookingSystem: \n def __init__(self):\n \"\"\"\n Initialize movies contains the information about movies\n >>> system.movies\n [{'name': 'Batman', 'price': 49.9, 'start_time': datetime.datetime(1900, 1, 1, 17, 5), 'end_time': datetime.datetime(1900, 1, 1, 19, 25),\n 'seats': array([[0., 0., 0.],\n [0., 0., 0.],\n [0., 0., 0.]])}]\n \"\"\"\n self.movies = []\n\n", "fields": [ "self.movies" ], "methods_info": [ { "method_name": "add_movie", "method_description": "def add_movie(self, name, price, start_time, end_time, n):\n \"\"\"\n Add a new movie into self.movies\n :param name: str, movie name\n :param price: float, price for one ticket\n :param start_time: str\n :param end_time: str\n :param n: int, the size of seats(n*n)\n >>> system.add_movie('Batman', 49.9, '17:05', '19:25', 3)\n >>> system.movies\n [{'name': 'Batman', 'price': 49.9, 'start_time': datetime.datetime(1900, 1, 1, 17, 5), 'end_time': datetime.datetime(1900, 1, 1, 19, 25),\n 'seats': array([[0., 0., 0.],\n [0., 0., 0.],\n [0., 0., 0.]])}]\n \"\"\"", "test_class": "MovieBookingSystemTestAddMovie", "test_code": "class MovieBookingSystemTestAddMovie(unittest.TestCase):\n def setUp(self):\n self.system = MovieBookingSystem()\n\n def tearDown(self):\n self.system = None\n\n def test_add_movie_1(self):\n self.system.add_movie('Batman', 49.9, '17:05', '19:25', 3)\n self.assertEqual(len(self.system.movies), 1)\n self.assertEqual(self.system.movies[0]['name'], 'Batman')\n self.assertEqual(self.system.movies[0]['price'], 49.9)\n self.assertEqual(self.system.movies[0]['start_time'], datetime.strptime('17:05', '%H:%M'))\n self.assertEqual(self.system.movies[0]['end_time'], datetime.strptime('19:25', '%H:%M'))\n self.assertEqual(self.system.movies[0]['seats'].shape, (3, 3))\n\n def test_add_movie_2(self):\n self.system.add_movie('Batman', 49.9, '17:05', '19:25', 3)\n self.system.add_movie('Superman', 49.9, '17:05', '19:25', 3)\n self.assertEqual(len(self.system.movies), 2)\n self.assertEqual(self.system.movies[0]['name'], 'Batman')\n self.assertEqual(self.system.movies[1]['name'], 'Superman')\n\n def test_add_movie_3(self):\n self.system.add_movie('Batman', 39.9, '17:05', '19:25', 3)\n self.assertEqual(len(self.system.movies), 1)\n self.assertEqual(self.system.movies[0]['name'], 'Batman')\n self.assertEqual(self.system.movies[0]['price'], 39.9)\n self.assertEqual(self.system.movies[0]['start_time'], datetime.strptime('17:05', '%H:%M'))\n self.assertEqual(self.system.movies[0]['end_time'], datetime.strptime('19:25', '%H:%M'))\n self.assertEqual(self.system.movies[0]['seats'].shape, (3, 3))\n\n def test_add_movie_4(self):\n self.system.add_movie('Batman', 29.9, '17:05', '19:25', 3)\n self.assertEqual(len(self.system.movies), 1)\n self.assertEqual(self.system.movies[0]['name'], 'Batman')\n self.assertEqual(self.system.movies[0]['price'], 29.9)\n self.assertEqual(self.system.movies[0]['start_time'], datetime.strptime('17:05', '%H:%M'))\n self.assertEqual(self.system.movies[0]['end_time'], datetime.strptime('19:25', '%H:%M'))\n self.assertEqual(self.system.movies[0]['seats'].shape, (3, 3))\n\n def test_add_movie_5(self):\n self.system.add_movie('Batman', 19.9, '17:05', '19:25', 3)\n self.assertEqual(len(self.system.movies), 1)\n self.assertEqual(self.system.movies[0]['name'], 'Batman')\n self.assertEqual(self.system.movies[0]['price'], 19.9)\n self.assertEqual(self.system.movies[0]['start_time'], datetime.strptime('17:05', '%H:%M'))\n self.assertEqual(self.system.movies[0]['end_time'], datetime.strptime('19:25', '%H:%M'))\n self.assertEqual(self.system.movies[0]['seats'].shape, (3, 3))", "solution_code": "def add_movie(self, name, price, start_time, end_time, n):\n movie = {\n 'name': name,\n 'price': price,\n 'start_time': datetime.strptime(start_time, '%H:%M'),\n 'end_time': datetime.strptime(end_time, '%H:%M'),\n 'seats': np.zeros((n, n))\n }\n self.movies.append(movie)", "dependencies": { "Standalone": false, "lib_dependencies": [ "datetime" ], "field_dependencies": [ "self.movies" ], "method_dependencies": [] } }, { "method_name": "book_ticket", "method_description": "def book_ticket(self, name, seats_to_book):\n \"\"\"\n Book tickets for a movie. Change the seats value in self.movies if book successfully.\n :param name: str, movie name\n :param seats_to_book: list of tuples, representing seats to book [(row1, col1), (row2, col2), ...]\n :return: str, booking status message. \"Movie not found.\" for no such movie.\n \"Booking success.\" for successfully booking, or \"Booking failed.\" otherwise\n >>> system.add_movie('Batman', 49.9, '17:05', '19:25', 3)\n >>> system.book_ticket('Batman', [(0, 0), (0, 1)])\n 'Booking success.'\n >>> system.book_ticket('Batman', [(0, 0)])\n 'Booking failed.'\n >>> system.book_ticket('batman', [(0, 0)])\n 'Movie not found.'\n \"\"\"", "test_class": "MovieBookingSystemTestBookTicket", "test_code": "class MovieBookingSystemTestBookTicket(unittest.TestCase):\n def setUp(self):\n self.system = MovieBookingSystem()\n self.system.add_movie('Batman', 49.9, '17:05', '19:25', 3)\n\n # book successfully\n def test_book_ticket_1(self):\n result = self.system.book_ticket('Batman', [(0, 0), (1, 1), (2, 2)])\n self.assertEqual(result, 'Booking success.')\n self.assertEqual(self.system.movies[0]['seats'][0][0], 1)\n self.assertEqual(self.system.movies[0]['seats'][1][1], 1)\n self.assertEqual(self.system.movies[0]['seats'][2][2], 1)\n\n # seat is not available\n def test_book_ticket_2(self):\n self.system.book_ticket('Batman', [(0, 0)])\n result = self.system.book_ticket('Batman', [(0, 0)])\n self.assertEqual(result, 'Booking failed.')\n self.assertEqual(self.system.movies[0]['seats'][0][0], 1)\n\n def test_book_ticket_3(self):\n result = self.system.book_ticket('batman', [(0, 0)])\n self.assertEqual(result, 'Movie not found.')\n self.assertEqual(self.system.movies[0]['seats'][0][0], 0)\n\n def test_book_ticket_4(self):\n result = self.system.book_ticket('Batman', [(0, 0), (1, 1)])\n self.assertEqual(result, 'Booking success.')\n self.assertEqual(self.system.movies[0]['seats'][0][0], 1)\n self.assertEqual(self.system.movies[0]['seats'][1][1], 1)\n\n def test_book_ticket_5(self):\n result = self.system.book_ticket('Batman', [(0, 0)])\n self.assertEqual(result, 'Booking success.')\n self.assertEqual(self.system.movies[0]['seats'][0][0], 1)", "solution_code": "def book_ticket(self, name, seats_to_book):\n for movie in self.movies:\n if movie['name'] == name:\n for seat in seats_to_book:\n if movie['seats'][seat[0]][seat[1]] == 0:\n movie['seats'][seat[0]][seat[1]] = 1\n else:\n return \"Booking failed.\"\n return \"Booking success.\"\n return \"Movie not found.\"", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.movies" ], "method_dependencies": [] } }, { "method_name": "available_movies", "method_description": "def available_movies(self, start_time, end_time):\n \"\"\"\n Get a list of available movies within the specified time range\n :param start_time: str, start time in HH:MM format\n :param end_time: str, end time in HH:MM format\n :return: list of str, names of available movies\n >>> system.add_movie('Batman', 49.9, '17:05', '19:25', 3)\n >>> system.available_movies('12:00', '22:00')\n ['Batman']\n \"\"\"", "test_class": "MovieBookingSystemTestAvailableMovies", "test_code": "class MovieBookingSystemTestAvailableMovies(unittest.TestCase):\n def setUp(self):\n self.system = MovieBookingSystem()\n self.system.add_movie('Batman', 49.9, '17:05', '19:25', 3)\n self.system.add_movie('Spiderman', 59.9, '20:00', '22:30', 4)\n\n def test_available_movies_1(self):\n result = self.system.available_movies('16:00', '23:00')\n self.assertEqual(result, ['Batman', 'Spiderman'])\n\n def test_available_movies_2(self):\n result = self.system.available_movies('23:00', '23:59')\n self.assertEqual(result, [])\n\n def test_available_movies_3(self):\n result = self.system.available_movies('17:00', '20:00')\n self.assertEqual(result, ['Batman'])\n\n def test_available_movies_4(self):\n result = self.system.available_movies('10:00', '23:00')\n self.assertEqual(result, ['Batman', 'Spiderman'])\n\n def test_available_movies_5(self):\n result = self.system.available_movies('20:00', '23:00')\n self.assertEqual(result, ['Spiderman'])", "solution_code": "def available_movies(self, start_time, end_time):\n start_time = datetime.strptime(start_time, '%H:%M')\n end_time = datetime.strptime(end_time, '%H:%M')\n\n available_movies = []\n for movie in self.movies:\n if start_time <= movie['start_time'] and movie['end_time'] <= end_time:\n available_movies.append(movie['name'])\n\n return available_movies", "dependencies": { "Standalone": false, "lib_dependencies": [ "datetime" ], "field_dependencies": [ "self.movies" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_60", "skeleton": "\nimport sqlite3\n\nclass MovieTicketDB:\n \"\"\"\n This is a class for movie database operations, which allows for inserting movie information, searching for movie information by name, and deleting movie information by name.\n \"\"\"\n\n def __init__(self, db_name):\n \"\"\"\n Initializes the MovieTicketDB object with the specified database name.\n :param db_name: str, the name of the SQLite database.\n \"\"\"\n self.connection = sqlite3.connect(db_name)\n self.cursor = self.connection.cursor()\n self.create_table()\n\n\n def create_table(self):\n \"\"\"\n Creates a \"tickets\" table in the database if it does not exist already.Fields include ID of type int, movie name of type str, author name of type str, seat number of type str, and customer name of type str\n :return: None\n \"\"\"\n\n def insert_ticket(self, movie_name, theater_name, seat_number, customer_name):\n \"\"\"\n Inserts a new ticket into the \"tickets\" table.\n :param movie_name: str, the name of the movie.\n :param theater_name: str, the name of the theater.\n :param seat_number: str, the seat number.\n :param customer_name: str, the name of the customer.\n :return: None\n \"\"\"\n\n def search_tickets_by_customer(self, customer_name):\n \"\"\"\n Searches for tickets in the \"tickets\" table by customer name.\n :param customer_name: str, the name of the customer to search for.\n :return: list of tuples, the rows from the \"tickets\" table that match the search criteria.\n >>> ticket_db = MovieTicketDB(\"ticket_database.db\")\n >>> ticket_db.create_table()\n >>> ticket_db.insert_ticket(\"Movie A\", \"Theater 1\", \"A1\", \"John Doe\")\n >>> result = ticket_db.search_tickets_by_customer(\"John Doe\")\n len(result) = 1\n \"\"\"\n\n def delete_ticket(self, ticket_id):\n \"\"\"\n Deletes a ticket from the \"tickets\" table by ticket ID.\n :param ticket_id: int, the ID of the ticket to delete.\n :return: None\n \"\"\"", "test": "import unittest\nimport os\n\n\nclass MovieTicketDBTestInsertTicket(unittest.TestCase):\n def setUp(self):\n self.db_name = 'test_database.db'\n self.db = MovieTicketDB(self.db_name)\n\n def tearDown(self):\n self.db.connection.close()\n os.remove(self.db_name)\n\n def test_insert_ticket_1(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'John Doe')\n tickets = self.db.search_tickets_by_customer('John Doe')\n self.assertEqual(len(tickets), 1)\n ticket = tickets[0]\n self.assertEqual(ticket[1], 'Avengers: Endgame')\n self.assertEqual(ticket[2], 'Cinema 1')\n self.assertEqual(ticket[3], 'A1')\n self.assertEqual(ticket[4], 'John Doe')\n\n def test_insert_ticket_2(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'aaa')\n tickets = self.db.search_tickets_by_customer('aaa')\n self.assertEqual(len(tickets), 1)\n ticket = tickets[0]\n self.assertEqual(ticket[1], 'Avengers: Endgame')\n self.assertEqual(ticket[2], 'Cinema 1')\n self.assertEqual(ticket[3], 'A1')\n self.assertEqual(ticket[4], 'aaa')\n\n def test_insert_ticket_3(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'bbb')\n tickets = self.db.search_tickets_by_customer('bbb')\n self.assertEqual(len(tickets), 1)\n ticket = tickets[0]\n self.assertEqual(ticket[1], 'Avengers: Endgame')\n self.assertEqual(ticket[2], 'Cinema 1')\n self.assertEqual(ticket[3], 'A1')\n self.assertEqual(ticket[4], 'bbb')\n\n def test_insert_ticket_4(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'ccc')\n tickets = self.db.search_tickets_by_customer('ccc')\n self.assertEqual(len(tickets), 1)\n ticket = tickets[0]\n self.assertEqual(ticket[1], 'Avengers: Endgame')\n self.assertEqual(ticket[2], 'Cinema 1')\n self.assertEqual(ticket[3], 'A1')\n self.assertEqual(ticket[4], 'ccc')\n\n def test_insert_ticket_5(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'ddd')\n tickets = self.db.search_tickets_by_customer('ddd')\n self.assertEqual(len(tickets), 1)\n ticket = tickets[0]\n self.assertEqual(ticket[1], 'Avengers: Endgame')\n self.assertEqual(ticket[2], 'Cinema 1')\n self.assertEqual(ticket[3], 'A1')\n self.assertEqual(ticket[4], 'ddd')\n\n\nclass MovieTicketDBTestSearchTicketsByCustomer(unittest.TestCase):\n def setUp(self):\n self.db_name = 'test_database.db'\n self.db = MovieTicketDB(self.db_name)\n\n def tearDown(self):\n self.db.connection.close()\n os.remove(self.db_name)\n\n def test_search_tickets_by_customer_1(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'John Doe')\n tickets = self.db.search_tickets_by_customer('John Doe')\n self.assertEqual(len(tickets), 1)\n ticket = tickets[0]\n self.assertEqual(ticket[1], 'Avengers: Endgame')\n self.assertEqual(ticket[2], 'Cinema 1')\n self.assertEqual(ticket[3], 'A1')\n self.assertEqual(ticket[4], 'John Doe')\n\n def test_search_tickets_by_customer_2(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'aaa')\n tickets = self.db.search_tickets_by_customer('aaa')\n self.assertEqual(len(tickets), 1)\n ticket = tickets[0]\n self.assertEqual(ticket[1], 'Avengers: Endgame')\n self.assertEqual(ticket[2], 'Cinema 1')\n self.assertEqual(ticket[3], 'A1')\n self.assertEqual(ticket[4], 'aaa')\n\n def test_search_tickets_by_customer_3(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'bbb')\n tickets = self.db.search_tickets_by_customer('bbb')\n self.assertEqual(len(tickets), 1)\n ticket = tickets[0]\n self.assertEqual(ticket[1], 'Avengers: Endgame')\n self.assertEqual(ticket[2], 'Cinema 1')\n self.assertEqual(ticket[3], 'A1')\n self.assertEqual(ticket[4], 'bbb')\n\n def test_search_tickets_by_customer_4(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'ccc')\n tickets = self.db.search_tickets_by_customer('ccc')\n self.assertEqual(len(tickets), 1)\n ticket = tickets[0]\n self.assertEqual(ticket[1], 'Avengers: Endgame')\n self.assertEqual(ticket[2], 'Cinema 1')\n self.assertEqual(ticket[3], 'A1')\n self.assertEqual(ticket[4], 'ccc')\n\n def test_search_tickets_by_customer_5(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'ddd')\n tickets = self.db.search_tickets_by_customer('ddd')\n self.assertEqual(len(tickets), 1)\n ticket = tickets[0]\n self.assertEqual(ticket[1], 'Avengers: Endgame')\n self.assertEqual(ticket[2], 'Cinema 1')\n self.assertEqual(ticket[3], 'A1')\n self.assertEqual(ticket[4], 'ddd')\n\n\nclass MovieTicketDBTestDeleteTicket(unittest.TestCase):\n def setUp(self):\n self.db_name = 'test_database.db'\n self.db = MovieTicketDB(self.db_name)\n\n def tearDown(self):\n self.db.connection.close()\n os.remove(self.db_name)\n\n def test_delete_ticket_1(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'John Doe')\n tickets = self.db.search_tickets_by_customer('John Doe')\n self.assertEqual(len(tickets), 1)\n ticket_id = tickets[0][0]\n self.db.delete_ticket(ticket_id)\n tickets = self.db.search_tickets_by_customer('John Doe')\n self.assertEqual(len(tickets), 0)\n\n def test_delete_ticket_2(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'aaa')\n tickets = self.db.search_tickets_by_customer('aaa')\n self.assertEqual(len(tickets), 1)\n ticket_id = tickets[0][0]\n self.db.delete_ticket(ticket_id)\n tickets = self.db.search_tickets_by_customer('aaa')\n self.assertEqual(len(tickets), 0)\n\n def test_delete_ticket_3(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'bbb')\n tickets = self.db.search_tickets_by_customer('bbb')\n self.assertEqual(len(tickets), 1)\n ticket_id = tickets[0][0]\n self.db.delete_ticket(ticket_id)\n tickets = self.db.search_tickets_by_customer('bbb')\n self.assertEqual(len(tickets), 0)\n\n def test_delete_ticket_4(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'ccc')\n tickets = self.db.search_tickets_by_customer('ccc')\n self.assertEqual(len(tickets), 1)\n ticket_id = tickets[0][0]\n self.db.delete_ticket(ticket_id)\n tickets = self.db.search_tickets_by_customer('ccc')\n self.assertEqual(len(tickets), 0)\n\n def test_delete_ticket_5(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'ddd')\n tickets = self.db.search_tickets_by_customer('ddd')\n self.assertEqual(len(tickets), 1)\n ticket_id = tickets[0][0]\n self.db.delete_ticket(ticket_id)\n tickets = self.db.search_tickets_by_customer('ddd')\n self.assertEqual(len(tickets), 0)\n\n\nclass MovieTicketDBTest(unittest.TestCase):\n def setUp(self):\n self.db_name = 'test_database.db'\n self.db = MovieTicketDB(self.db_name)\n\n def tearDown(self):\n self.db.connection.close()\n os.remove(self.db_name)\n\n def test_MovieTicketDB(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'John Doe')\n tickets = self.db.search_tickets_by_customer('John Doe')\n self.assertEqual(len(tickets), 1)\n ticket = tickets[0]\n self.assertEqual(ticket[1], 'Avengers: Endgame')\n self.assertEqual(ticket[2], 'Cinema 1')\n self.assertEqual(ticket[3], 'A1')\n self.assertEqual(ticket[4], 'John Doe')\n ticket_id = tickets[0][0]\n self.db.delete_ticket(ticket_id)\n tickets = self.db.search_tickets_by_customer('John Doe')\n self.assertEqual(len(tickets), 0)", "solution_code": "import sqlite3\n\n\nclass MovieTicketDB:\n def __init__(self, db_name):\n self.connection = sqlite3.connect(db_name)\n self.cursor = self.connection.cursor()\n self.create_table()\n\n def create_table(self):\n self.cursor.execute('''\n CREATE TABLE IF NOT EXISTS tickets (\n id INTEGER PRIMARY KEY,\n movie_name TEXT,\n theater_name TEXT,\n seat_number TEXT,\n customer_name TEXT\n )\n ''')\n self.connection.commit()\n\n def insert_ticket(self, movie_name, theater_name, seat_number, customer_name):\n self.cursor.execute('''\n INSERT INTO tickets (movie_name, theater_name, seat_number, customer_name)\n VALUES (?, ?, ?, ?)\n ''', (movie_name, theater_name, seat_number, customer_name))\n self.connection.commit()\n\n def search_tickets_by_customer(self, customer_name):\n self.cursor.execute('''\n SELECT * FROM tickets WHERE customer_name = ?\n ''', (customer_name,))\n tickets = self.cursor.fetchall()\n return tickets\n\n def delete_ticket(self, ticket_id):\n self.cursor.execute('''\n DELETE FROM tickets WHERE id = ?\n ''', (ticket_id,))\n self.connection.commit()", "import_statement": [ "import sqlite3" ], "class_description": " \"\"\"\n This is a class for movie database operations, which allows for inserting movie information, searching for movie information by name, and deleting movie information by name.\n \"\"\"\n", "class_name": "MovieTicketDB", "test_classes": [ "MovieTicketDBTestInsertTicket", "MovieTicketDBTestSearchTicketsByCustomer", "MovieTicketDBTestDeleteTicket", "MovieTicketDBTest" ], "class_constructor": "class MovieTicketDB: \n def __init__(self, db_name):\n \"\"\"\n Initializes the MovieTicketDB object with the specified database name.\n :param db_name: str, the name of the SQLite database.\n \"\"\"\n self.connection = sqlite3.connect(db_name)\n self.cursor = self.connection.cursor()\n self.create_table()\n\n\n", "fields": [ "self.connection", "self.cursor" ], "methods_info": [ { "method_name": "create_table", "method_description": "def create_table(self):\n \"\"\"\n Creates a \"tickets\" table in the database if it does not exist already.Fields include ID of type int, movie name of type str, author name of type str, seat number of type str, and customer name of type str\n :return: None\n \"\"\"", "test_class": "MovieTicketDBTestInsertTicket", "test_code": "class MovieTicketDBTestInsertTicket(unittest.TestCase):\n def setUp(self):\n self.db_name = 'test_database.db'\n self.db = MovieTicketDB(self.db_name)\n\n def tearDown(self):\n self.db.connection.close()\n os.remove(self.db_name)\n\n def test_insert_ticket_1(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'John Doe')\n tickets = self.db.search_tickets_by_customer('John Doe')\n self.assertEqual(len(tickets), 1)\n ticket = tickets[0]\n self.assertEqual(ticket[1], 'Avengers: Endgame')\n self.assertEqual(ticket[2], 'Cinema 1')\n self.assertEqual(ticket[3], 'A1')\n self.assertEqual(ticket[4], 'John Doe')\n\n def test_insert_ticket_2(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'aaa')\n tickets = self.db.search_tickets_by_customer('aaa')\n self.assertEqual(len(tickets), 1)\n ticket = tickets[0]\n self.assertEqual(ticket[1], 'Avengers: Endgame')\n self.assertEqual(ticket[2], 'Cinema 1')\n self.assertEqual(ticket[3], 'A1')\n self.assertEqual(ticket[4], 'aaa')\n\n def test_insert_ticket_3(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'bbb')\n tickets = self.db.search_tickets_by_customer('bbb')\n self.assertEqual(len(tickets), 1)\n ticket = tickets[0]\n self.assertEqual(ticket[1], 'Avengers: Endgame')\n self.assertEqual(ticket[2], 'Cinema 1')\n self.assertEqual(ticket[3], 'A1')\n self.assertEqual(ticket[4], 'bbb')\n\n def test_insert_ticket_4(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'ccc')\n tickets = self.db.search_tickets_by_customer('ccc')\n self.assertEqual(len(tickets), 1)\n ticket = tickets[0]\n self.assertEqual(ticket[1], 'Avengers: Endgame')\n self.assertEqual(ticket[2], 'Cinema 1')\n self.assertEqual(ticket[3], 'A1')\n self.assertEqual(ticket[4], 'ccc')\n\n def test_insert_ticket_5(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'ddd')\n tickets = self.db.search_tickets_by_customer('ddd')\n self.assertEqual(len(tickets), 1)\n ticket = tickets[0]\n self.assertEqual(ticket[1], 'Avengers: Endgame')\n self.assertEqual(ticket[2], 'Cinema 1')\n self.assertEqual(ticket[3], 'A1')\n self.assertEqual(ticket[4], 'ddd')", "solution_code": "def create_table(self):\n self.cursor.execute('''\n CREATE TABLE IF NOT EXISTS tickets (\n id INTEGER PRIMARY KEY,\n movie_name TEXT,\n theater_name TEXT,\n seat_number TEXT,\n customer_name TEXT\n )\n ''')\n self.connection.commit()", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.connection", "self.cursor" ], "method_dependencies": [] } }, { "method_name": "insert_ticket", "method_description": "def insert_ticket(self, movie_name, theater_name, seat_number, customer_name):\n \"\"\"\n Inserts a new ticket into the \"tickets\" table.\n :param movie_name: str, the name of the movie.\n :param theater_name: str, the name of the theater.\n :param seat_number: str, the seat number.\n :param customer_name: str, the name of the customer.\n :return: None\n \"\"\"", "test_class": "MovieTicketDBTestSearchTicketsByCustomer", "test_code": "class MovieTicketDBTestSearchTicketsByCustomer(unittest.TestCase):\n def setUp(self):\n self.db_name = 'test_database.db'\n self.db = MovieTicketDB(self.db_name)\n\n def tearDown(self):\n self.db.connection.close()\n os.remove(self.db_name)\n\n def test_search_tickets_by_customer_1(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'John Doe')\n tickets = self.db.search_tickets_by_customer('John Doe')\n self.assertEqual(len(tickets), 1)\n ticket = tickets[0]\n self.assertEqual(ticket[1], 'Avengers: Endgame')\n self.assertEqual(ticket[2], 'Cinema 1')\n self.assertEqual(ticket[3], 'A1')\n self.assertEqual(ticket[4], 'John Doe')\n\n def test_search_tickets_by_customer_2(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'aaa')\n tickets = self.db.search_tickets_by_customer('aaa')\n self.assertEqual(len(tickets), 1)\n ticket = tickets[0]\n self.assertEqual(ticket[1], 'Avengers: Endgame')\n self.assertEqual(ticket[2], 'Cinema 1')\n self.assertEqual(ticket[3], 'A1')\n self.assertEqual(ticket[4], 'aaa')\n\n def test_search_tickets_by_customer_3(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'bbb')\n tickets = self.db.search_tickets_by_customer('bbb')\n self.assertEqual(len(tickets), 1)\n ticket = tickets[0]\n self.assertEqual(ticket[1], 'Avengers: Endgame')\n self.assertEqual(ticket[2], 'Cinema 1')\n self.assertEqual(ticket[3], 'A1')\n self.assertEqual(ticket[4], 'bbb')\n\n def test_search_tickets_by_customer_4(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'ccc')\n tickets = self.db.search_tickets_by_customer('ccc')\n self.assertEqual(len(tickets), 1)\n ticket = tickets[0]\n self.assertEqual(ticket[1], 'Avengers: Endgame')\n self.assertEqual(ticket[2], 'Cinema 1')\n self.assertEqual(ticket[3], 'A1')\n self.assertEqual(ticket[4], 'ccc')\n\n def test_search_tickets_by_customer_5(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'ddd')\n tickets = self.db.search_tickets_by_customer('ddd')\n self.assertEqual(len(tickets), 1)\n ticket = tickets[0]\n self.assertEqual(ticket[1], 'Avengers: Endgame')\n self.assertEqual(ticket[2], 'Cinema 1')\n self.assertEqual(ticket[3], 'A1')\n self.assertEqual(ticket[4], 'ddd')", "solution_code": "def insert_ticket(self, movie_name, theater_name, seat_number, customer_name):\n self.cursor.execute('''\n INSERT INTO tickets (movie_name, theater_name, seat_number, customer_name)\n VALUES (?, ?, ?, ?)\n ''', (movie_name, theater_name, seat_number, customer_name))\n self.connection.commit()", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.connection", "self.cursor" ], "method_dependencies": [] } }, { "method_name": "search_tickets_by_customer", "method_description": "def search_tickets_by_customer(self, customer_name):\n \"\"\"\n Searches for tickets in the \"tickets\" table by customer name.\n :param customer_name: str, the name of the customer to search for.\n :return: list of tuples, the rows from the \"tickets\" table that match the search criteria.\n >>> ticket_db = MovieTicketDB(\"ticket_database.db\")\n >>> ticket_db.create_table()\n >>> ticket_db.insert_ticket(\"Movie A\", \"Theater 1\", \"A1\", \"John Doe\")\n >>> result = ticket_db.search_tickets_by_customer(\"John Doe\")\n len(result) = 1\n \"\"\"", "test_class": "MovieTicketDBTestDeleteTicket", "test_code": "class MovieTicketDBTestDeleteTicket(unittest.TestCase):\n def setUp(self):\n self.db_name = 'test_database.db'\n self.db = MovieTicketDB(self.db_name)\n\n def tearDown(self):\n self.db.connection.close()\n os.remove(self.db_name)\n\n def test_delete_ticket_1(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'John Doe')\n tickets = self.db.search_tickets_by_customer('John Doe')\n self.assertEqual(len(tickets), 1)\n ticket_id = tickets[0][0]\n self.db.delete_ticket(ticket_id)\n tickets = self.db.search_tickets_by_customer('John Doe')\n self.assertEqual(len(tickets), 0)\n\n def test_delete_ticket_2(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'aaa')\n tickets = self.db.search_tickets_by_customer('aaa')\n self.assertEqual(len(tickets), 1)\n ticket_id = tickets[0][0]\n self.db.delete_ticket(ticket_id)\n tickets = self.db.search_tickets_by_customer('aaa')\n self.assertEqual(len(tickets), 0)\n\n def test_delete_ticket_3(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'bbb')\n tickets = self.db.search_tickets_by_customer('bbb')\n self.assertEqual(len(tickets), 1)\n ticket_id = tickets[0][0]\n self.db.delete_ticket(ticket_id)\n tickets = self.db.search_tickets_by_customer('bbb')\n self.assertEqual(len(tickets), 0)\n\n def test_delete_ticket_4(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'ccc')\n tickets = self.db.search_tickets_by_customer('ccc')\n self.assertEqual(len(tickets), 1)\n ticket_id = tickets[0][0]\n self.db.delete_ticket(ticket_id)\n tickets = self.db.search_tickets_by_customer('ccc')\n self.assertEqual(len(tickets), 0)\n\n def test_delete_ticket_5(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'ddd')\n tickets = self.db.search_tickets_by_customer('ddd')\n self.assertEqual(len(tickets), 1)\n ticket_id = tickets[0][0]\n self.db.delete_ticket(ticket_id)\n tickets = self.db.search_tickets_by_customer('ddd')\n self.assertEqual(len(tickets), 0)", "solution_code": "def search_tickets_by_customer(self, customer_name):\n self.cursor.execute('''\n SELECT * FROM tickets WHERE customer_name = ?\n ''', (customer_name,))\n tickets = self.cursor.fetchall()\n return tickets", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.cursor" ], "method_dependencies": [] } }, { "method_name": "delete_ticket", "method_description": "def delete_ticket(self, ticket_id):\n \"\"\"\n Deletes a ticket from the \"tickets\" table by ticket ID.\n :param ticket_id: int, the ID of the ticket to delete.\n :return: None\n \"\"\"", "test_class": "MovieTicketDBTest", "test_code": "class MovieTicketDBTest(unittest.TestCase):\n def setUp(self):\n self.db_name = 'test_database.db'\n self.db = MovieTicketDB(self.db_name)\n\n def tearDown(self):\n self.db.connection.close()\n os.remove(self.db_name)\n\n def test_MovieTicketDB(self):\n self.db.insert_ticket('Avengers: Endgame', 'Cinema 1', 'A1', 'John Doe')\n tickets = self.db.search_tickets_by_customer('John Doe')\n self.assertEqual(len(tickets), 1)\n ticket = tickets[0]\n self.assertEqual(ticket[1], 'Avengers: Endgame')\n self.assertEqual(ticket[2], 'Cinema 1')\n self.assertEqual(ticket[3], 'A1')\n self.assertEqual(ticket[4], 'John Doe')\n ticket_id = tickets[0][0]\n self.db.delete_ticket(ticket_id)\n tickets = self.db.search_tickets_by_customer('John Doe')\n self.assertEqual(len(tickets), 0)", "solution_code": "def delete_ticket(self, ticket_id):\n self.cursor.execute('''\n DELETE FROM tickets WHERE id = ?\n ''', (ticket_id,))\n self.connection.commit()", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.connection", "self.cursor" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_61", "skeleton": "\nclass MusicPlayer:\n \"\"\"\n This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initializes the music player with an empty playlist, no current song, and a default volume of 50.\n \"\"\"\n self.playlist = []\n self.current_song = None\n self.volume = 50\n\n def add_song(self, song):\n \"\"\"\n Adds a song to the playlist.\n :param song: The song to add to the playlist, str.\n >>> musicPlayer = MusicPlayer()\n >>> musicPlayer.add_song(\"song1\")\n >>> musicPlayer.playlist\n ['song1']\n\n \"\"\"\n\n def remove_song(self, song):\n \"\"\"\n Removes a song from the playlist.\n :param song: The song to remove from the playlist, str.\n >>> musicPlayer = MusicPlayer()\n >>> musicPlayer.playlist = [\"song1\", \"song2\"]\n >>> musicPlayer.remove_song(\"song1\")\n >>> musicPlayer.playlist\n ['song2']\n\n \"\"\"\n\n def play(self):\n \"\"\"\n Plays the current song in the playlist.\n :return: The current song in the playlist, or False if there is no current song.\n >>> musicPlayer = MusicPlayer()\n >>> musicPlayer.playlist = [\"song1\", \"song2\"]\n >>> musicPlayer.current_song = \"song1\"\n >>> musicPlayer.play()\n 'song1'\n\n \"\"\"\n\n def stop(self):\n \"\"\"\n Stops the current song in the playlist.\n :return: True if the current song was stopped, False if there was no current song.\n >>> musicPlayer = MusicPlayer()\n >>> musicPlayer.playlist = [\"song1\", \"song2\"]\n >>> musicPlayer.current_song = \"song1\"\n >>> musicPlayer.stop()\n True\n\n \"\"\"\n\n def switch_song(self):\n \"\"\"\n Switches to the next song in the playlist.\n :return: True if the next song was switched to, False if there was no next song.\n >>> musicPlayer = MusicPlayer()\n >>> musicPlayer.playlist = [\"song1\", \"song2\"]\n >>> musicPlayer.current_song = \"song1\"\n >>> musicPlayer.switch_song()\n True\n\n \"\"\"\n\n def previous_song(self):\n \"\"\"\n Switches to the previous song in the playlist.\n :return: True if the previous song was switched to, False if there was no previous song.\n >>> musicPlayer = MusicPlayer()\n >>> musicPlayer.playlist = [\"song1\", \"song2\"]\n >>> musicPlayer.current_song = \"song2\"\n >>> musicPlayer.previous_song()\n True\n\n \"\"\"\n\n def set_volume(self, volume):\n \"\"\"\n Sets the volume of the music player,ifthe volume is between 0 and 100 is valid.\n :param volume: The volume to set the music player to,int.\n :return: True if the volume was set, False if the volume was invalid.\n >>> musicPlayer = MusicPlayer()\n >>> musicPlayer.set_volume(50)\n >>> musicPlayer.volume\n 50\n\n \"\"\"\n\n def shuffle(self):\n \"\"\"\n Shuffles the playlist.\n :return: True if the playlist was shuffled, False if the playlist was empty.\n >>> musicPlayer = MusicPlayer()\n >>> musicPlayer.playlist = [\"song1\", \"song2\"]\n >>> musicPlayer.shuffle()\n True\n\n \"\"\"", "test": "import unittest\n\n\nclass MusicPlayerTestAddSong(unittest.TestCase):\n def test_add_song(self):\n musicPlayer = MusicPlayer()\n musicPlayer.add_song(\"song1\")\n self.assertEqual(musicPlayer.playlist, [\"song1\"])\n\n def test_add_song2(self):\n musicPlayer = MusicPlayer()\n musicPlayer.add_song(\"song1\")\n musicPlayer.add_song(\"song2\")\n self.assertEqual(musicPlayer.playlist, [\"song1\", \"song2\"])\n\n def test_add_song3(self):\n musicPlayer = MusicPlayer()\n musicPlayer.add_song(\"song1\")\n musicPlayer.add_song(\"song2\")\n musicPlayer.add_song(\"song3\")\n self.assertEqual(musicPlayer.playlist, [\"song1\", \"song2\", \"song3\"])\n\n def test_add_song4(self):\n musicPlayer = MusicPlayer()\n musicPlayer.add_song(\"song1\")\n musicPlayer.add_song(\"song2\")\n musicPlayer.add_song(\"song3\")\n musicPlayer.add_song(\"song4\")\n self.assertEqual(musicPlayer.playlist, [\"song1\", \"song2\", \"song3\", \"song4\"])\n\n def test_add_song5(self):\n musicPlayer = MusicPlayer()\n musicPlayer.add_song(\"song1\")\n musicPlayer.add_song(\"song2\")\n musicPlayer.add_song(\"song3\")\n musicPlayer.add_song(\"song4\")\n musicPlayer.add_song(\"song5\")\n self.assertEqual(musicPlayer.playlist, [\"song1\", \"song2\", \"song3\", \"song4\", \"song5\"])\n\nclass MusicPlayerTestRemoveSong(unittest.TestCase):\n def test_remove_song(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.remove_song(\"song1\")\n self.assertEqual(musicPlayer.playlist, [\"song2\"])\n\n def test_remove_song2(self):\n musicPlayer = MusicPlayer()\n musicPlayer.current_song = \"song1\"\n musicPlayer.playlist = [\"song1\", \"song2\", \"song3\"]\n musicPlayer.remove_song(\"song1\")\n self.assertEqual(musicPlayer.playlist, [\"song2\", \"song3\"])\n\n def test_remove_song3(self):\n musicPlayer = MusicPlayer()\n musicPlayer.current_song = \"song1\"\n musicPlayer.playlist = [\"song1\", \"song2\", \"song3\", \"song4\"]\n musicPlayer.remove_song(\"song1\")\n self.assertEqual(musicPlayer.playlist, [\"song2\", \"song3\", \"song4\"])\n\n def test_remove_song4(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\", \"song3\", \"song4\", \"song5\"]\n musicPlayer.remove_song(\"song1\")\n self.assertEqual(musicPlayer.playlist, [\"song2\", \"song3\", \"song4\", \"song5\"])\n\n def test_remove_song5(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\", \"song3\", \"song4\", \"song5\"]\n musicPlayer.remove_song(\"song1\")\n musicPlayer.remove_song(\"song2\")\n self.assertEqual(musicPlayer.playlist, [\"song3\", \"song4\", \"song5\"])\n\n def test_remove_song6(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = []\n musicPlayer.remove_song(\"song1\")\n self.assertEqual(musicPlayer.playlist, [])\n\n\nclass MusicPlayerTestPlay(unittest.TestCase):\n def test_play(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song1\"\n self.assertEqual(musicPlayer.play(), \"song1\")\n\n def test_play_2(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = []\n musicPlayer.current_song = \"song2\"\n self.assertEqual(musicPlayer.play(), None)\n\n def test_play_3(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n self.assertEqual(musicPlayer.play(),False)\n\n def test_play_4(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song3\"\n self.assertEqual(musicPlayer.play(), \"song1\")\n\n def test_play_5(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song1\"\n self.assertEqual(musicPlayer.play(), \"song1\")\n\nclass MusicPlayerTestStop(unittest.TestCase):\n def test_stop(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song1\"\n self.assertEqual(musicPlayer.stop(), True)\n\n def test_stop_2(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = []\n musicPlayer.current_song = \"song1\"\n self.assertEqual(musicPlayer.stop(), True)\n\n def test_stop_3(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n self.assertEqual(musicPlayer.stop(), False)\n\n def test_stop_4(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song1\"\n self.assertEqual(musicPlayer.stop(), True)\n\n def test_stop_5(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song2\"\n self.assertEqual(musicPlayer.stop(), True)\n\nclass MusicPlayerTestSwitchSong(unittest.TestCase):\n def test_switch_song(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song1\"\n self.assertEqual(musicPlayer.switch_song(), True)\n\n def test_switch_song2(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song2\"\n self.assertEqual(musicPlayer.switch_song(), False)\n\n def test_switch_song3(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\", \"song3\"]\n musicPlayer.current_song = \"song3\"\n self.assertEqual(musicPlayer.switch_song(), False)\n\n def test_switch_song4(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n self.assertEqual(musicPlayer.switch_song(), False)\n\n def test_switch_song5(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = []\n self.assertEqual(musicPlayer.switch_song(), False)\n\nclass MusicPlayerTestPreviousSong(unittest.TestCase):\n def test_previous_song(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\", \"song3\"]\n musicPlayer.current_song = \"song2\"\n self.assertEqual(musicPlayer.previous_song(), True)\n\n def test_previous_song2(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\", \"song3\"]\n musicPlayer.current_song = \"song1\"\n self.assertEqual(musicPlayer.previous_song(), False)\n\n def test_previous_song3(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\", \"song3\"]\n musicPlayer.current_song = \"song3\"\n self.assertEqual(musicPlayer.previous_song(), True)\n\n def test_previous_song4(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\", \"song3\"]\n self.assertEqual(musicPlayer.previous_song(), False)\n\n def test_previous_song5(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = []\n self.assertEqual(musicPlayer.previous_song(), False)\n\nclass MusicPlayerTestSetVolume(unittest.TestCase):\n def test_set_volume(self):\n musicPlayer = MusicPlayer()\n self.assertEqual(musicPlayer.set_volume(50), None)\n self.assertEqual(musicPlayer.volume, 50)\n\n def test_set_volume2(self):\n musicPlayer = MusicPlayer()\n self.assertEqual(musicPlayer.set_volume(100), None)\n self.assertEqual(musicPlayer.volume, 100)\n\n def test_set_volume3(self):\n musicPlayer = MusicPlayer()\n self.assertEqual(musicPlayer.set_volume(0), None)\n self.assertEqual(musicPlayer.volume, 0)\n\n def test_set_volume4(self):\n musicPlayer = MusicPlayer()\n self.assertEqual(musicPlayer.set_volume(101), False)\n self.assertEqual(musicPlayer.volume, 50)\n\n def test_set_volume5(self):\n musicPlayer = MusicPlayer()\n self.assertEqual(musicPlayer.set_volume(-1), False)\n self.assertEqual(musicPlayer.volume, 50)\n\nclass MusicPlayerTestShuffle(unittest.TestCase):\n def test_shuffle(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n self.assertEqual(musicPlayer.shuffle(), True)\n\n def test_shuffle_2(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = []\n musicPlayer.current_song = \"song1\"\n self.assertEqual(musicPlayer.shuffle(), False)\n\n def test_shuffle_3(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song2\"\n self.assertEqual(musicPlayer.shuffle(), True)\n\n def test_shuffle_4(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song3\"\n self.assertEqual(musicPlayer.shuffle(), True)\n\n def test_shuffle_5(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song1\"\n self.assertEqual(musicPlayer.shuffle(), True)\n\nclass MusicPlayerTestMain(unittest.TestCase):\n def test_main(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song1\"\n self.assertEqual(musicPlayer.play(), \"song1\")\n self.assertEqual(musicPlayer.stop(), True)\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song1\"\n self.assertEqual(musicPlayer.switch_song(), True)\n self.assertEqual(musicPlayer.previous_song(), True)\n musicPlayer.set_volume(50)\n self.assertEqual(musicPlayer.volume, 50)", "solution_code": "class MusicPlayer:\n def __init__(self):\n self.playlist = []\n self.current_song = None\n self.volume = 50\n\n def add_song(self, song):\n self.playlist.append(song)\n\n def remove_song(self, song):\n if song in self.playlist:\n self.playlist.remove(song)\n if self.current_song == song:\n self.stop()\n\n def play(self):\n if self.playlist and self.current_song:\n return self.playlist[0]\n elif len(self.playlist): \n return False\n\n def stop(self):\n if self.current_song:\n self.current_song = None\n return True\n else:\n return False\n\n def switch_song(self):\n if self.current_song:\n current_index = self.playlist.index(self.current_song)\n if current_index < len(self.playlist) - 1:\n self.current_song = self.playlist[current_index + 1]\n return True\n else:\n return False\n else:\n return False\n\n def previous_song(self):\n if self.current_song:\n current_index = self.playlist.index(self.current_song)\n if current_index > 0:\n self.current_song = self.playlist[current_index - 1]\n return True\n else:\n return False\n else:\n return False\n\n def set_volume(self, volume):\n if 0 <= volume <= 100:\n self.volume = volume\n else:\n return False\n\n def shuffle(self):\n if self.playlist:\n import random\n random.shuffle(self.playlist)\n return True\n else:\n return False", "import_statement": [ "import random" ], "class_description": " \"\"\"\n This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song.\n \"\"\"\n", "class_name": "MusicPlayer", "test_classes": [ "MusicPlayerTestAddSong", "MusicPlayerTestRemoveSong", "MusicPlayerTestPlay", "MusicPlayerTestStop", "MusicPlayerTestSwitchSong", "MusicPlayerTestPreviousSong", "MusicPlayerTestSetVolume", "MusicPlayerTestShuffle", "MusicPlayerTestMain" ], "class_constructor": "class MusicPlayer: \n def __init__(self):\n \"\"\"\n Initializes the music player with an empty playlist, no current song, and a default volume of 50.\n \"\"\"\n self.playlist = []\n self.current_song = None\n self.volume = 50\n\n", "fields": [ "self.current_song", "self.playlist", "self.volume" ], "methods_info": [ { "method_name": "add_song", "method_description": "def add_song(self, song):\n \"\"\"\n Adds a song to the playlist.\n :param song: The song to add to the playlist, str.\n >>> musicPlayer = MusicPlayer()\n >>> musicPlayer.add_song(\"song1\")\n >>> musicPlayer.playlist\n ['song1']\n\n \"\"\"", "test_class": "MusicPlayerTestAddSong", "test_code": "class MusicPlayerTestAddSong(unittest.TestCase):\n def test_add_song(self):\n musicPlayer = MusicPlayer()\n musicPlayer.add_song(\"song1\")\n self.assertEqual(musicPlayer.playlist, [\"song1\"])\n\n def test_add_song2(self):\n musicPlayer = MusicPlayer()\n musicPlayer.add_song(\"song1\")\n musicPlayer.add_song(\"song2\")\n self.assertEqual(musicPlayer.playlist, [\"song1\", \"song2\"])\n\n def test_add_song3(self):\n musicPlayer = MusicPlayer()\n musicPlayer.add_song(\"song1\")\n musicPlayer.add_song(\"song2\")\n musicPlayer.add_song(\"song3\")\n self.assertEqual(musicPlayer.playlist, [\"song1\", \"song2\", \"song3\"])\n\n def test_add_song4(self):\n musicPlayer = MusicPlayer()\n musicPlayer.add_song(\"song1\")\n musicPlayer.add_song(\"song2\")\n musicPlayer.add_song(\"song3\")\n musicPlayer.add_song(\"song4\")\n self.assertEqual(musicPlayer.playlist, [\"song1\", \"song2\", \"song3\", \"song4\"])\n\n def test_add_song5(self):\n musicPlayer = MusicPlayer()\n musicPlayer.add_song(\"song1\")\n musicPlayer.add_song(\"song2\")\n musicPlayer.add_song(\"song3\")\n musicPlayer.add_song(\"song4\")\n musicPlayer.add_song(\"song5\")\n self.assertEqual(musicPlayer.playlist, [\"song1\", \"song2\", \"song3\", \"song4\", \"song5\"])", "solution_code": "def add_song(self, song):\n self.playlist.append(song)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.playlist" ], "method_dependencies": [ "play" ] } }, { "method_name": "remove_song", "method_description": "def remove_song(self, song):\n \"\"\"\n Removes a song from the playlist.\n :param song: The song to remove from the playlist, str.\n >>> musicPlayer = MusicPlayer()\n >>> musicPlayer.playlist = [\"song1\", \"song2\"]\n >>> musicPlayer.remove_song(\"song1\")\n >>> musicPlayer.playlist\n ['song2']\n\n \"\"\"", "test_class": "MusicPlayerTestRemoveSong", "test_code": "class MusicPlayerTestRemoveSong(unittest.TestCase):\n def test_remove_song(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.remove_song(\"song1\")\n self.assertEqual(musicPlayer.playlist, [\"song2\"])\n\n def test_remove_song2(self):\n musicPlayer = MusicPlayer()\n musicPlayer.current_song = \"song1\"\n musicPlayer.playlist = [\"song1\", \"song2\", \"song3\"]\n musicPlayer.remove_song(\"song1\")\n self.assertEqual(musicPlayer.playlist, [\"song2\", \"song3\"])\n\n def test_remove_song3(self):\n musicPlayer = MusicPlayer()\n musicPlayer.current_song = \"song1\"\n musicPlayer.playlist = [\"song1\", \"song2\", \"song3\", \"song4\"]\n musicPlayer.remove_song(\"song1\")\n self.assertEqual(musicPlayer.playlist, [\"song2\", \"song3\", \"song4\"])\n\n def test_remove_song4(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\", \"song3\", \"song4\", \"song5\"]\n musicPlayer.remove_song(\"song1\")\n self.assertEqual(musicPlayer.playlist, [\"song2\", \"song3\", \"song4\", \"song5\"])\n\n def test_remove_song5(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\", \"song3\", \"song4\", \"song5\"]\n musicPlayer.remove_song(\"song1\")\n musicPlayer.remove_song(\"song2\")\n self.assertEqual(musicPlayer.playlist, [\"song3\", \"song4\", \"song5\"])\n\n def test_remove_song6(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = []\n musicPlayer.remove_song(\"song1\")\n self.assertEqual(musicPlayer.playlist, [])", "solution_code": "def remove_song(self, song):\n if song in self.playlist:\n self.playlist.remove(song)\n if self.current_song == song:\n self.stop()", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.current_song", "self.playlist" ], "method_dependencies": [ "play", "stop" ] } }, { "method_name": "play", "method_description": "def play(self):\n \"\"\"\n Plays the current song in the playlist.\n :return: The current song in the playlist, or False if there is no current song.\n >>> musicPlayer = MusicPlayer()\n >>> musicPlayer.playlist = [\"song1\", \"song2\"]\n >>> musicPlayer.current_song = \"song1\"\n >>> musicPlayer.play()\n 'song1'\n\n \"\"\"", "test_class": "MusicPlayerTestPlay", "test_code": "class MusicPlayerTestPlay(unittest.TestCase):\n def test_play(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song1\"\n self.assertEqual(musicPlayer.play(), \"song1\")\n\n def test_play_2(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = []\n musicPlayer.current_song = \"song2\"\n self.assertEqual(musicPlayer.play(), None)\n\n def test_play_3(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n self.assertEqual(musicPlayer.play(),False)\n\n def test_play_4(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song3\"\n self.assertEqual(musicPlayer.play(), \"song1\")\n\n def test_play_5(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song1\"\n self.assertEqual(musicPlayer.play(), \"song1\")", "solution_code": "def play(self):\n if self.playlist and self.current_song:\n return self.playlist[0]\n elif len(self.playlist): \n return False", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.current_song", "self.playlist" ], "method_dependencies": [] } }, { "method_name": "stop", "method_description": "def stop(self):\n \"\"\"\n Stops the current song in the playlist.\n :return: True if the current song was stopped, False if there was no current song.\n >>> musicPlayer = MusicPlayer()\n >>> musicPlayer.playlist = [\"song1\", \"song2\"]\n >>> musicPlayer.current_song = \"song1\"\n >>> musicPlayer.stop()\n True\n\n \"\"\"", "test_class": "MusicPlayerTestStop", "test_code": "class MusicPlayerTestStop(unittest.TestCase):\n def test_stop(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song1\"\n self.assertEqual(musicPlayer.stop(), True)\n\n def test_stop_2(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = []\n musicPlayer.current_song = \"song1\"\n self.assertEqual(musicPlayer.stop(), True)\n\n def test_stop_3(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n self.assertEqual(musicPlayer.stop(), False)\n\n def test_stop_4(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song1\"\n self.assertEqual(musicPlayer.stop(), True)\n\n def test_stop_5(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song2\"\n self.assertEqual(musicPlayer.stop(), True)", "solution_code": "def stop(self):\n if self.current_song:\n self.current_song = None\n return True\n else:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.current_song" ], "method_dependencies": [] } }, { "method_name": "switch_song", "method_description": "def switch_song(self):\n \"\"\"\n Switches to the next song in the playlist.\n :return: True if the next song was switched to, False if there was no next song.\n >>> musicPlayer = MusicPlayer()\n >>> musicPlayer.playlist = [\"song1\", \"song2\"]\n >>> musicPlayer.current_song = \"song1\"\n >>> musicPlayer.switch_song()\n True\n\n \"\"\"", "test_class": "MusicPlayerTestSwitchSong", "test_code": "class MusicPlayerTestSwitchSong(unittest.TestCase):\n def test_switch_song(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song1\"\n self.assertEqual(musicPlayer.switch_song(), True)\n\n def test_switch_song2(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song2\"\n self.assertEqual(musicPlayer.switch_song(), False)\n\n def test_switch_song3(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\", \"song3\"]\n musicPlayer.current_song = \"song3\"\n self.assertEqual(musicPlayer.switch_song(), False)\n\n def test_switch_song4(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n self.assertEqual(musicPlayer.switch_song(), False)\n\n def test_switch_song5(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = []\n self.assertEqual(musicPlayer.switch_song(), False)", "solution_code": "def switch_song(self):\n if self.current_song:\n current_index = self.playlist.index(self.current_song)\n if current_index < len(self.playlist) - 1:\n self.current_song = self.playlist[current_index + 1]\n return True\n else:\n return False\n else:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.current_song", "self.playlist" ], "method_dependencies": [ "play" ] } }, { "method_name": "previous_song", "method_description": "def previous_song(self):\n \"\"\"\n Switches to the previous song in the playlist.\n :return: True if the previous song was switched to, False if there was no previous song.\n >>> musicPlayer = MusicPlayer()\n >>> musicPlayer.playlist = [\"song1\", \"song2\"]\n >>> musicPlayer.current_song = \"song2\"\n >>> musicPlayer.previous_song()\n True\n\n \"\"\"", "test_class": "MusicPlayerTestPreviousSong", "test_code": "class MusicPlayerTestPreviousSong(unittest.TestCase):\n def test_previous_song(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\", \"song3\"]\n musicPlayer.current_song = \"song2\"\n self.assertEqual(musicPlayer.previous_song(), True)\n\n def test_previous_song2(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\", \"song3\"]\n musicPlayer.current_song = \"song1\"\n self.assertEqual(musicPlayer.previous_song(), False)\n\n def test_previous_song3(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\", \"song3\"]\n musicPlayer.current_song = \"song3\"\n self.assertEqual(musicPlayer.previous_song(), True)\n\n def test_previous_song4(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\", \"song3\"]\n self.assertEqual(musicPlayer.previous_song(), False)\n\n def test_previous_song5(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = []\n self.assertEqual(musicPlayer.previous_song(), False)", "solution_code": "def previous_song(self):\n if self.current_song:\n current_index = self.playlist.index(self.current_song)\n if current_index > 0:\n self.current_song = self.playlist[current_index - 1]\n return True\n else:\n return False\n else:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.current_song", "self.playlist" ], "method_dependencies": [ "play" ] } }, { "method_name": "set_volume", "method_description": "def set_volume(self, volume):\n \"\"\"\n Sets the volume of the music player,ifthe volume is between 0 and 100 is valid.\n :param volume: The volume to set the music player to,int.\n :return: True if the volume was set, False if the volume was invalid.\n >>> musicPlayer = MusicPlayer()\n >>> musicPlayer.set_volume(50)\n >>> musicPlayer.volume\n 50\n\n \"\"\"", "test_class": "MusicPlayerTestSetVolume", "test_code": "class MusicPlayerTestSetVolume(unittest.TestCase):\n def test_set_volume(self):\n musicPlayer = MusicPlayer()\n self.assertEqual(musicPlayer.set_volume(50), None)\n self.assertEqual(musicPlayer.volume, 50)\n\n def test_set_volume2(self):\n musicPlayer = MusicPlayer()\n self.assertEqual(musicPlayer.set_volume(100), None)\n self.assertEqual(musicPlayer.volume, 100)\n\n def test_set_volume3(self):\n musicPlayer = MusicPlayer()\n self.assertEqual(musicPlayer.set_volume(0), None)\n self.assertEqual(musicPlayer.volume, 0)\n\n def test_set_volume4(self):\n musicPlayer = MusicPlayer()\n self.assertEqual(musicPlayer.set_volume(101), False)\n self.assertEqual(musicPlayer.volume, 50)\n\n def test_set_volume5(self):\n musicPlayer = MusicPlayer()\n self.assertEqual(musicPlayer.set_volume(-1), False)\n self.assertEqual(musicPlayer.volume, 50)", "solution_code": "def set_volume(self, volume):\n if 0 <= volume <= 100:\n self.volume = volume\n else:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.volume" ], "method_dependencies": [] } }, { "method_name": "shuffle", "method_description": "def shuffle(self):\n \"\"\"\n Shuffles the playlist.\n :return: True if the playlist was shuffled, False if the playlist was empty.\n >>> musicPlayer = MusicPlayer()\n >>> musicPlayer.playlist = [\"song1\", \"song2\"]\n >>> musicPlayer.shuffle()\n True\n\n \"\"\"", "test_class": "MusicPlayerTestShuffle", "test_code": "class MusicPlayerTestShuffle(unittest.TestCase):\n def test_shuffle(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n self.assertEqual(musicPlayer.shuffle(), True)\n\n def test_shuffle_2(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = []\n musicPlayer.current_song = \"song1\"\n self.assertEqual(musicPlayer.shuffle(), False)\n\n def test_shuffle_3(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song2\"\n self.assertEqual(musicPlayer.shuffle(), True)\n\n def test_shuffle_4(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song3\"\n self.assertEqual(musicPlayer.shuffle(), True)\n\n def test_shuffle_5(self):\n musicPlayer = MusicPlayer()\n musicPlayer.playlist = [\"song1\", \"song2\"]\n musicPlayer.current_song = \"song1\"\n self.assertEqual(musicPlayer.shuffle(), True)", "solution_code": "def shuffle(self):\n if self.playlist:\n import random\n random.shuffle(self.playlist)\n return True\n else:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [ "random" ], "field_dependencies": [ "self.playlist" ], "method_dependencies": [ "play" ] } } ] }, { "task_id": "ClassEval_62", "skeleton": "\nclass NLPDataProcessor:\n \"\"\"\n The class processes NLP data by removing stop words from a list of strings using a pre-defined stop word list.\n \"\"\"\n\n\n def construct_stop_word_list(self):\n \"\"\"\n Construct a stop word list including 'a', 'an', 'the'.\n :return: a list of stop words\n >>> NLPDataProcessor.construct_stop_word_list()\n ['a', 'an', 'the']\n \"\"\"\n def remove_stop_words(self, string_list, stop_word_list):\n \"\"\"\n Remove all the stop words from the list of strings.\n :param string_list: a list of strings\n :param stop_word_list: a list of stop words\n :return: a list of words without stop words\n >>> NLPDataProcessor.process(['This is a test.'])\n [['This', 'is', 'test.']]\n \"\"\"\n def process(self, string_list):\n \"\"\"\n Construct a stop word list including 'a', 'an', 'the', and remove all the stop words from the list of strings.\n :param string_list: a list of strings\n :return: a list of words without stop words\n >>> NLPDataProcessor.process(['This is a test.'])\n [['This', 'is', 'test.']]\n \"\"\"", "test": "import unittest\n\nclass NLPDataProcessorTestConstruct(unittest.TestCase):\n def setUp(self):\n self.processor = NLPDataProcessor()\n\n def test_construct_stop_word_list(self):\n stop_word_list = self.processor.construct_stop_word_list()\n expected_stop_words = ['a', 'an', 'the']\n self.assertEqual(stop_word_list, expected_stop_words)\n\nclass NLPDataProcessorTestRemove(unittest.TestCase):\n def setUp(self):\n self.processor = NLPDataProcessor()\n\n def test_remove_stop_words(self):\n string_list = ['This is a test', 'This is an apple', 'This is the dog']\n stop_word_list = ['a', 'an', 'the']\n words_list = self.processor.remove_stop_words(string_list, stop_word_list)\n expected_words_list = [['This', 'is', 'test'], ['This', 'is', 'apple'], ['This', 'is', 'dog']]\n self.assertEqual(words_list, expected_words_list)\n\n def test_remove_stop_words_2(self):\n string_list = ['a', 'an', 'the']\n stop_word_list = ['a', 'an', 'the']\n words_list = self.processor.remove_stop_words(string_list, stop_word_list)\n self.assertEqual(words_list, [[], [], []])\n\n def test_remove_stop_words_3(self):\n string_list = []\n stop_word_list = ['a', 'an', 'the']\n words_list = self.processor.remove_stop_words(string_list, stop_word_list)\n self.assertEqual(words_list, [])\n\n def test_remove_stop_words_4(self):\n string_list = ['This is a test', 'This is an apple', 'This is the dog']\n stop_word_list = []\n words_list = self.processor.remove_stop_words(string_list, stop_word_list)\n expected_words_list = [['This', 'is', 'a', 'test'], ['This', 'is', 'an', 'apple'], ['This', 'is', 'the', 'dog']]\n self.assertEqual(words_list, expected_words_list)\n\n def test_remove_stop_words_5(self):\n string_list = ['This is a test', 'This is an apple', 'This is the dog']\n stop_word_list = ['a', 'an', 'the', 'This', 'is']\n words_list = self.processor.remove_stop_words(string_list, stop_word_list)\n expected_words_list = [['is', 'test'], ['is', 'apple'], ['is', 'dog']]\n self.assertEqual(words_list, expected_words_list)\n\nclass NLPDataProcessorTestProcess(unittest.TestCase):\n def setUp(self):\n self.processor = NLPDataProcessor()\n\n def test_process(self):\n string_list = ['This is a test.', 'This is an apple.', 'This is the dog.']\n words_list = self.processor.process(string_list)\n expected_words_list = [['This', 'is', 'test.'], ['This', 'is', 'apple.'], ['This', 'is', 'dog.']]\n self.assertEqual(words_list, expected_words_list)\n\n def test_process_with_empty_string_list(self):\n string_list = []\n words_list = self.processor.process(string_list)\n self.assertEqual(words_list, [])\n\n def test_process_with_single_word_sentences(self):\n string_list = ['Hello aa', 'World']\n words_list = self.processor.process(string_list)\n expected_words_list = [['Hello', 'aa'], ['World']]\n self.assertEqual(words_list, expected_words_list)\n\n def test_process_with_stop_words_only(self):\n string_list = ['a', 'an', 'the']\n words_list = self.processor.process(string_list)\n self.assertEqual(words_list, [[], [], []])\n\n def test_process_with_stop_words_only_2(self):\n string_list = ['a', 'an', 'the','This']\n words_list = self.processor.process(string_list)\n self.assertEqual(words_list,[[], [], [], ['This']])", "solution_code": "class NLPDataProcessor:\n\n def construct_stop_word_list(self):\n stop_word_list = ['a', 'an', 'the']\n return stop_word_list\n\n def remove_stop_words(self, string_list, stop_word_list):\n answer = []\n for string in string_list:\n string_split = string.split()\n for word in string_split:\n if word in stop_word_list:\n string_split.remove(word)\n answer.append(string_split)\n return answer\n\n def process(self, string_list):\n stop_word_list = self.construct_stop_word_list()\n words_list = self.remove_stop_words(string_list, stop_word_list)\n return words_list", "import_statement": [], "class_description": " \"\"\"\n The class processes NLP data by removing stop words from a list of strings using a pre-defined stop word list.\n \"\"\"\n", "class_name": "NLPDataProcessor", "test_classes": [ "NLPDataProcessorTestConstruct", "NLPDataProcessorTestRemove", "NLPDataProcessorTestProcess" ], "class_constructor": "class NLPDataProcessor: \n", "fields": [], "methods_info": [ { "method_name": "construct_stop_word_list", "method_description": "def construct_stop_word_list(self):\n \"\"\"\n Construct a stop word list including 'a', 'an', 'the'.\n :return: a list of stop words\n >>> NLPDataProcessor.construct_stop_word_list()\n ['a', 'an', 'the']\n \"\"\"", "test_class": "NLPDataProcessorTestConstruct", "test_code": "class NLPDataProcessorTestConstruct(unittest.TestCase):\n def setUp(self):\n self.processor = NLPDataProcessor()\n\n def test_construct_stop_word_list(self):\n stop_word_list = self.processor.construct_stop_word_list()\n expected_stop_words = ['a', 'an', 'the']\n self.assertEqual(stop_word_list, expected_stop_words)", "solution_code": "def construct_stop_word_list(self):\n stop_word_list = ['a', 'an', 'the']\n return stop_word_list", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "remove_stop_words", "method_description": "def remove_stop_words(self, string_list, stop_word_list):\n \"\"\"\n Remove all the stop words from the list of strings.\n :param string_list: a list of strings\n :param stop_word_list: a list of stop words\n :return: a list of words without stop words\n >>> NLPDataProcessor.process(['This is a test.'])\n [['This', 'is', 'test.']]\n \"\"\"", "test_class": "NLPDataProcessorTestRemove", "test_code": "class NLPDataProcessorTestRemove(unittest.TestCase):\n def setUp(self):\n self.processor = NLPDataProcessor()\n\n def test_remove_stop_words(self):\n string_list = ['This is a test', 'This is an apple', 'This is the dog']\n stop_word_list = ['a', 'an', 'the']\n words_list = self.processor.remove_stop_words(string_list, stop_word_list)\n expected_words_list = [['This', 'is', 'test'], ['This', 'is', 'apple'], ['This', 'is', 'dog']]\n self.assertEqual(words_list, expected_words_list)\n\n def test_remove_stop_words_2(self):\n string_list = ['a', 'an', 'the']\n stop_word_list = ['a', 'an', 'the']\n words_list = self.processor.remove_stop_words(string_list, stop_word_list)\n self.assertEqual(words_list, [[], [], []])\n\n def test_remove_stop_words_3(self):\n string_list = []\n stop_word_list = ['a', 'an', 'the']\n words_list = self.processor.remove_stop_words(string_list, stop_word_list)\n self.assertEqual(words_list, [])\n\n def test_remove_stop_words_4(self):\n string_list = ['This is a test', 'This is an apple', 'This is the dog']\n stop_word_list = []\n words_list = self.processor.remove_stop_words(string_list, stop_word_list)\n expected_words_list = [['This', 'is', 'a', 'test'], ['This', 'is', 'an', 'apple'], ['This', 'is', 'the', 'dog']]\n self.assertEqual(words_list, expected_words_list)\n\n def test_remove_stop_words_5(self):\n string_list = ['This is a test', 'This is an apple', 'This is the dog']\n stop_word_list = ['a', 'an', 'the', 'This', 'is']\n words_list = self.processor.remove_stop_words(string_list, stop_word_list)\n expected_words_list = [['is', 'test'], ['is', 'apple'], ['is', 'dog']]\n self.assertEqual(words_list, expected_words_list)", "solution_code": "def remove_stop_words(self, string_list, stop_word_list):\n answer = []\n for string in string_list:\n string_split = string.split()\n for word in string_split:\n if word in stop_word_list:\n string_split.remove(word)\n answer.append(string_split)\n return answer", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "process", "method_description": "def process(self, string_list):\n \"\"\"\n Construct a stop word list including 'a', 'an', 'the', and remove all the stop words from the list of strings.\n :param string_list: a list of strings\n :return: a list of words without stop words\n >>> NLPDataProcessor.process(['This is a test.'])\n [['This', 'is', 'test.']]\n \"\"\"", "test_class": "NLPDataProcessorTestProcess", "test_code": "class NLPDataProcessorTestProcess(unittest.TestCase):\n def setUp(self):\n self.processor = NLPDataProcessor()\n\n def test_process(self):\n string_list = ['This is a test.', 'This is an apple.', 'This is the dog.']\n words_list = self.processor.process(string_list)\n expected_words_list = [['This', 'is', 'test.'], ['This', 'is', 'apple.'], ['This', 'is', 'dog.']]\n self.assertEqual(words_list, expected_words_list)\n\n def test_process_with_empty_string_list(self):\n string_list = []\n words_list = self.processor.process(string_list)\n self.assertEqual(words_list, [])\n\n def test_process_with_single_word_sentences(self):\n string_list = ['Hello aa', 'World']\n words_list = self.processor.process(string_list)\n expected_words_list = [['Hello', 'aa'], ['World']]\n self.assertEqual(words_list, expected_words_list)\n\n def test_process_with_stop_words_only(self):\n string_list = ['a', 'an', 'the']\n words_list = self.processor.process(string_list)\n self.assertEqual(words_list, [[], [], []])\n\n def test_process_with_stop_words_only_2(self):\n string_list = ['a', 'an', 'the','This']\n words_list = self.processor.process(string_list)\n self.assertEqual(words_list,[[], [], [], ['This']])", "solution_code": "def process(self, string_list):\n stop_word_list = self.construct_stop_word_list()\n words_list = self.remove_stop_words(string_list, stop_word_list)\n return words_list", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "construct_stop_word_list", "remove_stop_words" ] } } ] }, { "task_id": "ClassEval_63", "skeleton": "\nimport re\nfrom collections import Counter\n\nclass NLPDataProcessor2:\n \"\"\"\n The class processes NLP data by extracting words from a list of strings, calculating the frequency of each word, and returning the top 5 most frequent words.\n \"\"\"\n\n\n def process_data(self, string_list):\n \"\"\"\n keep only English letters and spaces in the string, then convert the string to lower case, and then split the string into a list of words.\n :param string_list: a list of strings\n :return: words_list: a list of words lists\n >>> NLPDataProcessor.process_data(['This is a test.'])\n [['this', 'is', 'a', 'test']]\n \"\"\"\n\n def calculate_word_frequency(self, words_list):\n \"\"\"\n Calculate the word frequency of each word in the list of words list, and sort the word frequency dictionary by value in descending order.\n :param words_list: a list of words lists\n :return: top 5 word frequency dictionary, a dictionary of word frequency, key is word, value is frequency\n >>> NLPDataProcessor.calculate_word_frequency([['this', 'is', 'a', 'test'], ['this', 'is', 'another', 'test']])\n {'this': 2, 'is': 2, 'test': 2, 'a': 1, 'another': 1}\n \"\"\"\n\n def process(self, string_list):\n \"\"\"\n keep only English letters and spaces in the string, then convert the string to lower case, and then split the string into a list of words. Calculate the word frequency of each word in the list of words list, and sort the word frequency dictionary by value in descending order.\n :param string_list: a list of strings\n :return: top 5 word frequency dictionary, a dictionary of word frequency, key is word, value is frequency\n >>> NLPDataProcessor.process(['This is a test.', 'This is another test.'])\n {'this': 2, 'is': 2, 'test': 2, 'a': 1, 'another': 1}\n \"\"\"", "test": "import unittest\n\nclass NLPDataProcessorTestProcessData(unittest.TestCase):\n\n def setUp(self):\n self.processor = NLPDataProcessor2()\n\n def test_process_data(self):\n string_list = [\"Hello World!\", \"This is a test.\"]\n expected_output = [['hello', 'world'], ['this', 'is', 'a', 'test']]\n self.assertEqual(self.processor.process_data(string_list), expected_output)\n\n def test_process_data2(self):\n string_list = [\"12345\", \"Special@Characters\"]\n expected_output = [[], ['specialcharacters']]\n self.assertEqual(self.processor.process_data(string_list), expected_output)\n\n def test_process_data3(self):\n string_list = []\n expected_output = []\n self.assertEqual(self.processor.process_data(string_list), expected_output)\n\n def test_process_data4(self):\n string_list = [\"Hello World!\", \"This is a test.\", \"12345\", \"Special@Characters\"]\n expected_output = [['hello', 'world'], ['this', 'is', 'a', 'test'], [], ['specialcharacters']]\n self.assertEqual(self.processor.process_data(string_list), expected_output)\n\n def test_process_data5(self):\n string_list = [\"Hello World!\", \"This is a test.\", \"12345\", \"Special@Characters\", \"Hello World!\", \"This is a test.\", \"12345\", \"Special@Characters\"]\n expected_output = [['hello', 'world'], ['this', 'is', 'a', 'test'], [], ['specialcharacters'], ['hello', 'world'], ['this', 'is', 'a', 'test'], [], ['specialcharacters']]\n self.assertEqual(self.processor.process_data(string_list), expected_output)\n\nclass NLPDataProcessorTestCalculate(unittest.TestCase):\n\n def setUp(self):\n self.processor = NLPDataProcessor2()\n\n def test_calculate_word_frequency(self):\n words_list = [['hello', 'world'], ['this', 'is', 'a', 'test'], ['hello', 'world', 'this', 'is', 'another', 'test'],\n ['hello', 'hello', 'world']]\n expected_output = {'hello': 4, 'world': 3, 'this': 2, 'is': 2, 'test': 2}\n self.assertEqual(self.processor.calculate_word_frequency(words_list), expected_output)\n\n def test_calculate_word_frequency2(self):\n words_list = [['hello', 'world'], ['this', 'is', 'a', 'test'], ['hello', 'world', 'this', 'is', 'another', 'test'],\n ['hello', 'hello', 'world'], ['world', 'world', 'world']]\n expected_output = {'world': 6, 'hello': 4, 'this': 2, 'is': 2, 'test': 2}\n self.assertEqual(self.processor.calculate_word_frequency(words_list), expected_output)\n\n def test_calculate_word_frequency3(self):\n words_list = [['hello', 'world'], ['hello', 'hello', 'world'], ['world', 'world']]\n expected_output = {'world': 4, 'hello': 3}\n self.assertEqual(self.processor.calculate_word_frequency(words_list), expected_output)\n\n def test_calculate_word_frequency4(self):\n words_list = [['hello', 'world'], ['this', 'is', 'a', '%%%'], ['hello', 'world', 'this', 'is', 'another', '%%%'],\n ['hello', 'hello', 'world'], ['%%%', 'world', 'a', '%%%'], ['%%%', 'hello', '%%%']]\n expected_output = {'%%%': 6, 'hello': 5, 'world': 4, 'is': 2, 'this': 2}\n self.assertEqual(self.processor.calculate_word_frequency(words_list), expected_output)\n\n def test_calculate_word_frequency5(self):\n words_list = [['hello', 'world'], ['this', 'is', 'a', '%%%'], ['hello', 'world', 'this', 'is', 'another', '%%%'],\n ['hello', 'hello', 'world'], ['%%%', 'world', 'a', '%%%'], ['%%%', 'hello', '%%%'], ['hello', 'world'], ['this', 'is', 'a', '%%%'], ['hello', 'world', 'this', 'is', 'another', '%%%'],\n ['hello', 'hello', 'world'], ['%%%', 'world', 'a', '%%%'], ['%%%', 'hello', '%%%']]\n expected_output = {'%%%': 12, 'hello': 10, 'world': 8, 'is': 4, 'this': 4}\n self.assertEqual(self.processor.calculate_word_frequency(words_list), expected_output)\n\nclass NLPDataProcessorTestProcess(unittest.TestCase):\n\n def setUp(self):\n self.processor = NLPDataProcessor2()\n\n def test_process(self):\n string_list = [\"Hello World!\", \"This is a test.\", \"Hello World, this is a test.\"]\n expected_output = {'hello': 2, 'world': 2, 'this': 2, 'is': 2, 'a': 2}\n self.assertEqual(self.processor.process(string_list), expected_output)\n\n def test_process2(self):\n string_list = []\n expected_output = []\n self.assertEqual(self.processor.process_data(string_list), expected_output)\n\n def test_calculate3(self):\n words_list = []\n expected_output = {}\n self.assertEqual(self.processor.calculate_word_frequency(words_list), expected_output)\n\n def test_process4(self):\n string_list = [\"@#$%^&*\", \"Special_Characters\", \"12345\"]\n expected_output = [[], ['specialcharacters'], []]\n self.assertEqual(self.processor.process_data(string_list), expected_output)\n\n def test_process5(self):\n string_list = [\"Hello World! %%%\", \"This is a %%% test. %%% \", \"Hello World, this is a test. %%%\"]\n expected_output = {'hello': 2, 'world': 2, 'this': 2, 'is': 2, 'a': 2}\n self.assertEqual(self.processor.process(string_list), expected_output)\n\n def test_process6(self):\n string_list = [\"12345\", \"67890\", \"98765\"]\n expected_output = [[], [], []]\n self.assertEqual(self.processor.process_data(string_list), expected_output)", "solution_code": "from collections import Counter\nimport re\n\nclass NLPDataProcessor2:\n\n def process_data(self, string_list):\n words_list = []\n for string in string_list:\n # Remove non-English letters and convert to lowercase\n processed_string = re.sub(r'[^a-zA-Z\\s]', '', string.lower())\n # Split the string into words\n words = processed_string.split()\n words_list.append(words)\n return words_list\n\n def calculate_word_frequency(self, words_list):\n word_frequency = Counter()\n for words in words_list:\n word_frequency.update(words)\n sorted_word_frequency = dict(sorted(word_frequency.items(), key=lambda x: x[1], reverse=True))\n top_5_word_frequency = dict(list(sorted_word_frequency.items())[:5])\n return top_5_word_frequency\n\n def process(self, string_list):\n words_list = self.process_data(string_list)\n word_frequency_dict = self.calculate_word_frequency(words_list)\n return word_frequency_dict", "import_statement": [ "from collections import Counter", "import re" ], "class_description": " \"\"\"\n The class processes NLP data by extracting words from a list of strings, calculating the frequency of each word, and returning the top 5 most frequent words.\n \"\"\"\n", "class_name": "NLPDataProcessor2", "test_classes": [ "NLPDataProcessorTestProcessData", "NLPDataProcessorTestCalculate", "NLPDataProcessorTestProcess" ], "class_constructor": "class NLPDataProcessor2: \n", "fields": [], "methods_info": [ { "method_name": "process_data", "method_description": "def process_data(self, string_list):\n \"\"\"\n keep only English letters and spaces in the string, then convert the string to lower case, and then split the string into a list of words.\n :param string_list: a list of strings\n :return: words_list: a list of words lists\n >>> NLPDataProcessor.process_data(['This is a test.'])\n [['this', 'is', 'a', 'test']]\n \"\"\"", "test_class": "NLPDataProcessorTestProcessData", "test_code": "class NLPDataProcessorTestProcessData(unittest.TestCase):\n\n def setUp(self):\n self.processor = NLPDataProcessor2()\n\n def test_process_data(self):\n string_list = [\"Hello World!\", \"This is a test.\"]\n expected_output = [['hello', 'world'], ['this', 'is', 'a', 'test']]\n self.assertEqual(self.processor.process_data(string_list), expected_output)\n\n def test_process_data2(self):\n string_list = [\"12345\", \"Special@Characters\"]\n expected_output = [[], ['specialcharacters']]\n self.assertEqual(self.processor.process_data(string_list), expected_output)\n\n def test_process_data3(self):\n string_list = []\n expected_output = []\n self.assertEqual(self.processor.process_data(string_list), expected_output)\n\n def test_process_data4(self):\n string_list = [\"Hello World!\", \"This is a test.\", \"12345\", \"Special@Characters\"]\n expected_output = [['hello', 'world'], ['this', 'is', 'a', 'test'], [], ['specialcharacters']]\n self.assertEqual(self.processor.process_data(string_list), expected_output)\n\n def test_process_data5(self):\n string_list = [\"Hello World!\", \"This is a test.\", \"12345\", \"Special@Characters\", \"Hello World!\", \"This is a test.\", \"12345\", \"Special@Characters\"]\n expected_output = [['hello', 'world'], ['this', 'is', 'a', 'test'], [], ['specialcharacters'], ['hello', 'world'], ['this', 'is', 'a', 'test'], [], ['specialcharacters']]\n self.assertEqual(self.processor.process_data(string_list), expected_output)", "solution_code": "def process_data(self, string_list):\n words_list = []\n for string in string_list:\n # Remove non-English letters and convert to lowercase\n processed_string = re.sub(r'[^a-zA-Z\\s]', '', string.lower())\n # Split the string into words\n words = processed_string.split()\n words_list.append(words)\n return words_list", "dependencies": { "Standalone": false, "lib_dependencies": [ "re" ], "field_dependencies": [], "method_dependencies": [ "process" ] } }, { "method_name": "calculate_word_frequency", "method_description": "def calculate_word_frequency(self, words_list):\n \"\"\"\n Calculate the word frequency of each word in the list of words list, and sort the word frequency dictionary by value in descending order.\n :param words_list: a list of words lists\n :return: top 5 word frequency dictionary, a dictionary of word frequency, key is word, value is frequency\n >>> NLPDataProcessor.calculate_word_frequency([['this', 'is', 'a', 'test'], ['this', 'is', 'another', 'test']])\n {'this': 2, 'is': 2, 'test': 2, 'a': 1, 'another': 1}\n \"\"\"", "test_class": "NLPDataProcessorTestCalculate", "test_code": "class NLPDataProcessorTestCalculate(unittest.TestCase):\n\n def setUp(self):\n self.processor = NLPDataProcessor2()\n\n def test_calculate_word_frequency(self):\n words_list = [['hello', 'world'], ['this', 'is', 'a', 'test'], ['hello', 'world', 'this', 'is', 'another', 'test'],\n ['hello', 'hello', 'world']]\n expected_output = {'hello': 4, 'world': 3, 'this': 2, 'is': 2, 'test': 2}\n self.assertEqual(self.processor.calculate_word_frequency(words_list), expected_output)\n\n def test_calculate_word_frequency2(self):\n words_list = [['hello', 'world'], ['this', 'is', 'a', 'test'], ['hello', 'world', 'this', 'is', 'another', 'test'],\n ['hello', 'hello', 'world'], ['world', 'world', 'world']]\n expected_output = {'world': 6, 'hello': 4, 'this': 2, 'is': 2, 'test': 2}\n self.assertEqual(self.processor.calculate_word_frequency(words_list), expected_output)\n\n def test_calculate_word_frequency3(self):\n words_list = [['hello', 'world'], ['hello', 'hello', 'world'], ['world', 'world']]\n expected_output = {'world': 4, 'hello': 3}\n self.assertEqual(self.processor.calculate_word_frequency(words_list), expected_output)\n\n def test_calculate_word_frequency4(self):\n words_list = [['hello', 'world'], ['this', 'is', 'a', '%%%'], ['hello', 'world', 'this', 'is', 'another', '%%%'],\n ['hello', 'hello', 'world'], ['%%%', 'world', 'a', '%%%'], ['%%%', 'hello', '%%%']]\n expected_output = {'%%%': 6, 'hello': 5, 'world': 4, 'is': 2, 'this': 2}\n self.assertEqual(self.processor.calculate_word_frequency(words_list), expected_output)\n\n def test_calculate_word_frequency5(self):\n words_list = [['hello', 'world'], ['this', 'is', 'a', '%%%'], ['hello', 'world', 'this', 'is', 'another', '%%%'],\n ['hello', 'hello', 'world'], ['%%%', 'world', 'a', '%%%'], ['%%%', 'hello', '%%%'], ['hello', 'world'], ['this', 'is', 'a', '%%%'], ['hello', 'world', 'this', 'is', 'another', '%%%'],\n ['hello', 'hello', 'world'], ['%%%', 'world', 'a', '%%%'], ['%%%', 'hello', '%%%']]\n expected_output = {'%%%': 12, 'hello': 10, 'world': 8, 'is': 4, 'this': 4}\n self.assertEqual(self.processor.calculate_word_frequency(words_list), expected_output)", "solution_code": "def calculate_word_frequency(self, words_list):\n word_frequency = Counter()\n for words in words_list:\n word_frequency.update(words)\n sorted_word_frequency = dict(sorted(word_frequency.items(), key=lambda x: x[1], reverse=True))\n top_5_word_frequency = dict(list(sorted_word_frequency.items())[:5])\n return top_5_word_frequency", "dependencies": { "Standalone": false, "lib_dependencies": [ "Counter" ], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "process", "method_description": "def process(self, string_list):\n \"\"\"\n keep only English letters and spaces in the string, then convert the string to lower case, and then split the string into a list of words. Calculate the word frequency of each word in the list of words list, and sort the word frequency dictionary by value in descending order.\n :param string_list: a list of strings\n :return: top 5 word frequency dictionary, a dictionary of word frequency, key is word, value is frequency\n >>> NLPDataProcessor.process(['This is a test.', 'This is another test.'])\n {'this': 2, 'is': 2, 'test': 2, 'a': 1, 'another': 1}\n \"\"\"", "test_class": "NLPDataProcessorTestProcess", "test_code": "class NLPDataProcessorTestProcess(unittest.TestCase):\n\n def setUp(self):\n self.processor = NLPDataProcessor2()\n\n def test_process(self):\n string_list = [\"Hello World!\", \"This is a test.\", \"Hello World, this is a test.\"]\n expected_output = {'hello': 2, 'world': 2, 'this': 2, 'is': 2, 'a': 2}\n self.assertEqual(self.processor.process(string_list), expected_output)\n\n def test_process2(self):\n string_list = []\n expected_output = []\n self.assertEqual(self.processor.process_data(string_list), expected_output)\n\n def test_calculate3(self):\n words_list = []\n expected_output = {}\n self.assertEqual(self.processor.calculate_word_frequency(words_list), expected_output)\n\n def test_process4(self):\n string_list = [\"@#$%^&*\", \"Special_Characters\", \"12345\"]\n expected_output = [[], ['specialcharacters'], []]\n self.assertEqual(self.processor.process_data(string_list), expected_output)\n\n def test_process5(self):\n string_list = [\"Hello World! %%%\", \"This is a %%% test. %%% \", \"Hello World, this is a test. %%%\"]\n expected_output = {'hello': 2, 'world': 2, 'this': 2, 'is': 2, 'a': 2}\n self.assertEqual(self.processor.process(string_list), expected_output)\n\n def test_process6(self):\n string_list = [\"12345\", \"67890\", \"98765\"]\n expected_output = [[], [], []]\n self.assertEqual(self.processor.process_data(string_list), expected_output)", "solution_code": "def process(self, string_list):\n words_list = self.process_data(string_list)\n word_frequency_dict = self.calculate_word_frequency(words_list)\n return word_frequency_dict", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "process_data", "calculate_word_frequency" ] } } ] }, { "task_id": "ClassEval_64", "skeleton": "\nclass NumberConverter:\n \"\"\"\n The class allows to convert decimal to binary, octal and hexadecimal repectively and contrarily\n \"\"\"\n\n @staticmethod\n def decimal_to_binary(decimal_num):\n \"\"\"\n Convert a number from decimal format to binary format.\n :param decimal_num: int, decimal number\n :return: str, the binary representation of an integer.\n >>> NumberConverter.decimal_to_binary(42423)\n '1010010110110111'\n \"\"\"\n\n @staticmethod\n def binary_to_decimal(binary_num):\n \"\"\"\n Convert a number from binary format to decimal format.\n :param binary_num: str, binary number\n :return: int, the decimal representation of binary number str.\n >>> NumberConverter.binary_to_decimal('1010010110110111')\n 42423\n \"\"\"\n\n\n @staticmethod\n def decimal_to_octal(decimal_num):\n \"\"\"\n Convert a number from decimal format to octal format.\n :param decimal_num: int, decimal number\n :return: str, the octal representation of an integer.\n >>> NumberConverter.decimal_to_octal(42423)\n '122667'\n \"\"\"\n\n @staticmethod\n def octal_to_decimal(octal_num):\n \"\"\"\n Convert a number from octal format to decimal format.\n :param octal_num: str, octal num\n :return: int, the decimal representation of octal number str.\n >>> NumberConverter.octal_to_decimal('122667')\n 42423\n \"\"\"\n\n @staticmethod\n def decimal_to_hex(decimal_num):\n \"\"\"\n Convert a number from decimal format to hex format.\n :param decimal_num: int, decimal number\n :return hex_num: str, the hex representation of an integer.\n >>> NumberConverter.decimal_to_hex(42423)\n 'a5b7'\n \"\"\"\n\n @staticmethod\n def hex_to_decimal(hex_num):\n \"\"\"\n Convert a number from hex format to decimal format.\n :param hex_num: str, hex num\n :return: int, the decimal representation of hex number str.\n >>> NumberConverter.hex_to_decimal('a5b7')\n 42423\n \"\"\"", "test": "import unittest\n\n\nclass NumberConverterTestDecimalToBinary(unittest.TestCase):\n def test_decimal_to_binary(self):\n self.assertEqual('1010010110110111', NumberConverter.decimal_to_binary(42423))\n\n def test_decimal_to_binary_2(self):\n self.assertEqual('101001100010111', NumberConverter.decimal_to_binary(21271))\n\n def test_decimal_to_binary_3(self):\n self.assertEqual('1010010111010111', NumberConverter.decimal_to_binary(42455))\n\n def test_decimal_to_binary_4(self):\n self.assertEqual('10100101110101011', NumberConverter.decimal_to_binary(84907))\n\n def test_decimal_to_binary_5(self):\n self.assertEqual('101001011101010111', NumberConverter.decimal_to_binary(169815))\n\nclass NumberConverterTestBinaryToDecimal(unittest.TestCase):\n def test_binary_to_decimal(self):\n self.assertEqual(42423, NumberConverter.binary_to_decimal('1010010110110111'))\n\n def test_binary_to_decimal_2(self):\n self.assertEqual(10615, NumberConverter.binary_to_decimal('10100101110111'))\n\n def test_binary_to_decimal_3(self):\n self.assertEqual(42455, NumberConverter.binary_to_decimal('1010010111010111'))\n\n def test_binary_to_decimal_4(self):\n self.assertEqual(169819, NumberConverter.binary_to_decimal('101001011101011011'))\n\n def test_binary_to_decimal_5(self):\n self.assertEqual(339639, NumberConverter.binary_to_decimal('1010010111010110111'))\n\nclass NumberConvertTestDecimalToOctal(unittest.TestCase):\n def test_decimal_to_octal(self):\n self.assertEqual('122667', NumberConverter.decimal_to_octal(42423))\n\n def test_decimal_to_octal_2(self):\n self.assertEqual('51427', NumberConverter.decimal_to_octal(21271))\n\n def test_decimal_to_octal_3(self):\n self.assertEqual('245653', NumberConverter.decimal_to_octal(84907))\n\n def test_decimal_to_octal_4(self):\n self.assertEqual('513527', NumberConverter.decimal_to_octal(169815))\n\n def test_decimal_to_octal_5(self):\n self.assertEqual('1227256', NumberConverter.decimal_to_octal(339630))\n\nclass NumberConvertTestOctalToDecimal(unittest.TestCase):\n def test_octal_to_decimal(self):\n self.assertEqual(42423, NumberConverter.octal_to_decimal('122667'))\n\n def test_octal_to_decimal_2(self):\n self.assertEqual(21271, NumberConverter.octal_to_decimal('51427'))\n\n def test_octal_to_decimal_3(self):\n self.assertEqual(84907, NumberConverter.octal_to_decimal('245653'))\n\n def test_octal_to_decimal_4(self):\n self.assertEqual(169815, NumberConverter.octal_to_decimal('513527'))\n\n def test_octal_to_decimal_5(self):\n self.assertEqual(339630, NumberConverter.octal_to_decimal('1227256'))\n\nclass NumberConvertTestDecimalToHex(unittest.TestCase):\n def test_decimal_to_hex(self):\n self.assertEqual('a5b7', NumberConverter.decimal_to_hex(42423))\n\n def test_decimal_to_hex_2(self):\n self.assertEqual('5317', NumberConverter.decimal_to_hex(21271))\n\n def test_decimal_to_hex_3(self):\n self.assertEqual('14bab', NumberConverter.decimal_to_hex(84907))\n\n def test_decimal_to_hex_4(self):\n self.assertEqual('29757', NumberConverter.decimal_to_hex(169815))\n\n def test_decimal_to_hex_5(self):\n self.assertEqual('52eb7', NumberConverter.decimal_to_hex(339639))\n\nclass NumberConvertTestHexToDecimal(unittest.TestCase):\n def test_hex_to_decimal(self):\n self.assertEqual(42423, NumberConverter.hex_to_decimal('a5b7'))\n\n def test_hex_to_decimal_2(self):\n self.assertEqual(21207, NumberConverter.hex_to_decimal('52d7'))\n\n def test_hex_to_decimal_3(self):\n self.assertEqual(84627, NumberConverter.hex_to_decimal('14a93'))\n\n def test_hex_to_decimal_4(self):\n self.assertEqual(170615, NumberConverter.hex_to_decimal('29a77'))\n\n def test_hex_to_decimal_5(self):\n self.assertEqual(342647, NumberConverter.hex_to_decimal('53a77'))\n\nclass NumberConvertTestMain(unittest.TestCase):\n def test_main(self):\n self.assertEqual('1010010110110111', NumberConverter.decimal_to_binary(42423))\n self.assertEqual(42423, NumberConverter.binary_to_decimal('1010010110110111'))\n self.assertEqual('122667', NumberConverter.decimal_to_octal(42423))\n self.assertEqual('122667', NumberConverter.decimal_to_octal(42423))\n self.assertEqual('a5b7', NumberConverter.decimal_to_hex(42423))\n self.assertEqual(42423, NumberConverter.hex_to_decimal('a5b7'))", "solution_code": "class NumberConverter:\n @staticmethod\n def decimal_to_binary(decimal_num):\n binary_num = bin(decimal_num)[2:]\n return binary_num\n\n @staticmethod\n def binary_to_decimal(binary_num):\n decimal_num = int(binary_num, 2)\n return decimal_num\n\n @staticmethod\n def decimal_to_octal(decimal_num):\n octal_num = oct(decimal_num)[2:]\n return octal_num\n\n @staticmethod\n def octal_to_decimal(octal_num):\n decimal_num = int(octal_num, 8)\n return decimal_num\n\n @staticmethod\n def decimal_to_hex(decimal_num):\n hex_num = hex(decimal_num)[2:]\n return hex_num\n\n @staticmethod\n def hex_to_decimal(hex_num):\n decimal_num = int(hex_num, 16)\n return decimal_num", "import_statement": [], "class_description": " \"\"\"\n The class allows to convert decimal to binary, octal and hexadecimal repectively and contrarily\n \"\"\"\n", "class_name": "NumberConverter", "test_classes": [ "NumberConverterTestDecimalToBinary", "NumberConverterTestBinaryToDecimal", "NumberConvertTestDecimalToOctal", "NumberConvertTestOctalToDecimal", "NumberConvertTestDecimalToHex", "NumberConvertTestHexToDecimal", "NumberConvertTestMain" ], "class_constructor": "class NumberConverter: \n", "fields": [], "methods_info": [ { "method_name": "decimal_to_binary", "method_description": "def decimal_to_binary(decimal_num):\n \"\"\"\n Convert a number from decimal format to binary format.\n :param decimal_num: int, decimal number\n :return: str, the binary representation of an integer.\n >>> NumberConverter.decimal_to_binary(42423)\n '1010010110110111'\n \"\"\"", "test_class": "NumberConverterTestDecimalToBinary", "test_code": "class NumberConverterTestDecimalToBinary(unittest.TestCase):\n def test_decimal_to_binary(self):\n self.assertEqual('1010010110110111', NumberConverter.decimal_to_binary(42423))\n\n def test_decimal_to_binary_2(self):\n self.assertEqual('101001100010111', NumberConverter.decimal_to_binary(21271))\n\n def test_decimal_to_binary_3(self):\n self.assertEqual('1010010111010111', NumberConverter.decimal_to_binary(42455))\n\n def test_decimal_to_binary_4(self):\n self.assertEqual('10100101110101011', NumberConverter.decimal_to_binary(84907))\n\n def test_decimal_to_binary_5(self):\n self.assertEqual('101001011101010111', NumberConverter.decimal_to_binary(169815))", "solution_code": "def decimal_to_binary(decimal_num):\n binary_num = bin(decimal_num)[2:]\n return binary_num", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "binary_to_decimal", "method_description": "@staticmethod\n def binary_to_decimal(binary_num):\n \"\"\"\n Convert a number from binary format to decimal format.\n :param binary_num: str, binary number\n :return: int, the decimal representation of binary number str.\n >>> NumberConverter.binary_to_decimal('1010010110110111')\n 42423\n \"\"\"", "test_class": "NumberConverterTestBinaryToDecimal", "test_code": "class NumberConverterTestBinaryToDecimal(unittest.TestCase):\n def test_binary_to_decimal(self):\n self.assertEqual(42423, NumberConverter.binary_to_decimal('1010010110110111'))\n\n def test_binary_to_decimal_2(self):\n self.assertEqual(10615, NumberConverter.binary_to_decimal('10100101110111'))\n\n def test_binary_to_decimal_3(self):\n self.assertEqual(42455, NumberConverter.binary_to_decimal('1010010111010111'))\n\n def test_binary_to_decimal_4(self):\n self.assertEqual(169819, NumberConverter.binary_to_decimal('101001011101011011'))\n\n def test_binary_to_decimal_5(self):\n self.assertEqual(339639, NumberConverter.binary_to_decimal('1010010111010110111'))", "solution_code": "@staticmethod\n def binary_to_decimal(binary_num):\n decimal_num = int(binary_num, 2)\n return decimal_num", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "decimal_to_octal", "method_description": "@staticmethod\n def decimal_to_octal(decimal_num):\n \"\"\"\n Convert a number from decimal format to octal format.\n :param decimal_num: int, decimal number\n :return: str, the octal representation of an integer.\n >>> NumberConverter.decimal_to_octal(42423)\n '122667'\n \"\"\"", "test_class": "NumberConvertTestDecimalToOctal", "test_code": "class NumberConvertTestDecimalToOctal(unittest.TestCase):\n def test_decimal_to_octal(self):\n self.assertEqual('122667', NumberConverter.decimal_to_octal(42423))\n\n def test_decimal_to_octal_2(self):\n self.assertEqual('51427', NumberConverter.decimal_to_octal(21271))\n\n def test_decimal_to_octal_3(self):\n self.assertEqual('245653', NumberConverter.decimal_to_octal(84907))\n\n def test_decimal_to_octal_4(self):\n self.assertEqual('513527', NumberConverter.decimal_to_octal(169815))\n\n def test_decimal_to_octal_5(self):\n self.assertEqual('1227256', NumberConverter.decimal_to_octal(339630))", "solution_code": "@staticmethod\n def decimal_to_octal(decimal_num):\n octal_num = oct(decimal_num)[2:]\n return octal_num", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "octal_to_decimal", "method_description": "@staticmethod\n def octal_to_decimal(octal_num):\n \"\"\"\n Convert a number from octal format to decimal format.\n :param octal_num: str, octal num\n :return: int, the decimal representation of octal number str.\n >>> NumberConverter.octal_to_decimal('122667')\n 42423\n \"\"\"", "test_class": "NumberConvertTestOctalToDecimal", "test_code": "class NumberConvertTestOctalToDecimal(unittest.TestCase):\n def test_octal_to_decimal(self):\n self.assertEqual(42423, NumberConverter.octal_to_decimal('122667'))\n\n def test_octal_to_decimal_2(self):\n self.assertEqual(21271, NumberConverter.octal_to_decimal('51427'))\n\n def test_octal_to_decimal_3(self):\n self.assertEqual(84907, NumberConverter.octal_to_decimal('245653'))\n\n def test_octal_to_decimal_4(self):\n self.assertEqual(169815, NumberConverter.octal_to_decimal('513527'))\n\n def test_octal_to_decimal_5(self):\n self.assertEqual(339630, NumberConverter.octal_to_decimal('1227256'))", "solution_code": "@staticmethod\n def octal_to_decimal(octal_num):\n decimal_num = int(octal_num, 8)\n return decimal_num", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "decimal_to_hex", "method_description": "@staticmethod\n def decimal_to_hex(decimal_num):\n \"\"\"\n Convert a number from decimal format to hex format.\n :param decimal_num: int, decimal number\n :return hex_num: str, the hex representation of an integer.\n >>> NumberConverter.decimal_to_hex(42423)\n 'a5b7'\n \"\"\"", "test_class": "NumberConvertTestDecimalToHex", "test_code": "class NumberConvertTestDecimalToHex(unittest.TestCase):\n def test_decimal_to_hex(self):\n self.assertEqual('a5b7', NumberConverter.decimal_to_hex(42423))\n\n def test_decimal_to_hex_2(self):\n self.assertEqual('5317', NumberConverter.decimal_to_hex(21271))\n\n def test_decimal_to_hex_3(self):\n self.assertEqual('14bab', NumberConverter.decimal_to_hex(84907))\n\n def test_decimal_to_hex_4(self):\n self.assertEqual('29757', NumberConverter.decimal_to_hex(169815))\n\n def test_decimal_to_hex_5(self):\n self.assertEqual('52eb7', NumberConverter.decimal_to_hex(339639))", "solution_code": "@staticmethod\n def decimal_to_hex(decimal_num):\n hex_num = hex(decimal_num)[2:]\n return hex_num", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "hex_to_decimal", "method_description": "@staticmethod\n def hex_to_decimal(hex_num):\n \"\"\"\n Convert a number from hex format to decimal format.\n :param hex_num: str, hex num\n :return: int, the decimal representation of hex number str.\n >>> NumberConverter.hex_to_decimal('a5b7')\n 42423\n \"\"\"", "test_class": "NumberConvertTestHexToDecimal", "test_code": "class NumberConvertTestHexToDecimal(unittest.TestCase):\n def test_hex_to_decimal(self):\n self.assertEqual(42423, NumberConverter.hex_to_decimal('a5b7'))\n\n def test_hex_to_decimal_2(self):\n self.assertEqual(21207, NumberConverter.hex_to_decimal('52d7'))\n\n def test_hex_to_decimal_3(self):\n self.assertEqual(84627, NumberConverter.hex_to_decimal('14a93'))\n\n def test_hex_to_decimal_4(self):\n self.assertEqual(170615, NumberConverter.hex_to_decimal('29a77'))\n\n def test_hex_to_decimal_5(self):\n self.assertEqual(342647, NumberConverter.hex_to_decimal('53a77'))", "solution_code": "@staticmethod\n def hex_to_decimal(hex_num):\n decimal_num = int(hex_num, 16)\n return decimal_num", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_65", "skeleton": "\nclass NumberWordFormatter:\n \"\"\"\n This is a class that provides to convert numbers into their corresponding English word representation, including handling the conversion of both the integer and decimal parts, and incorporating appropriate connectors and units.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialize NumberWordFormatter object.\n \"\"\"\n self.NUMBER = [\"\", \"ONE\", \"TWO\", \"THREE\", \"FOUR\", \"FIVE\", \"SIX\", \"SEVEN\", \"EIGHT\", \"NINE\"]\n self.NUMBER_TEEN = [\"TEN\", \"ELEVEN\", \"TWELVE\", \"THIRTEEN\", \"FOURTEEN\", \"FIFTEEN\", \"SIXTEEN\", \"SEVENTEEN\",\n \"EIGHTEEN\",\n \"NINETEEN\"]\n self.NUMBER_TEN = [\"TEN\", \"TWENTY\", \"THIRTY\", \"FORTY\", \"FIFTY\", \"SIXTY\", \"SEVENTY\", \"EIGHTY\", \"NINETY\"]\n self.NUMBER_MORE = [\"\", \"THOUSAND\", \"MILLION\", \"BILLION\"]\n self.NUMBER_SUFFIX = [\"k\", \"w\", \"\", \"m\", \"\", \"\", \"b\", \"\", \"\", \"t\", \"\", \"\", \"p\", \"\", \"\", \"e\"]\n\n def format(self, x):\n \"\"\"\n Converts a number into words format\n :param x: int or float, the number to be converted into words format\n :return: str, the number in words format\n >>> formatter = NumberWordFormatter()\n >>> formatter.format(123456)\n \"ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY\"\n \"\"\"\n\n\n def format_string(self, x):\n \"\"\"\n Converts a string representation of a number into words format\n :param x: str, the string representation of a number\n :return: str, the number in words format\n >>> formatter = NumberWordFormatter()\n >>> formatter.format_string(\"123456\")\n \"ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY\"\n \"\"\"\n\n\n def trans_two(self, s):\n \"\"\"\n Converts a two-digit number into words format\n :param s: str, the two-digit number\n :return: str, the number in words format\n >>> formatter = NumberWordFormatter()\n >>> formatter.trans_two(\"23\")\n \"TWENTY THREE\"\n \"\"\"\n\n\n def trans_three(self, s):\n \"\"\"\n Converts a three-digit number into words format\n :param s: str, the three-digit number\n :return: str, the number in words format\n >>> formatter = NumberWordFormatter()\n >>> formatter.trans_three(\"123\")\n \"ONE HUNDRED AND TWENTY THREE\"\n \"\"\"\n\n def parse_more(self, i):\n \"\"\"\n Parses the thousand/million/billion suffix based on the index\n :param i: int, the index representing the magnitude (thousand, million, billion)\n :return: str, the corresponding suffix for the magnitude\n >>> formatter = NumberWordFormatter()\n >>> formatter.parse_more(1)\n \"THOUSAND\"\n \"\"\"", "test": "import unittest\n\n\nclass NumberWordFormatterTestFormat(unittest.TestCase):\n def test_format_1(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format(123456),\n \"ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY\")\n\n def test_format_2(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format(1000), \"ONE THOUSAND ONLY\")\n\n def test_format_3(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format(1000000), \"ONE MILLION ONLY\")\n\n def test_format_4(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format(1.23), \"ONE AND CENTS TWENTY THREE ONLY\")\n\n def test_format_5(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format(0), \"ZERO ONLY\")\n\n def test_format_6(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format(None), \"\")\n\n\nclass NumberWordFormatterTestFormatString(unittest.TestCase):\n def test_format_string_1(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format_string('123456'),\n \"ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY\")\n\n def test_format_string_2(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format_string('1000'), \"ONE THOUSAND ONLY\")\n\n def test_format_string_3(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format_string('1000000'), \"ONE MILLION ONLY\")\n\n def test_format_string_4(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format_string('1.23'), \"ONE AND CENTS TWENTY THREE ONLY\")\n\n def test_format_string_5(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format_string('0'), \"ZERO ONLY\")\n\n def test_format_string_6(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format_string('10'), \"TEN ONLY\")\n\n\nclass NumberWordFormatterTestTransTwo(unittest.TestCase):\n def test_trans_two_1(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_two(\"23\"), \"TWENTY THREE\")\n\n def test_trans_two_2(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_two(\"10\"), \"TEN\")\n\n def test_trans_two_3(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_two(\"05\"), \"FIVE\")\n\n def test_trans_two_4(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_two(\"00\"), \"\")\n\n def test_trans_two_5(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_two(\"01\"), \"ONE\")\n\n def test_trans_two_6(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_two(\"80\"), \"EIGHTY\")\n\n\nclass NumberWordFormatterTestTransThree(unittest.TestCase):\n def test_trans_three_1(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_three(\"123\"), \"ONE HUNDRED AND TWENTY THREE\")\n\n def test_trans_three_2(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_three(\"900\"), \"NINE HUNDRED\")\n\n def test_trans_three_3(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_three(\"007\"), \"SEVEN\")\n\n def test_trans_three_4(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_three(\"001\"), \"ONE\")\n\n def test_trans_three_5(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_three(\"006\"), \"SIX\")\n\n\nclass NumberWordFormatterTestParseMore(unittest.TestCase):\n def test_parse_more_1(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.parse_more(0), \"\")\n\n def test_parse_more_2(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.parse_more(1), \"THOUSAND\")\n\n def test_parse_more_3(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.parse_more(2), \"MILLION\")\n\n def test_parse_more_4(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.parse_more(3), \"BILLION\")\n\n\nclass NumberWordFormatterTest(unittest.TestCase):\n def test_NumberWordFormatter(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format(123456),\n \"ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY\")\n\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format_string('123456'),\n \"ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY\")\n\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_two(\"23\"), \"TWENTY THREE\")\n\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_three(\"123\"), \"ONE HUNDRED AND TWENTY THREE\")\n\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.parse_more(1), \"THOUSAND\")", "solution_code": "class NumberWordFormatter:\n def __init__(self):\n self.NUMBER = [\"\", \"ONE\", \"TWO\", \"THREE\", \"FOUR\", \"FIVE\", \"SIX\", \"SEVEN\", \"EIGHT\", \"NINE\"]\n self.NUMBER_TEEN = [\"TEN\", \"ELEVEN\", \"TWELVE\", \"THIRTEEN\", \"FOURTEEN\", \"FIFTEEN\", \"SIXTEEN\", \"SEVENTEEN\",\n \"EIGHTEEN\",\n \"NINETEEN\"]\n self.NUMBER_TEN = [\"TEN\", \"TWENTY\", \"THIRTY\", \"FORTY\", \"FIFTY\", \"SIXTY\", \"SEVENTY\", \"EIGHTY\", \"NINETY\"]\n self.NUMBER_MORE = [\"\", \"THOUSAND\", \"MILLION\", \"BILLION\"]\n self.NUMBER_SUFFIX = [\"k\", \"w\", \"\", \"m\", \"\", \"\", \"b\", \"\", \"\", \"t\", \"\", \"\", \"p\", \"\", \"\", \"e\"]\n\n def format(self, x):\n if x is not None:\n return self.format_string(str(x))\n else:\n return \"\"\n\n def format_string(self, x):\n lstr, rstr = (x.split('.') + [''])[:2]\n lstrrev = lstr[::-1]\n a = [''] * 5\n\n if len(lstrrev) % 3 == 1:\n lstrrev += \"00\"\n elif len(lstrrev) % 3 == 2:\n lstrrev += \"0\"\n\n lm = \"\"\n for i in range(len(lstrrev) // 3):\n a[i] = lstrrev[3 * i:3 * i + 3][::-1]\n if a[i] != \"000\":\n lm = self.trans_three(a[i]) + \" \" + self.parse_more(i) + \" \" + lm\n else:\n lm += self.trans_three(a[i])\n\n xs = f\"AND CENTS {self.trans_two(rstr)} \" if rstr else \"\"\n if not lm.strip():\n return \"ZERO ONLY\"\n else:\n return f\"{lm.strip()} {xs}ONLY\"\n\n def trans_two(self, s):\n s = s.zfill(2)\n if s[0] == \"0\":\n return self.NUMBER[int(s[-1])]\n elif s[0] == \"1\":\n return self.NUMBER_TEEN[int(s) - 10]\n elif s[1] == \"0\":\n return self.NUMBER_TEN[int(s[0]) - 1]\n else:\n return self.NUMBER_TEN[int(s[0]) - 1] + \" \" + self.NUMBER[int(s[-1])]\n\n def trans_three(self, s):\n if s[0] == \"0\":\n return self.trans_two(s[1:])\n elif s[1:] == \"00\":\n return f\"{self.NUMBER[int(s[0])]} HUNDRED\"\n else:\n return f\"{self.NUMBER[int(s[0])]} HUNDRED AND {self.trans_two(s[1:])}\"\n\n def parse_more(self, i):\n return self.NUMBER_MORE[i]", "import_statement": [], "class_description": " \"\"\"\n This is a class that provides to convert numbers into their corresponding English word representation, including handling the conversion of both the integer and decimal parts, and incorporating appropriate connectors and units.\n \"\"\"\n", "class_name": "NumberWordFormatter", "test_classes": [ "NumberWordFormatterTestFormat", "NumberWordFormatterTestFormatString", "NumberWordFormatterTestTransTwo", "NumberWordFormatterTestTransThree", "NumberWordFormatterTestParseMore", "NumberWordFormatterTest" ], "class_constructor": "class NumberWordFormatter: \n def __init__(self):\n \"\"\"\n Initialize NumberWordFormatter object.\n \"\"\"\n self.NUMBER = [\"\", \"ONE\", \"TWO\", \"THREE\", \"FOUR\", \"FIVE\", \"SIX\", \"SEVEN\", \"EIGHT\", \"NINE\"]\n self.NUMBER_TEEN = [\"TEN\", \"ELEVEN\", \"TWELVE\", \"THIRTEEN\", \"FOURTEEN\", \"FIFTEEN\", \"SIXTEEN\", \"SEVENTEEN\",\n \"EIGHTEEN\",\n \"NINETEEN\"]\n self.NUMBER_TEN = [\"TEN\", \"TWENTY\", \"THIRTY\", \"FORTY\", \"FIFTY\", \"SIXTY\", \"SEVENTY\", \"EIGHTY\", \"NINETY\"]\n self.NUMBER_MORE = [\"\", \"THOUSAND\", \"MILLION\", \"BILLION\"]\n self.NUMBER_SUFFIX = [\"k\", \"w\", \"\", \"m\", \"\", \"\", \"b\", \"\", \"\", \"t\", \"\", \"\", \"p\", \"\", \"\", \"e\"]\n\n", "fields": [ "self.NUMBER", "self.NUMBER_MORE", "self.NUMBER_SUFFIX", "self.NUMBER_TEEN", "self.NUMBER_TEN" ], "methods_info": [ { "method_name": "format", "method_description": "def format(self, x):\n \"\"\"\n Converts a number into words format\n :param x: int or float, the number to be converted into words format\n :return: str, the number in words format\n >>> formatter = NumberWordFormatter()\n >>> formatter.format(123456)\n \"ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY\"\n \"\"\"", "test_class": "NumberWordFormatterTestFormat", "test_code": "class NumberWordFormatterTestFormat(unittest.TestCase):\n def test_format_1(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format(123456),\n \"ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY\")\n\n def test_format_2(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format(1000), \"ONE THOUSAND ONLY\")\n\n def test_format_3(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format(1000000), \"ONE MILLION ONLY\")\n\n def test_format_4(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format(1.23), \"ONE AND CENTS TWENTY THREE ONLY\")\n\n def test_format_5(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format(0), \"ZERO ONLY\")\n\n def test_format_6(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format(None), \"\")", "solution_code": "def format(self, x):\n if x is not None:\n return self.format_string(str(x))\n else:\n return \"\"", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "format_string" ] } }, { "method_name": "format_string", "method_description": "def format_string(self, x):\n \"\"\"\n Converts a string representation of a number into words format\n :param x: str, the string representation of a number\n :return: str, the number in words format\n >>> formatter = NumberWordFormatter()\n >>> formatter.format_string(\"123456\")\n \"ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY\"\n \"\"\"", "test_class": "NumberWordFormatterTestFormatString", "test_code": "class NumberWordFormatterTestFormatString(unittest.TestCase):\n def test_format_string_1(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format_string('123456'),\n \"ONE HUNDRED AND TWENTY THREE THOUSAND FOUR HUNDRED AND FIFTY SIX ONLY\")\n\n def test_format_string_2(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format_string('1000'), \"ONE THOUSAND ONLY\")\n\n def test_format_string_3(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format_string('1000000'), \"ONE MILLION ONLY\")\n\n def test_format_string_4(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format_string('1.23'), \"ONE AND CENTS TWENTY THREE ONLY\")\n\n def test_format_string_5(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format_string('0'), \"ZERO ONLY\")\n\n def test_format_string_6(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.format_string('10'), \"TEN ONLY\")", "solution_code": "def format_string(self, x):\n lstr, rstr = (x.split('.') + [''])[:2]\n lstrrev = lstr[::-1]\n a = [''] * 5\n\n if len(lstrrev) % 3 == 1:\n lstrrev += \"00\"\n elif len(lstrrev) % 3 == 2:\n lstrrev += \"0\"\n\n lm = \"\"\n for i in range(len(lstrrev) // 3):\n a[i] = lstrrev[3 * i:3 * i + 3][::-1]\n if a[i] != \"000\":\n lm = self.trans_three(a[i]) + \" \" + self.parse_more(i) + \" \" + lm\n else:\n lm += self.trans_three(a[i])\n\n xs = f\"AND CENTS {self.trans_two(rstr)} \" if rstr else \"\"\n if not lm.strip():\n return \"ZERO ONLY\"\n else:\n return f\"{lm.strip()} {xs}ONLY\"", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "trans_two", "trans_three", "parse_more" ] } }, { "method_name": "trans_two", "method_description": "def trans_two(self, s):\n \"\"\"\n Converts a two-digit number into words format\n :param s: str, the two-digit number\n :return: str, the number in words format\n >>> formatter = NumberWordFormatter()\n >>> formatter.trans_two(\"23\")\n \"TWENTY THREE\"\n \"\"\"", "test_class": "NumberWordFormatterTestTransTwo", "test_code": "class NumberWordFormatterTestTransTwo(unittest.TestCase):\n def test_trans_two_1(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_two(\"23\"), \"TWENTY THREE\")\n\n def test_trans_two_2(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_two(\"10\"), \"TEN\")\n\n def test_trans_two_3(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_two(\"05\"), \"FIVE\")\n\n def test_trans_two_4(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_two(\"00\"), \"\")\n\n def test_trans_two_5(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_two(\"01\"), \"ONE\")\n\n def test_trans_two_6(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_two(\"80\"), \"EIGHTY\")", "solution_code": "def trans_two(self, s):\n s = s.zfill(2)\n if s[0] == \"0\":\n return self.NUMBER[int(s[-1])]\n elif s[0] == \"1\":\n return self.NUMBER_TEEN[int(s) - 10]\n elif s[1] == \"0\":\n return self.NUMBER_TEN[int(s[0]) - 1]\n else:\n return self.NUMBER_TEN[int(s[0]) - 1] + \" \" + self.NUMBER[int(s[-1])]", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.NUMBER", "self.NUMBER_TEEN", "self.NUMBER_TEN" ], "method_dependencies": [] } }, { "method_name": "trans_three", "method_description": "def trans_three(self, s):\n \"\"\"\n Converts a three-digit number into words format\n :param s: str, the three-digit number\n :return: str, the number in words format\n >>> formatter = NumberWordFormatter()\n >>> formatter.trans_three(\"123\")\n \"ONE HUNDRED AND TWENTY THREE\"\n \"\"\"", "test_class": "NumberWordFormatterTestTransThree", "test_code": "class NumberWordFormatterTestTransThree(unittest.TestCase):\n def test_trans_three_1(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_three(\"123\"), \"ONE HUNDRED AND TWENTY THREE\")\n\n def test_trans_three_2(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_three(\"900\"), \"NINE HUNDRED\")\n\n def test_trans_three_3(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_three(\"007\"), \"SEVEN\")\n\n def test_trans_three_4(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_three(\"001\"), \"ONE\")\n\n def test_trans_three_5(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.trans_three(\"006\"), \"SIX\")", "solution_code": "def trans_three(self, s):\n if s[0] == \"0\":\n return self.trans_two(s[1:])\n elif s[1:] == \"00\":\n return f\"{self.NUMBER[int(s[0])]} HUNDRED\"\n else:\n return f\"{self.NUMBER[int(s[0])]} HUNDRED AND {self.trans_two(s[1:])}\"", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.NUMBER" ], "method_dependencies": [ "trans_two" ] } }, { "method_name": "parse_more", "method_description": "def parse_more(self, i):\n \"\"\"\n Parses the thousand/million/billion suffix based on the index\n :param i: int, the index representing the magnitude (thousand, million, billion)\n :return: str, the corresponding suffix for the magnitude\n >>> formatter = NumberWordFormatter()\n >>> formatter.parse_more(1)\n \"THOUSAND\"\n \"\"\"", "test_class": "NumberWordFormatterTestParseMore", "test_code": "class NumberWordFormatterTestParseMore(unittest.TestCase):\n def test_parse_more_1(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.parse_more(0), \"\")\n\n def test_parse_more_2(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.parse_more(1), \"THOUSAND\")\n\n def test_parse_more_3(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.parse_more(2), \"MILLION\")\n\n def test_parse_more_4(self):\n formatter = NumberWordFormatter()\n self.assertEqual(formatter.parse_more(3), \"BILLION\")", "solution_code": "def parse_more(self, i):\n return self.NUMBER_MORE[i]", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.NUMBER", "self.NUMBER_MORE" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_66", "skeleton": "\nclass NumericEntityUnescaper:\n \"\"\"\n This is a class that provides functionality to replace numeric entities with their corresponding characters in a given string.\n \"\"\"\n\n def __init__(self):\n pass\n\n def replace(self, string):\n \"\"\"\n Replaces numeric character references (HTML entities) in the input string with their corresponding Unicode characters.\n :param string: str, the input string containing numeric character references.\n :return: str, the input string with numeric character references replaced with their corresponding Unicode characters.\n >>> unescaper = NumericEntityUnescaper()\n >>> unescaper.replace(\"ABC\")\n 'ABC'\n\n \"\"\"\n\n\n @staticmethod\n def is_hex_char(char):\n \"\"\"\n Determines whether a given character is a hexadecimal digit.\n :param char: str, the character to check.\n :return: bool, True if the character is a hexadecimal digit, False otherwise.\n >>> NumericEntityUnescaper.is_hex_char('a')\n True\n\n \"\"\"", "test": "import unittest\n\n\nclass NumericEntityUnescaperTestReplace(unittest.TestCase):\n def test_replace_1(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"ABC\")\n self.assertEqual(res, \"ABC\")\n\n def test_replace_2(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"AAA\")\n self.assertEqual(res, \"AAA\")\n\n def test_replace_3(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"BBB\")\n self.assertEqual(res, \"BBB\")\n\n def test_replace_4(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"CCC\")\n self.assertEqual(res, \"CCC\")\n\n def test_replace_5(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"\")\n self.assertEqual(res, \"\")\n\n def test_replace_6(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"&#\")\n self.assertEqual(res, \"\")\n\n def test_replace_7(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"eBC\")\n self.assertEqual(res, \"eBC\")\n\n def test_replace_8(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"&#???;BC\")\n self.assertEqual(res, \"&#???;BC\")\n\n def test_replace_9(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"CCC;\")\n self.assertEqual(res, \"CCC\")\n\n def test_replace_10(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"&#X\")\n self.assertEqual(res, \"\")\n\n def test_replace_11(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"&#c1d;BC\")\n self.assertEqual(res, \"\")\n\n\nclass NumericEntityUnescaperTestIsHexChar(unittest.TestCase):\n def test_is_hex_char_1(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.is_hex_char('0')\n self.assertEqual(res, True)\n\n def test_is_hex_char_2(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.is_hex_char('F')\n self.assertEqual(res, True)\n\n def test_is_hex_char_3(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.is_hex_char('G')\n self.assertEqual(res, False)\n\n def test_is_hex_char_4(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.is_hex_char('X')\n self.assertEqual(res, False)\n\n def test_is_hex_char_5(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.is_hex_char('Z')\n self.assertEqual(res, False)\n\n\nclass unescaperTest(unittest.TestCase):\n def test_numericentityunescaper(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"ABC\")\n self.assertEqual(res, \"ABC\")\n\n unescaper = NumericEntityUnescaper()\n res = unescaper.is_hex_char('0')\n self.assertEqual(res, True)", "solution_code": "class NumericEntityUnescaper:\n def __init__(self):\n pass\n\n def replace(self, string):\n out = []\n pos = 0\n length = len(string)\n\n while pos < length - 2:\n if string[pos] == '&' and string[pos + 1] == '#':\n start = pos + 2\n is_hex = False\n first_char = string[start]\n\n if first_char == 'x' or first_char == 'X':\n start += 1\n is_hex = True\n\n if start == length:\n return ''.join(out)\n\n end = start\n while end < length and self.is_hex_char(string[end]):\n end += 1\n\n if end < length and string[end] == ';':\n try:\n entity_value = int(string[start:end], 16 if is_hex else 10)\n except:\n return ''.join(out)\n\n out.append(chr(entity_value))\n pos = end + 1\n continue\n\n out.append(string[pos])\n pos += 1\n\n return ''.join(out)\n\n @staticmethod\n def is_hex_char(char):\n return char.isdigit() or ('a' <= char.lower() <= 'f')", "import_statement": [], "class_description": " \"\"\"\n This is a class that provides functionality to replace numeric entities with their corresponding characters in a given string.\n \"\"\"\n", "class_name": "NumericEntityUnescaper", "test_classes": [ "NumericEntityUnescaperTestReplace", "NumericEntityUnescaperTestIsHexChar", "unescaperTest" ], "class_constructor": "class NumericEntityUnescaper: \n def __init__(self):\n pass\n\n", "fields": [], "methods_info": [ { "method_name": "replace", "method_description": "def replace(self, string):\n \"\"\"\n Replaces numeric character references (HTML entities) in the input string with their corresponding Unicode characters.\n :param string: str, the input string containing numeric character references.\n :return: str, the input string with numeric character references replaced with their corresponding Unicode characters.\n >>> unescaper = NumericEntityUnescaper()\n >>> unescaper.replace(\"ABC\")\n 'ABC'\n\n \"\"\"", "test_class": "NumericEntityUnescaperTestReplace", "test_code": "class NumericEntityUnescaperTestReplace(unittest.TestCase):\n def test_replace_1(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"ABC\")\n self.assertEqual(res, \"ABC\")\n\n def test_replace_2(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"AAA\")\n self.assertEqual(res, \"AAA\")\n\n def test_replace_3(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"BBB\")\n self.assertEqual(res, \"BBB\")\n\n def test_replace_4(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"CCC\")\n self.assertEqual(res, \"CCC\")\n\n def test_replace_5(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"\")\n self.assertEqual(res, \"\")\n\n def test_replace_6(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"&#\")\n self.assertEqual(res, \"\")\n\n def test_replace_7(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"eBC\")\n self.assertEqual(res, \"eBC\")\n\n def test_replace_8(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"&#???;BC\")\n self.assertEqual(res, \"&#???;BC\")\n\n def test_replace_9(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"CCC;\")\n self.assertEqual(res, \"CCC\")\n\n def test_replace_10(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"&#X\")\n self.assertEqual(res, \"\")\n\n def test_replace_11(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.replace(\"&#c1d;BC\")\n self.assertEqual(res, \"\")", "solution_code": "def replace(self, string):\n out = []\n pos = 0\n length = len(string)\n\n while pos < length - 2:\n if string[pos] == '&' and string[pos + 1] == '#':\n start = pos + 2\n is_hex = False\n first_char = string[start]\n\n if first_char == 'x' or first_char == 'X':\n start += 1\n is_hex = True\n\n if start == length:\n return ''.join(out)\n\n end = start\n while end < length and self.is_hex_char(string[end]):\n end += 1\n\n if end < length and string[end] == ';':\n try:\n entity_value = int(string[start:end], 16 if is_hex else 10)\n except:\n return ''.join(out)\n\n out.append(chr(entity_value))\n pos = end + 1\n continue\n\n out.append(string[pos])\n pos += 1\n\n return ''.join(out)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "is_hex_char" ] } }, { "method_name": "is_hex_char", "method_description": "@staticmethod\n def is_hex_char(char):\n \"\"\"\n Determines whether a given character is a hexadecimal digit.\n :param char: str, the character to check.\n :return: bool, True if the character is a hexadecimal digit, False otherwise.\n >>> NumericEntityUnescaper.is_hex_char('a')\n True\n\n \"\"\"", "test_class": "NumericEntityUnescaperTestIsHexChar", "test_code": "class NumericEntityUnescaperTestIsHexChar(unittest.TestCase):\n def test_is_hex_char_1(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.is_hex_char('0')\n self.assertEqual(res, True)\n\n def test_is_hex_char_2(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.is_hex_char('F')\n self.assertEqual(res, True)\n\n def test_is_hex_char_3(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.is_hex_char('G')\n self.assertEqual(res, False)\n\n def test_is_hex_char_4(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.is_hex_char('X')\n self.assertEqual(res, False)\n\n def test_is_hex_char_5(self):\n unescaper = NumericEntityUnescaper()\n res = unescaper.is_hex_char('Z')\n self.assertEqual(res, False)", "solution_code": "@staticmethod\n def is_hex_char(char):\n return char.isdigit() or ('a' <= char.lower() <= 'f')", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_67", "skeleton": "\nclass Order:\n \"\"\"\n The class manages restaurant orders by allowing the addition of dishes, calculation of the total cost, and checkout.\n \"\"\"\n\n\n def __init__(self):\n \"\"\"\n Initialize the order management system\n self.menu stores the dishes of resturant inventory\n menu = [{\"dish\": dish name, \"price\": price, \"count\": count}, ...]\n self.selected_dishes stores the dished selected by customer\n selected_dish = {\"dish\": dish name, \"count\": count, price: price}\n self.sales stores the sales of each dish\n sales = {dish name: sales}\n \"\"\"\n self.menu = []\n self.selected_dishes = []\n self.sales = {}\n\n\n def add_dish(self, dish):\n \"\"\"\n Check the self.menu and add into self.selected_dish if the dish count is valid.\n And if the dish has successfully been added, change the count in self.menu.\n :param dish: dict, the information of dish. dish = {\"dish\": dish name, \"count\": count, price: price}\n :return: True if successfully added, or False otherwise.\n >>> order = Order()\n >>> order.menu.append({\"dish\": \"dish1\", \"price\": 10, \"count\": 5})\n >>> order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 3})\n True\n \"\"\"\n\n def calculate_total(self):\n \"\"\"\n Calculate the total price of dishes that have been ordered. Multiply the count, price and sales.\n :return total: float, the final total price.\n >>> order = Order()\n >>> order.menu.append({\"dish\": \"dish1\", \"price\": 10, \"count\": 5})\n >>> order.sales = {\"dish1\": 0.8}\n >>> order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 4})\n True\n >>> order.calculate_total()\n 32.0\n \"\"\"\n\n def checkout(self):\n \"\"\"\n Check out the dished ordered. IF the self.selected_dishes is not empty, invoke the calculate_total\n method to check out.\n :return Flase if the self.selected_dishes is empty, or total(return value of calculate_total) otherwise.\n >>> order = Order()\n >>> order.menu.append({\"dish\": \"dish1\", \"price\": 10, \"count\": 5})\n >>> order.sales = {\"dish1\": 0.8}\n >>> order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 4})\n True\n >>> order.checkout()\n 32.0\n \"\"\"", "test": "import unittest\n\n\nclass OrderTestAddDish(unittest.TestCase):\n def setUp(self):\n self.order = Order()\n\n self.order.menu.append({\"dish\": \"dish1\", \"price\": 10, \"count\": 5})\n self.order.menu.append({\"dish\": \"dish2\", \"price\": 15, \"count\": 3})\n self.order.menu.append({\"dish\": \"dish3\", \"price\": 20, \"count\": 7})\n self.order.sales = {\"dish1\": 0.9, \"dish2\": 1, \"dish3\": 0.8}\n\n # add dish in menu\n def test_add_dish_1(self):\n result = self.order.add_dish({\"dish\": \"dish3\", \"price\": 15, \"count\": 4})\n self.assertTrue(result)\n\n # test the status of self.menu and self.selected_dishes\n menu = self.order.menu\n for menu_dish in menu:\n if menu_dish[\"dish\"] == \"dish1\":\n self.assertEqual(menu_dish[\"count\"], 5)\n if menu_dish[\"dish\"] == \"dish2\":\n self.assertEqual(menu_dish[\"count\"], 3)\n if menu_dish[\"dish\"] == \"dish3\":\n self.assertEqual(menu_dish[\"count\"], 3)\n self.assertEqual(self.order.selected_dishes, [{\"dish\": \"dish3\", \"price\": 15, \"count\": 4}])\n\n # add dish when dish count exceeds the remaining count\n def test_add_dish_2(self):\n result = self.order.add_dish({\"dish\": \"dish3\", \"price\": 15, \"count\": 8})\n self.assertFalse(result)\n\n menu = self.order.menu\n for menu_dish in menu:\n if menu_dish[\"dish\"] == \"dish1\":\n self.assertEqual(menu_dish[\"count\"], 5)\n if menu_dish[\"dish\"] == \"dish2\":\n self.assertEqual(menu_dish[\"count\"], 3)\n if menu_dish[\"dish\"] == \"dish3\":\n self.assertEqual(menu_dish[\"count\"], 7)\n self.assertEqual(self.order.selected_dishes, [])\n\n def test_add_dish_3(self):\n result = self.order.add_dish({\"dish\": \"dish3\", \"price\": 15, \"count\": 7})\n self.assertTrue(result)\n\n # test the status of self.menu and self.selected_dishes\n menu = self.order.menu\n for menu_dish in menu:\n if menu_dish[\"dish\"] == \"dish1\":\n self.assertEqual(menu_dish[\"count\"], 5)\n if menu_dish[\"dish\"] == \"dish2\":\n self.assertEqual(menu_dish[\"count\"], 3)\n if menu_dish[\"dish\"] == \"dish3\":\n self.assertEqual(menu_dish[\"count\"], 0)\n self.assertEqual(self.order.selected_dishes, [{\"dish\": \"dish3\", \"price\": 15, \"count\": 7}])\n\n def test_add_dish_4(self):\n result = self.order.add_dish({\"dish\": \"dish3\", \"price\": 15, \"count\": 6})\n self.assertTrue(result)\n\n # test the status of self.menu and self.selected_dishes\n menu = self.order.menu\n for menu_dish in menu:\n if menu_dish[\"dish\"] == \"dish1\":\n self.assertEqual(menu_dish[\"count\"], 5)\n if menu_dish[\"dish\"] == \"dish2\":\n self.assertEqual(menu_dish[\"count\"], 3)\n if menu_dish[\"dish\"] == \"dish3\":\n self.assertEqual(menu_dish[\"count\"], 1)\n self.assertEqual(self.order.selected_dishes, [{\"dish\": \"dish3\", \"price\": 15, \"count\": 6}])\n\n def test_add_dish_5(self):\n result = self.order.add_dish({\"dish\": \"dish3\", \"price\": 15, \"count\": 5})\n self.assertTrue(result)\n\n # test the status of self.menu and self.selected_dishes\n menu = self.order.menu\n for menu_dish in menu:\n if menu_dish[\"dish\"] == \"dish1\":\n self.assertEqual(menu_dish[\"count\"], 5)\n if menu_dish[\"dish\"] == \"dish2\":\n self.assertEqual(menu_dish[\"count\"], 3)\n if menu_dish[\"dish\"] == \"dish3\":\n self.assertEqual(menu_dish[\"count\"], 2)\n self.assertEqual(self.order.selected_dishes, [{\"dish\": \"dish3\", \"price\": 15, \"count\": 5}])\n\n def test_add_dish_6(self):\n self.order.menu = []\n result = self.order.add_dish({})\n self.assertTrue(result)\n\n\nclass OrderTestCalculateTotal(unittest.TestCase):\n def setUp(self):\n self.order = Order()\n self.order.menu.append({\"dish\": \"dish1\", \"price\": 10, \"count\": 5})\n self.order.menu.append({\"dish\": \"dish2\", \"price\": 15, \"count\": 3})\n self.order.menu.append({\"dish\": \"dish3\", \"price\": 20, \"count\": 7})\n self.order.sales = {\"dish1\": 0.9, \"dish2\": 1, \"dish3\": 0.8}\n\n def test_calculate_total_1(self):\n self.order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 2})\n self.order.add_dish({\"dish\": \"dish3\", \"price\": 20, \"count\": 2})\n result = self.order.calculate_total()\n self.assertEqual(50, result)\n\n def test_calculate_total_2(self):\n self.order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 2})\n self.order.add_dish({\"dish\": \"dish2\", \"price\": 15, \"count\": 2})\n result = self.order.calculate_total()\n self.assertEqual(48, result)\n\n def test_calculate_total_3(self):\n self.order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 1})\n self.order.add_dish({\"dish\": \"dish3\", \"price\": 20, \"count\": 1})\n result = self.order.calculate_total()\n self.assertEqual(25, result)\n\n def test_calculate_total_4(self):\n self.order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 3})\n self.order.add_dish({\"dish\": \"dish3\", \"price\": 20, \"count\": 3})\n result = self.order.calculate_total()\n self.assertEqual(75, result)\n\n def test_calculate_total_5(self):\n self.order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 4})\n self.order.add_dish({\"dish\": \"dish3\", \"price\": 20, \"count\": 4})\n result = self.order.calculate_total()\n self.assertEqual(100, result)\n\n\nclass OrderTestCheckout(unittest.TestCase):\n def setUp(self):\n self.order = Order()\n self.order.menu.append({\"dish\": \"dish1\", \"price\": 10, \"count\": 5})\n self.order.menu.append({\"dish\": \"dish2\", \"price\": 15, \"count\": 3})\n self.order.menu.append({\"dish\": \"dish3\", \"price\": 20, \"count\": 7})\n self.order.sales = {\"dish1\": 0.9, \"dish2\": 1, \"dish3\": 0.8}\n\n # as test_main\n def test_checkout_1(self):\n self.order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 2})\n self.order.add_dish({\"dish\": \"dish3\", \"price\": 20, \"count\": 2})\n result = self.order.checkout()\n self.assertEqual(50, result)\n\n menu = self.order.menu\n for menu_dish in menu:\n if menu_dish[\"dish\"] == \"dish1\":\n self.assertEqual(menu_dish[\"count\"], 3)\n if menu_dish[\"dish\"] == \"dish2\":\n self.assertEqual(menu_dish[\"count\"], 3)\n if menu_dish[\"dish\"] == \"dish3\":\n self.assertEqual(menu_dish[\"count\"], 5)\n self.assertEqual([], self.order.selected_dishes)\n\n # haven't ordered dishes.\n # self.selected_dishes is empty\n def test_checkout_2(self):\n result = self.order.checkout()\n self.assertFalse(result)\n\n def test_checkout_3(self):\n self.order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 1})\n self.order.add_dish({\"dish\": \"dish3\", \"price\": 20, \"count\": 1})\n result = self.order.checkout()\n self.assertEqual(25, result)\n\n menu = self.order.menu\n for menu_dish in menu:\n if menu_dish[\"dish\"] == \"dish1\":\n self.assertEqual(menu_dish[\"count\"], 4)\n if menu_dish[\"dish\"] == \"dish2\":\n self.assertEqual(menu_dish[\"count\"], 3)\n if menu_dish[\"dish\"] == \"dish3\":\n self.assertEqual(menu_dish[\"count\"], 6)\n self.assertEqual([], self.order.selected_dishes)\n\n def test_checkout_4(self):\n self.order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 3})\n self.order.add_dish({\"dish\": \"dish3\", \"price\": 20, \"count\": 3})\n result = self.order.checkout()\n self.assertEqual(75, result)\n\n menu = self.order.menu\n for menu_dish in menu:\n if menu_dish[\"dish\"] == \"dish1\":\n self.assertEqual(menu_dish[\"count\"], 2)\n if menu_dish[\"dish\"] == \"dish2\":\n self.assertEqual(menu_dish[\"count\"], 3)\n if menu_dish[\"dish\"] == \"dish3\":\n self.assertEqual(menu_dish[\"count\"], 4)\n self.assertEqual([], self.order.selected_dishes)\n\n def test_checkout_5(self):\n self.order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 5})\n self.order.add_dish({\"dish\": \"dish3\", \"price\": 20, \"count\": 5})\n result = self.order.checkout()\n self.assertEqual(125, result)\n\n menu = self.order.menu\n for menu_dish in menu:\n if menu_dish[\"dish\"] == \"dish1\":\n self.assertEqual(menu_dish[\"count\"], 0)\n if menu_dish[\"dish\"] == \"dish2\":\n self.assertEqual(menu_dish[\"count\"], 3)\n if menu_dish[\"dish\"] == \"dish3\":\n self.assertEqual(menu_dish[\"count\"], 2)\n self.assertEqual([], self.order.selected_dishes)\n\n\nclass OrderTest(unittest.TestCase):\n def setUp(self):\n self.order = Order()\n\n self.order.menu.append({\"dish\": \"dish1\", \"price\": 10, \"count\": 5})\n self.order.menu.append({\"dish\": \"dish2\", \"price\": 15, \"count\": 3})\n self.order.menu.append({\"dish\": \"dish3\", \"price\": 20, \"count\": 7})\n self.order.sales = {\"dish1\": 0.9, \"dish2\": 1, \"dish3\": 0.8}\n\n def test_order(self):\n self.order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 2})\n self.order.add_dish({\"dish\": \"dish3\", \"price\": 20, \"count\": 2})\n result = self.order.checkout()\n self.assertEqual(50, result)\n\n menu = self.order.menu\n for menu_dish in menu:\n if menu_dish[\"dish\"] == \"dish1\":\n self.assertEqual(menu_dish[\"count\"], 3)\n if menu_dish[\"dish\"] == \"dish2\":\n self.assertEqual(menu_dish[\"count\"], 3)\n if menu_dish[\"dish\"] == \"dish3\":\n self.assertEqual(menu_dish[\"count\"], 5)\n self.assertEqual([], self.order.selected_dishes)", "solution_code": "class Order:\n\n def __init__(self):\n self.menu = []\n # menu = [{\"dish\": dish name, \"price\": price, \"count\": count}, ...]\n self.selected_dishes = []\n # selected_dish = {\"dish\": dish name, \"count\": count, price: price}\n self.sales = {}\n # \n\n\n def add_dish(self, dish):\n for menu_dish in self.menu:\n if dish[\"dish\"] == menu_dish[\"dish\"]:\n if menu_dish[\"count\"] < dish[\"count\"]:\n return False\n else:\n menu_dish[\"count\"] -= dish[\"count\"]\n break\n self.selected_dishes.append(dish)\n return True\n\n def calculate_total(self):\n total = 0\n for dish in self.selected_dishes:\n total += dish[\"price\"] * dish[\"count\"] * self.sales[dish[\"dish\"]]\n return total\n\n def checkout(self):\n if len(self.selected_dishes) == 0:\n return False\n total = self.calculate_total()\n self.selected_dishes = []\n return total", "import_statement": [], "class_description": " \"\"\"\n The class manages restaurant orders by allowing the addition of dishes, calculation of the total cost, and checkout.\n \"\"\"\n", "class_name": "Order", "test_classes": [ "OrderTestAddDish", "OrderTestCalculateTotal", "OrderTestCheckout", "OrderTest" ], "class_constructor": "class Order: \n def __init__(self):\n \"\"\"\n Initialize the order management system\n self.menu stores the dishes of resturant inventory\n menu = [{\"dish\": dish name, \"price\": price, \"count\": count}, ...]\n self.selected_dishes stores the dished selected by customer\n selected_dish = {\"dish\": dish name, \"count\": count, price: price}\n self.sales stores the sales of each dish\n sales = {dish name: sales}\n \"\"\"\n self.menu = []\n self.selected_dishes = []\n self.sales = {}\n\n\n", "fields": [ "self.menu", "self.sales", "self.selected_dishes" ], "methods_info": [ { "method_name": "add_dish", "method_description": "def add_dish(self, dish):\n \"\"\"\n Check the self.menu and add into self.selected_dish if the dish count is valid.\n And if the dish has successfully been added, change the count in self.menu.\n :param dish: dict, the information of dish. dish = {\"dish\": dish name, \"count\": count, price: price}\n :return: True if successfully added, or False otherwise.\n >>> order = Order()\n >>> order.menu.append({\"dish\": \"dish1\", \"price\": 10, \"count\": 5})\n >>> order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 3})\n True\n \"\"\"", "test_class": "OrderTestAddDish", "test_code": "class OrderTestAddDish(unittest.TestCase):\n def setUp(self):\n self.order = Order()\n\n self.order.menu.append({\"dish\": \"dish1\", \"price\": 10, \"count\": 5})\n self.order.menu.append({\"dish\": \"dish2\", \"price\": 15, \"count\": 3})\n self.order.menu.append({\"dish\": \"dish3\", \"price\": 20, \"count\": 7})\n self.order.sales = {\"dish1\": 0.9, \"dish2\": 1, \"dish3\": 0.8}\n\n # add dish in menu\n def test_add_dish_1(self):\n result = self.order.add_dish({\"dish\": \"dish3\", \"price\": 15, \"count\": 4})\n self.assertTrue(result)\n\n # test the status of self.menu and self.selected_dishes\n menu = self.order.menu\n for menu_dish in menu:\n if menu_dish[\"dish\"] == \"dish1\":\n self.assertEqual(menu_dish[\"count\"], 5)\n if menu_dish[\"dish\"] == \"dish2\":\n self.assertEqual(menu_dish[\"count\"], 3)\n if menu_dish[\"dish\"] == \"dish3\":\n self.assertEqual(menu_dish[\"count\"], 3)\n self.assertEqual(self.order.selected_dishes, [{\"dish\": \"dish3\", \"price\": 15, \"count\": 4}])\n\n # add dish when dish count exceeds the remaining count\n def test_add_dish_2(self):\n result = self.order.add_dish({\"dish\": \"dish3\", \"price\": 15, \"count\": 8})\n self.assertFalse(result)\n\n menu = self.order.menu\n for menu_dish in menu:\n if menu_dish[\"dish\"] == \"dish1\":\n self.assertEqual(menu_dish[\"count\"], 5)\n if menu_dish[\"dish\"] == \"dish2\":\n self.assertEqual(menu_dish[\"count\"], 3)\n if menu_dish[\"dish\"] == \"dish3\":\n self.assertEqual(menu_dish[\"count\"], 7)\n self.assertEqual(self.order.selected_dishes, [])\n\n def test_add_dish_3(self):\n result = self.order.add_dish({\"dish\": \"dish3\", \"price\": 15, \"count\": 7})\n self.assertTrue(result)\n\n # test the status of self.menu and self.selected_dishes\n menu = self.order.menu\n for menu_dish in menu:\n if menu_dish[\"dish\"] == \"dish1\":\n self.assertEqual(menu_dish[\"count\"], 5)\n if menu_dish[\"dish\"] == \"dish2\":\n self.assertEqual(menu_dish[\"count\"], 3)\n if menu_dish[\"dish\"] == \"dish3\":\n self.assertEqual(menu_dish[\"count\"], 0)\n self.assertEqual(self.order.selected_dishes, [{\"dish\": \"dish3\", \"price\": 15, \"count\": 7}])\n\n def test_add_dish_4(self):\n result = self.order.add_dish({\"dish\": \"dish3\", \"price\": 15, \"count\": 6})\n self.assertTrue(result)\n\n # test the status of self.menu and self.selected_dishes\n menu = self.order.menu\n for menu_dish in menu:\n if menu_dish[\"dish\"] == \"dish1\":\n self.assertEqual(menu_dish[\"count\"], 5)\n if menu_dish[\"dish\"] == \"dish2\":\n self.assertEqual(menu_dish[\"count\"], 3)\n if menu_dish[\"dish\"] == \"dish3\":\n self.assertEqual(menu_dish[\"count\"], 1)\n self.assertEqual(self.order.selected_dishes, [{\"dish\": \"dish3\", \"price\": 15, \"count\": 6}])\n\n def test_add_dish_5(self):\n result = self.order.add_dish({\"dish\": \"dish3\", \"price\": 15, \"count\": 5})\n self.assertTrue(result)\n\n # test the status of self.menu and self.selected_dishes\n menu = self.order.menu\n for menu_dish in menu:\n if menu_dish[\"dish\"] == \"dish1\":\n self.assertEqual(menu_dish[\"count\"], 5)\n if menu_dish[\"dish\"] == \"dish2\":\n self.assertEqual(menu_dish[\"count\"], 3)\n if menu_dish[\"dish\"] == \"dish3\":\n self.assertEqual(menu_dish[\"count\"], 2)\n self.assertEqual(self.order.selected_dishes, [{\"dish\": \"dish3\", \"price\": 15, \"count\": 5}])\n\n def test_add_dish_6(self):\n self.order.menu = []\n result = self.order.add_dish({})\n self.assertTrue(result)", "solution_code": "def add_dish(self, dish):\n for menu_dish in self.menu:\n if dish[\"dish\"] == menu_dish[\"dish\"]:\n if menu_dish[\"count\"] < dish[\"count\"]:\n return False\n else:\n menu_dish[\"count\"] -= dish[\"count\"]\n break\n self.selected_dishes.append(dish)\n return True", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.menu", "self.selected_dishes" ], "method_dependencies": [] } }, { "method_name": "calculate_total", "method_description": "def calculate_total(self):\n \"\"\"\n Calculate the total price of dishes that have been ordered. Multiply the count, price and sales.\n :return total: float, the final total price.\n >>> order = Order()\n >>> order.menu.append({\"dish\": \"dish1\", \"price\": 10, \"count\": 5})\n >>> order.sales = {\"dish1\": 0.8}\n >>> order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 4})\n True\n >>> order.calculate_total()\n 32.0\n \"\"\"", "test_class": "OrderTestCalculateTotal", "test_code": "class OrderTestCalculateTotal(unittest.TestCase):\n def setUp(self):\n self.order = Order()\n self.order.menu.append({\"dish\": \"dish1\", \"price\": 10, \"count\": 5})\n self.order.menu.append({\"dish\": \"dish2\", \"price\": 15, \"count\": 3})\n self.order.menu.append({\"dish\": \"dish3\", \"price\": 20, \"count\": 7})\n self.order.sales = {\"dish1\": 0.9, \"dish2\": 1, \"dish3\": 0.8}\n\n def test_calculate_total_1(self):\n self.order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 2})\n self.order.add_dish({\"dish\": \"dish3\", \"price\": 20, \"count\": 2})\n result = self.order.calculate_total()\n self.assertEqual(50, result)\n\n def test_calculate_total_2(self):\n self.order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 2})\n self.order.add_dish({\"dish\": \"dish2\", \"price\": 15, \"count\": 2})\n result = self.order.calculate_total()\n self.assertEqual(48, result)\n\n def test_calculate_total_3(self):\n self.order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 1})\n self.order.add_dish({\"dish\": \"dish3\", \"price\": 20, \"count\": 1})\n result = self.order.calculate_total()\n self.assertEqual(25, result)\n\n def test_calculate_total_4(self):\n self.order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 3})\n self.order.add_dish({\"dish\": \"dish3\", \"price\": 20, \"count\": 3})\n result = self.order.calculate_total()\n self.assertEqual(75, result)\n\n def test_calculate_total_5(self):\n self.order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 4})\n self.order.add_dish({\"dish\": \"dish3\", \"price\": 20, \"count\": 4})\n result = self.order.calculate_total()\n self.assertEqual(100, result)", "solution_code": "def calculate_total(self):\n total = 0\n for dish in self.selected_dishes:\n total += dish[\"price\"] * dish[\"count\"] * self.sales[dish[\"dish\"]]\n return total", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.sales", "self.selected_dishes" ], "method_dependencies": [] } }, { "method_name": "checkout", "method_description": "def checkout(self):\n \"\"\"\n Check out the dished ordered. IF the self.selected_dishes is not empty, invoke the calculate_total\n method to check out.\n :return Flase if the self.selected_dishes is empty, or total(return value of calculate_total) otherwise.\n >>> order = Order()\n >>> order.menu.append({\"dish\": \"dish1\", \"price\": 10, \"count\": 5})\n >>> order.sales = {\"dish1\": 0.8}\n >>> order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 4})\n True\n >>> order.checkout()\n 32.0\n \"\"\"", "test_class": "OrderTestCheckout", "test_code": "class OrderTestCheckout(unittest.TestCase):\n def setUp(self):\n self.order = Order()\n self.order.menu.append({\"dish\": \"dish1\", \"price\": 10, \"count\": 5})\n self.order.menu.append({\"dish\": \"dish2\", \"price\": 15, \"count\": 3})\n self.order.menu.append({\"dish\": \"dish3\", \"price\": 20, \"count\": 7})\n self.order.sales = {\"dish1\": 0.9, \"dish2\": 1, \"dish3\": 0.8}\n\n # as test_main\n def test_checkout_1(self):\n self.order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 2})\n self.order.add_dish({\"dish\": \"dish3\", \"price\": 20, \"count\": 2})\n result = self.order.checkout()\n self.assertEqual(50, result)\n\n menu = self.order.menu\n for menu_dish in menu:\n if menu_dish[\"dish\"] == \"dish1\":\n self.assertEqual(menu_dish[\"count\"], 3)\n if menu_dish[\"dish\"] == \"dish2\":\n self.assertEqual(menu_dish[\"count\"], 3)\n if menu_dish[\"dish\"] == \"dish3\":\n self.assertEqual(menu_dish[\"count\"], 5)\n self.assertEqual([], self.order.selected_dishes)\n\n # haven't ordered dishes.\n # self.selected_dishes is empty\n def test_checkout_2(self):\n result = self.order.checkout()\n self.assertFalse(result)\n\n def test_checkout_3(self):\n self.order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 1})\n self.order.add_dish({\"dish\": \"dish3\", \"price\": 20, \"count\": 1})\n result = self.order.checkout()\n self.assertEqual(25, result)\n\n menu = self.order.menu\n for menu_dish in menu:\n if menu_dish[\"dish\"] == \"dish1\":\n self.assertEqual(menu_dish[\"count\"], 4)\n if menu_dish[\"dish\"] == \"dish2\":\n self.assertEqual(menu_dish[\"count\"], 3)\n if menu_dish[\"dish\"] == \"dish3\":\n self.assertEqual(menu_dish[\"count\"], 6)\n self.assertEqual([], self.order.selected_dishes)\n\n def test_checkout_4(self):\n self.order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 3})\n self.order.add_dish({\"dish\": \"dish3\", \"price\": 20, \"count\": 3})\n result = self.order.checkout()\n self.assertEqual(75, result)\n\n menu = self.order.menu\n for menu_dish in menu:\n if menu_dish[\"dish\"] == \"dish1\":\n self.assertEqual(menu_dish[\"count\"], 2)\n if menu_dish[\"dish\"] == \"dish2\":\n self.assertEqual(menu_dish[\"count\"], 3)\n if menu_dish[\"dish\"] == \"dish3\":\n self.assertEqual(menu_dish[\"count\"], 4)\n self.assertEqual([], self.order.selected_dishes)\n\n def test_checkout_5(self):\n self.order.add_dish({\"dish\": \"dish1\", \"price\": 10, \"count\": 5})\n self.order.add_dish({\"dish\": \"dish3\", \"price\": 20, \"count\": 5})\n result = self.order.checkout()\n self.assertEqual(125, result)\n\n menu = self.order.menu\n for menu_dish in menu:\n if menu_dish[\"dish\"] == \"dish1\":\n self.assertEqual(menu_dish[\"count\"], 0)\n if menu_dish[\"dish\"] == \"dish2\":\n self.assertEqual(menu_dish[\"count\"], 3)\n if menu_dish[\"dish\"] == \"dish3\":\n self.assertEqual(menu_dish[\"count\"], 2)\n self.assertEqual([], self.order.selected_dishes)", "solution_code": "def checkout(self):\n if len(self.selected_dishes) == 0:\n return False\n total = self.calculate_total()\n self.selected_dishes = []\n return total", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.selected_dishes" ], "method_dependencies": [ "calculate_total" ] } } ] }, { "task_id": "ClassEval_68", "skeleton": "\nclass PageUtil:\n \"\"\"\n PageUtil class is a versatile utility for handling pagination and search functionalities in an efficient and convenient manner.\n \"\"\"\n\n def __init__(self, data, page_size):\n \"\"\"\n Initialize the PageUtil object with the given data and page size.\n :param data: list, the data to be paginated\n :param page_size: int, the number of items per page\n \"\"\"\n self.data = data\n self.page_size = page_size\n self.total_items = len(data)\n self.total_pages = (self.total_items + page_size - 1) // page_size\n\n def get_page(self, page_number):\n \"\"\"\n Retrieve a specific page of data.\n :param page_number: int, the page number to fetch\n :return: list, the data on the specified page\n >>> page_util = PageUtil([1, 2, 3, 4], 1)\n >>> page_util.get_page(1)\n [1]\n\n \"\"\"\n\n\n def get_page_info(self, page_number):\n \"\"\"\n Retrieve information about a specific page.\n :param page_number: int, the page number to fetch information about\n :return: dict, containing page information such as current page number, total pages, etc.\n >>> page_util = PageUtil([1, 2, 3, 4], 1)\n >>> page_util.get_page_info(1)\n >>> {\n >>> \"current_page\": 1,\n >>> \"per_page\": 1,\n >>> \"total_pages\": 4,\n >>> \"total_items\": 4,\n >>> \"has_previous\": False,\n >>> \"has_next\": True,\n >>> \"data\": [1]\n >>> }\n\n \"\"\"\n\n\n def search(self, keyword):\n \"\"\"\n Search for items in the data that contain the given keyword.\n :param keyword: str, the keyword to search for\n :return: dict, containing search information such as total results and matching items\n >>> page_util = PageUtil([1, 2, 3, 4], 1)\n >>> page_util.search(\"1\")\n >>> search_info = {\n >>> \"keyword\": \"1\",\n >>> \"total_results\": 1,\n >>> \"total_pages\": 1,\n >>> \"results\": [1]\n >>> }\n \"\"\"", "test": "import unittest\n\n\nclass PageUtilTestGetPage(unittest.TestCase):\n def setUp(self):\n self.data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n self.page_size = 3\n self.page_util = PageUtil(self.data, self.page_size)\n\n def test_get_page_1(self):\n page_number = 1\n expected_page = [1, 2, 3]\n actual_page = self.page_util.get_page(page_number)\n self.assertEqual(actual_page, expected_page)\n\n def test_get_page_2(self):\n page_number = 2\n expected_page = [4, 5, 6]\n actual_page = self.page_util.get_page(page_number)\n self.assertEqual(actual_page, expected_page)\n\n def test_get_page_3(self):\n page_number = 3\n expected_page = [7, 8, 9]\n actual_page = self.page_util.get_page(page_number)\n self.assertEqual(actual_page, expected_page)\n\n def test_get_page_4(self):\n page_number = 4\n expected_page = [10]\n actual_page = self.page_util.get_page(page_number)\n self.assertEqual(actual_page, expected_page)\n\n def test_get_page_5(self):\n invalid_page_number = 0\n empty_page = []\n actual_page = self.page_util.get_page(invalid_page_number)\n self.assertEqual(actual_page, empty_page)\n\n\nclass PageUtilTestGetPageInfo(unittest.TestCase):\n def setUp(self):\n self.data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n self.page_size = 3\n self.page_util = PageUtil(self.data, self.page_size)\n\n def test_get_page_info_1(self):\n page_number = 2\n expected_info = {\n \"current_page\": 2,\n \"per_page\": 3,\n \"total_pages\": 4,\n \"total_items\": 10,\n \"has_previous\": True,\n \"has_next\": True,\n \"data\": [4, 5, 6]\n }\n actual_info = self.page_util.get_page_info(page_number)\n self.assertEqual(actual_info, expected_info)\n\n def test_get_page_info_2(self):\n page_number = 1\n expected_info = {\n \"current_page\": 1,\n \"per_page\": 3,\n \"total_pages\": 4,\n \"total_items\": 10,\n \"has_previous\": False,\n \"has_next\": True,\n \"data\": [1, 2, 3]\n }\n actual_info = self.page_util.get_page_info(page_number)\n self.assertEqual(actual_info, expected_info)\n\n def test_get_page_info_3(self):\n page_number = 3\n expected_info = {\n \"current_page\": 3,\n \"per_page\": 3,\n \"total_pages\": 4,\n \"total_items\": 10,\n \"has_previous\": True,\n \"has_next\": True,\n \"data\": [7, 8, 9]\n }\n actual_info = self.page_util.get_page_info(page_number)\n self.assertEqual(actual_info, expected_info)\n\n def test_get_page_info_4(self):\n page_number = 4\n expected_info = {\n \"current_page\": 4,\n \"per_page\": 3,\n \"total_pages\": 4,\n \"total_items\": 10,\n \"has_previous\": True,\n \"has_next\": False,\n \"data\": [10]\n }\n actual_info = self.page_util.get_page_info(page_number)\n self.assertEqual(actual_info, expected_info)\n\n def test_get_page_info_5(self):\n invalid_page_number = 5\n empty_info = {}\n actual_info = self.page_util.get_page_info(invalid_page_number)\n self.assertEqual(actual_info, empty_info)\n\n\nclass PageUtilTestSearch(unittest.TestCase):\n def setUp(self):\n self.data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n self.page_size = 3\n self.page_util = PageUtil(self.data, self.page_size)\n\n def test_search_1(self):\n keyword = \"1\"\n expected_results = {\n \"keyword\": \"1\",\n \"total_results\": 2,\n \"total_pages\": 1,\n \"results\": [1, 10]\n }\n actual_results = self.page_util.search(keyword)\n self.assertEqual(actual_results, expected_results)\n\n def test_search_2(self):\n keyword = \"2\"\n expected_results = {\n \"keyword\": \"2\",\n \"total_results\": 1,\n \"total_pages\": 1,\n \"results\": [2]\n }\n actual_results = self.page_util.search(keyword)\n self.assertEqual(actual_results, expected_results)\n\n def test_search_3(self):\n keyword = \"3\"\n expected_results = {\n \"keyword\": \"3\",\n \"total_results\": 1,\n \"total_pages\": 1,\n \"results\": [3]\n }\n actual_results = self.page_util.search(keyword)\n self.assertEqual(actual_results, expected_results)\n\n def test_search_4(self):\n keyword = \"4\"\n expected_results = {\n \"keyword\": \"4\",\n \"total_results\": 1,\n \"total_pages\": 1,\n \"results\": [4]\n }\n actual_results = self.page_util.search(keyword)\n self.assertEqual(actual_results, expected_results)\n\n def test_search_5(self):\n keyword = \"11\"\n expected_results = {\n \"keyword\": \"11\",\n \"total_results\": 0,\n \"total_pages\": 0,\n \"results\": []\n }\n actual_results = self.page_util.search(keyword)\n self.assertEqual(actual_results, expected_results)\n\n\nclass PageUtilTest(unittest.TestCase):\n def setUp(self):\n self.data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n self.page_size = 3\n self.page_util = PageUtil(self.data, self.page_size)\n\n def test_pageutil(self):\n page_number = 1\n expected_page = [1, 2, 3]\n actual_page = self.page_util.get_page(page_number)\n self.assertEqual(actual_page, expected_page)\n\n page_number = 2\n expected_info = {\n \"current_page\": 2,\n \"per_page\": 3,\n \"total_pages\": 4,\n \"total_items\": 10,\n \"has_previous\": True,\n \"has_next\": True,\n \"data\": [4, 5, 6]\n }\n actual_info = self.page_util.get_page_info(page_number)\n self.assertEqual(actual_info, expected_info)\n\n keyword = \"4\"\n expected_results = {\n \"keyword\": \"4\",\n \"total_results\": 1,\n \"total_pages\": 1,\n \"results\": [4]\n }\n actual_results = self.page_util.search(keyword)\n self.assertEqual(actual_results, expected_results)", "solution_code": "class PageUtil:\n def __init__(self, data, page_size):\n self.data = data\n self.page_size = page_size\n self.total_items = len(data)\n self.total_pages = (self.total_items + page_size - 1) // page_size\n\n def get_page(self, page_number):\n if page_number < 1 or page_number > self.total_pages:\n return []\n\n start_index = (page_number - 1) * self.page_size\n end_index = start_index + self.page_size\n return self.data[start_index:end_index]\n\n def get_page_info(self, page_number):\n if page_number < 1 or page_number > self.total_pages:\n return {}\n\n start_index = (page_number - 1) * self.page_size\n end_index = min(start_index + self.page_size, self.total_items)\n page_data = self.data[start_index:end_index]\n\n page_info = {\n \"current_page\": page_number,\n \"per_page\": self.page_size,\n \"total_pages\": self.total_pages,\n \"total_items\": self.total_items,\n \"has_previous\": page_number > 1,\n \"has_next\": page_number < self.total_pages,\n \"data\": page_data\n }\n return page_info\n\n def search(self, keyword):\n results = [item for item in self.data if keyword in str(item)]\n num_results = len(results)\n num_pages = (num_results + self.page_size - 1) // self.page_size\n\n search_info = {\n \"keyword\": keyword,\n \"total_results\": num_results,\n \"total_pages\": num_pages,\n \"results\": results\n }\n return search_info", "import_statement": [], "class_description": " \"\"\"\n PageUtil class is a versatile utility for handling pagination and search functionalities in an efficient and convenient manner.\n \"\"\"\n", "class_name": "PageUtil", "test_classes": [ "PageUtilTestGetPage", "PageUtilTestGetPageInfo", "PageUtilTestSearch", "PageUtilTest" ], "class_constructor": "class PageUtil: \n def __init__(self, data, page_size):\n \"\"\"\n Initialize the PageUtil object with the given data and page size.\n :param data: list, the data to be paginated\n :param page_size: int, the number of items per page\n \"\"\"\n self.data = data\n self.page_size = page_size\n self.total_items = len(data)\n self.total_pages = (self.total_items + page_size - 1) // page_size\n\n", "fields": [ "self.data", "self.page_size", "self.total_items", "self.total_pages" ], "methods_info": [ { "method_name": "get_page", "method_description": "def get_page(self, page_number):\n \"\"\"\n Retrieve a specific page of data.\n :param page_number: int, the page number to fetch\n :return: list, the data on the specified page\n >>> page_util = PageUtil([1, 2, 3, 4], 1)\n >>> page_util.get_page(1)\n [1]\n\n \"\"\"", "test_class": "PageUtilTestGetPage", "test_code": "class PageUtilTestGetPage(unittest.TestCase):\n def setUp(self):\n self.data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n self.page_size = 3\n self.page_util = PageUtil(self.data, self.page_size)\n\n def test_get_page_1(self):\n page_number = 1\n expected_page = [1, 2, 3]\n actual_page = self.page_util.get_page(page_number)\n self.assertEqual(actual_page, expected_page)\n\n def test_get_page_2(self):\n page_number = 2\n expected_page = [4, 5, 6]\n actual_page = self.page_util.get_page(page_number)\n self.assertEqual(actual_page, expected_page)\n\n def test_get_page_3(self):\n page_number = 3\n expected_page = [7, 8, 9]\n actual_page = self.page_util.get_page(page_number)\n self.assertEqual(actual_page, expected_page)\n\n def test_get_page_4(self):\n page_number = 4\n expected_page = [10]\n actual_page = self.page_util.get_page(page_number)\n self.assertEqual(actual_page, expected_page)\n\n def test_get_page_5(self):\n invalid_page_number = 0\n empty_page = []\n actual_page = self.page_util.get_page(invalid_page_number)\n self.assertEqual(actual_page, empty_page)", "solution_code": "def get_page(self, page_number):\n if page_number < 1 or page_number > self.total_pages:\n return []\n\n start_index = (page_number - 1) * self.page_size\n end_index = start_index + self.page_size\n return self.data[start_index:end_index]", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.data", "self.page_size", "self.total_pages" ], "method_dependencies": [] } }, { "method_name": "get_page_info", "method_description": "def get_page_info(self, page_number):\n \"\"\"\n Retrieve information about a specific page.\n :param page_number: int, the page number to fetch information about\n :return: dict, containing page information such as current page number, total pages, etc.\n >>> page_util = PageUtil([1, 2, 3, 4], 1)\n >>> page_util.get_page_info(1)\n >>> {\n >>> \"current_page\": 1,\n >>> \"per_page\": 1,\n >>> \"total_pages\": 4,\n >>> \"total_items\": 4,\n >>> \"has_previous\": False,\n >>> \"has_next\": True,\n >>> \"data\": [1]\n >>> }\n\n \"\"\"", "test_class": "PageUtilTestGetPageInfo", "test_code": "class PageUtilTestGetPageInfo(unittest.TestCase):\n def setUp(self):\n self.data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n self.page_size = 3\n self.page_util = PageUtil(self.data, self.page_size)\n\n def test_get_page_info_1(self):\n page_number = 2\n expected_info = {\n \"current_page\": 2,\n \"per_page\": 3,\n \"total_pages\": 4,\n \"total_items\": 10,\n \"has_previous\": True,\n \"has_next\": True,\n \"data\": [4, 5, 6]\n }\n actual_info = self.page_util.get_page_info(page_number)\n self.assertEqual(actual_info, expected_info)\n\n def test_get_page_info_2(self):\n page_number = 1\n expected_info = {\n \"current_page\": 1,\n \"per_page\": 3,\n \"total_pages\": 4,\n \"total_items\": 10,\n \"has_previous\": False,\n \"has_next\": True,\n \"data\": [1, 2, 3]\n }\n actual_info = self.page_util.get_page_info(page_number)\n self.assertEqual(actual_info, expected_info)\n\n def test_get_page_info_3(self):\n page_number = 3\n expected_info = {\n \"current_page\": 3,\n \"per_page\": 3,\n \"total_pages\": 4,\n \"total_items\": 10,\n \"has_previous\": True,\n \"has_next\": True,\n \"data\": [7, 8, 9]\n }\n actual_info = self.page_util.get_page_info(page_number)\n self.assertEqual(actual_info, expected_info)\n\n def test_get_page_info_4(self):\n page_number = 4\n expected_info = {\n \"current_page\": 4,\n \"per_page\": 3,\n \"total_pages\": 4,\n \"total_items\": 10,\n \"has_previous\": True,\n \"has_next\": False,\n \"data\": [10]\n }\n actual_info = self.page_util.get_page_info(page_number)\n self.assertEqual(actual_info, expected_info)\n\n def test_get_page_info_5(self):\n invalid_page_number = 5\n empty_info = {}\n actual_info = self.page_util.get_page_info(invalid_page_number)\n self.assertEqual(actual_info, empty_info)", "solution_code": "def get_page_info(self, page_number):\n if page_number < 1 or page_number > self.total_pages:\n return {}\n\n start_index = (page_number - 1) * self.page_size\n end_index = min(start_index + self.page_size, self.total_items)\n page_data = self.data[start_index:end_index]\n\n page_info = {\n \"current_page\": page_number,\n \"per_page\": self.page_size,\n \"total_pages\": self.total_pages,\n \"total_items\": self.total_items,\n \"has_previous\": page_number > 1,\n \"has_next\": page_number < self.total_pages,\n \"data\": page_data\n }\n return page_info", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.data", "self.page_size", "self.total_items", "self.total_pages" ], "method_dependencies": [] } }, { "method_name": "search", "method_description": "def search(self, keyword):\n \"\"\"\n Search for items in the data that contain the given keyword.\n :param keyword: str, the keyword to search for\n :return: dict, containing search information such as total results and matching items\n >>> page_util = PageUtil([1, 2, 3, 4], 1)\n >>> page_util.search(\"1\")\n >>> search_info = {\n >>> \"keyword\": \"1\",\n >>> \"total_results\": 1,\n >>> \"total_pages\": 1,\n >>> \"results\": [1]\n >>> }\n \"\"\"", "test_class": "PageUtilTestSearch", "test_code": "class PageUtilTestSearch(unittest.TestCase):\n def setUp(self):\n self.data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n self.page_size = 3\n self.page_util = PageUtil(self.data, self.page_size)\n\n def test_search_1(self):\n keyword = \"1\"\n expected_results = {\n \"keyword\": \"1\",\n \"total_results\": 2,\n \"total_pages\": 1,\n \"results\": [1, 10]\n }\n actual_results = self.page_util.search(keyword)\n self.assertEqual(actual_results, expected_results)\n\n def test_search_2(self):\n keyword = \"2\"\n expected_results = {\n \"keyword\": \"2\",\n \"total_results\": 1,\n \"total_pages\": 1,\n \"results\": [2]\n }\n actual_results = self.page_util.search(keyword)\n self.assertEqual(actual_results, expected_results)\n\n def test_search_3(self):\n keyword = \"3\"\n expected_results = {\n \"keyword\": \"3\",\n \"total_results\": 1,\n \"total_pages\": 1,\n \"results\": [3]\n }\n actual_results = self.page_util.search(keyword)\n self.assertEqual(actual_results, expected_results)\n\n def test_search_4(self):\n keyword = \"4\"\n expected_results = {\n \"keyword\": \"4\",\n \"total_results\": 1,\n \"total_pages\": 1,\n \"results\": [4]\n }\n actual_results = self.page_util.search(keyword)\n self.assertEqual(actual_results, expected_results)\n\n def test_search_5(self):\n keyword = \"11\"\n expected_results = {\n \"keyword\": \"11\",\n \"total_results\": 0,\n \"total_pages\": 0,\n \"results\": []\n }\n actual_results = self.page_util.search(keyword)\n self.assertEqual(actual_results, expected_results)", "solution_code": "def search(self, keyword):\n results = [item for item in self.data if keyword in str(item)]\n num_results = len(results)\n num_pages = (num_results + self.page_size - 1) // self.page_size\n\n search_info = {\n \"keyword\": keyword,\n \"total_results\": num_results,\n \"total_pages\": num_pages,\n \"results\": results\n }\n return search_info", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.data", "self.page_size" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_69", "skeleton": "\nimport PyPDF2\n\nclass PDFHandler:\n \"\"\"\n The class allows merging multiple PDF files into one and extracting text from PDFs using PyPDF2 library.\n \"\"\"\n\n def __init__(self, filepaths):\n \"\"\"\n takes a list of file paths filepaths as a parameter.\n It creates a list named readers using PyPDF2, where each reader opens a file from the given paths.\n \"\"\"\n self.filepaths = filepaths\n self.readers = [PyPDF2.PdfFileReader(fp) for fp in filepaths]\n\n def merge_pdfs(self, output_filepath):\n \"\"\"\n Read files in self.readers which stores handles to multiple PDF files.\n Merge them to one pdf and update the page number, then save in disk.\n :param output_filepath: str, ouput file path to save to\n :return: str, \"Merged PDFs saved at {output_filepath}\" if successfully merged\n >>> handler = PDFHandler(['a.pdf', 'b.pdf'])\n >>> handler.merge_pdfs('out.pdf')\n Merged PDFs saved at out.pdf\n \"\"\"\n\n def extract_text_from_pdfs(self):\n \"\"\"\n Extract text from pdf files in self.readers\n :return pdf_texts: list of str, each element is the text of one pdf file\n >>> handler = PDFHandler(['a.pdf', 'b.pdf'])\n >>> handler.extract_text_from_pdfs()\n ['Test a.pdf', 'Test b.pdf']\n \"\"\"", "test": "import os\nimport unittest\nfrom PyPDF2 import PdfFileReader\nfrom reportlab.pdfgen import canvas\n\n\nclass TestPDFHandler(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.test_files = [\"test1.pdf\", \"test2.pdf\"]\n cls.test_text = [\"This is a test1.\", \"This is a test2.\"]\n for i in range(2):\n c = canvas.Canvas(cls.test_files[i])\n c.drawString(100, 100, cls.test_text[i])\n c.showPage()\n c.save()\n\n @classmethod\n def tearDownClass(cls):\n for filename in cls.test_files:\n os.remove(filename)\n os.remove(\"merged.pdf\")\n\n\n\nclass PDFHandlerTestMergePdfs(unittest.TestCase):\n def setUp(self) -> None:\n TestPDFHandler.setUpClass()\n\n def tearDown(self) -> None:\n TestPDFHandler.tearDownClass()\n\n def test_merge_pdfs(self):\n TestPDFHandler.setUpClass()\n handler = PDFHandler(TestPDFHandler.test_files)\n result = handler.merge_pdfs(\"merged.pdf\")\n self.assertEqual(\"Merged PDFs saved at merged.pdf\", result)\n self.assertTrue(os.path.exists(\"merged.pdf\"))\n\n\n\nclass PDFHandlerTestExtractTextFromPdfs(unittest.TestCase):\n def setUp(self) -> None:\n TestPDFHandler.setUpClass()\n\n def test_extract_text_from_pdfs(self):\n TestPDFHandler.setUpClass()\n handler = PDFHandler(TestPDFHandler.test_files)\n result = handler.extract_text_from_pdfs()\n self.assertEqual(result, [\"This is a test1.\\n\", \"This is a test2.\\n\"])\n\n\nclass PDFHandlerTestMain(unittest.TestCase):\n def setUp(self) -> None:\n TestPDFHandler.setUpClass()\n\n def tearDown(self) -> None:\n TestPDFHandler.tearDownClass()\n\n def test_main(self):\n TestPDFHandler.setUpClass()\n handler = PDFHandler(TestPDFHandler.test_files)\n result = handler.merge_pdfs(\"merged.pdf\")\n self.assertEqual(\"Merged PDFs saved at merged.pdf\", result)\n self.assertTrue(os.path.exists(\"merged.pdf\"))\n\n result = handler.extract_text_from_pdfs()\n self.assertEqual(result, [\"This is a test1.\\n\", \"This is a test2.\\n\"])", "solution_code": "import PyPDF2\n\n\nclass PDFHandler:\n def __init__(self, filepaths):\n self.filepaths = filepaths\n # PdfFileReader is deprecated and was removed in PyPDF2 3.0.0. Use PdfReader instead.\n self.readers = [PyPDF2.PdfReader(fp) for fp in filepaths]\n\n def merge_pdfs(self, output_filepath):\n pdf_writer = PyPDF2.PdfWriter()\n\n for reader in self.readers:\n # reader.getNumPages is deprecated and was removed in PyPDF2 3.0.0. Use len(reader.pages) instead.\n for page_num in range(len(reader.pages)):\n # reader.getPage(pageNumber) is deprecated and was removed in PyPDF2 3.0.0. Use reader.pages[page_number] instead.\n page = reader.pages[page_num]\n # addPage is deprecated and was removed in PyPDF2 3.0.0. Use add_page instead.\n pdf_writer.add_page(page)\n\n with open(output_filepath, 'wb') as out:\n pdf_writer.write(out)\n return f\"Merged PDFs saved at {output_filepath}\"\n\n def extract_text_from_pdfs(self):\n pdf_texts = []\n for reader in self.readers:\n for page_num in range(len(reader.pages)):\n page = reader.pages[page_num]\n pdf_texts.append(page.extract_text())\n return pdf_texts", "import_statement": [ "import PyPDF2" ], "class_description": " \"\"\"\n The class allows merging multiple PDF files into one and extracting text from PDFs using PyPDF2 library.\n \"\"\"\n", "class_name": "PDFHandler", "test_classes": [ "TestPDFHandler", "PDFHandlerTestMergePdfs", "PDFHandlerTestExtractTextFromPdfs", "PDFHandlerTestMain" ], "class_constructor": "class PDFHandler: \n def __init__(self, filepaths):\n \"\"\"\n takes a list of file paths filepaths as a parameter.\n It creates a list named readers using PyPDF2, where each reader opens a file from the given paths.\n \"\"\"\n self.filepaths = filepaths\n self.readers = [PyPDF2.PdfFileReader(fp) for fp in filepaths]\n\n", "fields": [ "self.filepaths", "self.readers" ], "methods_info": [ { "method_name": "merge_pdfs", "method_description": "def merge_pdfs(self, output_filepath):\n \"\"\"\n Read files in self.readers which stores handles to multiple PDF files.\n Merge them to one pdf and update the page number, then save in disk.\n :param output_filepath: str, ouput file path to save to\n :return: str, \"Merged PDFs saved at {output_filepath}\" if successfully merged\n >>> handler = PDFHandler(['a.pdf', 'b.pdf'])\n >>> handler.merge_pdfs('out.pdf')\n Merged PDFs saved at out.pdf\n \"\"\"", "test_class": "TestPDFHandler", "test_code": "class TestPDFHandler(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.test_files = [\"test1.pdf\", \"test2.pdf\"]\n cls.test_text = [\"This is a test1.\", \"This is a test2.\"]\n for i in range(2):\n c = canvas.Canvas(cls.test_files[i])\n c.drawString(100, 100, cls.test_text[i])\n c.showPage()\n c.save()\n\n @classmethod\n def tearDownClass(cls):\n for filename in cls.test_files:\n os.remove(filename)\n os.remove(\"merged.pdf\")", "solution_code": "def merge_pdfs(self, output_filepath):\n pdf_writer = PyPDF2.PdfWriter()\n\n for reader in self.readers:\n # reader.getNumPages is deprecated and was removed in PyPDF2 3.0.0. Use len(reader.pages) instead.\n for page_num in range(len(reader.pages)):\n # reader.getPage(pageNumber) is deprecated and was removed in PyPDF2 3.0.0. Use reader.pages[page_number] instead.\n page = reader.pages[page_num]\n # addPage is deprecated and was removed in PyPDF2 3.0.0. Use add_page instead.\n pdf_writer.add_page(page)\n\n with open(output_filepath, 'wb') as out:\n pdf_writer.write(out)\n return f\"Merged PDFs saved at {output_filepath}\"", "dependencies": { "Standalone": false, "lib_dependencies": [ "PyPDF2" ], "field_dependencies": [ "self.readers" ], "method_dependencies": [] } }, { "method_name": "extract_text_from_pdfs", "method_description": "def extract_text_from_pdfs(self):\n \"\"\"\n Extract text from pdf files in self.readers\n :return pdf_texts: list of str, each element is the text of one pdf file\n >>> handler = PDFHandler(['a.pdf', 'b.pdf'])\n >>> handler.extract_text_from_pdfs()\n ['Test a.pdf', 'Test b.pdf']\n \"\"\"", "test_class": "PDFHandlerTestMergePdfs", "test_code": "class PDFHandlerTestMergePdfs(unittest.TestCase):\n def setUp(self) -> None:\n TestPDFHandler.setUpClass()\n\n def tearDown(self) -> None:\n TestPDFHandler.tearDownClass()\n\n def test_merge_pdfs(self):\n TestPDFHandler.setUpClass()\n handler = PDFHandler(TestPDFHandler.test_files)\n result = handler.merge_pdfs(\"merged.pdf\")\n self.assertEqual(\"Merged PDFs saved at merged.pdf\", result)\n self.assertTrue(os.path.exists(\"merged.pdf\"))", "solution_code": "def extract_text_from_pdfs(self):\n pdf_texts = []\n for reader in self.readers:\n for page_num in range(len(reader.pages)):\n page = reader.pages[page_num]\n pdf_texts.append(page.extract_text())\n return pdf_texts", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.readers" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_70", "skeleton": "\nclass PersonRequest:\n \"\"\"\n This class validates input personal information data and sets invalid fields to None based to specific rules.\n \"\"\"\n\n def __init__(self, name: str, sex: str, phoneNumber: str):\n \"\"\"\n Initialize PersonRequest object with the provided information.\n :param name: str, the name of the person\n :param sex: str, the sex of the person\n :param phoneNumber: str, the phone number of the person\n \"\"\"\n self.name = self._validate_name(name)\n self.sex = self._validate_sex(sex)\n self.phoneNumber = self._validate_phoneNumber(phoneNumber)\n\n\n def _validate_name(self, name: str) -> str:\n \"\"\"\n Validate the name and return it. If name is empty or exceeds 33 characters in length, set to None.\n :param name: str, the name to validate\n :return: str, the validated name or None if invalid\n \"\"\"\n\n\n def _validate_sex(self, sex: str) -> str:\n \"\"\"\n Validate the sex and return it. If sex is not Man, Woman, or UGM, set to None.\n :param sex: str, the sex to validate\n :return: str, the validated sex or None if invalid\n \"\"\"\n\n def _validate_phoneNumber(self, phoneNumber: str) -> str:\n \"\"\"\n Validate the phone number and return it. If phoneNumber is empty or not an 11 digit number, set to None.\n :param phoneNumber: str, the phone number to validate\n :return: str, the validated phone number or None if invalid\n \"\"\"", "test": "import unittest\n\n\nclass PersonRequestTestValidateName(unittest.TestCase):\n def test_validate_name_1(self):\n pr = PersonRequest(\"\", \"Man\", \"12345678901\")\n self.assertIsNone(pr.name)\n\n def test_validate_name_2(self):\n pr = PersonRequest(\"This is a very long name that exceeds the character limit\", \"Man\",\n \"12345678901\")\n self.assertIsNone(pr.name)\n\n def test_validate_name_3(self):\n pr = PersonRequest(\"aaa\", \"Man\", \"12345678901\")\n self.assertEqual(pr.name, 'aaa')\n\n def test_validate_name_4(self):\n pr = PersonRequest(\"bbb\", \"Man\", \"12345678901\")\n self.assertEqual(pr.name, 'bbb')\n\n def test_validate_name_5(self):\n pr = PersonRequest(\"ccc\", \"Man\", \"12345678901\")\n self.assertEqual(pr.name, 'ccc')\n\n\nclass PersonRequestTestValidateSex(unittest.TestCase):\n def test_validate_sex_1(self):\n pr = PersonRequest(\"John Doe\", \"Unknown\", \"12345678901\")\n self.assertIsNone(pr.sex)\n\n def test_validate_sex_2(self):\n pr = PersonRequest(\"John Doe\", \"UGM\", \"12345678901\")\n self.assertEqual(pr.sex, \"UGM\")\n\n def test_validate_sex_3(self):\n pr = PersonRequest(\"John Doe\", \"Man\", \"12345678901\")\n self.assertEqual(pr.sex, \"Man\")\n\n def test_validate_sex_4(self):\n pr = PersonRequest(\"John Doe\", \"Woman\", \"12345678901\")\n self.assertEqual(pr.sex, \"Woman\")\n\n def test_validate_sex_5(self):\n pr = PersonRequest(\"John Doe\", \"khsigy\", \"12345678901\")\n self.assertIsNone(pr.sex)\n\n\nclass PersonRequestTestValidatePhoneNumber(unittest.TestCase):\n def test_validate_phoneNumber_1(self):\n pr = PersonRequest(\"John Doe\", \"Man\", \"\")\n self.assertIsNone(pr.phoneNumber)\n\n def test_validate_phoneNumber_2(self):\n pr = PersonRequest(\"John Doe\", \"Man\", \"12345\")\n self.assertIsNone(pr.phoneNumber)\n\n def test_validate_phoneNumber_3(self):\n pr = PersonRequest(\"John Doe\", \"Man\", \"jgdjrj\")\n self.assertIsNone(pr.phoneNumber)\n\n def test_validate_phoneNumber_4(self):\n pr = PersonRequest(\"John Doe\", \"Man\", \"12345678901\")\n self.assertEqual(pr.phoneNumber, \"12345678901\")\n\n def test_validate_phoneNumber_5(self):\n pr = PersonRequest(\"John Doe\", \"Man\", \"11111111111\")\n self.assertEqual(pr.phoneNumber, \"11111111111\")\n\n\nclass PersonRequestTest(unittest.TestCase):\n def test_PersonRequest(self):\n pr = PersonRequest(\"\", \"Man\", \"12345678901\")\n self.assertIsNone(pr.name)\n\n pr = PersonRequest(\"John Doe\", \"Unknown\", \"12345678901\")\n self.assertIsNone(pr.sex)\n\n pr = PersonRequest(\"John Doe\", \"Man\", \"\")\n self.assertIsNone(pr.phoneNumber)", "solution_code": "class PersonRequest:\n def __init__(self, name: str, sex: str, phoneNumber: str):\n self.name = self._validate_name(name)\n self.sex = self._validate_sex(sex)\n self.phoneNumber = self._validate_phoneNumber(phoneNumber)\n\n def _validate_name(self, name: str) -> str:\n if not name:\n return None\n if len(name) > 33:\n return None\n return name\n\n def _validate_sex(self, sex: str) -> str:\n if sex not in [\"Man\", \"Woman\", \"UGM\"]:\n return None\n return sex\n\n def _validate_phoneNumber(self, phoneNumber: str) -> str:\n if not phoneNumber:\n return None\n if len(phoneNumber) != 11 or not phoneNumber.isdigit():\n return None\n return phoneNumber", "import_statement": [], "class_description": " \"\"\"\n This class validates input personal information data and sets invalid fields to None based to specific rules.\n \"\"\"\n", "class_name": "PersonRequest", "test_classes": [ "PersonRequestTestValidateName", "PersonRequestTestValidateSex", "PersonRequestTestValidatePhoneNumber", "PersonRequestTest" ], "class_constructor": "class PersonRequest: \n def __init__(self, name: str, sex: str, phoneNumber: str):\n \"\"\"\n Initialize PersonRequest object with the provided information.\n :param name: str, the name of the person\n :param sex: str, the sex of the person\n :param phoneNumber: str, the phone number of the person\n \"\"\"\n self.name = self._validate_name(name)\n self.sex = self._validate_sex(sex)\n self.phoneNumber = self._validate_phoneNumber(phoneNumber)\n\n\n", "fields": [ "self.name", "self.phoneNumber", "self.sex" ], "methods_info": [ { "method_name": "_validate_name", "method_description": "def _validate_name(self, name: str) -> str:\n \"\"\"\n Validate the name and return it. If name is empty or exceeds 33 characters in length, set to None.\n :param name: str, the name to validate\n :return: str, the validated name or None if invalid\n \"\"\"", "test_class": "PersonRequestTestValidateName", "test_code": "class PersonRequestTestValidateName(unittest.TestCase):\n def test_validate_name_1(self):\n pr = PersonRequest(\"\", \"Man\", \"12345678901\")\n self.assertIsNone(pr.name)\n\n def test_validate_name_2(self):\n pr = PersonRequest(\"This is a very long name that exceeds the character limit\", \"Man\",\n \"12345678901\")\n self.assertIsNone(pr.name)\n\n def test_validate_name_3(self):\n pr = PersonRequest(\"aaa\", \"Man\", \"12345678901\")\n self.assertEqual(pr.name, 'aaa')\n\n def test_validate_name_4(self):\n pr = PersonRequest(\"bbb\", \"Man\", \"12345678901\")\n self.assertEqual(pr.name, 'bbb')\n\n def test_validate_name_5(self):\n pr = PersonRequest(\"ccc\", \"Man\", \"12345678901\")\n self.assertEqual(pr.name, 'ccc')", "solution_code": "def _validate_name(self, name: str) -> str:\n if not name:\n return None\n if len(name) > 33:\n return None\n return name", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "_validate_sex", "method_description": "def _validate_sex(self, sex: str) -> str:\n \"\"\"\n Validate the sex and return it. If sex is not Man, Woman, or UGM, set to None.\n :param sex: str, the sex to validate\n :return: str, the validated sex or None if invalid\n \"\"\"", "test_class": "PersonRequestTestValidateSex", "test_code": "class PersonRequestTestValidateSex(unittest.TestCase):\n def test_validate_sex_1(self):\n pr = PersonRequest(\"John Doe\", \"Unknown\", \"12345678901\")\n self.assertIsNone(pr.sex)\n\n def test_validate_sex_2(self):\n pr = PersonRequest(\"John Doe\", \"UGM\", \"12345678901\")\n self.assertEqual(pr.sex, \"UGM\")\n\n def test_validate_sex_3(self):\n pr = PersonRequest(\"John Doe\", \"Man\", \"12345678901\")\n self.assertEqual(pr.sex, \"Man\")\n\n def test_validate_sex_4(self):\n pr = PersonRequest(\"John Doe\", \"Woman\", \"12345678901\")\n self.assertEqual(pr.sex, \"Woman\")\n\n def test_validate_sex_5(self):\n pr = PersonRequest(\"John Doe\", \"khsigy\", \"12345678901\")\n self.assertIsNone(pr.sex)", "solution_code": "def _validate_sex(self, sex: str) -> str:\n if sex not in [\"Man\", \"Woman\", \"UGM\"]:\n return None\n return sex", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "_validate_phoneNumber", "method_description": "def _validate_phoneNumber(self, phoneNumber: str) -> str:\n \"\"\"\n Validate the phone number and return it. If phoneNumber is empty or not an 11 digit number, set to None.\n :param phoneNumber: str, the phone number to validate\n :return: str, the validated phone number or None if invalid\n \"\"\"", "test_class": "PersonRequestTestValidatePhoneNumber", "test_code": "class PersonRequestTestValidatePhoneNumber(unittest.TestCase):\n def test_validate_phoneNumber_1(self):\n pr = PersonRequest(\"John Doe\", \"Man\", \"\")\n self.assertIsNone(pr.phoneNumber)\n\n def test_validate_phoneNumber_2(self):\n pr = PersonRequest(\"John Doe\", \"Man\", \"12345\")\n self.assertIsNone(pr.phoneNumber)\n\n def test_validate_phoneNumber_3(self):\n pr = PersonRequest(\"John Doe\", \"Man\", \"jgdjrj\")\n self.assertIsNone(pr.phoneNumber)\n\n def test_validate_phoneNumber_4(self):\n pr = PersonRequest(\"John Doe\", \"Man\", \"12345678901\")\n self.assertEqual(pr.phoneNumber, \"12345678901\")\n\n def test_validate_phoneNumber_5(self):\n pr = PersonRequest(\"John Doe\", \"Man\", \"11111111111\")\n self.assertEqual(pr.phoneNumber, \"11111111111\")", "solution_code": "def _validate_phoneNumber(self, phoneNumber: str) -> str:\n if not phoneNumber:\n return None\n if len(phoneNumber) != 11 or not phoneNumber.isdigit():\n return None\n return phoneNumber", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_71", "skeleton": "\nclass PushBoxGame:\n \"\"\"\n This class implements a functionality of a sokoban game, where the player needs to move boxes to designated targets in order to win.\n \"\"\"\n\n def __init__(self, map):\n \"\"\"\n Initialize the push box game with the map and various attributes.\n :param map: list[str], the map of the push box game, represented as a list of strings. \n Each character on the map represents a different element, including the following:\n - '#' represents a wall that neither the player nor the box can pass through;\n - 'O' represents the initial position of the player;\n - 'G' represents the target position;\n - 'X' represents the initial position of the box.\n >>> map = [\"#####\", \"#O #\", \"# X #\", \"# G#\", \"#####\"] \n >>> game = PushBoxGame(map) \n \"\"\"\n self.map = map\n self.player_row = 0\n self.player_col = 0\n self.targets = []\n self.boxes = []\n self.target_count = 0\n self.is_game_over = False\n self.init_game()\n\n def init_game(self):\n \"\"\"\n Initialize the game by setting the positions of the player, targets, and boxes based on the map.\n >>> game = PushBoxGame([\"#####\", \"#O #\", \"# X #\", \"# G#\", \"#####\"]) \n >>> game.targets\n [(3, 3)]\n >>> game.boxes\n [(2, 2)]\n >>> game.player_row\n 1\n >>> game.player_col\n 1\n \"\"\"\n\n def check_win(self):\n \"\"\"\n Check if the game is won. The game is won when all the boxes are placed on target positions.\n And update the value of self.is_game_over.\n :return self.is_game_over: True if all the boxes are placed on target positions, or False otherwise.\n >>> game = PushBoxGame([\"#####\", \"#O #\", \"# X #\", \"# G#\", \"#####\"]) \n >>> game.check_win()\n \"\"\"\n\n\n def move(self, direction):\n \"\"\"\n Move the player based on the specified direction and check if the game is won.\n :param direction: str, the direction of the player's movement. \n It can be 'w', 's', 'a', or 'd' representing up, down, left, or right respectively.\n\n :return: True if the game is won, False otherwise.\n >>> game = PushBoxGame([\"#####\", \"#O #\", \"# X #\", \"# G#\", \"#####\"]) \n >>> game.print_map()\n # # # # # \n # O #\n # X #\n # G #\n # # # # #\n >>> game.move('d')\n False\n >>> game.move('s') \n False\n >>> game.move('a') \n False\n >>> game.move('s') \n False\n >>> game.move('d') \n True\n \"\"\"", "test": "import unittest\n\n\nclass PushBoxGameTestInitGame(unittest.TestCase):\n def setUp(self) -> None:\n self.game_map = [\n \"#####\",\n \"#O #\",\n \"# X #\",\n \"# G#\",\n \"#####\"\n ]\n self.game = PushBoxGame(self.game_map)\n\n def test_init_game_1(self):\n self.assertEqual(self.game.map, self.game_map)\n\n def test_init_game_2(self):\n self.assertEqual(self.game.is_game_over, False)\n\n def test_init_game_3(self):\n self.assertEqual(self.game.player_col, 1)\n\n def test_init_game_4(self):\n self.assertEqual(self.game.player_row, 1)\n\n def test_init_game_5(self):\n self.assertEqual(self.game.targets, [(3, 3)])\n\n def test_init_game_6(self):\n self.assertEqual(self.game.boxes, [(2, 2)])\n\n def test_init_game_7(self):\n self.assertEqual(self.game.target_count, 1)\n\n\nclass PushBoxGameTestCheckWin(unittest.TestCase):\n def setUp(self) -> None:\n self.game_map = [\n \"#####\",\n \"#O #\",\n \"# X #\",\n \"# G#\",\n \"#####\"\n ]\n self.game = PushBoxGame(self.game_map)\n\n def test_check_win_1(self):\n self.assertFalse(self.game.check_win())\n\n def test_check_win_2(self):\n moves = ['d', 's', 'a', 's', 'd']\n for move in moves:\n self.game.move(move)\n self.assertTrue(self.game.check_win())\n\nclass PushBoxGameTestMove(unittest.TestCase):\n def setUp(self) -> None:\n self.game_map = [\n \"#####\",\n \"#O #\",\n \"# X #\",\n \"# G#\",\n \"#####\"\n ]\n self.game = PushBoxGame(self.game_map)\n\n def test_move_1(self):\n moves = ['d', 's', 'a', 's']\n for move in moves:\n self.assertFalse(self.game.move(move))\n self.assertTrue(self.game.move('d'))\n\n def test_move_2(self):\n self.game.move('a')\n self.assertEqual(self.game.player_col, 1)\n self.assertEqual(self.game.player_row, 1)\n self.assertFalse(self.game.is_game_over)\n\n def test_move_3(self):\n self.game.move('d')\n self.assertEqual(self.game.player_col, 2)\n self.assertEqual(self.game.player_row, 1)\n self.assertFalse(self.game.is_game_over)\n\n def test_move_4(self):\n self.game.move('s')\n self.assertEqual(self.game.player_col, 1)\n self.assertEqual(self.game.player_row, 2)\n self.assertFalse(self.game.is_game_over)\n\n def test_move_5(self):\n self.game.move('w')\n self.assertEqual(self.game.player_col, 1)\n self.assertEqual(self.game.player_row, 1)\n self.assertFalse(self.game.is_game_over)\n\n def test_move_6(self):\n self.game.move('?')\n self.assertFalse(self.game.is_game_over)\n\n def test_move_7(self):\n self.game_map = [\n \"#####\",\n \"# X #\",\n \"# O #\",\n \"# G#\",\n \"#####\"\n ]\n self.game = PushBoxGame(self.game_map)\n self.game.move('w')\n self.assertEqual(self.game.player_col, 2)\n self.assertEqual(self.game.player_row, 2)\n self.assertFalse(self.game.is_game_over)", "solution_code": "class PushBoxGame:\n def __init__(self, map):\n self.map = map\n self.player_row = 0\n self.player_col = 0\n self.targets = []\n self.boxes = []\n self.target_count = 0\n self.is_game_over = False\n\n self.init_game()\n\n def init_game(self):\n for row in range(len(self.map)):\n for col in range(len(self.map[row])):\n if self.map[row][col] == \"O\":\n self.player_row = row\n self.player_col = col\n elif self.map[row][col] == \"G\":\n self.targets.append((row, col))\n self.target_count += 1\n elif self.map[row][col] == \"X\":\n self.boxes.append((row, col))\n\n def check_win(self):\n box_on_target_count = 0\n for box in self.boxes:\n if box in self.targets:\n box_on_target_count += 1\n if box_on_target_count == self.target_count:\n self.is_game_over = True\n return self.is_game_over\n\n def move(self, direction):\n new_player_row = self.player_row\n new_player_col = self.player_col\n\n if direction == \"w\":\n new_player_row -= 1\n elif direction == \"s\":\n new_player_row += 1\n elif direction == \"a\":\n new_player_col -= 1\n elif direction == \"d\":\n new_player_col += 1\n\n if self.map[new_player_row][new_player_col] != \"#\":\n if (new_player_row, new_player_col) in self.boxes:\n new_box_row = new_player_row + (new_player_row - self.player_row)\n new_box_col = new_player_col + (new_player_col - self.player_col)\n\n if self.map[new_box_row][new_box_col] != \"#\":\n self.boxes.remove((new_player_row, new_player_col))\n self.boxes.append((new_box_row, new_box_col))\n self.player_row = new_player_row\n self.player_col = new_player_col\n else:\n self.player_row = new_player_row\n self.player_col = new_player_col\n\n return self.check_win()", "import_statement": [], "class_description": " \"\"\"\n This class implements a functionality of a sokoban game, where the player needs to move boxes to designated targets in order to win.\n \"\"\"\n", "class_name": "PushBoxGame", "test_classes": [ "PushBoxGameTestInitGame", "PushBoxGameTestCheckWin", "PushBoxGameTestMove" ], "class_constructor": "class PushBoxGame: \n def __init__(self, map):\n \"\"\"\n Initialize the push box game with the map and various attributes.\n :param map: list[str], the map of the push box game, represented as a list of strings. \n Each character on the map represents a different element, including the following:\n - '#' represents a wall that neither the player nor the box can pass through;\n - 'O' represents the initial position of the player;\n - 'G' represents the target position;\n - 'X' represents the initial position of the box.\n >>> map = [\"#####\", \"#O #\", \"# X #\", \"# G#\", \"#####\"] \n >>> game = PushBoxGame(map) \n \"\"\"\n self.map = map\n self.player_row = 0\n self.player_col = 0\n self.targets = []\n self.boxes = []\n self.target_count = 0\n self.is_game_over = False\n self.init_game()\n\n", "fields": [ "self.boxes", "self.is_game_over", "self.map", "self.player_col", "self.player_row", "self.target_count", "self.targets" ], "methods_info": [ { "method_name": "init_game", "method_description": "def init_game(self):\n \"\"\"\n Initialize the game by setting the positions of the player, targets, and boxes based on the map.\n >>> game = PushBoxGame([\"#####\", \"#O #\", \"# X #\", \"# G#\", \"#####\"]) \n >>> game.targets\n [(3, 3)]\n >>> game.boxes\n [(2, 2)]\n >>> game.player_row\n 1\n >>> game.player_col\n 1\n \"\"\"", "test_class": "PushBoxGameTestInitGame", "test_code": "class PushBoxGameTestInitGame(unittest.TestCase):\n def setUp(self) -> None:\n self.game_map = [\n \"#####\",\n \"#O #\",\n \"# X #\",\n \"# G#\",\n \"#####\"\n ]\n self.game = PushBoxGame(self.game_map)\n\n def test_init_game_1(self):\n self.assertEqual(self.game.map, self.game_map)\n\n def test_init_game_2(self):\n self.assertEqual(self.game.is_game_over, False)\n\n def test_init_game_3(self):\n self.assertEqual(self.game.player_col, 1)\n\n def test_init_game_4(self):\n self.assertEqual(self.game.player_row, 1)\n\n def test_init_game_5(self):\n self.assertEqual(self.game.targets, [(3, 3)])\n\n def test_init_game_6(self):\n self.assertEqual(self.game.boxes, [(2, 2)])\n\n def test_init_game_7(self):\n self.assertEqual(self.game.target_count, 1)", "solution_code": "def init_game(self):\n for row in range(len(self.map)):\n for col in range(len(self.map[row])):\n if self.map[row][col] == \"O\":\n self.player_row = row\n self.player_col = col\n elif self.map[row][col] == \"G\":\n self.targets.append((row, col))\n self.target_count += 1\n elif self.map[row][col] == \"X\":\n self.boxes.append((row, col))", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.boxes", "self.map", "self.player_col", "self.player_row", "self.target_count", "self.targets" ], "method_dependencies": [] } }, { "method_name": "check_win", "method_description": "def check_win(self):\n \"\"\"\n Check if the game is won. The game is won when all the boxes are placed on target positions.\n And update the value of self.is_game_over.\n :return self.is_game_over: True if all the boxes are placed on target positions, or False otherwise.\n >>> game = PushBoxGame([\"#####\", \"#O #\", \"# X #\", \"# G#\", \"#####\"]) \n >>> game.check_win()\n \"\"\"", "test_class": "PushBoxGameTestCheckWin", "test_code": "class PushBoxGameTestCheckWin(unittest.TestCase):\n def setUp(self) -> None:\n self.game_map = [\n \"#####\",\n \"#O #\",\n \"# X #\",\n \"# G#\",\n \"#####\"\n ]\n self.game = PushBoxGame(self.game_map)\n\n def test_check_win_1(self):\n self.assertFalse(self.game.check_win())\n\n def test_check_win_2(self):\n moves = ['d', 's', 'a', 's', 'd']\n for move in moves:\n self.game.move(move)\n self.assertTrue(self.game.check_win())", "solution_code": "def check_win(self):\n box_on_target_count = 0\n for box in self.boxes:\n if box in self.targets:\n box_on_target_count += 1\n if box_on_target_count == self.target_count:\n self.is_game_over = True\n return self.is_game_over", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.boxes", "self.is_game_over", "self.target_count", "self.targets" ], "method_dependencies": [] } }, { "method_name": "move", "method_description": "def move(self, direction):\n \"\"\"\n Move the player based on the specified direction and check if the game is won.\n :param direction: str, the direction of the player's movement. \n It can be 'w', 's', 'a', or 'd' representing up, down, left, or right respectively.\n\n :return: True if the game is won, False otherwise.\n >>> game = PushBoxGame([\"#####\", \"#O #\", \"# X #\", \"# G#\", \"#####\"]) \n >>> game.print_map()\n # # # # # \n # O #\n # X #\n # G #\n # # # # #\n >>> game.move('d')\n False\n >>> game.move('s') \n False\n >>> game.move('a') \n False\n >>> game.move('s') \n False\n >>> game.move('d') \n True\n \"\"\"", "test_class": "PushBoxGameTestMove", "test_code": "class PushBoxGameTestMove(unittest.TestCase):\n def setUp(self) -> None:\n self.game_map = [\n \"#####\",\n \"#O #\",\n \"# X #\",\n \"# G#\",\n \"#####\"\n ]\n self.game = PushBoxGame(self.game_map)\n\n def test_move_1(self):\n moves = ['d', 's', 'a', 's']\n for move in moves:\n self.assertFalse(self.game.move(move))\n self.assertTrue(self.game.move('d'))\n\n def test_move_2(self):\n self.game.move('a')\n self.assertEqual(self.game.player_col, 1)\n self.assertEqual(self.game.player_row, 1)\n self.assertFalse(self.game.is_game_over)\n\n def test_move_3(self):\n self.game.move('d')\n self.assertEqual(self.game.player_col, 2)\n self.assertEqual(self.game.player_row, 1)\n self.assertFalse(self.game.is_game_over)\n\n def test_move_4(self):\n self.game.move('s')\n self.assertEqual(self.game.player_col, 1)\n self.assertEqual(self.game.player_row, 2)\n self.assertFalse(self.game.is_game_over)\n\n def test_move_5(self):\n self.game.move('w')\n self.assertEqual(self.game.player_col, 1)\n self.assertEqual(self.game.player_row, 1)\n self.assertFalse(self.game.is_game_over)\n\n def test_move_6(self):\n self.game.move('?')\n self.assertFalse(self.game.is_game_over)\n\n def test_move_7(self):\n self.game_map = [\n \"#####\",\n \"# X #\",\n \"# O #\",\n \"# G#\",\n \"#####\"\n ]\n self.game = PushBoxGame(self.game_map)\n self.game.move('w')\n self.assertEqual(self.game.player_col, 2)\n self.assertEqual(self.game.player_row, 2)\n self.assertFalse(self.game.is_game_over)", "solution_code": "def move(self, direction):\n new_player_row = self.player_row\n new_player_col = self.player_col\n\n if direction == \"w\":\n new_player_row -= 1\n elif direction == \"s\":\n new_player_row += 1\n elif direction == \"a\":\n new_player_col -= 1\n elif direction == \"d\":\n new_player_col += 1\n\n if self.map[new_player_row][new_player_col] != \"#\":\n if (new_player_row, new_player_col) in self.boxes:\n new_box_row = new_player_row + (new_player_row - self.player_row)\n new_box_col = new_player_col + (new_player_col - self.player_col)\n\n if self.map[new_box_row][new_box_col] != \"#\":\n self.boxes.remove((new_player_row, new_player_col))\n self.boxes.append((new_box_row, new_box_col))\n self.player_row = new_player_row\n self.player_col = new_player_col\n else:\n self.player_row = new_player_row\n self.player_col = new_player_col\n\n return self.check_win()", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.boxes", "self.map", "self.player_col", "self.player_row" ], "method_dependencies": [ "check_win" ] } } ] }, { "task_id": "ClassEval_72", "skeleton": "\nimport re\n\nclass RegexUtils:\n \"\"\"\n The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses.\n \"\"\"\n\n\n def match(self, pattern, text):\n \"\"\"\n Check if the text matches the regular expression\n :param pattern: string, Regular expression pattern\n :param text: string, Text to match\n :return: True or False, representing whether the text matches the regular expression or not\n >>> ru = RegexUtils()\n >>> ru.match(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"123-456-7890\")\n True\n \"\"\"\n\n def findall(self, pattern, text):\n \"\"\"\n Find all matching substrings and return a list of all matching substrings\n :param pattern: string, Regular expression pattern\n :param text: string, Text to match\n :return: list of string, List of all matching substrings\n >>> ru = RegexUtils()\n >>> ru.findall(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n ['123-456-7890', '876-286-9876', '987-762-9767']\n \"\"\"\n\n def split(self, pattern, text):\n \"\"\"\n Split text based on regular expression patterns and return a list of substrings\n :param pattern: string, Regular expression pattern\n :param text: string, Text to be split\n :return: list of string, List of substrings after splitting\n >>> ru = RegexUtils()\n >>> ru.split(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n ['', ' abiguygusu ', ' kjgufwycs ', '']\n \"\"\"\n\n def sub(self, pattern, replacement, text):\n \"\"\"\n Replace the substring matched by a regular expression with the specified string\n :param pattern: string, Regular expression pattern\n :param replacement: Text to replace with\n :param text: string, Text to be replaced\n :return: string, Text after replacement\n >>> ru = RegexUtils()\n >>> ru.sub(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', 'phone num', \"123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n 'phone num abiguygusu phone num kjgufwycs phone num'\n \"\"\"\n\n def generate_email_pattern(self):\n \"\"\"\n Generate regular expression patterns that match email addresses\n :return: string, regular expression patterns that match email addresses\n >>> ru = RegexUtils()\n >>> ru.generate_email_pattern()\n '\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b'\n \"\"\"\n\n def generate_phone_number_pattern(self):\n \"\"\"\n Generate regular expression patterns that match phone numbers\n :return: string, regular expression patterns that match phone numbers\n >>> ru = RegexUtils()\n >>> ru.generate_phone_number_pattern()\n '\\b\\d{3}-\\d{3}-\\d{4}\\b'\n \"\"\"\n\n def generate_split_sentences_pattern(self):\n \"\"\"\n Generate regular expression patterns that match the middle characters of two sentences\n :return: string, regular expression patterns that match the middle characters of two sentences\n >>> ru = RegexUtils()\n >>> ru.generate_split_sentences_pattern()\n '[.!?][\\s]{1,2}(?=[A-Z])'\n \"\"\"\n\n def split_sentences(self, text):\n \"\"\"\n Split the text into a list of sentences without Punctuation except the last sentence\n :param text: Text to be split\n :return: Split Text List\n >>> ru = RegexUtils()\n >>> ru.split_sentences(\"Aaa. Bbbb? Ccc!\")\n ['Aaa', 'Bbbb', 'Ccc!']\n \"\"\"\n\n def validate_phone_number(self, phone_number):\n \"\"\"\n Verify if the phone number is valid\n :param phone_number: Phone number to be verified\n :return: True or False, indicating whether the phone number is valid\n >>> ru = RegexUtils()\n >>> ru.validate_phone_number(\"123-456-7890\")\n True\n \"\"\"\n\n def extract_email(self, text):\n \"\"\"\n Extract all email addresses from the text\n :param text: string, input text\n :return: list of string, All extracted email addresses\n >>> ru = RegexUtils()\n >>> ru.extract_email(\"abcdefg@163.com ygusyfysy@126.com wljduyuv@qq.com\")\n ['abcdefg@163.com', 'ygusyfysy@126.com', 'wljduyuv@qq.com']\n \"\"\"", "test": "import unittest\n\n\nclass RegexUtilsTestMatch(unittest.TestCase):\n def test_match_1(self):\n ru = RegexUtils()\n res = ru.match(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"123-456-7890\")\n self.assertEqual(res, True)\n\n def test_match_2(self):\n ru = RegexUtils()\n res = ru.match(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"1234567890\")\n self.assertEqual(res, False)\n\n def test_match_3(self):\n ru = RegexUtils()\n res = ru.match(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"111-111-1111\")\n self.assertEqual(res, True)\n\n def test_match_4(self):\n ru = RegexUtils()\n res = ru.match(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"123-456-789\")\n self.assertEqual(res, False)\n\n def test_match_5(self):\n ru = RegexUtils()\n res = ru.match(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"123-456-789a\")\n self.assertEqual(res, False)\n\n\nclass RegexUtilsTestFindall(unittest.TestCase):\n def test_findall_1(self):\n ru = RegexUtils()\n res = ru.findall(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n self.assertEqual(res, ['123-456-7890', '876-286-9876', '987-762-9767'])\n\n def test_findall_2(self):\n ru = RegexUtils()\n res = ru.findall(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"abiguygusu kjgufwycs 987-762-9767\")\n self.assertEqual(res, ['987-762-9767'])\n\n def test_findall_3(self):\n ru = RegexUtils()\n res = ru.findall(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"abiguygusu kjgufwycs \")\n self.assertEqual(res, [])\n\n def test_findall_4(self):\n ru = RegexUtils()\n res = ru.findall(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"abiguygusu 111-111-1111 kjgufwycs 987-762-9767\")\n self.assertEqual(res, ['111-111-1111', '987-762-9767'])\n\n def test_findall_5(self):\n ru = RegexUtils()\n res = ru.findall(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"abiguygusu 111-111-111a kjgufwycs 987-762-9767\")\n self.assertEqual(res, ['987-762-9767'])\n\n\nclass RegexUtilsTestSplit(unittest.TestCase):\n def test_split_1(self):\n ru = RegexUtils()\n res = ru.split(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n self.assertEqual(res, ['', ' abiguygusu ', ' kjgufwycs ', ''])\n\n def test_split_2(self):\n ru = RegexUtils()\n res = ru.split(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"1234567890 abiguygusu 8762869876 kjgufwycs 9877629767\")\n self.assertEqual(res, ['1234567890 abiguygusu 8762869876 kjgufwycs 9877629767'])\n\n def test_split_3(self):\n ru = RegexUtils()\n res = ru.split(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"111-111-1111 abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n self.assertEqual(res, ['', ' abiguygusu ', ' kjgufwycs ', ''])\n\n def test_split_4(self):\n ru = RegexUtils()\n res = ru.split(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"123456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n self.assertEqual(res, ['123456-7890 abiguygusu ', ' kjgufwycs ', ''])\n\n def test_split_5(self):\n ru = RegexUtils()\n res = ru.split(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"123-456-789a abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n self.assertEqual(res, ['123-456-789a abiguygusu ', ' kjgufwycs ', ''])\n\n\nclass RegexUtilsTestSub(unittest.TestCase):\n def test_sub_1(self):\n ru = RegexUtils()\n res = ru.sub(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', 'phone num',\n \"123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n self.assertEqual(res, 'phone num abiguygusu phone num kjgufwycs phone num')\n\n def test_sub_2(self):\n ru = RegexUtils()\n res = ru.sub(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', 'phone num',\n \"1234567890 abiguygusu 8762869876 kjgufwycs 9877629767\")\n self.assertEqual(res, \"1234567890 abiguygusu 8762869876 kjgufwycs 9877629767\")\n\n def test_sub_3(self):\n ru = RegexUtils()\n res = ru.sub(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', 'phone num',\n \"123456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n self.assertEqual(res, '123456-7890 abiguygusu phone num kjgufwycs phone num')\n\n def test_sub_4(self):\n ru = RegexUtils()\n res = ru.sub(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', 'phone num',\n \"123-456-789a abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n self.assertEqual(res, '123-456-789a abiguygusu phone num kjgufwycs phone num')\n\n def test_sub_5(self):\n ru = RegexUtils()\n res = ru.sub(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', 'phone num',\n \"123-456-780 abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n self.assertEqual(res, '123-456-780 abiguygusu phone num kjgufwycs phone num')\n\n\nclass RegexUtilsTestGenerateEmailPattern(unittest.TestCase):\n def test_generate_email_pattern_1(self):\n ru = RegexUtils()\n pat = ru.generate_email_pattern()\n res = ru.match(pat, 'iustd87t2euh@163.com')\n self.assertEqual(res, True)\n\n def test_generate_email_pattern_2(self):\n ru = RegexUtils()\n pat = ru.generate_email_pattern()\n res = ru.match(pat, 'iustd87t2euhifg.com')\n self.assertEqual(res, False)\n\n def test_generate_email_pattern_3(self):\n ru = RegexUtils()\n pat = ru.generate_email_pattern()\n res = ru.match(pat, 'iustd87t2euhifg@.com')\n self.assertEqual(res, False)\n\n def test_generate_email_pattern_4(self):\n ru = RegexUtils()\n pat = ru.generate_email_pattern()\n res = ru.match(pat, 'iustd87t2euhifg@.')\n self.assertEqual(res, False)\n\n def test_generate_email_pattern_5(self):\n ru = RegexUtils()\n pat = ru.generate_email_pattern()\n res = ru.match(pat, 'iustd87t2euhifg@com.')\n self.assertEqual(res, False)\n\n\nclass RegexUtilsTestGeneratePhoneNumberPattern(unittest.TestCase):\n def test_generate_phone_number_pattern_1(self):\n ru = RegexUtils()\n pat = ru.generate_phone_number_pattern()\n res = ru.match(pat, '123-456-7890')\n self.assertEqual(res, True)\n\n def test_generate_phone_number_pattern_2(self):\n ru = RegexUtils()\n pat = ru.generate_phone_number_pattern()\n res = ru.match(pat, '1234567890')\n self.assertEqual(res, False)\n\n def test_generate_phone_number_pattern_3(self):\n ru = RegexUtils()\n pat = ru.generate_phone_number_pattern()\n res = ru.match(pat, '123-456-789')\n self.assertEqual(res, False)\n\n def test_generate_phone_number_pattern_4(self):\n ru = RegexUtils()\n pat = ru.generate_phone_number_pattern()\n res = ru.match(pat, 'a23-456-7890')\n self.assertEqual(res, False)\n\n def test_generate_phone_number_pattern_5(self):\n ru = RegexUtils()\n pat = ru.generate_phone_number_pattern()\n res = ru.match(pat, '1234-56-7890')\n self.assertEqual(res, False)\n\n\nclass RegexUtilsTestGenerateSplitSentencesPattern(unittest.TestCase):\n def test_generate_split_sentences_pattern_1(self):\n ru = RegexUtils()\n pat = ru.generate_split_sentences_pattern()\n res = ru.match(pat, '? Y')\n self.assertEqual(res, True)\n\n def test_generate_split_sentences_pattern_2(self):\n ru = RegexUtils()\n pat = ru.generate_split_sentences_pattern()\n res = ru.match(pat, '! Y')\n self.assertEqual(res, True)\n\n def test_generate_split_sentences_pattern_3(self):\n ru = RegexUtils()\n pat = ru.generate_split_sentences_pattern()\n res = ru.match(pat, '? ')\n self.assertEqual(res, False)\n\n def test_generate_split_sentences_pattern_4(self):\n ru = RegexUtils()\n pat = ru.generate_split_sentences_pattern()\n res = ru.match(pat, '?Y')\n self.assertEqual(res, False)\n\n def test_generate_split_sentences_pattern_5(self):\n ru = RegexUtils()\n pat = ru.generate_split_sentences_pattern()\n res = ru.match(pat, '.Y')\n self.assertEqual(res, False)\n\n\nclass RegexUtilsTestSplitSentences(unittest.TestCase):\n def test_split_sentences_1(self):\n ru = RegexUtils()\n res = ru.split_sentences(\"Aaa. Bbbb? Ccc!\")\n self.assertEqual(res, ['Aaa', 'Bbbb', 'Ccc!'])\n\n def test_split_sentences_2(self):\n ru = RegexUtils()\n res = ru.split_sentences(\"Aaa.Bbbb? Ccc!\")\n self.assertEqual(res, ['Aaa.Bbbb', 'Ccc!'])\n\n def test_split_sentences_3(self):\n ru = RegexUtils()\n res = ru.split_sentences(\"Aaa. bbbb? Ccc!\")\n self.assertEqual(res, ['Aaa. bbbb', 'Ccc!'])\n\n def test_split_sentences_4(self):\n ru = RegexUtils()\n res = ru.split_sentences(\"Aaa. bbbb, Ccc!\")\n self.assertEqual(res, ['Aaa. bbbb, Ccc!'])\n\n def test_split_sentences_5(self):\n ru = RegexUtils()\n res = ru.split_sentences(\"Aaa, Bbbb? Ccc!\")\n self.assertEqual(res, ['Aaa, Bbbb', 'Ccc!'])\n\n\nclass RegexUtilsTestValidatePhoneNumber(unittest.TestCase):\n def test_validate_phone_number_1(self):\n ru = RegexUtils()\n res = ru.validate_phone_number(\"123-456-7890\")\n self.assertEqual(res, True)\n\n def test_validate_phone_number_2(self):\n ru = RegexUtils()\n res = ru.validate_phone_number(\"1234567890\")\n self.assertEqual(res, False)\n\n def test_validate_phone_number_3(self):\n ru = RegexUtils()\n res = ru.validate_phone_number(\"a23-456-7890\")\n self.assertEqual(res, False)\n\n def test_validate_phone_number_4(self):\n ru = RegexUtils()\n res = ru.validate_phone_number(\"123-456-789\")\n self.assertEqual(res, False)\n\n def test_validate_phone_number_5(self):\n ru = RegexUtils()\n res = ru.validate_phone_number(\"1234-56-789\")\n self.assertEqual(res, False)\n\n\nclass RegexUtilsTestExtractEmail(unittest.TestCase):\n def test_extract_email_1(self):\n ru = RegexUtils()\n res = ru.extract_email(\"abcdefg@163.com ygusyfysy@126.com wljduyuv@qq.com\")\n self.assertEqual(res, ['abcdefg@163.com', 'ygusyfysy@126.com', 'wljduyuv@qq.com'])\n\n def test_extract_email_2(self):\n ru = RegexUtils()\n res = ru.extract_email(\"abcdefg@.com ygusyfysy@126.com wljduyuv@qq.com\")\n self.assertEqual(res, ['ygusyfysy@126.com', 'wljduyuv@qq.com'])\n\n def test_extract_email_3(self):\n ru = RegexUtils()\n res = ru.extract_email(\"abcdefgiscom ygusyfysy@126.com wljduyuv@qq.com\")\n self.assertEqual(res, ['ygusyfysy@126.com', 'wljduyuv@qq.com'])\n\n def test_extract_email_4(self):\n ru = RegexUtils()\n res = ru.extract_email(\"abcdefgiscom ygusyfysy126.com wljduyuv@qq.com\")\n self.assertEqual(res, ['wljduyuv@qq.com'])\n\n def test_extract_email_5(self):\n ru = RegexUtils()\n res = ru.extract_email(\"abcdefgiscom ygusyfysy@.com wljduyuv@qq.com\")\n self.assertEqual(res, ['wljduyuv@qq.com'])\n\n\nclass RegexUtilsTest(unittest.TestCase):\n def test_regexutils(self):\n ru = RegexUtils()\n res = ru.match(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"123-456-7890\")\n self.assertEqual(res, True)\n\n res = ru.findall(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n self.assertEqual(res, ['123-456-7890', '876-286-9876', '987-762-9767'])\n\n res = ru.split(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n self.assertEqual(res, ['', ' abiguygusu ', ' kjgufwycs ', ''])\n\n res = ru.sub(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', 'phone num',\n \"123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n self.assertEqual(res, 'phone num abiguygusu phone num kjgufwycs phone num')\n\n pat = ru.generate_email_pattern()\n res = ru.match(pat, 'iustd87t2euh@163.com')\n self.assertEqual(res, True)\n\n pat = ru.generate_phone_number_pattern()\n res = ru.match(pat, '123-456-7890')\n self.assertEqual(res, True)\n\n pat = ru.generate_split_sentences_pattern()\n res = ru.match(pat, '? Y')\n self.assertEqual(res, True)\n\n res = ru.split_sentences(\"Aaa. Bbbb? Ccc!\")\n self.assertEqual(res, ['Aaa', 'Bbbb', 'Ccc!'])\n\n res = ru.validate_phone_number(\"123-456-7890\")\n self.assertEqual(res, True)\n\n res = ru.extract_email(\"abcdefg@163.com ygusyfysy@126.com wljduyuv@qq.com\")\n self.assertEqual(res, ['abcdefg@163.com', 'ygusyfysy@126.com', 'wljduyuv@qq.com'])", "solution_code": "import re\n\n\nclass RegexUtils:\n\n def match(self, pattern, text):\n ans = re.match(pattern, text)\n if ans:\n return True\n else:\n return False\n\n def findall(self, pattern, text):\n return re.findall(pattern, text)\n\n def split(self, pattern, text):\n return re.split(pattern, text)\n\n def sub(self, pattern, replacement, text):\n return re.sub(pattern, replacement, text)\n\n def generate_email_pattern(self):\n pattern = r'\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b'\n return pattern\n\n def generate_phone_number_pattern(self):\n pattern = r'\\b\\d{3}-\\d{3}-\\d{4}\\b'\n return pattern\n\n def generate_split_sentences_pattern(self):\n pattern = r'[.!?][\\s]{1,2}(?=[A-Z])'\n return pattern\n\n def split_sentences(self, text):\n pattern = self.generate_split_sentences_pattern()\n return self.split(pattern, text)\n\n def validate_phone_number(self, phone_number):\n pattern = self.generate_phone_number_pattern()\n return self.match(pattern, phone_number)\n\n def extract_email(self, text):\n pattern = self.generate_email_pattern()\n return self.findall(pattern, text)", "import_statement": [ "import re" ], "class_description": " \"\"\"\n The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses.\n \"\"\"\n", "class_name": "RegexUtils", "test_classes": [ "RegexUtilsTestMatch", "RegexUtilsTestFindall", "RegexUtilsTestSplit", "RegexUtilsTestSub", "RegexUtilsTestGenerateEmailPattern", "RegexUtilsTestGeneratePhoneNumberPattern", "RegexUtilsTestGenerateSplitSentencesPattern", "RegexUtilsTestSplitSentences", "RegexUtilsTestValidatePhoneNumber", "RegexUtilsTestExtractEmail", "RegexUtilsTest" ], "class_constructor": "class RegexUtils: \n", "fields": [], "methods_info": [ { "method_name": "match", "method_description": "def match(self, pattern, text):\n \"\"\"\n Check if the text matches the regular expression\n :param pattern: string, Regular expression pattern\n :param text: string, Text to match\n :return: True or False, representing whether the text matches the regular expression or not\n >>> ru = RegexUtils()\n >>> ru.match(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"123-456-7890\")\n True\n \"\"\"", "test_class": "RegexUtilsTestMatch", "test_code": "class RegexUtilsTestMatch(unittest.TestCase):\n def test_match_1(self):\n ru = RegexUtils()\n res = ru.match(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"123-456-7890\")\n self.assertEqual(res, True)\n\n def test_match_2(self):\n ru = RegexUtils()\n res = ru.match(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"1234567890\")\n self.assertEqual(res, False)\n\n def test_match_3(self):\n ru = RegexUtils()\n res = ru.match(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"111-111-1111\")\n self.assertEqual(res, True)\n\n def test_match_4(self):\n ru = RegexUtils()\n res = ru.match(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"123-456-789\")\n self.assertEqual(res, False)\n\n def test_match_5(self):\n ru = RegexUtils()\n res = ru.match(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"123-456-789a\")\n self.assertEqual(res, False)", "solution_code": "def match(self, pattern, text):\n ans = re.match(pattern, text)\n if ans:\n return True\n else:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [ "re" ], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "findall", "method_description": "def findall(self, pattern, text):\n \"\"\"\n Find all matching substrings and return a list of all matching substrings\n :param pattern: string, Regular expression pattern\n :param text: string, Text to match\n :return: list of string, List of all matching substrings\n >>> ru = RegexUtils()\n >>> ru.findall(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n ['123-456-7890', '876-286-9876', '987-762-9767']\n \"\"\"", "test_class": "RegexUtilsTestFindall", "test_code": "class RegexUtilsTestFindall(unittest.TestCase):\n def test_findall_1(self):\n ru = RegexUtils()\n res = ru.findall(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n self.assertEqual(res, ['123-456-7890', '876-286-9876', '987-762-9767'])\n\n def test_findall_2(self):\n ru = RegexUtils()\n res = ru.findall(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"abiguygusu kjgufwycs 987-762-9767\")\n self.assertEqual(res, ['987-762-9767'])\n\n def test_findall_3(self):\n ru = RegexUtils()\n res = ru.findall(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"abiguygusu kjgufwycs \")\n self.assertEqual(res, [])\n\n def test_findall_4(self):\n ru = RegexUtils()\n res = ru.findall(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"abiguygusu 111-111-1111 kjgufwycs 987-762-9767\")\n self.assertEqual(res, ['111-111-1111', '987-762-9767'])\n\n def test_findall_5(self):\n ru = RegexUtils()\n res = ru.findall(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"abiguygusu 111-111-111a kjgufwycs 987-762-9767\")\n self.assertEqual(res, ['987-762-9767'])", "solution_code": "def findall(self, pattern, text):\n return re.findall(pattern, text)", "dependencies": { "Standalone": false, "lib_dependencies": [ "re" ], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "split", "method_description": "def split(self, pattern, text):\n \"\"\"\n Split text based on regular expression patterns and return a list of substrings\n :param pattern: string, Regular expression pattern\n :param text: string, Text to be split\n :return: list of string, List of substrings after splitting\n >>> ru = RegexUtils()\n >>> ru.split(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n ['', ' abiguygusu ', ' kjgufwycs ', '']\n \"\"\"", "test_class": "RegexUtilsTestSplit", "test_code": "class RegexUtilsTestSplit(unittest.TestCase):\n def test_split_1(self):\n ru = RegexUtils()\n res = ru.split(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n self.assertEqual(res, ['', ' abiguygusu ', ' kjgufwycs ', ''])\n\n def test_split_2(self):\n ru = RegexUtils()\n res = ru.split(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"1234567890 abiguygusu 8762869876 kjgufwycs 9877629767\")\n self.assertEqual(res, ['1234567890 abiguygusu 8762869876 kjgufwycs 9877629767'])\n\n def test_split_3(self):\n ru = RegexUtils()\n res = ru.split(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"111-111-1111 abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n self.assertEqual(res, ['', ' abiguygusu ', ' kjgufwycs ', ''])\n\n def test_split_4(self):\n ru = RegexUtils()\n res = ru.split(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"123456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n self.assertEqual(res, ['123456-7890 abiguygusu ', ' kjgufwycs ', ''])\n\n def test_split_5(self):\n ru = RegexUtils()\n res = ru.split(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', \"123-456-789a abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n self.assertEqual(res, ['123-456-789a abiguygusu ', ' kjgufwycs ', ''])", "solution_code": "def split(self, pattern, text):\n return re.split(pattern, text)", "dependencies": { "Standalone": false, "lib_dependencies": [ "re" ], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "sub", "method_description": "def sub(self, pattern, replacement, text):\n \"\"\"\n Replace the substring matched by a regular expression with the specified string\n :param pattern: string, Regular expression pattern\n :param replacement: Text to replace with\n :param text: string, Text to be replaced\n :return: string, Text after replacement\n >>> ru = RegexUtils()\n >>> ru.sub(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', 'phone num', \"123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n 'phone num abiguygusu phone num kjgufwycs phone num'\n \"\"\"", "test_class": "RegexUtilsTestSub", "test_code": "class RegexUtilsTestSub(unittest.TestCase):\n def test_sub_1(self):\n ru = RegexUtils()\n res = ru.sub(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', 'phone num',\n \"123-456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n self.assertEqual(res, 'phone num abiguygusu phone num kjgufwycs phone num')\n\n def test_sub_2(self):\n ru = RegexUtils()\n res = ru.sub(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', 'phone num',\n \"1234567890 abiguygusu 8762869876 kjgufwycs 9877629767\")\n self.assertEqual(res, \"1234567890 abiguygusu 8762869876 kjgufwycs 9877629767\")\n\n def test_sub_3(self):\n ru = RegexUtils()\n res = ru.sub(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', 'phone num',\n \"123456-7890 abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n self.assertEqual(res, '123456-7890 abiguygusu phone num kjgufwycs phone num')\n\n def test_sub_4(self):\n ru = RegexUtils()\n res = ru.sub(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', 'phone num',\n \"123-456-789a abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n self.assertEqual(res, '123-456-789a abiguygusu phone num kjgufwycs phone num')\n\n def test_sub_5(self):\n ru = RegexUtils()\n res = ru.sub(r'\\b\\d{3}-\\d{3}-\\d{4}\\b', 'phone num',\n \"123-456-780 abiguygusu 876-286-9876 kjgufwycs 987-762-9767\")\n self.assertEqual(res, '123-456-780 abiguygusu phone num kjgufwycs phone num')", "solution_code": "def sub(self, pattern, replacement, text):\n return re.sub(pattern, replacement, text)", "dependencies": { "Standalone": false, "lib_dependencies": [ "re" ], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "generate_email_pattern", "method_description": "def generate_email_pattern(self):\n \"\"\"\n Generate regular expression patterns that match email addresses\n :return: string, regular expression patterns that match email addresses\n >>> ru = RegexUtils()\n >>> ru.generate_email_pattern()\n '\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b'\n \"\"\"", "test_class": "RegexUtilsTestGenerateEmailPattern", "test_code": "class RegexUtilsTestGenerateEmailPattern(unittest.TestCase):\n def test_generate_email_pattern_1(self):\n ru = RegexUtils()\n pat = ru.generate_email_pattern()\n res = ru.match(pat, 'iustd87t2euh@163.com')\n self.assertEqual(res, True)\n\n def test_generate_email_pattern_2(self):\n ru = RegexUtils()\n pat = ru.generate_email_pattern()\n res = ru.match(pat, 'iustd87t2euhifg.com')\n self.assertEqual(res, False)\n\n def test_generate_email_pattern_3(self):\n ru = RegexUtils()\n pat = ru.generate_email_pattern()\n res = ru.match(pat, 'iustd87t2euhifg@.com')\n self.assertEqual(res, False)\n\n def test_generate_email_pattern_4(self):\n ru = RegexUtils()\n pat = ru.generate_email_pattern()\n res = ru.match(pat, 'iustd87t2euhifg@.')\n self.assertEqual(res, False)\n\n def test_generate_email_pattern_5(self):\n ru = RegexUtils()\n pat = ru.generate_email_pattern()\n res = ru.match(pat, 'iustd87t2euhifg@com.')\n self.assertEqual(res, False)", "solution_code": "def generate_email_pattern(self):\n pattern = r'\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b'\n return pattern", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "generate_phone_number_pattern", "method_description": "def generate_phone_number_pattern(self):\n \"\"\"\n Generate regular expression patterns that match phone numbers\n :return: string, regular expression patterns that match phone numbers\n >>> ru = RegexUtils()\n >>> ru.generate_phone_number_pattern()\n '\\b\\d{3}-\\d{3}-\\d{4}\\b'\n \"\"\"", "test_class": "RegexUtilsTestGeneratePhoneNumberPattern", "test_code": "class RegexUtilsTestGeneratePhoneNumberPattern(unittest.TestCase):\n def test_generate_phone_number_pattern_1(self):\n ru = RegexUtils()\n pat = ru.generate_phone_number_pattern()\n res = ru.match(pat, '123-456-7890')\n self.assertEqual(res, True)\n\n def test_generate_phone_number_pattern_2(self):\n ru = RegexUtils()\n pat = ru.generate_phone_number_pattern()\n res = ru.match(pat, '1234567890')\n self.assertEqual(res, False)\n\n def test_generate_phone_number_pattern_3(self):\n ru = RegexUtils()\n pat = ru.generate_phone_number_pattern()\n res = ru.match(pat, '123-456-789')\n self.assertEqual(res, False)\n\n def test_generate_phone_number_pattern_4(self):\n ru = RegexUtils()\n pat = ru.generate_phone_number_pattern()\n res = ru.match(pat, 'a23-456-7890')\n self.assertEqual(res, False)\n\n def test_generate_phone_number_pattern_5(self):\n ru = RegexUtils()\n pat = ru.generate_phone_number_pattern()\n res = ru.match(pat, '1234-56-7890')\n self.assertEqual(res, False)", "solution_code": "def generate_phone_number_pattern(self):\n pattern = r'\\b\\d{3}-\\d{3}-\\d{4}\\b'\n return pattern", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "generate_split_sentences_pattern", "method_description": "def generate_split_sentences_pattern(self):\n \"\"\"\n Generate regular expression patterns that match the middle characters of two sentences\n :return: string, regular expression patterns that match the middle characters of two sentences\n >>> ru = RegexUtils()\n >>> ru.generate_split_sentences_pattern()\n '[.!?][\\s]{1,2}(?=[A-Z])'\n \"\"\"", "test_class": "RegexUtilsTestGenerateSplitSentencesPattern", "test_code": "class RegexUtilsTestGenerateSplitSentencesPattern(unittest.TestCase):\n def test_generate_split_sentences_pattern_1(self):\n ru = RegexUtils()\n pat = ru.generate_split_sentences_pattern()\n res = ru.match(pat, '? Y')\n self.assertEqual(res, True)\n\n def test_generate_split_sentences_pattern_2(self):\n ru = RegexUtils()\n pat = ru.generate_split_sentences_pattern()\n res = ru.match(pat, '! Y')\n self.assertEqual(res, True)\n\n def test_generate_split_sentences_pattern_3(self):\n ru = RegexUtils()\n pat = ru.generate_split_sentences_pattern()\n res = ru.match(pat, '? ')\n self.assertEqual(res, False)\n\n def test_generate_split_sentences_pattern_4(self):\n ru = RegexUtils()\n pat = ru.generate_split_sentences_pattern()\n res = ru.match(pat, '?Y')\n self.assertEqual(res, False)\n\n def test_generate_split_sentences_pattern_5(self):\n ru = RegexUtils()\n pat = ru.generate_split_sentences_pattern()\n res = ru.match(pat, '.Y')\n self.assertEqual(res, False)", "solution_code": "def generate_split_sentences_pattern(self):\n pattern = r'[.!?][\\s]{1,2}(?=[A-Z])'\n return pattern", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "split_sentences", "method_description": "def split_sentences(self, text):\n \"\"\"\n Split the text into a list of sentences without Punctuation except the last sentence\n :param text: Text to be split\n :return: Split Text List\n >>> ru = RegexUtils()\n >>> ru.split_sentences(\"Aaa. Bbbb? Ccc!\")\n ['Aaa', 'Bbbb', 'Ccc!']\n \"\"\"", "test_class": "RegexUtilsTestSplitSentences", "test_code": "class RegexUtilsTestSplitSentences(unittest.TestCase):\n def test_split_sentences_1(self):\n ru = RegexUtils()\n res = ru.split_sentences(\"Aaa. Bbbb? Ccc!\")\n self.assertEqual(res, ['Aaa', 'Bbbb', 'Ccc!'])\n\n def test_split_sentences_2(self):\n ru = RegexUtils()\n res = ru.split_sentences(\"Aaa.Bbbb? Ccc!\")\n self.assertEqual(res, ['Aaa.Bbbb', 'Ccc!'])\n\n def test_split_sentences_3(self):\n ru = RegexUtils()\n res = ru.split_sentences(\"Aaa. bbbb? Ccc!\")\n self.assertEqual(res, ['Aaa. bbbb', 'Ccc!'])\n\n def test_split_sentences_4(self):\n ru = RegexUtils()\n res = ru.split_sentences(\"Aaa. bbbb, Ccc!\")\n self.assertEqual(res, ['Aaa. bbbb, Ccc!'])\n\n def test_split_sentences_5(self):\n ru = RegexUtils()\n res = ru.split_sentences(\"Aaa, Bbbb? Ccc!\")\n self.assertEqual(res, ['Aaa, Bbbb', 'Ccc!'])", "solution_code": "def split_sentences(self, text):\n pattern = self.generate_split_sentences_pattern()\n return self.split(pattern, text)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "split", "generate_split_sentences_pattern" ] } }, { "method_name": "validate_phone_number", "method_description": "def validate_phone_number(self, phone_number):\n \"\"\"\n Verify if the phone number is valid\n :param phone_number: Phone number to be verified\n :return: True or False, indicating whether the phone number is valid\n >>> ru = RegexUtils()\n >>> ru.validate_phone_number(\"123-456-7890\")\n True\n \"\"\"", "test_class": "RegexUtilsTestValidatePhoneNumber", "test_code": "class RegexUtilsTestValidatePhoneNumber(unittest.TestCase):\n def test_validate_phone_number_1(self):\n ru = RegexUtils()\n res = ru.validate_phone_number(\"123-456-7890\")\n self.assertEqual(res, True)\n\n def test_validate_phone_number_2(self):\n ru = RegexUtils()\n res = ru.validate_phone_number(\"1234567890\")\n self.assertEqual(res, False)\n\n def test_validate_phone_number_3(self):\n ru = RegexUtils()\n res = ru.validate_phone_number(\"a23-456-7890\")\n self.assertEqual(res, False)\n\n def test_validate_phone_number_4(self):\n ru = RegexUtils()\n res = ru.validate_phone_number(\"123-456-789\")\n self.assertEqual(res, False)\n\n def test_validate_phone_number_5(self):\n ru = RegexUtils()\n res = ru.validate_phone_number(\"1234-56-789\")\n self.assertEqual(res, False)", "solution_code": "def validate_phone_number(self, phone_number):\n pattern = self.generate_phone_number_pattern()\n return self.match(pattern, phone_number)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "match", "generate_phone_number_pattern" ] } }, { "method_name": "extract_email", "method_description": "def extract_email(self, text):\n \"\"\"\n Extract all email addresses from the text\n :param text: string, input text\n :return: list of string, All extracted email addresses\n >>> ru = RegexUtils()\n >>> ru.extract_email(\"abcdefg@163.com ygusyfysy@126.com wljduyuv@qq.com\")\n ['abcdefg@163.com', 'ygusyfysy@126.com', 'wljduyuv@qq.com']\n \"\"\"", "test_class": "RegexUtilsTestExtractEmail", "test_code": "class RegexUtilsTestExtractEmail(unittest.TestCase):\n def test_extract_email_1(self):\n ru = RegexUtils()\n res = ru.extract_email(\"abcdefg@163.com ygusyfysy@126.com wljduyuv@qq.com\")\n self.assertEqual(res, ['abcdefg@163.com', 'ygusyfysy@126.com', 'wljduyuv@qq.com'])\n\n def test_extract_email_2(self):\n ru = RegexUtils()\n res = ru.extract_email(\"abcdefg@.com ygusyfysy@126.com wljduyuv@qq.com\")\n self.assertEqual(res, ['ygusyfysy@126.com', 'wljduyuv@qq.com'])\n\n def test_extract_email_3(self):\n ru = RegexUtils()\n res = ru.extract_email(\"abcdefgiscom ygusyfysy@126.com wljduyuv@qq.com\")\n self.assertEqual(res, ['ygusyfysy@126.com', 'wljduyuv@qq.com'])\n\n def test_extract_email_4(self):\n ru = RegexUtils()\n res = ru.extract_email(\"abcdefgiscom ygusyfysy126.com wljduyuv@qq.com\")\n self.assertEqual(res, ['wljduyuv@qq.com'])\n\n def test_extract_email_5(self):\n ru = RegexUtils()\n res = ru.extract_email(\"abcdefgiscom ygusyfysy@.com wljduyuv@qq.com\")\n self.assertEqual(res, ['wljduyuv@qq.com'])", "solution_code": "def extract_email(self, text):\n pattern = self.generate_email_pattern()\n return self.findall(pattern, text)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "findall", "generate_email_pattern" ] } } ] }, { "task_id": "ClassEval_73", "skeleton": "\nclass RPGCharacter:\n \"\"\"\n The class represents a role-playing game character, which allows to attack other characters, heal, gain experience, level up, and check if the character is alive.\n \"\"\"\n\n def __init__(self, name, hp, attack_power, defense, level=1):\n \"\"\"\n Initialize an RPG character object.\n :param name: strm, the name of the character.\n :param hp: int, The health points of the character.\n :param attack_power: int, the attack power of the character.\n :param defense: int, the defense points of the character.\n :param level: int, the level of the character. Default is 1.\n \"\"\"\n self.name = name\n self.hp = hp\n self.attack_power = attack_power\n self.defense = defense\n self.level = level\n self.exp = 0\n\n def attack(self, other_character):\n \"\"\"\n Attack another character. The damage caused needs to offset the defense value.\n :param other_character: str, The character being attacked.\n >>> player_1 = RPGCharacter('player 1', 100, 10, 3)\n >>> player_2 = RPGCharacter('player 2', 100, 7, 2)\n >>> player_1.attack(player_2)\n >>> player_2.hp\n 92\n \"\"\"\n\n def heal(self):\n \"\"\"\n Heal the character with 10 hp and the max hp is 100.\n :return: int, the current health points after healing.\n >>> player_1 = RPGCharacter('player 1', 93, 10, 3)\n >>> player_1.heal()\n 100\n \"\"\"\n\n def gain_exp(self, amount):\n \"\"\"\n Gain experience points for the character and level_up when the exp has reached the values that is 100 times the current level\n The experience that overflows should be used to calculate the next leve up untill exhausts\n :param amount: int, the amount of experience points to gain.\n >>> player_1 = RPGCharacter('player 1', 100, 10, 3)\n >>> player_1.gain_exp(1100)\n >>> player_1.exp\n 100\n >>> player_1.level\n 5\n \"\"\"\n\n def level_up(self):\n \"\"\"\n Level up the character and return to zero experience points, increase hp by 20 points, attack power and defense points by 5 points.\n max level is 100\n :return: tuple[int, int, int, int], the new level, health points, attack power, and defense points after leveling up.\n >>> player_1 = RPGCharacter('player 1', 100, 10, 3)\n >>> player_1.level_up()\n (2, 120, 15, 8)\n \"\"\"\n\n def is_alive(self):\n \"\"\"\n Check if player is alive.\n :return: True if the hp is larger than 0, or False otherwise.\n >>> player_1 = RPGCharacter('player 1', 100, 10, 3)\n >>> player_1.is_alive()\n True\n \"\"\"", "test": "import unittest\n\nclass RPGCharacterTestAttack(unittest.TestCase):\n def test_attack(self):\n character1 = RPGCharacter(\"John\", 100, 20, 10)\n character2 = RPGCharacter(\"Enemy\", 100, 15, 5)\n character1.attack(character2)\n self.assertEqual(character2.hp, 85)\n\n def test_attack_2(self):\n character1 = RPGCharacter(\"John\", 100, 20, 10)\n character2 = RPGCharacter(\"Enemy\", 100, 15, 5)\n character2.attack(character1)\n self.assertEqual(character1.hp, 95)\n\n def test_attack_3(self):\n character1 = RPGCharacter(\"John\", 100, 20, 10)\n character2 = RPGCharacter(\"Enemy\", 100, 15, 5)\n character1.attack(character2)\n character2.attack(character1)\n self.assertEqual(character1.hp, 95)\n self.assertEqual(character2.hp, 85)\n\n def test_attack_4(self):\n character1 = RPGCharacter(\"John\", 100, 20, 10)\n character2 = RPGCharacter(\"Enemy\", 100, 15, 5)\n character1.attack(character2)\n character1.attack(character2)\n self.assertEqual(character2.hp, 70)\n\n def test_attack_5(self):\n character1 = RPGCharacter(\"John\", 100, 20, 10)\n character2 = RPGCharacter(\"Enemy\", 100, 15, 5)\n character1.attack(character2)\n character1.attack(character2)\n character1.attack(character2)\n self.assertEqual(character2.hp, 55)\n\nclass RPGCharacterTestHeal(unittest.TestCase):\n def test_heal_1(self):\n character = RPGCharacter(\"John\", 90, 20, 10)\n character.heal()\n self.assertEqual(character.hp, 100)\n\n # overflow healing \n def test_heal_2(self):\n character = RPGCharacter(\"John\", 97, 20, 10)\n character.heal()\n self.assertEqual(character.hp, 100)\n\n def test_heal_3(self):\n character = RPGCharacter(\"John\", 100, 20, 10)\n character.heal()\n self.assertEqual(character.hp, 100)\n\n def test_heal_4(self):\n character = RPGCharacter(\"John\", 100, 20, 10)\n character.hp = 50\n character.heal()\n self.assertEqual(character.hp, 60)\n\n def test_heal_5(self):\n character = RPGCharacter(\"John\", 100, 20, 10)\n character.hp = 10\n character.heal()\n self.assertEqual(character.hp, 20)\n\n\nclass RPGCharacterTestGainExp(unittest.TestCase):\n\n # exp not overflow\n def test_gain_exp_1(self):\n character = RPGCharacter(\"John\", 100, 20, 10)\n character.gain_exp(100)\n self.assertEqual(character.level, 2)\n self.assertEqual(character.exp, 0)\n\n # exp overflow\n def test_gain_exp_2(self):\n character = RPGCharacter(\"John\", 100, 20, 10)\n character.gain_exp(1100)\n self.assertEqual(character.level, 5)\n self.assertEqual(character.exp, 100)\n\n def test_gain_exp_3(self):\n character = RPGCharacter(\"John\", 100, 20, 10)\n character.gain_exp(200)\n self.assertEqual(character.level, 2)\n self.assertEqual(character.exp, 100)\n\n def test_gain_exp_4(self):\n character = RPGCharacter(\"John\", 100, 20, 10)\n character.gain_exp(300)\n self.assertEqual(character.level, 3)\n self.assertEqual(character.exp, 0)\n\n def test_gain_exp_5(self):\n character = RPGCharacter(\"John\", 100, 20, 10)\n character.gain_exp(400)\n self.assertEqual(character.level, 3)\n self.assertEqual(character.exp, 100)\n\n\nclass RPGCharacterTestLevelUp(unittest.TestCase):\n def test_level_up_1(self):\n character = RPGCharacter(\"John\", 100, 20, 10)\n character.level_up()\n self.assertEqual(character.level, 2)\n self.assertEqual(character.exp, 0)\n self.assertEqual(character.hp, 120)\n self.assertEqual(character.attack_power, 25)\n self.assertEqual(character.defense, 15)\n\n # full level\n def test_level_up_2(self):\n character = RPGCharacter(\"John\", 100, 20, 10, 100)\n character.level_up()\n self.assertEqual(character.level, 100)\n self.assertEqual(character.exp, 0)\n self.assertEqual(character.hp, 100)\n self.assertEqual(character.attack_power, 20)\n self.assertEqual(character.defense, 10)\n\n def test_level_up_3(self):\n character = RPGCharacter(\"John\", 100, 20, 10, 2)\n character.level_up()\n self.assertEqual(character.level, 3)\n self.assertEqual(character.exp, 0)\n self.assertEqual(character.hp, 120)\n self.assertEqual(character.attack_power, 25)\n self.assertEqual(character.defense, 15)\n\n def test_level_up_4(self):\n character = RPGCharacter(\"John\", 100, 20, 10, 3)\n character.level_up()\n self.assertEqual(character.level, 4)\n self.assertEqual(character.exp, 0)\n self.assertEqual(character.hp, 120)\n self.assertEqual(character.attack_power, 25)\n self.assertEqual(character.defense, 15)\n\n def test_level_up_5(self):\n character = RPGCharacter(\"John\", 100, 20, 10, 4)\n character.level_up()\n self.assertEqual(character.level, 5)\n self.assertEqual(character.exp, 0)\n self.assertEqual(character.hp, 120)\n self.assertEqual(character.attack_power, 25)\n self.assertEqual(character.defense, 15)\n\n\nclass RPGCharacterTestIsAlive(unittest.TestCase):\n def test_is_alive_1(self):\n character = RPGCharacter(\"John\", 100, 20, 10)\n self.assertTrue(character.is_alive())\n\n def test_is_alive_2(self):\n character = RPGCharacter(\"John\", 0, 20, 10)\n self.assertFalse(character.is_alive())\n\n def test_is_alive_3(self):\n character = RPGCharacter(\"John\", -10, 20, 10)\n self.assertFalse(character.is_alive())\n\n def test_is_alive_4(self):\n character = RPGCharacter(\"John\", 1, 20, 10)\n self.assertTrue(character.is_alive())\n\n def test_is_alive_5(self):\n character = RPGCharacter(\"John\", 10, 20, 10)\n self.assertTrue(character.is_alive())\n\nclass RPGCharacterTestMain(unittest.TestCase):\n def test_main(self):\n character1 = RPGCharacter(\"John\", 100, 20, 10)\n character2 = RPGCharacter(\"Enemy\", 100, 15, 5)\n character1.attack(character2)\n self.assertEqual(character2.hp, 85)\n character2.heal()\n self.assertEqual(character2.hp, 95)\n character1.gain_exp(200)\n self.assertEqual(character1.exp, 100)\n self.assertEqual(character1.hp, 120)\n self.assertEqual(character1.attack_power, 25)\n self.assertEqual(character1.defense, 15)\n self.assertTrue(character1.is_alive())", "solution_code": "class RPGCharacter:\n def __init__(self, name, hp, attack_power, defense, level=1):\n self.name = name\n self.hp = hp\n self.attack_power = attack_power\n self.defense = defense\n self.level = level\n self.exp = 0\n\n def attack(self, other_character):\n damage = max(self.attack_power - other_character.defense, 1)\n other_character.hp -= damage\n\n def heal(self):\n self.hp += 10\n if self.hp > 100:\n self.hp = 100\n return self.hp\n\n def gain_exp(self, amount):\n while amount != 0:\n if self.exp + amount >= self.level * 100:\n amount -= (self.level * 100 - self.exp)\n self.level_up()\n else:\n self.exp += amount\n amount = 0\n\n def level_up(self):\n if self.level < 100:\n self.level += 1\n self.exp = 0\n self.hp += 20\n self.attack_power += 5\n self.defense += 5\n return self.level, self.hp, self.attack_power, self.defense\n\n def is_alive(self):\n return self.hp > 0", "import_statement": [], "class_description": " \"\"\"\n The class represents a role-playing game character, which allows to attack other characters, heal, gain experience, level up, and check if the character is alive.\n \"\"\"\n", "class_name": "RPGCharacter", "test_classes": [ "RPGCharacterTestAttack", "RPGCharacterTestHeal", "RPGCharacterTestGainExp", "RPGCharacterTestLevelUp", "RPGCharacterTestIsAlive", "RPGCharacterTestMain" ], "class_constructor": "class RPGCharacter: \n def __init__(self, name, hp, attack_power, defense, level=1):\n \"\"\"\n Initialize an RPG character object.\n :param name: strm, the name of the character.\n :param hp: int, The health points of the character.\n :param attack_power: int, the attack power of the character.\n :param defense: int, the defense points of the character.\n :param level: int, the level of the character. Default is 1.\n \"\"\"\n self.name = name\n self.hp = hp\n self.attack_power = attack_power\n self.defense = defense\n self.level = level\n self.exp = 0\n\n", "fields": [ "self.attack_power", "self.defense", "self.exp", "self.hp", "self.level", "self.name" ], "methods_info": [ { "method_name": "attack", "method_description": "def attack(self, other_character):\n \"\"\"\n Attack another character. The damage caused needs to offset the defense value.\n :param other_character: str, The character being attacked.\n >>> player_1 = RPGCharacter('player 1', 100, 10, 3)\n >>> player_2 = RPGCharacter('player 2', 100, 7, 2)\n >>> player_1.attack(player_2)\n >>> player_2.hp\n 92\n \"\"\"", "test_class": "RPGCharacterTestAttack", "test_code": "class RPGCharacterTestAttack(unittest.TestCase):\n def test_attack(self):\n character1 = RPGCharacter(\"John\", 100, 20, 10)\n character2 = RPGCharacter(\"Enemy\", 100, 15, 5)\n character1.attack(character2)\n self.assertEqual(character2.hp, 85)\n\n def test_attack_2(self):\n character1 = RPGCharacter(\"John\", 100, 20, 10)\n character2 = RPGCharacter(\"Enemy\", 100, 15, 5)\n character2.attack(character1)\n self.assertEqual(character1.hp, 95)\n\n def test_attack_3(self):\n character1 = RPGCharacter(\"John\", 100, 20, 10)\n character2 = RPGCharacter(\"Enemy\", 100, 15, 5)\n character1.attack(character2)\n character2.attack(character1)\n self.assertEqual(character1.hp, 95)\n self.assertEqual(character2.hp, 85)\n\n def test_attack_4(self):\n character1 = RPGCharacter(\"John\", 100, 20, 10)\n character2 = RPGCharacter(\"Enemy\", 100, 15, 5)\n character1.attack(character2)\n character1.attack(character2)\n self.assertEqual(character2.hp, 70)\n\n def test_attack_5(self):\n character1 = RPGCharacter(\"John\", 100, 20, 10)\n character2 = RPGCharacter(\"Enemy\", 100, 15, 5)\n character1.attack(character2)\n character1.attack(character2)\n character1.attack(character2)\n self.assertEqual(character2.hp, 55)", "solution_code": "def attack(self, other_character):\n damage = max(self.attack_power - other_character.defense, 1)\n other_character.hp -= damage", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.attack_power" ], "method_dependencies": [] } }, { "method_name": "heal", "method_description": "def heal(self):\n \"\"\"\n Heal the character with 10 hp and the max hp is 100.\n :return: int, the current health points after healing.\n >>> player_1 = RPGCharacter('player 1', 93, 10, 3)\n >>> player_1.heal()\n 100\n \"\"\"", "test_class": "RPGCharacterTestHeal", "test_code": "class RPGCharacterTestHeal(unittest.TestCase):\n def test_heal_1(self):\n character = RPGCharacter(\"John\", 90, 20, 10)\n character.heal()\n self.assertEqual(character.hp, 100)\n\n # overflow healing \n def test_heal_2(self):\n character = RPGCharacter(\"John\", 97, 20, 10)\n character.heal()\n self.assertEqual(character.hp, 100)\n\n def test_heal_3(self):\n character = RPGCharacter(\"John\", 100, 20, 10)\n character.heal()\n self.assertEqual(character.hp, 100)\n\n def test_heal_4(self):\n character = RPGCharacter(\"John\", 100, 20, 10)\n character.hp = 50\n character.heal()\n self.assertEqual(character.hp, 60)\n\n def test_heal_5(self):\n character = RPGCharacter(\"John\", 100, 20, 10)\n character.hp = 10\n character.heal()\n self.assertEqual(character.hp, 20)", "solution_code": "def heal(self):\n self.hp += 10\n if self.hp > 100:\n self.hp = 100\n return self.hp", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.hp" ], "method_dependencies": [] } }, { "method_name": "gain_exp", "method_description": "def gain_exp(self, amount):\n \"\"\"\n Gain experience points for the character and level_up when the exp has reached the values that is 100 times the current level\n The experience that overflows should be used to calculate the next leve up untill exhausts\n :param amount: int, the amount of experience points to gain.\n >>> player_1 = RPGCharacter('player 1', 100, 10, 3)\n >>> player_1.gain_exp(1100)\n >>> player_1.exp\n 100\n >>> player_1.level\n 5\n \"\"\"", "test_class": "RPGCharacterTestGainExp", "test_code": "class RPGCharacterTestGainExp(unittest.TestCase):\n\n # exp not overflow\n def test_gain_exp_1(self):\n character = RPGCharacter(\"John\", 100, 20, 10)\n character.gain_exp(100)\n self.assertEqual(character.level, 2)\n self.assertEqual(character.exp, 0)\n\n # exp overflow\n def test_gain_exp_2(self):\n character = RPGCharacter(\"John\", 100, 20, 10)\n character.gain_exp(1100)\n self.assertEqual(character.level, 5)\n self.assertEqual(character.exp, 100)\n\n def test_gain_exp_3(self):\n character = RPGCharacter(\"John\", 100, 20, 10)\n character.gain_exp(200)\n self.assertEqual(character.level, 2)\n self.assertEqual(character.exp, 100)\n\n def test_gain_exp_4(self):\n character = RPGCharacter(\"John\", 100, 20, 10)\n character.gain_exp(300)\n self.assertEqual(character.level, 3)\n self.assertEqual(character.exp, 0)\n\n def test_gain_exp_5(self):\n character = RPGCharacter(\"John\", 100, 20, 10)\n character.gain_exp(400)\n self.assertEqual(character.level, 3)\n self.assertEqual(character.exp, 100)", "solution_code": "def gain_exp(self, amount):\n while amount != 0:\n if self.exp + amount >= self.level * 100:\n amount -= (self.level * 100 - self.exp)\n self.level_up()\n else:\n self.exp += amount\n amount = 0", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.exp", "self.level" ], "method_dependencies": [ "level_up" ] } }, { "method_name": "level_up", "method_description": "def level_up(self):\n \"\"\"\n Level up the character and return to zero experience points, increase hp by 20 points, attack power and defense points by 5 points.\n max level is 100\n :return: tuple[int, int, int, int], the new level, health points, attack power, and defense points after leveling up.\n >>> player_1 = RPGCharacter('player 1', 100, 10, 3)\n >>> player_1.level_up()\n (2, 120, 15, 8)\n \"\"\"", "test_class": "RPGCharacterTestLevelUp", "test_code": "class RPGCharacterTestLevelUp(unittest.TestCase):\n def test_level_up_1(self):\n character = RPGCharacter(\"John\", 100, 20, 10)\n character.level_up()\n self.assertEqual(character.level, 2)\n self.assertEqual(character.exp, 0)\n self.assertEqual(character.hp, 120)\n self.assertEqual(character.attack_power, 25)\n self.assertEqual(character.defense, 15)\n\n # full level\n def test_level_up_2(self):\n character = RPGCharacter(\"John\", 100, 20, 10, 100)\n character.level_up()\n self.assertEqual(character.level, 100)\n self.assertEqual(character.exp, 0)\n self.assertEqual(character.hp, 100)\n self.assertEqual(character.attack_power, 20)\n self.assertEqual(character.defense, 10)\n\n def test_level_up_3(self):\n character = RPGCharacter(\"John\", 100, 20, 10, 2)\n character.level_up()\n self.assertEqual(character.level, 3)\n self.assertEqual(character.exp, 0)\n self.assertEqual(character.hp, 120)\n self.assertEqual(character.attack_power, 25)\n self.assertEqual(character.defense, 15)\n\n def test_level_up_4(self):\n character = RPGCharacter(\"John\", 100, 20, 10, 3)\n character.level_up()\n self.assertEqual(character.level, 4)\n self.assertEqual(character.exp, 0)\n self.assertEqual(character.hp, 120)\n self.assertEqual(character.attack_power, 25)\n self.assertEqual(character.defense, 15)\n\n def test_level_up_5(self):\n character = RPGCharacter(\"John\", 100, 20, 10, 4)\n character.level_up()\n self.assertEqual(character.level, 5)\n self.assertEqual(character.exp, 0)\n self.assertEqual(character.hp, 120)\n self.assertEqual(character.attack_power, 25)\n self.assertEqual(character.defense, 15)", "solution_code": "def level_up(self):\n if self.level < 100:\n self.level += 1\n self.exp = 0\n self.hp += 20\n self.attack_power += 5\n self.defense += 5\n return self.level, self.hp, self.attack_power, self.defense", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.attack_power", "self.defense", "self.exp", "self.hp", "self.level" ], "method_dependencies": [ "attack" ] } }, { "method_name": "is_alive", "method_description": "def is_alive(self):\n \"\"\"\n Check if player is alive.\n :return: True if the hp is larger than 0, or False otherwise.\n >>> player_1 = RPGCharacter('player 1', 100, 10, 3)\n >>> player_1.is_alive()\n True\n \"\"\"", "test_class": "RPGCharacterTestIsAlive", "test_code": "class RPGCharacterTestIsAlive(unittest.TestCase):\n def test_is_alive_1(self):\n character = RPGCharacter(\"John\", 100, 20, 10)\n self.assertTrue(character.is_alive())\n\n def test_is_alive_2(self):\n character = RPGCharacter(\"John\", 0, 20, 10)\n self.assertFalse(character.is_alive())\n\n def test_is_alive_3(self):\n character = RPGCharacter(\"John\", -10, 20, 10)\n self.assertFalse(character.is_alive())\n\n def test_is_alive_4(self):\n character = RPGCharacter(\"John\", 1, 20, 10)\n self.assertTrue(character.is_alive())\n\n def test_is_alive_5(self):\n character = RPGCharacter(\"John\", 10, 20, 10)\n self.assertTrue(character.is_alive())", "solution_code": "def is_alive(self):\n return self.hp > 0", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.hp" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_74", "skeleton": "\nclass Server:\n \"\"\"\n This is a class as a server, which handles a white list, message sending and receiving, and information display.\n \"\"\"\n\n\n def __init__(self):\n \"\"\"\n Initialize the whitelist as an empty list, and initialize the sending and receiving information as an empty dictionary\n \"\"\"\n self.white_list = []\n self.send_struct = {}\n self.receive_struct = {}\n\n\n\n def add_white_list(self, addr):\n \"\"\"\n Add an address to the whitelist and do nothing if it already exists\n :param addr: int, address to be added\n :return: new whitelist, return False if the address already exists\n >>> server = Server()\n >>> server.add_white_list(88)\n [88]\n \"\"\"\n\n def del_white_list(self, addr):\n \"\"\"\n Remove an address from the whitelist and do nothing if it does not exist\n :param addr: int, address to be deleted\n :return: new whitelist, return False if the address does not exist\n >>> server.add_white_list(88)\n >>> server.del_white_list(88)\n []\n \"\"\"\n\n def recv(self, info):\n \"\"\"\n Receive information containing address and content. If the address is on the whitelist, receive the content; otherwise, do not receive it\n :param info: dict, information dictionary containing address and content\n :return: if successfully received, return the content of the infomation; otherwise, return False\n >>> server.recv({\"addr\":88,\"content\":\"abc\"})\n abc\n \"\"\"\n\n def send(self, info):\n \"\"\"\n Send information containing address and content\n :param info: dict, information dictionary containing address and content\n :return: if successfully sent, return nothing; otherwise, return a string indicating an error message\n >>> server.send({\"addr\":66,\"content\":\"ABC\"})\n self.send_struct = {\"addr\":66,\"content\":\"ABC\"}\n \"\"\"\n\n def show(self, type):\n \"\"\"\n Returns struct of the specified type\n :param type: string, the type of struct to be returned, which can be 'send' or 'receive'\n :return: if type is equal to 'send' or 'receive', return the corresponding struct; otherwise, return False\n >>> server.recv({\"addr\":88,\"content\":\"abc\"})\n >>> server.send({\"addr\":66,\"content\":\"ABC\"})\n >>> server.show(\"send\")\n {\"addr\":66,\"content\":\"ABC\"}\n \"\"\"", "test": "import unittest\n\n\nclass ServerTestAddWhiteList(unittest.TestCase):\n def test_add_white_list_1(self):\n server = Server()\n server.add_white_list(88)\n self.assertEqual(server.white_list, [88])\n\n def test_add_white_list_2(self):\n server = Server()\n server.add_white_list(88)\n self.assertEqual(server.add_white_list(88), False)\n\n def test_add_white_list_3(self):\n server = Server()\n server.add_white_list(88)\n server.add_white_list(11)\n self.assertEqual(server.add_white_list(11), False)\n\n def test_add_white_list_4(self):\n server = Server()\n server.add_white_list(11)\n self.assertEqual(server.white_list, [11])\n\n def test_add_white_list_5(self):\n server = Server()\n server.add_white_list(88)\n server.add_white_list(11)\n server.add_white_list(22)\n self.assertEqual(server.add_white_list(22), False)\n\n\nclass ServerTestDelWhiteList(unittest.TestCase):\n def test_del_white_list_1(self):\n server = Server()\n server.add_white_list(88)\n server.del_white_list(88)\n self.assertEqual(server.white_list, [])\n\n def test_del_white_list_2(self):\n server = Server()\n self.assertEqual(server.del_white_list(88), False)\n\n def test_del_white_list_3(self):\n server = Server()\n self.assertEqual(server.del_white_list(11), False)\n\n def test_del_white_list_4(self):\n server = Server()\n self.assertEqual(server.del_white_list(22), False)\n\n def test_del_white_list_5(self):\n server = Server()\n server.add_white_list(11)\n self.assertEqual(server.del_white_list(22), False)\n\n\nclass ServerTestRecv(unittest.TestCase):\n def test_recv_1(self):\n server = Server()\n server.add_white_list(88)\n server.recv({\"addr\": 88, \"content\": \"abc\"})\n self.assertEqual(server.receive_struct, {\"addr\": 88, \"content\": \"abc\"})\n\n def test_recv_2(self):\n server = Server()\n server.add_white_list(88)\n flag = server.recv({\"addr\": 66, \"content\": \"abc\"})\n self.assertEqual(server.receive_struct, {})\n self.assertEqual(flag, False)\n\n def test_recv_3(self):\n server = Server()\n flag = server.recv([88])\n self.assertEqual(server.receive_struct, {})\n self.assertEqual(flag, -1)\n\n def test_recv_4(self):\n server = Server()\n flag = server.recv({\"addr\": 88})\n self.assertEqual(server.receive_struct, {})\n self.assertEqual(flag, -1)\n\n def test_recv_5(self):\n server = Server()\n flag = server.recv({\"content\": \"abc\"})\n self.assertEqual(server.receive_struct, {})\n self.assertEqual(flag, -1)\n\n\nclass ServerTestSend(unittest.TestCase):\n def test_send_1(self):\n server = Server()\n server.send({\"addr\": 88, \"content\": \"abc\"})\n self.assertEqual(server.send_struct, {\"addr\": 88, \"content\": \"abc\"})\n\n def test_send_2(self):\n server = Server()\n flag = server.send({\"addr\": 88})\n self.assertEqual(flag, \"info structure is not correct\")\n\n def test_send_3(self):\n server = Server()\n flag = server.send({\"content\": \"abc\"})\n self.assertEqual(flag, \"info structure is not correct\")\n\n def test_send_4(self):\n server = Server()\n flag = server.send([])\n self.assertEqual(flag, \"info structure is not correct\")\n\n def test_send_5(self):\n server = Server()\n server.send({\"addr\": 66, \"content\": \"abc\"})\n self.assertEqual(server.send_struct, {\"addr\": 66, \"content\": \"abc\"})\n\n\nclass ServerTestShow(unittest.TestCase):\n def test_show_1(self):\n server = Server()\n server.add_white_list(66)\n server.send({\"addr\": 88, \"content\": \"abc\"})\n server.recv({\"addr\": 66, \"content\": \"ABC\"})\n self.assertEqual(server.show(\"send\"), {\"addr\": 88, \"content\": \"abc\"})\n\n def test_show_2(self):\n server = Server()\n server.add_white_list(66)\n server.send({\"addr\": 88, \"content\": \"abc\"})\n server.recv({\"addr\": 66, \"content\": \"ABC\"})\n self.assertEqual(server.show(\"receive\"), {\"addr\": 66, \"content\": \"ABC\"})\n\n def test_show_3(self):\n server = Server()\n server.add_white_list(66)\n server.send({\"addr\": 88, \"content\": \"abc\"})\n server.recv({\"addr\": 66, \"content\": \"ABC\"})\n self.assertEqual(server.show(\"abcdefg\"), False)\n\n def test_show_4(self):\n server = Server()\n server.add_white_list(66)\n server.send({\"addr\": 11, \"content\": \"abc\"})\n server.recv({\"addr\": 66, \"content\": \"ABC\"})\n self.assertEqual(server.show(\"send\"), {\"addr\": 11, \"content\": \"abc\"})\n\n def test_show_5(self):\n server = Server()\n server.add_white_list(66)\n server.send({\"addr\": 22, \"content\": \"abc\"})\n server.recv({\"addr\": 66, \"content\": \"ABC\"})\n self.assertEqual(server.show(\"send\"), {\"addr\": 22, \"content\": \"abc\"})\n\n\nclass ServerTest(unittest.TestCase):\n def test_server(self):\n server = Server()\n server.add_white_list(88)\n self.assertEqual(server.white_list, [88])\n server.del_white_list(88)\n self.assertEqual(server.white_list, [])\n server.add_white_list(88)\n server.recv({\"addr\": 88, \"content\": \"abc\"})\n self.assertEqual(server.receive_struct, {\"addr\": 88, \"content\": \"abc\"})\n server.send({\"addr\": 66, \"content\": \"ABC\"})\n self.assertEqual(server.send_struct, {\"addr\": 66, \"content\": \"ABC\"})\n server.recv({\"addr\": 88, \"content\": \"abc\"})\n self.assertEqual(server.show(\"receive\"), {\"addr\": 88, \"content\": \"abc\"})", "solution_code": "class Server:\n\n def __init__(self):\n self.white_list = []\n self.send_struct = {}\n self.receive_struct = {}\n\n def add_white_list(self, addr):\n if addr in self.white_list:\n return False\n else:\n self.white_list.append(addr)\n return self.white_list\n\n def del_white_list(self, addr):\n if addr not in self.white_list:\n return False\n else:\n self.white_list.remove(addr)\n return self.white_list\n\n def recv(self, info):\n if not isinstance(info, dict) or \"addr\" not in info or \"content\" not in info:\n return -1\n addr = info[\"addr\"]\n content = info[\"content\"]\n if addr not in self.white_list:\n return False\n else:\n self.receive_struct = {\"addr\": addr, \"content\": content}\n return self.receive_struct[\"content\"]\n\n def send(self, info):\n if not isinstance(info, dict) or \"addr\" not in info or \"content\" not in info:\n return \"info structure is not correct\"\n self.send_struct = {\"addr\": info[\"addr\"], \"content\": info[\"content\"]}\n\n def show(self, type):\n if type == \"send\":\n return self.send_struct\n elif type == \"receive\":\n return self.receive_struct\n else:\n return False", "import_statement": [], "class_description": " \"\"\"\n This is a class as a server, which handles a white list, message sending and receiving, and information display.\n \"\"\"\n", "class_name": "Server", "test_classes": [ "ServerTestAddWhiteList", "ServerTestDelWhiteList", "ServerTestRecv", "ServerTestSend", "ServerTestShow", "ServerTest" ], "class_constructor": "class Server: \n def __init__(self):\n \"\"\"\n Initialize the whitelist as an empty list, and initialize the sending and receiving information as an empty dictionary\n \"\"\"\n self.white_list = []\n self.send_struct = {}\n self.receive_struct = {}\n\n\n\n", "fields": [ "self.receive_struct", "self.send_struct", "self.white_list" ], "methods_info": [ { "method_name": "add_white_list", "method_description": "def add_white_list(self, addr):\n \"\"\"\n Add an address to the whitelist and do nothing if it already exists\n :param addr: int, address to be added\n :return: new whitelist, return False if the address already exists\n >>> server = Server()\n >>> server.add_white_list(88)\n [88]\n \"\"\"", "test_class": "ServerTestAddWhiteList", "test_code": "class ServerTestAddWhiteList(unittest.TestCase):\n def test_add_white_list_1(self):\n server = Server()\n server.add_white_list(88)\n self.assertEqual(server.white_list, [88])\n\n def test_add_white_list_2(self):\n server = Server()\n server.add_white_list(88)\n self.assertEqual(server.add_white_list(88), False)\n\n def test_add_white_list_3(self):\n server = Server()\n server.add_white_list(88)\n server.add_white_list(11)\n self.assertEqual(server.add_white_list(11), False)\n\n def test_add_white_list_4(self):\n server = Server()\n server.add_white_list(11)\n self.assertEqual(server.white_list, [11])\n\n def test_add_white_list_5(self):\n server = Server()\n server.add_white_list(88)\n server.add_white_list(11)\n server.add_white_list(22)\n self.assertEqual(server.add_white_list(22), False)", "solution_code": "def add_white_list(self, addr):\n if addr in self.white_list:\n return False\n else:\n self.white_list.append(addr)\n return self.white_list", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.white_list" ], "method_dependencies": [] } }, { "method_name": "del_white_list", "method_description": "def del_white_list(self, addr):\n \"\"\"\n Remove an address from the whitelist and do nothing if it does not exist\n :param addr: int, address to be deleted\n :return: new whitelist, return False if the address does not exist\n >>> server.add_white_list(88)\n >>> server.del_white_list(88)\n []\n \"\"\"", "test_class": "ServerTestDelWhiteList", "test_code": "class ServerTestDelWhiteList(unittest.TestCase):\n def test_del_white_list_1(self):\n server = Server()\n server.add_white_list(88)\n server.del_white_list(88)\n self.assertEqual(server.white_list, [])\n\n def test_del_white_list_2(self):\n server = Server()\n self.assertEqual(server.del_white_list(88), False)\n\n def test_del_white_list_3(self):\n server = Server()\n self.assertEqual(server.del_white_list(11), False)\n\n def test_del_white_list_4(self):\n server = Server()\n self.assertEqual(server.del_white_list(22), False)\n\n def test_del_white_list_5(self):\n server = Server()\n server.add_white_list(11)\n self.assertEqual(server.del_white_list(22), False)", "solution_code": "def del_white_list(self, addr):\n if addr not in self.white_list:\n return False\n else:\n self.white_list.remove(addr)\n return self.white_list", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.white_list" ], "method_dependencies": [] } }, { "method_name": "recv", "method_description": "def recv(self, info):\n \"\"\"\n Receive information containing address and content. If the address is on the whitelist, receive the content; otherwise, do not receive it\n :param info: dict, information dictionary containing address and content\n :return: if successfully received, return the content of the infomation; otherwise, return False\n >>> server.recv({\"addr\":88,\"content\":\"abc\"})\n abc\n \"\"\"", "test_class": "ServerTestRecv", "test_code": "class ServerTestRecv(unittest.TestCase):\n def test_recv_1(self):\n server = Server()\n server.add_white_list(88)\n server.recv({\"addr\": 88, \"content\": \"abc\"})\n self.assertEqual(server.receive_struct, {\"addr\": 88, \"content\": \"abc\"})\n\n def test_recv_2(self):\n server = Server()\n server.add_white_list(88)\n flag = server.recv({\"addr\": 66, \"content\": \"abc\"})\n self.assertEqual(server.receive_struct, {})\n self.assertEqual(flag, False)\n\n def test_recv_3(self):\n server = Server()\n flag = server.recv([88])\n self.assertEqual(server.receive_struct, {})\n self.assertEqual(flag, -1)\n\n def test_recv_4(self):\n server = Server()\n flag = server.recv({\"addr\": 88})\n self.assertEqual(server.receive_struct, {})\n self.assertEqual(flag, -1)\n\n def test_recv_5(self):\n server = Server()\n flag = server.recv({\"content\": \"abc\"})\n self.assertEqual(server.receive_struct, {})\n self.assertEqual(flag, -1)", "solution_code": "def recv(self, info):\n if not isinstance(info, dict) or \"addr\" not in info or \"content\" not in info:\n return -1\n addr = info[\"addr\"]\n content = info[\"content\"]\n if addr not in self.white_list:\n return False\n else:\n self.receive_struct = {\"addr\": addr, \"content\": content}\n return self.receive_struct[\"content\"]", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.receive_struct", "self.white_list" ], "method_dependencies": [] } }, { "method_name": "send", "method_description": "def send(self, info):\n \"\"\"\n Send information containing address and content\n :param info: dict, information dictionary containing address and content\n :return: if successfully sent, return nothing; otherwise, return a string indicating an error message\n >>> server.send({\"addr\":66,\"content\":\"ABC\"})\n self.send_struct = {\"addr\":66,\"content\":\"ABC\"}\n \"\"\"", "test_class": "ServerTestSend", "test_code": "class ServerTestSend(unittest.TestCase):\n def test_send_1(self):\n server = Server()\n server.send({\"addr\": 88, \"content\": \"abc\"})\n self.assertEqual(server.send_struct, {\"addr\": 88, \"content\": \"abc\"})\n\n def test_send_2(self):\n server = Server()\n flag = server.send({\"addr\": 88})\n self.assertEqual(flag, \"info structure is not correct\")\n\n def test_send_3(self):\n server = Server()\n flag = server.send({\"content\": \"abc\"})\n self.assertEqual(flag, \"info structure is not correct\")\n\n def test_send_4(self):\n server = Server()\n flag = server.send([])\n self.assertEqual(flag, \"info structure is not correct\")\n\n def test_send_5(self):\n server = Server()\n server.send({\"addr\": 66, \"content\": \"abc\"})\n self.assertEqual(server.send_struct, {\"addr\": 66, \"content\": \"abc\"})", "solution_code": "def send(self, info):\n if not isinstance(info, dict) or \"addr\" not in info or \"content\" not in info:\n return \"info structure is not correct\"\n self.send_struct = {\"addr\": info[\"addr\"], \"content\": info[\"content\"]}", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.send_struct" ], "method_dependencies": [] } }, { "method_name": "show", "method_description": "def show(self, type):\n \"\"\"\n Returns struct of the specified type\n :param type: string, the type of struct to be returned, which can be 'send' or 'receive'\n :return: if type is equal to 'send' or 'receive', return the corresponding struct; otherwise, return False\n >>> server.recv({\"addr\":88,\"content\":\"abc\"})\n >>> server.send({\"addr\":66,\"content\":\"ABC\"})\n >>> server.show(\"send\")\n {\"addr\":66,\"content\":\"ABC\"}\n \"\"\"", "test_class": "ServerTestShow", "test_code": "class ServerTestShow(unittest.TestCase):\n def test_show_1(self):\n server = Server()\n server.add_white_list(66)\n server.send({\"addr\": 88, \"content\": \"abc\"})\n server.recv({\"addr\": 66, \"content\": \"ABC\"})\n self.assertEqual(server.show(\"send\"), {\"addr\": 88, \"content\": \"abc\"})\n\n def test_show_2(self):\n server = Server()\n server.add_white_list(66)\n server.send({\"addr\": 88, \"content\": \"abc\"})\n server.recv({\"addr\": 66, \"content\": \"ABC\"})\n self.assertEqual(server.show(\"receive\"), {\"addr\": 66, \"content\": \"ABC\"})\n\n def test_show_3(self):\n server = Server()\n server.add_white_list(66)\n server.send({\"addr\": 88, \"content\": \"abc\"})\n server.recv({\"addr\": 66, \"content\": \"ABC\"})\n self.assertEqual(server.show(\"abcdefg\"), False)\n\n def test_show_4(self):\n server = Server()\n server.add_white_list(66)\n server.send({\"addr\": 11, \"content\": \"abc\"})\n server.recv({\"addr\": 66, \"content\": \"ABC\"})\n self.assertEqual(server.show(\"send\"), {\"addr\": 11, \"content\": \"abc\"})\n\n def test_show_5(self):\n server = Server()\n server.add_white_list(66)\n server.send({\"addr\": 22, \"content\": \"abc\"})\n server.recv({\"addr\": 66, \"content\": \"ABC\"})\n self.assertEqual(server.show(\"send\"), {\"addr\": 22, \"content\": \"abc\"})", "solution_code": "def show(self, type):\n if type == \"send\":\n return self.send_struct\n elif type == \"receive\":\n return self.receive_struct\n else:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.receive_struct", "self.send_struct" ], "method_dependencies": [ "send" ] } } ] }, { "task_id": "ClassEval_75", "skeleton": "\nclass ShoppingCart:\n \"\"\"\n The class manages items, their prices, quantities, and allows to for add, removie, view items, and calculate the total price.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialize the items representing the shopping list as an empty dictionary\n \"\"\"\n self.items = {}\n\n\n def add_item(self, item, price, quantity=1):\n \"\"\"\n Add item information to the shopping list items, including price and quantity. The default quantity is 1\n :param item: string, Item to be added\n :param price: float, The price of the item\n :param quantity:int, The number of items, defaults to 1\n :return:None\n >>> shoppingcart = ShoppingCart()\n >>> shoppingcart.add_item(\"apple\", 1, 5)\n self.items = {\"apple\":{\"price\":1, \"quantity\":5}}\n \"\"\"\n\n\n def remove_item(self, item, quantity=1):\n \"\"\"\n Subtract the specified quantity of item from the shopping list items\n :param item:string, Item to be subtracted in quantity\n :param quantity:int, Quantity to be subtracted\n :return:None\n >>> shoppingcart.add_item(\"apple\", 1, 5)\n >>> shoppingcart.remove_item(\"apple\", 3)\n self.items = {\"apple\":{\"price\":1, \"quantity\":2}}\n \"\"\"\n\n\n def view_items(self) -> dict:\n \"\"\"\n Return the current shopping list items\n :return:dict, the current shopping list items\n >>> shoppingcart.add_item(\"apple\", 1, 5)\n >>> shoppingcart.remove_item(\"apple\", 3)\n >>> shoppingcart.view_items()\n {\"apple\":{\"price\":1, \"quantity\":2}}\n \"\"\"\n\n\n def total_price(self) -> float:\n \"\"\"\n Calculate the total price of all items in the shopping list, which is the quantity of each item multiplied by the price\n :return:float, the total price of all items in the shopping list\n >>> shoppingcart = ShoppingCart()\n >>> shoppingcart.add_item(\"apple\", 1, 5)\n >>> shoppingcart.add_item(\"banana\", 2, 3)\n >>> shoppingcart.total_price()\n 11.0\n \"\"\"", "test": "import unittest\n\n\nclass ShoppingCartTestAddItem(unittest.TestCase):\n def test_add_item_1(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n self.assertEqual(shoppingcart.items, {\"apple\": {\"price\": 1, \"quantity\": 5}})\n\n def test_add_item_2(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1)\n self.assertEqual(shoppingcart.items, {\"apple\": {\"price\": 1, \"quantity\": 1}})\n\n def test_add_item_3(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"aaa\", 1)\n self.assertEqual(shoppingcart.items, {\"aaa\": {\"price\": 1, \"quantity\": 1}})\n\n def test_add_item_4(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"bbb\", 1)\n self.assertEqual(shoppingcart.items, {\"bbb\": {\"price\": 1, \"quantity\": 1}})\n\n def test_add_item_5(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"ccc\", 1)\n self.assertEqual(shoppingcart.items, {\"ccc\": {\"price\": 1, \"quantity\": 1}})\n\n def test_add_item_6(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n shoppingcart.add_item(\"apple\", 1, 5)\n self.assertEqual(shoppingcart.items, {\"apple\": {\"price\": 1, \"quantity\": 5}})\n\n\nclass ShoppingCartTestRemoveItem(unittest.TestCase):\n def test_remove_item_1(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n shoppingcart.remove_item(\"apple\", 3)\n self.assertEqual(shoppingcart.items, {\"apple\": {\"price\": 1, \"quantity\": 2}})\n\n def test_remove_item_2(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n shoppingcart.remove_item(\"apple\")\n self.assertEqual(shoppingcart.items, {\"apple\": {\"price\": 1, \"quantity\": 4}})\n\n def test_remove_item_3(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n shoppingcart.remove_item(\"apple\", 1)\n self.assertEqual(shoppingcart.items, {\"apple\": {\"price\": 1, \"quantity\": 4}})\n\n def test_remove_item_4(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n shoppingcart.remove_item(\"apple\", 2)\n self.assertEqual(shoppingcart.items, {\"apple\": {\"price\": 1, \"quantity\": 3}})\n\n def test_remove_item_5(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n shoppingcart.remove_item(\"apple\", 4)\n self.assertEqual(shoppingcart.items, {\"apple\": {\"price\": 1, \"quantity\": 1}})\n\n def test_remove_item_6(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n shoppingcart.remove_item(\"banana\", 4)\n self.assertEqual(shoppingcart.items, {\"apple\": {\"price\": 1, \"quantity\": 5}})\n\n\nclass ShoppingCartTestViewItems(unittest.TestCase):\n def test_view_items_1(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n self.assertEqual(shoppingcart.view_items(), {\"apple\": {\"price\": 1, \"quantity\": 5}})\n\n def test_view_items_2(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 4)\n self.assertEqual(shoppingcart.view_items(), {\"apple\": {\"price\": 1, \"quantity\": 4}})\n\n def test_view_items_3(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 3)\n self.assertEqual(shoppingcart.view_items(), {\"apple\": {\"price\": 1, \"quantity\": 3}})\n\n def test_view_items_4(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 2)\n self.assertEqual(shoppingcart.view_items(), {\"apple\": {\"price\": 1, \"quantity\": 2}})\n\n def test_view_items_5(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 1)\n self.assertEqual(shoppingcart.view_items(), {\"apple\": {\"price\": 1, \"quantity\": 1}})\n\n\nclass ShoppingCartTestTotalPrice(unittest.TestCase):\n def test_total_price_1(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n shoppingcart.add_item(\"banana\", 2, 3)\n self.assertEqual(shoppingcart.total_price(), 11.0)\n\n def test_total_price_2(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n shoppingcart.add_item(\"banana\", 2, 3)\n shoppingcart.remove_item(\"apple\", 3)\n self.assertEqual(shoppingcart.total_price(), 8.0)\n\n def test_total_price_3(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 1)\n shoppingcart.add_item(\"banana\", 2, 1)\n self.assertEqual(shoppingcart.total_price(), 3.0)\n\n def test_total_price_4(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 2)\n shoppingcart.add_item(\"banana\", 2, 1)\n self.assertEqual(shoppingcart.total_price(), 4.0)\n\n def test_total_price_5(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 3)\n shoppingcart.add_item(\"banana\", 2, 1)\n self.assertEqual(shoppingcart.total_price(), 5.0)\n\n\nclass ShoppingCartTest(unittest.TestCase):\n def test_shoppingcart(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n self.assertEqual(shoppingcart.items, {\"apple\": {\"price\": 1, \"quantity\": 5}})\n self.assertEqual(shoppingcart.view_items(), {\"apple\": {\"price\": 1, \"quantity\": 5}})\n shoppingcart.remove_item(\"apple\", 3)\n self.assertEqual(shoppingcart.items, {\"apple\": {\"price\": 1, \"quantity\": 2}})\n shoppingcart.add_item(\"banana\", 2, 3)\n self.assertEqual(shoppingcart.total_price(), 8.0)", "solution_code": "class ShoppingCart:\n def __init__(self):\n self.items = {}\n\n def add_item(self, item, price, quantity=1):\n if item in self.items:\n self.items[item] = {'price': price, 'quantity': quantity}\n else:\n self.items[item] = {'price': price, 'quantity': quantity}\n\n def remove_item(self, item, quantity=1):\n if item in self.items:\n self.items[item]['quantity'] -= quantity\n else:\n pass\n\n def view_items(self) -> dict:\n return self.items\n\n def total_price(self) -> float:\n return sum([item['quantity'] * item['price'] for item in self.items.values()])", "import_statement": [], "class_description": " \"\"\"\n The class manages items, their prices, quantities, and allows to for add, removie, view items, and calculate the total price.\n \"\"\"\n", "class_name": "ShoppingCart", "test_classes": [ "ShoppingCartTestAddItem", "ShoppingCartTestRemoveItem", "ShoppingCartTestViewItems", "ShoppingCartTestTotalPrice", "ShoppingCartTest" ], "class_constructor": "class ShoppingCart: \n def __init__(self):\n \"\"\"\n Initialize the items representing the shopping list as an empty dictionary\n \"\"\"\n self.items = {}\n\n\n", "fields": [ "self.items" ], "methods_info": [ { "method_name": "add_item", "method_description": "def add_item(self, item, price, quantity=1):\n \"\"\"\n Add item information to the shopping list items, including price and quantity. The default quantity is 1\n :param item: string, Item to be added\n :param price: float, The price of the item\n :param quantity:int, The number of items, defaults to 1\n :return:None\n >>> shoppingcart = ShoppingCart()\n >>> shoppingcart.add_item(\"apple\", 1, 5)\n self.items = {\"apple\":{\"price\":1, \"quantity\":5}}\n \"\"\"", "test_class": "ShoppingCartTestAddItem", "test_code": "class ShoppingCartTestAddItem(unittest.TestCase):\n def test_add_item_1(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n self.assertEqual(shoppingcart.items, {\"apple\": {\"price\": 1, \"quantity\": 5}})\n\n def test_add_item_2(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1)\n self.assertEqual(shoppingcart.items, {\"apple\": {\"price\": 1, \"quantity\": 1}})\n\n def test_add_item_3(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"aaa\", 1)\n self.assertEqual(shoppingcart.items, {\"aaa\": {\"price\": 1, \"quantity\": 1}})\n\n def test_add_item_4(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"bbb\", 1)\n self.assertEqual(shoppingcart.items, {\"bbb\": {\"price\": 1, \"quantity\": 1}})\n\n def test_add_item_5(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"ccc\", 1)\n self.assertEqual(shoppingcart.items, {\"ccc\": {\"price\": 1, \"quantity\": 1}})\n\n def test_add_item_6(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n shoppingcart.add_item(\"apple\", 1, 5)\n self.assertEqual(shoppingcart.items, {\"apple\": {\"price\": 1, \"quantity\": 5}})", "solution_code": "def add_item(self, item, price, quantity=1):\n if item in self.items:\n self.items[item] = {'price': price, 'quantity': quantity}\n else:\n self.items[item] = {'price': price, 'quantity': quantity}", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.items" ], "method_dependencies": [] } }, { "method_name": "remove_item", "method_description": "def remove_item(self, item, quantity=1):\n \"\"\"\n Subtract the specified quantity of item from the shopping list items\n :param item:string, Item to be subtracted in quantity\n :param quantity:int, Quantity to be subtracted\n :return:None\n >>> shoppingcart.add_item(\"apple\", 1, 5)\n >>> shoppingcart.remove_item(\"apple\", 3)\n self.items = {\"apple\":{\"price\":1, \"quantity\":2}}\n \"\"\"", "test_class": "ShoppingCartTestRemoveItem", "test_code": "class ShoppingCartTestRemoveItem(unittest.TestCase):\n def test_remove_item_1(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n shoppingcart.remove_item(\"apple\", 3)\n self.assertEqual(shoppingcart.items, {\"apple\": {\"price\": 1, \"quantity\": 2}})\n\n def test_remove_item_2(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n shoppingcart.remove_item(\"apple\")\n self.assertEqual(shoppingcart.items, {\"apple\": {\"price\": 1, \"quantity\": 4}})\n\n def test_remove_item_3(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n shoppingcart.remove_item(\"apple\", 1)\n self.assertEqual(shoppingcart.items, {\"apple\": {\"price\": 1, \"quantity\": 4}})\n\n def test_remove_item_4(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n shoppingcart.remove_item(\"apple\", 2)\n self.assertEqual(shoppingcart.items, {\"apple\": {\"price\": 1, \"quantity\": 3}})\n\n def test_remove_item_5(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n shoppingcart.remove_item(\"apple\", 4)\n self.assertEqual(shoppingcart.items, {\"apple\": {\"price\": 1, \"quantity\": 1}})\n\n def test_remove_item_6(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n shoppingcart.remove_item(\"banana\", 4)\n self.assertEqual(shoppingcart.items, {\"apple\": {\"price\": 1, \"quantity\": 5}})", "solution_code": "def remove_item(self, item, quantity=1):\n if item in self.items:\n self.items[item]['quantity'] -= quantity\n else:\n pass", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.items" ], "method_dependencies": [] } }, { "method_name": "view_items", "method_description": "def view_items(self) -> dict:\n \"\"\"\n Return the current shopping list items\n :return:dict, the current shopping list items\n >>> shoppingcart.add_item(\"apple\", 1, 5)\n >>> shoppingcart.remove_item(\"apple\", 3)\n >>> shoppingcart.view_items()\n {\"apple\":{\"price\":1, \"quantity\":2}}\n \"\"\"", "test_class": "ShoppingCartTestViewItems", "test_code": "class ShoppingCartTestViewItems(unittest.TestCase):\n def test_view_items_1(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n self.assertEqual(shoppingcart.view_items(), {\"apple\": {\"price\": 1, \"quantity\": 5}})\n\n def test_view_items_2(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 4)\n self.assertEqual(shoppingcart.view_items(), {\"apple\": {\"price\": 1, \"quantity\": 4}})\n\n def test_view_items_3(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 3)\n self.assertEqual(shoppingcart.view_items(), {\"apple\": {\"price\": 1, \"quantity\": 3}})\n\n def test_view_items_4(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 2)\n self.assertEqual(shoppingcart.view_items(), {\"apple\": {\"price\": 1, \"quantity\": 2}})\n\n def test_view_items_5(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 1)\n self.assertEqual(shoppingcart.view_items(), {\"apple\": {\"price\": 1, \"quantity\": 1}})", "solution_code": "def view_items(self) -> dict:\n return self.items", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.items" ], "method_dependencies": [] } }, { "method_name": "total_price", "method_description": "def total_price(self) -> float:\n \"\"\"\n Calculate the total price of all items in the shopping list, which is the quantity of each item multiplied by the price\n :return:float, the total price of all items in the shopping list\n >>> shoppingcart = ShoppingCart()\n >>> shoppingcart.add_item(\"apple\", 1, 5)\n >>> shoppingcart.add_item(\"banana\", 2, 3)\n >>> shoppingcart.total_price()\n 11.0\n \"\"\"", "test_class": "ShoppingCartTestTotalPrice", "test_code": "class ShoppingCartTestTotalPrice(unittest.TestCase):\n def test_total_price_1(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n shoppingcart.add_item(\"banana\", 2, 3)\n self.assertEqual(shoppingcart.total_price(), 11.0)\n\n def test_total_price_2(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 5)\n shoppingcart.add_item(\"banana\", 2, 3)\n shoppingcart.remove_item(\"apple\", 3)\n self.assertEqual(shoppingcart.total_price(), 8.0)\n\n def test_total_price_3(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 1)\n shoppingcart.add_item(\"banana\", 2, 1)\n self.assertEqual(shoppingcart.total_price(), 3.0)\n\n def test_total_price_4(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 2)\n shoppingcart.add_item(\"banana\", 2, 1)\n self.assertEqual(shoppingcart.total_price(), 4.0)\n\n def test_total_price_5(self):\n shoppingcart = ShoppingCart()\n shoppingcart.add_item(\"apple\", 1, 3)\n shoppingcart.add_item(\"banana\", 2, 1)\n self.assertEqual(shoppingcart.total_price(), 5.0)", "solution_code": "def total_price(self) -> float:\n return sum([item['quantity'] * item['price'] for item in self.items.values()])", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.items" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_76", "skeleton": "\nclass SignInSystem:\n \"\"\"\n This is a class as sigin in system, including adding users, signing in/out, checking sign-in status, and retrieving signed-in/not signed-in users.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialize the sign-in system.\n \"\"\"\n self.users = {}\n\n def add_user(self, username):\n \"\"\"\n Add a user to the sign-in system if the user wasn't in the self.users.\n And the initial state is False.\n :param username: str, the username to be added.\n :return: bool, True if the user is added successfully, False if the user already exists.\n >>> signInSystem.add_user(\"mike\")\n True\n >>> signInSystem.add_user(\"mike\")\n False\n \"\"\"\n\n def sign_in(self, username):\n \"\"\"\n Sign in a user if the user was in the self.users and change the state to True.\n :param username: str, the username to be signed in.\n :return: bool, True if the user is signed in successfully, False if the user does not exist.\n >>> signInSystem.sign_in(\"mike\")\n True\n >>> signInSystem.sign_in(\"mik\")\n False\n \"\"\"\n\n def check_sign_in(self, username):\n \"\"\"\n Check if a user is signed in.\n :param username: str, the username to be checked.\n :return: bool, True if the user is signed in, False if the user does not exist or is not signed in.\n >>> signInSystem.check_sign_in(\"jack\")\n False\n >>> signInSystem.add_user(\"jack\")\n >>> signInSystem.check_sign_in(\"jack\")\n >>> signInSystem.sign_in(\"jack\")\n >>> signInSystem.check_sign_in(\"jack\")\n True\n \"\"\"\n\n def all_signed_in(self):\n \"\"\"\n Check if all users are signed in.\n :return: bool, True if all users are signed in, False otherwise.\n >>> signInSystem.add_user(\"jack\")\n True\n >>> signInSystem.sign_in(\"jack\")\n >>> signInSystem.all_signed_in()\n True\n \"\"\"\n\n def all_not_signed_in(self):\n \"\"\"\n Get a list of usernames that are not signed in.\n :return: list[str], a list of usernames that are not signed in.\n >>> signInSystem = SignInSystem()\n >>> signInSystem.add_user(\"a\")\n True\n >>> signInSystem.add_user(\"b\")\n True\n >>> signInSystem.all_not_signed_in()\n ['a', 'b']\n \"\"\"", "test": "import unittest\n\n\nclass SignInSystemTestAddUser(unittest.TestCase):\n def test_add_user_1(self):\n signin_system = SignInSystem()\n result = signin_system.add_user(\"user1\")\n self.assertTrue(result)\n\n def test_add_user_2(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"user1\")\n result = signin_system.add_user(\"user1\")\n self.assertFalse(result)\n\n def test_add_user_3(self):\n signin_system = SignInSystem()\n result = signin_system.add_user(\"aaa\")\n self.assertTrue(result)\n\n def test_add_user_4(self):\n signin_system = SignInSystem()\n result = signin_system.add_user(\"bbb\")\n self.assertTrue(result)\n\n def test_add_user_5(self):\n signin_system = SignInSystem()\n result = signin_system.add_user(\"ccc\")\n self.assertTrue(result)\n\n\nclass SignInSystemTestSignIn(unittest.TestCase):\n def test_sign_in_1(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"user1\")\n result = signin_system.sign_in(\"user1\")\n self.assertTrue(result)\n\n # user not exist\n def test_sign_in_2(self):\n signin_system = SignInSystem()\n result = signin_system.sign_in(\"user1\")\n self.assertFalse(result)\n\n def test_sign_in_3(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"aaa\")\n result = signin_system.sign_in(\"aaa\")\n self.assertTrue(result)\n\n def test_sign_in_4(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"bbb\")\n result = signin_system.sign_in(\"bbb\")\n self.assertTrue(result)\n\n def test_sign_in_5(self):\n signin_system = SignInSystem()\n result = signin_system.sign_in(\"ccc\")\n self.assertFalse(result)\n\n\nclass SignInSystemTestCheckSignIn(unittest.TestCase):\n # has signed in\n def test_check_sign_in_1(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"user1\")\n signin_system.sign_in(\"user1\")\n result = signin_system.check_sign_in(\"user1\")\n self.assertTrue(result)\n\n # hasn't signed in \n def test_check_sign_in_2(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"user1\")\n result = signin_system.check_sign_in(\"user1\")\n self.assertFalse(result)\n\n # not exist\n def test_check_sign_in_3(self):\n signin_system = SignInSystem()\n result = signin_system.check_sign_in(\"user1\")\n self.assertFalse(result)\n\n def test_check_sign_in_4(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"aaa\")\n signin_system.sign_in(\"aaa\")\n result = signin_system.check_sign_in(\"aaa\")\n self.assertTrue(result)\n\n def test_check_sign_in_5(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"bbb\")\n signin_system.sign_in(\"bbb\")\n result = signin_system.check_sign_in(\"bbb\")\n self.assertTrue(result)\n\n\nclass SignInSystemTestAllSignedIn(unittest.TestCase):\n def test_all_signed_in_1(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"user1\")\n signin_system.sign_in(\"user1\")\n result = signin_system.all_signed_in()\n self.assertTrue(result)\n\n def test_all_signed_in_2(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"user1\")\n result = signin_system.all_signed_in()\n self.assertFalse(result)\n\n def test_all_signed_in_3(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"aaa\")\n signin_system.sign_in(\"aaa\")\n result = signin_system.all_signed_in()\n self.assertTrue(result)\n\n def test_all_signed_in_4(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"bbb\")\n signin_system.sign_in(\"bbb\")\n result = signin_system.all_signed_in()\n self.assertTrue(result)\n\n def test_all_signed_in_5(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"aaa\")\n signin_system.add_user(\"bbb\")\n signin_system.sign_in(\"aaa\")\n result = signin_system.all_signed_in()\n self.assertFalse(result)\n\n\nclass SignInSystemTestAllNotSignedIn(unittest.TestCase):\n def test_all_not_signed_in_1(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"user1\")\n signin_system.sign_in(\"user1\")\n result = signin_system.all_not_signed_in()\n self.assertEqual([], result)\n\n def test_all_not_signed_in_2(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"user1\")\n signin_system.add_user(\"user2\")\n result = signin_system.all_not_signed_in()\n self.assertEqual([\"user1\", \"user2\"], result)\n\n def test_all_not_signed_in_3(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"aaa\")\n signin_system.sign_in(\"aaa\")\n result = signin_system.all_not_signed_in()\n self.assertEqual([], result)\n\n def test_all_not_signed_in_4(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"user1\")\n signin_system.add_user(\"aaa\")\n signin_system.sign_in(\"user1\")\n result = signin_system.all_not_signed_in()\n self.assertEqual(['aaa'], result)\n\n def test_all_not_signed_in_5(self):\n signin_system = SignInSystem()\n result = signin_system.all_not_signed_in()\n self.assertEqual([], result)\n\n\nclass SignInSystemTestMain(unittest.TestCase):\n def setUp(self):\n self.signin_system = SignInSystem()\n\n def test_main(self):\n result = self.signin_system.add_user(\"user1\")\n result = self.signin_system.add_user(\"user2\")\n self.assertTrue(result)\n\n result = self.signin_system.sign_in(\"user1\")\n self.assertTrue(result)\n\n result = self.signin_system.check_sign_in(\"user1\")\n self.assertTrue(result)\n\n result = self.signin_system.all_signed_in()\n self.assertFalse(result)\n\n result = self.signin_system.all_not_signed_in()\n self.assertEqual([\"user2\"], result)", "solution_code": "class SignInSystem:\n def __init__(self):\n self.users = {}\n\n def add_user(self, username):\n if username in self.users:\n return False\n else:\n self.users[username] = False\n return True\n\n def sign_in(self, username):\n if username not in self.users:\n return False\n else:\n self.users[username] = True\n return True\n\n def check_sign_in(self, username):\n if username not in self.users:\n return False\n else:\n if self.users[username]:\n return True\n else:\n return False\n\n def all_signed_in(self):\n if all(self.users.values()):\n return True\n else:\n return False\n\n def all_not_signed_in(self):\n not_signed_in_users = []\n for username, signed_in in self.users.items():\n if not signed_in:\n not_signed_in_users.append(username)\n return not_signed_in_users", "import_statement": [], "class_description": " \"\"\"\n This is a class as sigin in system, including adding users, signing in/out, checking sign-in status, and retrieving signed-in/not signed-in users.\n \"\"\"\n", "class_name": "SignInSystem", "test_classes": [ "SignInSystemTestAddUser", "SignInSystemTestSignIn", "SignInSystemTestCheckSignIn", "SignInSystemTestAllSignedIn", "SignInSystemTestAllNotSignedIn", "SignInSystemTestMain" ], "class_constructor": "class SignInSystem: \n def __init__(self):\n \"\"\"\n Initialize the sign-in system.\n \"\"\"\n self.users = {}\n\n", "fields": [ "self.users" ], "methods_info": [ { "method_name": "add_user", "method_description": "def add_user(self, username):\n \"\"\"\n Add a user to the sign-in system if the user wasn't in the self.users.\n And the initial state is False.\n :param username: str, the username to be added.\n :return: bool, True if the user is added successfully, False if the user already exists.\n >>> signInSystem.add_user(\"mike\")\n True\n >>> signInSystem.add_user(\"mike\")\n False\n \"\"\"", "test_class": "SignInSystemTestAddUser", "test_code": "class SignInSystemTestAddUser(unittest.TestCase):\n def test_add_user_1(self):\n signin_system = SignInSystem()\n result = signin_system.add_user(\"user1\")\n self.assertTrue(result)\n\n def test_add_user_2(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"user1\")\n result = signin_system.add_user(\"user1\")\n self.assertFalse(result)\n\n def test_add_user_3(self):\n signin_system = SignInSystem()\n result = signin_system.add_user(\"aaa\")\n self.assertTrue(result)\n\n def test_add_user_4(self):\n signin_system = SignInSystem()\n result = signin_system.add_user(\"bbb\")\n self.assertTrue(result)\n\n def test_add_user_5(self):\n signin_system = SignInSystem()\n result = signin_system.add_user(\"ccc\")\n self.assertTrue(result)", "solution_code": "def add_user(self, username):\n if username in self.users:\n return False\n else:\n self.users[username] = False\n return True", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.users" ], "method_dependencies": [] } }, { "method_name": "sign_in", "method_description": "def sign_in(self, username):\n \"\"\"\n Sign in a user if the user was in the self.users and change the state to True.\n :param username: str, the username to be signed in.\n :return: bool, True if the user is signed in successfully, False if the user does not exist.\n >>> signInSystem.sign_in(\"mike\")\n True\n >>> signInSystem.sign_in(\"mik\")\n False\n \"\"\"", "test_class": "SignInSystemTestSignIn", "test_code": "class SignInSystemTestSignIn(unittest.TestCase):\n def test_sign_in_1(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"user1\")\n result = signin_system.sign_in(\"user1\")\n self.assertTrue(result)\n\n # user not exist\n def test_sign_in_2(self):\n signin_system = SignInSystem()\n result = signin_system.sign_in(\"user1\")\n self.assertFalse(result)\n\n def test_sign_in_3(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"aaa\")\n result = signin_system.sign_in(\"aaa\")\n self.assertTrue(result)\n\n def test_sign_in_4(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"bbb\")\n result = signin_system.sign_in(\"bbb\")\n self.assertTrue(result)\n\n def test_sign_in_5(self):\n signin_system = SignInSystem()\n result = signin_system.sign_in(\"ccc\")\n self.assertFalse(result)", "solution_code": "def sign_in(self, username):\n if username not in self.users:\n return False\n else:\n self.users[username] = True\n return True", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.users" ], "method_dependencies": [] } }, { "method_name": "check_sign_in", "method_description": "def check_sign_in(self, username):\n \"\"\"\n Check if a user is signed in.\n :param username: str, the username to be checked.\n :return: bool, True if the user is signed in, False if the user does not exist or is not signed in.\n >>> signInSystem.check_sign_in(\"jack\")\n False\n >>> signInSystem.add_user(\"jack\")\n >>> signInSystem.check_sign_in(\"jack\")\n >>> signInSystem.sign_in(\"jack\")\n >>> signInSystem.check_sign_in(\"jack\")\n True\n \"\"\"", "test_class": "SignInSystemTestCheckSignIn", "test_code": "class SignInSystemTestCheckSignIn(unittest.TestCase):\n # has signed in\n def test_check_sign_in_1(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"user1\")\n signin_system.sign_in(\"user1\")\n result = signin_system.check_sign_in(\"user1\")\n self.assertTrue(result)\n\n # hasn't signed in \n def test_check_sign_in_2(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"user1\")\n result = signin_system.check_sign_in(\"user1\")\n self.assertFalse(result)\n\n # not exist\n def test_check_sign_in_3(self):\n signin_system = SignInSystem()\n result = signin_system.check_sign_in(\"user1\")\n self.assertFalse(result)\n\n def test_check_sign_in_4(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"aaa\")\n signin_system.sign_in(\"aaa\")\n result = signin_system.check_sign_in(\"aaa\")\n self.assertTrue(result)\n\n def test_check_sign_in_5(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"bbb\")\n signin_system.sign_in(\"bbb\")\n result = signin_system.check_sign_in(\"bbb\")\n self.assertTrue(result)", "solution_code": "def check_sign_in(self, username):\n if username not in self.users:\n return False\n else:\n if self.users[username]:\n return True\n else:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.users" ], "method_dependencies": [] } }, { "method_name": "all_signed_in", "method_description": "def all_signed_in(self):\n \"\"\"\n Check if all users are signed in.\n :return: bool, True if all users are signed in, False otherwise.\n >>> signInSystem.add_user(\"jack\")\n True\n >>> signInSystem.sign_in(\"jack\")\n >>> signInSystem.all_signed_in()\n True\n \"\"\"", "test_class": "SignInSystemTestAllSignedIn", "test_code": "class SignInSystemTestAllSignedIn(unittest.TestCase):\n def test_all_signed_in_1(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"user1\")\n signin_system.sign_in(\"user1\")\n result = signin_system.all_signed_in()\n self.assertTrue(result)\n\n def test_all_signed_in_2(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"user1\")\n result = signin_system.all_signed_in()\n self.assertFalse(result)\n\n def test_all_signed_in_3(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"aaa\")\n signin_system.sign_in(\"aaa\")\n result = signin_system.all_signed_in()\n self.assertTrue(result)\n\n def test_all_signed_in_4(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"bbb\")\n signin_system.sign_in(\"bbb\")\n result = signin_system.all_signed_in()\n self.assertTrue(result)\n\n def test_all_signed_in_5(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"aaa\")\n signin_system.add_user(\"bbb\")\n signin_system.sign_in(\"aaa\")\n result = signin_system.all_signed_in()\n self.assertFalse(result)", "solution_code": "def all_signed_in(self):\n if all(self.users.values()):\n return True\n else:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.users" ], "method_dependencies": [] } }, { "method_name": "all_not_signed_in", "method_description": "def all_not_signed_in(self):\n \"\"\"\n Get a list of usernames that are not signed in.\n :return: list[str], a list of usernames that are not signed in.\n >>> signInSystem = SignInSystem()\n >>> signInSystem.add_user(\"a\")\n True\n >>> signInSystem.add_user(\"b\")\n True\n >>> signInSystem.all_not_signed_in()\n ['a', 'b']\n \"\"\"", "test_class": "SignInSystemTestAllNotSignedIn", "test_code": "class SignInSystemTestAllNotSignedIn(unittest.TestCase):\n def test_all_not_signed_in_1(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"user1\")\n signin_system.sign_in(\"user1\")\n result = signin_system.all_not_signed_in()\n self.assertEqual([], result)\n\n def test_all_not_signed_in_2(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"user1\")\n signin_system.add_user(\"user2\")\n result = signin_system.all_not_signed_in()\n self.assertEqual([\"user1\", \"user2\"], result)\n\n def test_all_not_signed_in_3(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"aaa\")\n signin_system.sign_in(\"aaa\")\n result = signin_system.all_not_signed_in()\n self.assertEqual([], result)\n\n def test_all_not_signed_in_4(self):\n signin_system = SignInSystem()\n signin_system.add_user(\"user1\")\n signin_system.add_user(\"aaa\")\n signin_system.sign_in(\"user1\")\n result = signin_system.all_not_signed_in()\n self.assertEqual(['aaa'], result)\n\n def test_all_not_signed_in_5(self):\n signin_system = SignInSystem()\n result = signin_system.all_not_signed_in()\n self.assertEqual([], result)", "solution_code": "def all_not_signed_in(self):\n not_signed_in_users = []\n for username, signed_in in self.users.items():\n if not signed_in:\n not_signed_in_users.append(username)\n return not_signed_in_users", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.users" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_77", "skeleton": "\nimport random\n\nclass Snake:\n \"\"\"\n The class is a snake game, with allows snake to move and eat food, and also enables to reset, and generat a random food position.\n \"\"\"\n\n def __init__(self, SCREEN_WIDTH, SCREEN_HEIGHT, BLOCK_SIZE, food_position):\n \"\"\"\n Initialize the length of the snake, screen width, screen height, block size, snake head position, score, and food position.\n :param SCREEN_WIDTH: int\n :param SCREEN_HEIGHT: int\n :param BLOCK_SIZE: int, Size of moving units\n :param food_position: tuple, representing the position(x, y) of food.\n \"\"\"\n self.length = 1\n self.SCREEN_WIDTH = SCREEN_WIDTH\n self.SCREEN_HEIGHT = SCREEN_HEIGHT\n self.BLOCK_SIZE = BLOCK_SIZE\n self.positions = [((SCREEN_WIDTH / 2), (SCREEN_HEIGHT / 2))]\n self.score = 0\n self.food_position = food_position\n\n\n def move(self, direction):\n \"\"\"\n Move the snake in the specified direction. If the new position of the snake's head is equal to the position of the food, then eat the food; If the position of the snake's head is equal to the position of its body, then start over, otherwise its own length plus one.\n :param direction: tuple, representing the direction of movement (x, y).\n :return: None\n >>> snake.move((1,1))\n self.length = 1\n self.positions = [(51, 51), (50, 50)]\n self.score = 10\n \"\"\"\n\n\n def random_food_position(self):\n \"\"\"\n Randomly generate a new food position, but don't place it on the snake.\n :return: None, Change the food position\n \"\"\"\n\n\n def reset(self):\n \"\"\"\n Reset the snake to its initial state. Set the length to 1, the snake head position to ((SCREEN_WIDTH/2), (SCREEN_HEIGHT/2)), the score to 0, and randomly generate new food position.\n :return: None\n >>> snake = Snake(100, 100, 1, (51, 51))\n >>> snake.reset()\n self.length = 1\n self.positions = [(50, 50)]\n self.score = 0\n self.random_food_position()\n \"\"\"\n\n\n def eat_food(self):\n \"\"\"\n Increase the length of the snake by 1 and increase the score by 100. Randomly generate a new food position, but\n don't place it on the snake.\n :return: None\n >>> snake = Snake(100, 100, 1, (51, 51))\n >>> snake.move((1,1))\n >>> snake.eat_food()\n self.length = 2\n self.score = 10\n \"\"\"", "test": "import unittest\n\n\nclass SnakeTestMove(unittest.TestCase):\n def test_move_1(self):\n snake = Snake(100, 100, 1, (51, 51))\n snake.move((1, 1))\n self.assertEqual(snake.length, 2)\n self.assertEqual(snake.positions[0], (51, 51))\n self.assertEqual(snake.positions[1], (50, 50))\n self.assertEqual(snake.score, 100)\n\n def test_move_2(self):\n snake = Snake(100, 100, 1, (80, 80))\n snake.move((1, 1))\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.positions[0], (51, 51))\n self.assertEqual(snake.score, 0)\n\n def test_move_3(self):\n snake = Snake(100, 100, 1, (51, 51))\n snake.move((1, 0))\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.positions[0], (51, 50))\n self.assertEqual(snake.score, 0)\n\n def test_move_4(self):\n snake = Snake(100, 100, 1, (51, 51))\n snake.move((0, 0))\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.positions[0], (50, 50))\n self.assertEqual(snake.score, 0)\n\n def test_move_5(self):\n snake = Snake(100, 100, 1, (99, 99))\n snake.move((1, 0))\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.positions[0], (51, 50))\n self.assertEqual(snake.score, 0)\n\n\nclass SnakeTestRandomFoodPosition(unittest.TestCase):\n def test_random_food_position_1(self):\n snake = Snake(100, 100, 1, (51, 51))\n self.assertEqual(snake.food_position, (51, 51))\n snake.random_food_position()\n self.assertNotIn(snake.food_position, snake.positions)\n self.assertGreaterEqual(snake.food_position[0], 0)\n self.assertGreaterEqual(snake.food_position[1], 0)\n self.assertLessEqual(snake.food_position[0], 100)\n self.assertLessEqual(snake.food_position[1], 100)\n\n def test_random_food_position_2(self):\n snake = Snake(100, 100, 1, (99, 99))\n self.assertEqual(snake.food_position, (99, 99))\n snake.random_food_position()\n self.assertNotIn(snake.food_position, snake.positions)\n self.assertGreaterEqual(snake.food_position[0], 0)\n self.assertGreaterEqual(snake.food_position[1], 0)\n self.assertLessEqual(snake.food_position[0], 100)\n self.assertLessEqual(snake.food_position[1], 100)\n\n def test_random_food_position_3(self):\n snake = Snake(100, 100, 1, (0, 0))\n self.assertEqual(snake.food_position, (0, 0))\n snake.random_food_position()\n self.assertNotIn(snake.food_position, snake.positions)\n self.assertGreaterEqual(snake.food_position[0], 0)\n self.assertGreaterEqual(snake.food_position[1], 0)\n self.assertLessEqual(snake.food_position[0], 100)\n self.assertLessEqual(snake.food_position[1], 100)\n\n def test_random_food_position_4(self):\n snake = Snake(100, 100, 1, (40, 40))\n self.assertEqual(snake.food_position, (40, 40))\n snake.random_food_position()\n self.assertNotIn(snake.food_position, snake.positions)\n self.assertGreaterEqual(snake.food_position[0], 0)\n self.assertGreaterEqual(snake.food_position[1], 0)\n self.assertLessEqual(snake.food_position[0], 100)\n self.assertLessEqual(snake.food_position[1], 100)\n\n def test_random_food_position_5(self):\n snake = Snake(100, 100, 1, (60, 60))\n self.assertEqual(snake.food_position, (60, 60))\n snake.random_food_position()\n self.assertNotIn(snake.food_position, snake.positions)\n self.assertGreaterEqual(snake.food_position[0], 0)\n self.assertGreaterEqual(snake.food_position[1], 0)\n self.assertLessEqual(snake.food_position[0], 100)\n self.assertLessEqual(snake.food_position[1], 100)\n\n\nclass SnakeTestReset(unittest.TestCase):\n def test_reset_1(self):\n snake = Snake(100, 100, 1, (51, 51))\n snake.move((1, 1))\n snake.reset()\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.positions[0], (50, 50))\n self.assertEqual(snake.score, 0)\n\n def test_reset_2(self):\n snake = Snake(100, 100, 1, (51, 51))\n snake.move((0, 1))\n snake.reset()\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.positions[0], (50, 50))\n self.assertEqual(snake.score, 0)\n\n def test_reset_3(self):\n snake = Snake(100, 100, 1, (51, 51))\n snake.move((0, -1))\n snake.reset()\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.positions[0], (50, 50))\n self.assertEqual(snake.score, 0)\n\n def test_reset_4(self):\n snake = Snake(100, 100, 1, (51, 51))\n snake.move((-1, 0))\n snake.reset()\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.positions[0], (50, 50))\n self.assertEqual(snake.score, 0)\n\n def test_reset_5(self):\n snake = Snake(100, 100, 1, (51, 51))\n snake.move((1, 0))\n snake.reset()\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.positions[0], (50, 50))\n self.assertEqual(snake.score, 0)\n\n\nclass SnakeTestEatFood(unittest.TestCase):\n def test_eat_food_1(self):\n snake = Snake(100, 100, 1, (51, 51))\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.score, 0)\n snake.eat_food()\n self.assertEqual(snake.length, 2)\n self.assertEqual(snake.score, 100)\n\n def test_eat_food_2(self):\n snake = Snake(100, 100, 1, (51, 51))\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.score, 0)\n snake.eat_food()\n snake.eat_food()\n self.assertEqual(snake.length, 3)\n self.assertEqual(snake.score, 200)\n\n def test_eat_food_3(self):\n snake = Snake(100, 100, 1, (51, 51))\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.score, 0)\n snake.eat_food()\n snake.eat_food()\n snake.eat_food()\n self.assertEqual(snake.length, 4)\n self.assertEqual(snake.score, 300)\n\n def test_eat_food_4(self):\n snake = Snake(100, 100, 1, (51, 51))\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.score, 0)\n snake.eat_food()\n snake.eat_food()\n snake.eat_food()\n snake.eat_food()\n self.assertEqual(snake.length, 5)\n self.assertEqual(snake.score, 400)\n\n def test_eat_food_5(self):\n snake = Snake(100, 100, 1, (51, 51))\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.score, 0)\n snake.eat_food()\n snake.eat_food()\n snake.eat_food()\n snake.eat_food()\n snake.eat_food()\n self.assertEqual(snake.length, 6)\n self.assertEqual(snake.score, 500)\n\n\nclass SnakeTest(unittest.TestCase):\n def test_snake(self):\n snake = Snake(100, 100, 1, (51, 51))\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.SCREEN_WIDTH, 100)\n self.assertEqual(snake.SCREEN_HEIGHT, 100)\n self.assertEqual(snake.BLOCK_SIZE, 1)\n self.assertEqual(snake.positions[0], (50, 50))\n self.assertEqual(snake.score, 0)\n self.assertEqual(snake.food_position, (51, 51))\n snake.move((1, 1))\n self.assertEqual(snake.length, 2)\n self.assertEqual(snake.positions[0], (51, 51))\n self.assertEqual(snake.score, 100)\n snake.random_food_position()\n self.assertNotIn(snake.food_position, snake.positions)\n snake.reset()\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.positions[0], (50, 50))\n self.assertEqual(snake.score, 0)", "solution_code": "import random\n\n\nclass Snake:\n def __init__(self, SCREEN_WIDTH, SCREEN_HEIGHT, BLOCK_SIZE, food_position):\n self.length = 1\n self.SCREEN_WIDTH = SCREEN_WIDTH\n self.SCREEN_HEIGHT = SCREEN_HEIGHT\n self.BLOCK_SIZE = BLOCK_SIZE\n self.positions = [((SCREEN_WIDTH / 2), (SCREEN_HEIGHT / 2))]\n self.score = 0\n self.food_position = food_position\n\n def move(self, direction):\n cur = self.positions[0]\n x, y = direction\n\n new = (\n ((cur[0] + (x * self.BLOCK_SIZE)) % self.SCREEN_WIDTH),\n (cur[1] + (y * self.BLOCK_SIZE)) % self.SCREEN_HEIGHT,\n )\n\n if new == self.food_position:\n self.eat_food()\n\n if len(self.positions) > 2 and new in self.positions[2:]:\n self.reset()\n else:\n self.positions.insert(0, new)\n if len(self.positions) > self.length:\n self.positions.pop()\n\n def random_food_position(self):\n while self.food_position in self.positions:\n self.food_position = (random.randint(0, self.SCREEN_WIDTH // self.BLOCK_SIZE - 1) * self.BLOCK_SIZE,\n random.randint(0, self.SCREEN_HEIGHT // self.BLOCK_SIZE - 1) * self.BLOCK_SIZE)\n\n def reset(self):\n self.length = 1\n self.positions = [((self.SCREEN_WIDTH / 2), (self.SCREEN_HEIGHT / 2))]\n self.score = 0\n self.random_food_position()\n\n def eat_food(self):\n self.length += 1\n self.score += 100\n self.random_food_position()", "import_statement": [ "import random" ], "class_description": " \"\"\"\n The class is a snake game, with allows snake to move and eat food, and also enables to reset, and generat a random food position.\n \"\"\"\n", "class_name": "Snake", "test_classes": [ "SnakeTestMove", "SnakeTestRandomFoodPosition", "SnakeTestReset", "SnakeTestEatFood", "SnakeTest" ], "class_constructor": "class Snake: \n def __init__(self, SCREEN_WIDTH, SCREEN_HEIGHT, BLOCK_SIZE, food_position):\n \"\"\"\n Initialize the length of the snake, screen width, screen height, block size, snake head position, score, and food position.\n :param SCREEN_WIDTH: int\n :param SCREEN_HEIGHT: int\n :param BLOCK_SIZE: int, Size of moving units\n :param food_position: tuple, representing the position(x, y) of food.\n \"\"\"\n self.length = 1\n self.SCREEN_WIDTH = SCREEN_WIDTH\n self.SCREEN_HEIGHT = SCREEN_HEIGHT\n self.BLOCK_SIZE = BLOCK_SIZE\n self.positions = [((SCREEN_WIDTH / 2), (SCREEN_HEIGHT / 2))]\n self.score = 0\n self.food_position = food_position\n\n\n", "fields": [ "self.BLOCK_SIZE", "self.SCREEN_HEIGHT", "self.SCREEN_WIDTH", "self.food_position", "self.length", "self.positions", "self.score" ], "methods_info": [ { "method_name": "move", "method_description": "def move(self, direction):\n \"\"\"\n Move the snake in the specified direction. If the new position of the snake's head is equal to the position of the food, then eat the food; If the position of the snake's head is equal to the position of its body, then start over, otherwise its own length plus one.\n :param direction: tuple, representing the direction of movement (x, y).\n :return: None\n >>> snake.move((1,1))\n self.length = 1\n self.positions = [(51, 51), (50, 50)]\n self.score = 10\n \"\"\"", "test_class": "SnakeTestMove", "test_code": "class SnakeTestMove(unittest.TestCase):\n def test_move_1(self):\n snake = Snake(100, 100, 1, (51, 51))\n snake.move((1, 1))\n self.assertEqual(snake.length, 2)\n self.assertEqual(snake.positions[0], (51, 51))\n self.assertEqual(snake.positions[1], (50, 50))\n self.assertEqual(snake.score, 100)\n\n def test_move_2(self):\n snake = Snake(100, 100, 1, (80, 80))\n snake.move((1, 1))\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.positions[0], (51, 51))\n self.assertEqual(snake.score, 0)\n\n def test_move_3(self):\n snake = Snake(100, 100, 1, (51, 51))\n snake.move((1, 0))\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.positions[0], (51, 50))\n self.assertEqual(snake.score, 0)\n\n def test_move_4(self):\n snake = Snake(100, 100, 1, (51, 51))\n snake.move((0, 0))\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.positions[0], (50, 50))\n self.assertEqual(snake.score, 0)\n\n def test_move_5(self):\n snake = Snake(100, 100, 1, (99, 99))\n snake.move((1, 0))\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.positions[0], (51, 50))\n self.assertEqual(snake.score, 0)", "solution_code": "def move(self, direction):\n cur = self.positions[0]\n x, y = direction\n\n new = (\n ((cur[0] + (x * self.BLOCK_SIZE)) % self.SCREEN_WIDTH),\n (cur[1] + (y * self.BLOCK_SIZE)) % self.SCREEN_HEIGHT,\n )\n\n if new == self.food_position:\n self.eat_food()\n\n if len(self.positions) > 2 and new in self.positions[2:]:\n self.reset()\n else:\n self.positions.insert(0, new)\n if len(self.positions) > self.length:\n self.positions.pop()", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.BLOCK_SIZE", "self.SCREEN_HEIGHT", "self.SCREEN_WIDTH", "self.food_position", "self.length", "self.positions" ], "method_dependencies": [ "reset", "eat_food" ] } }, { "method_name": "random_food_position", "method_description": "def random_food_position(self):\n \"\"\"\n Randomly generate a new food position, but don't place it on the snake.\n :return: None, Change the food position\n \"\"\"", "test_class": "SnakeTestRandomFoodPosition", "test_code": "class SnakeTestRandomFoodPosition(unittest.TestCase):\n def test_random_food_position_1(self):\n snake = Snake(100, 100, 1, (51, 51))\n self.assertEqual(snake.food_position, (51, 51))\n snake.random_food_position()\n self.assertNotIn(snake.food_position, snake.positions)\n self.assertGreaterEqual(snake.food_position[0], 0)\n self.assertGreaterEqual(snake.food_position[1], 0)\n self.assertLessEqual(snake.food_position[0], 100)\n self.assertLessEqual(snake.food_position[1], 100)\n\n def test_random_food_position_2(self):\n snake = Snake(100, 100, 1, (99, 99))\n self.assertEqual(snake.food_position, (99, 99))\n snake.random_food_position()\n self.assertNotIn(snake.food_position, snake.positions)\n self.assertGreaterEqual(snake.food_position[0], 0)\n self.assertGreaterEqual(snake.food_position[1], 0)\n self.assertLessEqual(snake.food_position[0], 100)\n self.assertLessEqual(snake.food_position[1], 100)\n\n def test_random_food_position_3(self):\n snake = Snake(100, 100, 1, (0, 0))\n self.assertEqual(snake.food_position, (0, 0))\n snake.random_food_position()\n self.assertNotIn(snake.food_position, snake.positions)\n self.assertGreaterEqual(snake.food_position[0], 0)\n self.assertGreaterEqual(snake.food_position[1], 0)\n self.assertLessEqual(snake.food_position[0], 100)\n self.assertLessEqual(snake.food_position[1], 100)\n\n def test_random_food_position_4(self):\n snake = Snake(100, 100, 1, (40, 40))\n self.assertEqual(snake.food_position, (40, 40))\n snake.random_food_position()\n self.assertNotIn(snake.food_position, snake.positions)\n self.assertGreaterEqual(snake.food_position[0], 0)\n self.assertGreaterEqual(snake.food_position[1], 0)\n self.assertLessEqual(snake.food_position[0], 100)\n self.assertLessEqual(snake.food_position[1], 100)\n\n def test_random_food_position_5(self):\n snake = Snake(100, 100, 1, (60, 60))\n self.assertEqual(snake.food_position, (60, 60))\n snake.random_food_position()\n self.assertNotIn(snake.food_position, snake.positions)\n self.assertGreaterEqual(snake.food_position[0], 0)\n self.assertGreaterEqual(snake.food_position[1], 0)\n self.assertLessEqual(snake.food_position[0], 100)\n self.assertLessEqual(snake.food_position[1], 100)", "solution_code": "def random_food_position(self):\n while self.food_position in self.positions:\n self.food_position = (random.randint(0, self.SCREEN_WIDTH // self.BLOCK_SIZE - 1) * self.BLOCK_SIZE,\n random.randint(0, self.SCREEN_HEIGHT // self.BLOCK_SIZE - 1) * self.BLOCK_SIZE)", "dependencies": { "Standalone": false, "lib_dependencies": [ "random" ], "field_dependencies": [ "self.BLOCK_SIZE", "self.SCREEN_HEIGHT", "self.SCREEN_WIDTH", "self.food_position", "self.positions" ], "method_dependencies": [] } }, { "method_name": "reset", "method_description": "def reset(self):\n \"\"\"\n Reset the snake to its initial state. Set the length to 1, the snake head position to ((SCREEN_WIDTH/2), (SCREEN_HEIGHT/2)), the score to 0, and randomly generate new food position.\n :return: None\n >>> snake = Snake(100, 100, 1, (51, 51))\n >>> snake.reset()\n self.length = 1\n self.positions = [(50, 50)]\n self.score = 0\n self.random_food_position()\n \"\"\"", "test_class": "SnakeTestReset", "test_code": "class SnakeTestReset(unittest.TestCase):\n def test_reset_1(self):\n snake = Snake(100, 100, 1, (51, 51))\n snake.move((1, 1))\n snake.reset()\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.positions[0], (50, 50))\n self.assertEqual(snake.score, 0)\n\n def test_reset_2(self):\n snake = Snake(100, 100, 1, (51, 51))\n snake.move((0, 1))\n snake.reset()\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.positions[0], (50, 50))\n self.assertEqual(snake.score, 0)\n\n def test_reset_3(self):\n snake = Snake(100, 100, 1, (51, 51))\n snake.move((0, -1))\n snake.reset()\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.positions[0], (50, 50))\n self.assertEqual(snake.score, 0)\n\n def test_reset_4(self):\n snake = Snake(100, 100, 1, (51, 51))\n snake.move((-1, 0))\n snake.reset()\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.positions[0], (50, 50))\n self.assertEqual(snake.score, 0)\n\n def test_reset_5(self):\n snake = Snake(100, 100, 1, (51, 51))\n snake.move((1, 0))\n snake.reset()\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.positions[0], (50, 50))\n self.assertEqual(snake.score, 0)", "solution_code": "def reset(self):\n self.length = 1\n self.positions = [((self.SCREEN_WIDTH / 2), (self.SCREEN_HEIGHT / 2))]\n self.score = 0\n self.random_food_position()", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.SCREEN_HEIGHT", "self.SCREEN_WIDTH", "self.length", "self.positions", "self.score" ], "method_dependencies": [ "random_food_position" ] } }, { "method_name": "eat_food", "method_description": "def eat_food(self):\n \"\"\"\n Increase the length of the snake by 1 and increase the score by 100. Randomly generate a new food position, but\n don't place it on the snake.\n :return: None\n >>> snake = Snake(100, 100, 1, (51, 51))\n >>> snake.move((1,1))\n >>> snake.eat_food()\n self.length = 2\n self.score = 10\n \"\"\"", "test_class": "SnakeTestEatFood", "test_code": "class SnakeTestEatFood(unittest.TestCase):\n def test_eat_food_1(self):\n snake = Snake(100, 100, 1, (51, 51))\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.score, 0)\n snake.eat_food()\n self.assertEqual(snake.length, 2)\n self.assertEqual(snake.score, 100)\n\n def test_eat_food_2(self):\n snake = Snake(100, 100, 1, (51, 51))\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.score, 0)\n snake.eat_food()\n snake.eat_food()\n self.assertEqual(snake.length, 3)\n self.assertEqual(snake.score, 200)\n\n def test_eat_food_3(self):\n snake = Snake(100, 100, 1, (51, 51))\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.score, 0)\n snake.eat_food()\n snake.eat_food()\n snake.eat_food()\n self.assertEqual(snake.length, 4)\n self.assertEqual(snake.score, 300)\n\n def test_eat_food_4(self):\n snake = Snake(100, 100, 1, (51, 51))\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.score, 0)\n snake.eat_food()\n snake.eat_food()\n snake.eat_food()\n snake.eat_food()\n self.assertEqual(snake.length, 5)\n self.assertEqual(snake.score, 400)\n\n def test_eat_food_5(self):\n snake = Snake(100, 100, 1, (51, 51))\n self.assertEqual(snake.length, 1)\n self.assertEqual(snake.score, 0)\n snake.eat_food()\n snake.eat_food()\n snake.eat_food()\n snake.eat_food()\n snake.eat_food()\n self.assertEqual(snake.length, 6)\n self.assertEqual(snake.score, 500)", "solution_code": "def eat_food(self):\n self.length += 1\n self.score += 100\n self.random_food_position()", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.length", "self.score" ], "method_dependencies": [ "random_food_position" ] } } ] }, { "task_id": "ClassEval_78", "skeleton": "\nimport re\n\nclass SplitSentence:\n \"\"\"\n The class allows to split sentences, count words in a sentence, and process a text file to find the maximum word count.\n \"\"\"\n\n\n def split_sentences(self, sentences_string):\n \"\"\"\n Split a string into a list of sentences. Sentences end with . or ? and with a space after that. Please note that Mr. also end with . but are not sentences.\n :param sentences_string: string, string to split\n :return:list, split sentence list\n >>> ss = SplitSentence()\n >>> ss.split_sentences(\"aaa aaaa. bb bbbb bbb? cccc cccc. dd ddd?\")\n ['aaa aaaa.', 'bb bbbb bbb?', 'cccc cccc.', 'dd ddd?']\n \"\"\"\n\n def count_words(self, sentence):\n \"\"\"\n Count the number of words in a sentence. Note that words are separated by spaces and that punctuation marks and numbers are not counted as words.\n :param sentence:string, sentence to be counted, where words are separated by spaces\n :return:int, number of words in the sentence\n >>> ss.count_words(\"abc def\")\n 2\n \"\"\"\n\n def process_text_file(self, sentences_string):\n \"\"\"\n Given a text, return the number of words in the longest sentence\n :param sentences_string: string, undivided long sentence\n :return:int, the number of words in the longest sentence\n >>> ss.process_text_file(\"aaa aaaa. bb bbbb bbb? cccc ccccccc cc ccc. dd ddd?\")\n 4\n \"\"\"", "test": "import unittest\n\n\nclass SplitSentenceTestSplitSentences(unittest.TestCase):\n def test_split_sentences_1(self):\n ss = SplitSentence()\n lst = ss.split_sentences(\"aaa aaaa. bb bbbb bbb? cccc cccc. dd ddd?\")\n self.assertEqual(lst, ['aaa aaaa.', 'bb bbbb bbb?', 'cccc cccc.', 'dd ddd?'])\n\n def test_split_sentences_2(self):\n ss = SplitSentence()\n lst = ss.split_sentences(\"Who is Mr. Smith? He is a teacher.\")\n self.assertEqual(lst, ['Who is Mr. Smith?', 'He is a teacher.'])\n\n def test_split_sentences_3(self):\n ss = SplitSentence()\n lst = ss.split_sentences(\"Who is A.B.C.? He is a teacher.\")\n self.assertEqual(lst, ['Who is A.B.C.?', 'He is a teacher.'])\n\n def test_split_sentences_4(self):\n ss = SplitSentence()\n lst = ss.split_sentences(\"aaa aaaa. bb bbbb bbb? cccc cccc.\")\n self.assertEqual(lst, ['aaa aaaa.', 'bb bbbb bbb?', 'cccc cccc.'])\n\n def test_split_sentences_5(self):\n ss = SplitSentence()\n lst = ss.split_sentences(\"aaa aaaa. bb bbbb bbb?\")\n self.assertEqual(lst, ['aaa aaaa.', 'bb bbbb bbb?'])\n\n\nclass SplitSentenceTestCountWords(unittest.TestCase):\n def test_count_words_1(self):\n ss = SplitSentence()\n cnt = ss.count_words(\"abc def\")\n self.assertEqual(cnt, 2)\n\n def test_count_words_2(self):\n ss = SplitSentence()\n cnt = ss.count_words(\"abc def 1\")\n self.assertEqual(cnt, 2)\n\n def test_count_words_3(self):\n ss = SplitSentence()\n cnt = ss.count_words(\"abc 1\")\n self.assertEqual(cnt, 1)\n\n def test_count_words_4(self):\n ss = SplitSentence()\n cnt = ss.count_words(\"abc def bbb1\")\n self.assertEqual(cnt, 3)\n\n def test_count_words_5(self):\n ss = SplitSentence()\n cnt = ss.count_words(\"abc def 111\")\n self.assertEqual(cnt, 2)\n\n\nclass SplitSentenceTestProcessTextFile(unittest.TestCase):\n def test_process_text_file_1(self):\n ss = SplitSentence()\n cnt = ss.process_text_file(\"aaa aaaa. bb bbbb bbb? cccc ccccccc cc ccc. dd ddd?\")\n self.assertEqual(cnt, 4)\n\n def test_process_text_file_2(self):\n ss = SplitSentence()\n cnt = ss.process_text_file(\"Mr. Smith is a teacher. Yes.\")\n self.assertEqual(cnt, 5)\n\n def test_process_text_file_3(self):\n ss = SplitSentence()\n cnt = ss.process_text_file(\"Mr. Smith is a teacher. Yes 1 2 3 4 5 6.\")\n self.assertEqual(cnt, 5)\n\n def test_process_text_file_4(self):\n ss = SplitSentence()\n cnt = ss.process_text_file(\"aaa aaaa. bb bbbb bbb? cccc ccccccc cc ccc.\")\n self.assertEqual(cnt, 4)\n\n def test_process_text_file_5(self):\n ss = SplitSentence()\n cnt = ss.process_text_file(\"aaa aaaa. bb bbbb bbb?\")\n self.assertEqual(cnt, 3)\n\n\nclass SplitSentenceTest(unittest.TestCase):\n def test_SplitSentence(self):\n ss = SplitSentence()\n lst = ss.split_sentences(\"aaa aaaa. bb bbbb bbb? cccc cccc. dd ddd?\")\n self.assertEqual(lst, ['aaa aaaa.', 'bb bbbb bbb?', 'cccc cccc.', 'dd ddd?'])\n\n cnt = ss.count_words(\"abc def\")\n self.assertEqual(cnt, 2)\n\n cnt = ss.process_text_file(\"aaa aaaa. bb bbbb bbb? cccc ccccccc cc ccc. dd ddd?\")\n self.assertEqual(cnt, 4)", "solution_code": "import re\n\n\nclass SplitSentence:\n\n def split_sentences(self, sentences_string):\n sentences = re.split(r'(? max_count:\n max_count = count\n\n return max_count", "import_statement": [ "import re" ], "class_description": " \"\"\"\n The class allows to split sentences, count words in a sentence, and process a text file to find the maximum word count.\n \"\"\"\n", "class_name": "SplitSentence", "test_classes": [ "SplitSentenceTestSplitSentences", "SplitSentenceTestCountWords", "SplitSentenceTestProcessTextFile", "SplitSentenceTest" ], "class_constructor": "class SplitSentence: \n", "fields": [], "methods_info": [ { "method_name": "split_sentences", "method_description": "def split_sentences(self, sentences_string):\n \"\"\"\n Split a string into a list of sentences. Sentences end with . or ? and with a space after that. Please note that Mr. also end with . but are not sentences.\n :param sentences_string: string, string to split\n :return:list, split sentence list\n >>> ss = SplitSentence()\n >>> ss.split_sentences(\"aaa aaaa. bb bbbb bbb? cccc cccc. dd ddd?\")\n ['aaa aaaa.', 'bb bbbb bbb?', 'cccc cccc.', 'dd ddd?']\n \"\"\"", "test_class": "SplitSentenceTestSplitSentences", "test_code": "class SplitSentenceTestSplitSentences(unittest.TestCase):\n def test_split_sentences_1(self):\n ss = SplitSentence()\n lst = ss.split_sentences(\"aaa aaaa. bb bbbb bbb? cccc cccc. dd ddd?\")\n self.assertEqual(lst, ['aaa aaaa.', 'bb bbbb bbb?', 'cccc cccc.', 'dd ddd?'])\n\n def test_split_sentences_2(self):\n ss = SplitSentence()\n lst = ss.split_sentences(\"Who is Mr. Smith? He is a teacher.\")\n self.assertEqual(lst, ['Who is Mr. Smith?', 'He is a teacher.'])\n\n def test_split_sentences_3(self):\n ss = SplitSentence()\n lst = ss.split_sentences(\"Who is A.B.C.? He is a teacher.\")\n self.assertEqual(lst, ['Who is A.B.C.?', 'He is a teacher.'])\n\n def test_split_sentences_4(self):\n ss = SplitSentence()\n lst = ss.split_sentences(\"aaa aaaa. bb bbbb bbb? cccc cccc.\")\n self.assertEqual(lst, ['aaa aaaa.', 'bb bbbb bbb?', 'cccc cccc.'])\n\n def test_split_sentences_5(self):\n ss = SplitSentence()\n lst = ss.split_sentences(\"aaa aaaa. bb bbbb bbb?\")\n self.assertEqual(lst, ['aaa aaaa.', 'bb bbbb bbb?'])", "solution_code": "def split_sentences(self, sentences_string):\n sentences = re.split(r'(?>> ss.count_words(\"abc def\")\n 2\n \"\"\"", "test_class": "SplitSentenceTestCountWords", "test_code": "class SplitSentenceTestCountWords(unittest.TestCase):\n def test_count_words_1(self):\n ss = SplitSentence()\n cnt = ss.count_words(\"abc def\")\n self.assertEqual(cnt, 2)\n\n def test_count_words_2(self):\n ss = SplitSentence()\n cnt = ss.count_words(\"abc def 1\")\n self.assertEqual(cnt, 2)\n\n def test_count_words_3(self):\n ss = SplitSentence()\n cnt = ss.count_words(\"abc 1\")\n self.assertEqual(cnt, 1)\n\n def test_count_words_4(self):\n ss = SplitSentence()\n cnt = ss.count_words(\"abc def bbb1\")\n self.assertEqual(cnt, 3)\n\n def test_count_words_5(self):\n ss = SplitSentence()\n cnt = ss.count_words(\"abc def 111\")\n self.assertEqual(cnt, 2)", "solution_code": "def count_words(self, sentence):\n sentence = re.sub(r'[^a-zA-Z\\s]', '', sentence)\n words = sentence.split()\n return len(words)", "dependencies": { "Standalone": false, "lib_dependencies": [ "re" ], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "process_text_file", "method_description": "def process_text_file(self, sentences_string):\n \"\"\"\n Given a text, return the number of words in the longest sentence\n :param sentences_string: string, undivided long sentence\n :return:int, the number of words in the longest sentence\n >>> ss.process_text_file(\"aaa aaaa. bb bbbb bbb? cccc ccccccc cc ccc. dd ddd?\")\n 4\n \"\"\"", "test_class": "SplitSentenceTestProcessTextFile", "test_code": "class SplitSentenceTestProcessTextFile(unittest.TestCase):\n def test_process_text_file_1(self):\n ss = SplitSentence()\n cnt = ss.process_text_file(\"aaa aaaa. bb bbbb bbb? cccc ccccccc cc ccc. dd ddd?\")\n self.assertEqual(cnt, 4)\n\n def test_process_text_file_2(self):\n ss = SplitSentence()\n cnt = ss.process_text_file(\"Mr. Smith is a teacher. Yes.\")\n self.assertEqual(cnt, 5)\n\n def test_process_text_file_3(self):\n ss = SplitSentence()\n cnt = ss.process_text_file(\"Mr. Smith is a teacher. Yes 1 2 3 4 5 6.\")\n self.assertEqual(cnt, 5)\n\n def test_process_text_file_4(self):\n ss = SplitSentence()\n cnt = ss.process_text_file(\"aaa aaaa. bb bbbb bbb? cccc ccccccc cc ccc.\")\n self.assertEqual(cnt, 4)\n\n def test_process_text_file_5(self):\n ss = SplitSentence()\n cnt = ss.process_text_file(\"aaa aaaa. bb bbbb bbb?\")\n self.assertEqual(cnt, 3)", "solution_code": "def process_text_file(self, sentences_string):\n sentences = self.split_sentences(sentences_string)\n max_count = 0\n for sentence in sentences:\n count = self.count_words(sentence)\n if count > max_count:\n max_count = count\n\n return max_count", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "split_sentences", "count_words" ] } } ] }, { "task_id": "ClassEval_79", "skeleton": "\nclass SQLGenerator:\n \"\"\"\n This class generates SQL statements for common operations on a table, such as SELECT, INSERT, UPDATE, and DELETE.\n \"\"\"\n\n def __init__(self, table_name):\n \"\"\"\n Initialize the table name.\n :param table_name: str\n \"\"\"\n self.table_name = table_name\n\n def select(self, fields=None, condition=None):\n \"\"\"\n Generates a SELECT SQL statement based on the specified fields and conditions.\n :param fields: list, optional. Default is None. The list of fields to be queried.\n :param condition: str, optional. Default is None. The condition expression for the query.\n :return: str. The generated SQL statement.\n >>> sql = SQLGenerator('table1')\n >>> sql.select(['field1', 'field2'], 'filed3 = value1')\n 'SELECT field1, field2 FROM table1 WHERE filed3 = value1;'\n \"\"\"\n\n def insert(self, data):\n \"\"\"\n Generates an INSERT SQL statement based on the given data.\n :param data: dict. The data to be inserted, in dictionary form where keys are field names and values are field values.\n :return: str. The generated SQL statement.\n >>> sql.insert({'key1': 'value1', 'key2': 'value2'})\n \"INSERT INTO table1 (key1, key2) VALUES ('value1', 'value2');\"\n \"\"\"\n\n\n def update(self, data, condition):\n \"\"\"\n Generates an UPDATE SQL statement based on the given data and condition.\n :param data: dict. The data to be updated, in dictionary form where keys are field names and values are new field values.\n :param condition: str. The condition expression for the update.\n :return: str. The generated SQL statement.\n >>> sql.update({'field1': 'new_value1', 'field2': 'new_value2'}, \"field3 = value1\")\n \"UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2' WHERE field3 = value1;\"\n \"\"\"\n\n def delete(self, condition):\n \"\"\"\n Generates a DELETE SQL statement based on the given condition.\n :param condition: str. The condition expression for the delete.\n :return: str. The generated SQL statement.\n >>> sql.delete(\"field1 = value1\")\n 'DELETE FROM table1 WHERE field1 = value1;'\n \"\"\"\n\n def select_female_under_age(self, age):\n \"\"\"\n Generates a SQL statement to select females under a specified age.\n :param age: int. The specified age.\n :return: str. The generated SQL statement.\n >>> sql.select_female_under_age(30)\n \"SELECT * FROM table1 WHERE age < 30 AND gender = 'female';\"\n \"\"\"\n\n def select_by_age_range(self, min_age, max_age):\n \"\"\"\n Generates a SQL statement to select records within a specified age range.\n :param min_age: int. The minimum age.\n :param max_age: int. The maximum age.\n :return: str. The generated SQL statement.\n >>> sql.select_by_age_range(20, 30)\n 'SELECT * FROM table1 WHERE age BETWEEN 20 AND 30;'\n \"\"\"", "test": "import unittest\n\nclass SQLGeneratorTestSelect(unittest.TestCase):\n def test_select_1(self):\n sql = SQLGenerator('table1')\n result = sql.select(['field1'], \"field2 = value1\")\n self.assertEqual(result, \"SELECT field1 FROM table1 WHERE field2 = value1;\")\n\n def test_select_2(self):\n sql = SQLGenerator('table1')\n result = sql.select(['field1', 'field2'], \"field3 = value1\")\n self.assertEqual(result, \"SELECT field1, field2 FROM table1 WHERE field3 = value1;\")\n\n def test_select_3(self):\n sql = SQLGenerator('table1')\n result = sql.select(['field1, field2'], \"field3 = value1\")\n self.assertEqual(result, \"SELECT field1, field2 FROM table1 WHERE field3 = value1;\")\n\n def test_select_4(self):\n sql = SQLGenerator('table1')\n result = sql.select(['field1, field2'], \"field3 = value1, field4 = value2\")\n self.assertEqual(result, \"SELECT field1, field2 FROM table1 WHERE field3 = value1, field4 = value2;\")\n\n def test_select_5(self):\n sql = SQLGenerator('table1')\n result = sql.select(['field1'], \"field2 = value1, field3 = value2\")\n self.assertEqual(result, \"SELECT field1 FROM table1 WHERE field2 = value1, field3 = value2;\")\n\n def test_select_6(self):\n sql = SQLGenerator('table1')\n result = sql.select(['field1'])\n self.assertEqual(result, \"SELECT field1 FROM table1;\")\n\n\n\nclass SQLGeneratorTestInsert(unittest.TestCase):\n def test_insert(self):\n sql = SQLGenerator('table1')\n result = sql.insert({'field1': 'value1', 'field2': 'value2'})\n self.assertEqual(result, \"INSERT INTO table1 (field1, field2) VALUES ('value1', 'value2');\")\n\n def test_insert_2(self):\n sql = SQLGenerator('table1')\n result = sql.insert({'field1': 'value1', 'field2': 'value2', 'field3': 'value3'})\n self.assertEqual(result, \"INSERT INTO table1 (field1, field2, field3) VALUES ('value1', 'value2', 'value3');\")\n\n def test_insert_3(self):\n sql = SQLGenerator('table1')\n result = sql.insert({'field1': 'value1', 'field2': 'value2', 'field3': 'value3', 'field4': 'value4'})\n self.assertEqual(result,\n \"INSERT INTO table1 (field1, field2, field3, field4) VALUES ('value1', 'value2', 'value3', 'value4');\")\n\n def test_insert_4(self):\n sql = SQLGenerator('table1')\n result = sql.insert({'field1': 'value1', 'field2': 'value2', 'field3': 'value3', 'field4': 'value4',\n 'field5': 'value5'})\n self.assertEqual(result,\n \"INSERT INTO table1 (field1, field2, field3, field4, field5) VALUES ('value1', 'value2', 'value3', 'value4', 'value5');\")\n\n def test_insert_5(self):\n sql = SQLGenerator('table1')\n result = sql.insert({'field1': 'value1', 'field2': 'value2', 'field3': 'value3', 'field4': 'value4',\n 'field5': 'value5', 'field6': 'value6'})\n self.assertEqual(result,\n \"INSERT INTO table1 (field1, field2, field3, field4, field5, field6) VALUES ('value1', 'value2', 'value3', 'value4', 'value5', 'value6');\")\n\nclass SQLGeneratorTestUpdate(unittest.TestCase):\n def test_update(self):\n sql = SQLGenerator('table1')\n result = sql.update({'field1': 'new_value1', 'field2': 'new_value2'}, \"field3 = value1\")\n self.assertEqual(result,\n \"UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2' WHERE field3 = value1;\")\n\n def test_update_2(self):\n sql = SQLGenerator('table1')\n result = sql.update({'field1': 'new_value1', 'field2': 'new_value2', 'field3': 'new_value3'},\n \"field4 = value1\")\n self.assertEqual(result,\n \"UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2', field3 = 'new_value3' WHERE field4 = value1;\")\n\n def test_update_3(self):\n sql = SQLGenerator('table1')\n result = sql.update({'field1': 'new_value1', 'field2': 'new_value2', 'field3': 'new_value3',\n 'field4': 'new_value4'}, \"field5 = value1\")\n self.assertEqual(result,\n \"UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2', field3 = 'new_value3', field4 = 'new_value4' WHERE field5 = value1;\")\n\n def test_update_4(self):\n sql = SQLGenerator('table1')\n result = sql.update({'field1': 'new_value1', 'field2': 'new_value2', 'field3': 'new_value3',\n 'field4': 'new_value4', 'field5': 'new_value5'}, \"field6 = value1\")\n self.assertEqual(result,\n \"UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2', field3 = 'new_value3', field4 = 'new_value4', field5 = 'new_value5' WHERE field6 = value1;\")\n\n def test_update_5(self):\n sql = SQLGenerator('table1')\n result = sql.update({'field1': 'new_value1', 'field2': 'new_value2', 'field3': 'new_value3',\n 'field4': 'new_value4', 'field5': 'new_value5', 'field6': 'new_value6'},\n \"field7 = value1\")\n self.assertEqual(result,\n \"UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2', field3 = 'new_value3', field4 = 'new_value4', field5 = 'new_value5', field6 = 'new_value6' WHERE field7 = value1;\")\n\nclass SQLGeneratorTestDelete(unittest.TestCase):\n def test_delete(self):\n sql = SQLGenerator('table1')\n result = sql.delete(\"field1 = value1\")\n self.assertEqual(result, \"DELETE FROM table1 WHERE field1 = value1;\")\n\n def test_delete_2(self):\n sql = SQLGenerator('table1')\n result = sql.delete(\"field1 = value1 AND field2 = value2\")\n self.assertEqual(result, \"DELETE FROM table1 WHERE field1 = value1 AND field2 = value2;\")\n\n def test_delete_3(self):\n sql = SQLGenerator('table1')\n result = sql.delete(\"field1 = value1 AND field2 = value2 AND field3 = value3\")\n self.assertEqual(result, \"DELETE FROM table1 WHERE field1 = value1 AND field2 = value2 AND field3 = value3;\")\n\n def test_delete_4(self):\n sql = SQLGenerator('table1')\n result = sql.delete(\"field1 = value1 AND field2 = value2 AND field3 = value3 AND field4 = value4\")\n self.assertEqual(result,\n \"DELETE FROM table1 WHERE field1 = value1 AND field2 = value2 AND field3 = value3 AND field4 = value4;\")\n\n def test_delete_5(self):\n sql = SQLGenerator('table1')\n result = sql.delete(\"field1 = value1 AND field2 = value2 AND field3 = value3 AND field4 = value4 AND field5 = value5\")\n self.assertEqual(result,\n \"DELETE FROM table1 WHERE field1 = value1 AND field2 = value2 AND field3 = value3 AND field4 = value4 AND field5 = value5;\")\n\nclass SQLGeneratorTestSelectFemaleUnderAge(unittest.TestCase):\n def test_select_female_under_age(self):\n sql = SQLGenerator('table1')\n result = sql.select_female_under_age(30)\n self.assertEqual(result, \"SELECT * FROM table1 WHERE age < 30 AND gender = 'female';\")\n\n def test_select_female_under_age_2(self):\n sql = SQLGenerator('table1')\n result = sql.select_female_under_age(40)\n self.assertEqual(result,\"SELECT * FROM table1 WHERE age < 40 AND gender = 'female';\")\n\n def test_select_female_under_age_3(self):\n sql = SQLGenerator('table1')\n result = sql.select_female_under_age(20)\n self.assertEqual(result,\"SELECT * FROM table1 WHERE age < 20 AND gender = 'female';\")\n\n def test_select_female_under_age_4(self):\n sql = SQLGenerator('table1')\n result = sql.select_female_under_age(10)\n self.assertEqual(result,\"SELECT * FROM table1 WHERE age < 10 AND gender = 'female';\")\n\n def test_select_female_under_age_5(self):\n sql = SQLGenerator('table1')\n result = sql.select_female_under_age(50)\n self.assertEqual(result,\"SELECT * FROM table1 WHERE age < 50 AND gender = 'female';\")\n\nclass SQLGeneratorTestSelectByAgeRange(unittest.TestCase):\n def test_select_by_age_range(self):\n sql = SQLGenerator('table1')\n result = sql.select_by_age_range(20, 30)\n self.assertEqual(result, \"SELECT * FROM table1 WHERE age BETWEEN 20 AND 30;\")\n\n def test_select_by_age_range_2(self):\n sql = SQLGenerator('table1')\n result = sql.select_by_age_range(10, 20)\n self.assertEqual(result, \"SELECT * FROM table1 WHERE age BETWEEN 10 AND 20;\")\n\n def test_select_by_age_range_3(self):\n sql = SQLGenerator('table1')\n result = sql.select_by_age_range(30, 40)\n self.assertEqual(result, \"SELECT * FROM table1 WHERE age BETWEEN 30 AND 40;\")\n\n def test_select_by_age_range_4(self):\n sql = SQLGenerator('table1')\n result = sql.select_by_age_range(40, 50)\n self.assertEqual(result, \"SELECT * FROM table1 WHERE age BETWEEN 40 AND 50;\")\n\n def test_select_by_age_range_5(self):\n sql = SQLGenerator('table1')\n result = sql.select_by_age_range(50, 60)\n self.assertEqual(result, \"SELECT * FROM table1 WHERE age BETWEEN 50 AND 60;\")\n\n\nclass SQLGeneratorTestMain(unittest.TestCase):\n def test_main(self):\n sql = SQLGenerator('table1')\n self.assertEqual(sql.select(['field1', 'field2'], \"field3 = value1\"),\n \"SELECT field1, field2 FROM table1 WHERE field3 = value1;\")\n self.assertEqual(sql.insert({'field1': 'value1', 'field2': 'value2'}),\n \"INSERT INTO table1 (field1, field2) VALUES ('value1', 'value2');\")\n self.assertEqual(sql.update({'field1': 'new_value1', 'field2': 'new_value2'},\n \"field3 = value1\"),\n \"UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2' WHERE field3 = value1;\")\n self.assertEqual(sql.delete(\"field1 = value1\"),\n \"DELETE FROM table1 WHERE field1 = value1;\")\n self.assertEqual(sql.select_female_under_age(30),\n \"SELECT * FROM table1 WHERE age < 30 AND gender = 'female';\")\n self.assertEqual(sql.select_by_age_range(20, 30),\n \"SELECT * FROM table1 WHERE age BETWEEN 20 AND 30;\")", "solution_code": "class SQLGenerator:\n def __init__(self, table_name):\n self.table_name = table_name\n\n def select(self, fields=None, condition=None):\n if fields is None:\n fields = \"*\"\n else:\n fields = \", \".join(fields)\n sql = f\"SELECT {fields} FROM {self.table_name}\"\n if condition is not None:\n sql += f\" WHERE {condition}\"\n return sql + \";\"\n\n def insert(self, data):\n fields = \", \".join(data.keys())\n values = \", \".join([f\"'{value}'\" for value in data.values()])\n sql = f\"INSERT INTO {self.table_name} ({fields}) VALUES ({values})\"\n return sql + \";\"\n\n def update(self, data, condition):\n set_clause = \", \".join([f\"{field} = '{value}'\" for field, value in data.items()])\n sql = f\"UPDATE {self.table_name} SET {set_clause} WHERE {condition}\"\n return sql + \";\"\n\n def delete(self, condition):\n sql = f\"DELETE FROM {self.table_name} WHERE {condition}\"\n return sql + \";\"\n\n def select_female_under_age(self, age):\n condition = f\"age < {age} AND gender = 'female'\"\n return self.select(condition=condition)\n\n def select_by_age_range(self, min_age, max_age):\n condition = f\"age BETWEEN {min_age} AND {max_age}\"\n return self.select(condition=condition)", "import_statement": [], "class_description": " \"\"\"\n This class generates SQL statements for common operations on a table, such as SELECT, INSERT, UPDATE, and DELETE.\n \"\"\"\n", "class_name": "SQLGenerator", "test_classes": [ "SQLGeneratorTestSelect", "SQLGeneratorTestInsert", "SQLGeneratorTestUpdate", "SQLGeneratorTestDelete", "SQLGeneratorTestSelectFemaleUnderAge", "SQLGeneratorTestSelectByAgeRange", "SQLGeneratorTestMain" ], "class_constructor": "class SQLGenerator: \n def __init__(self, table_name):\n \"\"\"\n Initialize the table name.\n :param table_name: str\n \"\"\"\n self.table_name = table_name\n\n", "fields": [ "self.table_name" ], "methods_info": [ { "method_name": "select", "method_description": "def select(self, fields=None, condition=None):\n \"\"\"\n Generates a SELECT SQL statement based on the specified fields and conditions.\n :param fields: list, optional. Default is None. The list of fields to be queried.\n :param condition: str, optional. Default is None. The condition expression for the query.\n :return: str. The generated SQL statement.\n >>> sql = SQLGenerator('table1')\n >>> sql.select(['field1', 'field2'], 'filed3 = value1')\n 'SELECT field1, field2 FROM table1 WHERE filed3 = value1;'\n \"\"\"", "test_class": "SQLGeneratorTestSelect", "test_code": "class SQLGeneratorTestSelect(unittest.TestCase):\n def test_select_1(self):\n sql = SQLGenerator('table1')\n result = sql.select(['field1'], \"field2 = value1\")\n self.assertEqual(result, \"SELECT field1 FROM table1 WHERE field2 = value1;\")\n\n def test_select_2(self):\n sql = SQLGenerator('table1')\n result = sql.select(['field1', 'field2'], \"field3 = value1\")\n self.assertEqual(result, \"SELECT field1, field2 FROM table1 WHERE field3 = value1;\")\n\n def test_select_3(self):\n sql = SQLGenerator('table1')\n result = sql.select(['field1, field2'], \"field3 = value1\")\n self.assertEqual(result, \"SELECT field1, field2 FROM table1 WHERE field3 = value1;\")\n\n def test_select_4(self):\n sql = SQLGenerator('table1')\n result = sql.select(['field1, field2'], \"field3 = value1, field4 = value2\")\n self.assertEqual(result, \"SELECT field1, field2 FROM table1 WHERE field3 = value1, field4 = value2;\")\n\n def test_select_5(self):\n sql = SQLGenerator('table1')\n result = sql.select(['field1'], \"field2 = value1, field3 = value2\")\n self.assertEqual(result, \"SELECT field1 FROM table1 WHERE field2 = value1, field3 = value2;\")\n\n def test_select_6(self):\n sql = SQLGenerator('table1')\n result = sql.select(['field1'])\n self.assertEqual(result, \"SELECT field1 FROM table1;\")", "solution_code": "def select(self, fields=None, condition=None):\n if fields is None:\n fields = \"*\"\n else:\n fields = \", \".join(fields)\n sql = f\"SELECT {fields} FROM {self.table_name}\"\n if condition is not None:\n sql += f\" WHERE {condition}\"\n return sql + \";\"", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.table_name" ], "method_dependencies": [] } }, { "method_name": "insert", "method_description": "def insert(self, data):\n \"\"\"\n Generates an INSERT SQL statement based on the given data.\n :param data: dict. The data to be inserted, in dictionary form where keys are field names and values are field values.\n :return: str. The generated SQL statement.\n >>> sql.insert({'key1': 'value1', 'key2': 'value2'})\n \"INSERT INTO table1 (key1, key2) VALUES ('value1', 'value2');\"\n \"\"\"", "test_class": "SQLGeneratorTestInsert", "test_code": "class SQLGeneratorTestInsert(unittest.TestCase):\n def test_insert(self):\n sql = SQLGenerator('table1')\n result = sql.insert({'field1': 'value1', 'field2': 'value2'})\n self.assertEqual(result, \"INSERT INTO table1 (field1, field2) VALUES ('value1', 'value2');\")\n\n def test_insert_2(self):\n sql = SQLGenerator('table1')\n result = sql.insert({'field1': 'value1', 'field2': 'value2', 'field3': 'value3'})\n self.assertEqual(result, \"INSERT INTO table1 (field1, field2, field3) VALUES ('value1', 'value2', 'value3');\")\n\n def test_insert_3(self):\n sql = SQLGenerator('table1')\n result = sql.insert({'field1': 'value1', 'field2': 'value2', 'field3': 'value3', 'field4': 'value4'})\n self.assertEqual(result,\n \"INSERT INTO table1 (field1, field2, field3, field4) VALUES ('value1', 'value2', 'value3', 'value4');\")\n\n def test_insert_4(self):\n sql = SQLGenerator('table1')\n result = sql.insert({'field1': 'value1', 'field2': 'value2', 'field3': 'value3', 'field4': 'value4',\n 'field5': 'value5'})\n self.assertEqual(result,\n \"INSERT INTO table1 (field1, field2, field3, field4, field5) VALUES ('value1', 'value2', 'value3', 'value4', 'value5');\")\n\n def test_insert_5(self):\n sql = SQLGenerator('table1')\n result = sql.insert({'field1': 'value1', 'field2': 'value2', 'field3': 'value3', 'field4': 'value4',\n 'field5': 'value5', 'field6': 'value6'})\n self.assertEqual(result,\n \"INSERT INTO table1 (field1, field2, field3, field4, field5, field6) VALUES ('value1', 'value2', 'value3', 'value4', 'value5', 'value6');\")", "solution_code": "def insert(self, data):\n fields = \", \".join(data.keys())\n values = \", \".join([f\"'{value}'\" for value in data.values()])\n sql = f\"INSERT INTO {self.table_name} ({fields}) VALUES ({values})\"\n return sql + \";\"", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.table_name" ], "method_dependencies": [] } }, { "method_name": "update", "method_description": "def update(self, data, condition):\n \"\"\"\n Generates an UPDATE SQL statement based on the given data and condition.\n :param data: dict. The data to be updated, in dictionary form where keys are field names and values are new field values.\n :param condition: str. The condition expression for the update.\n :return: str. The generated SQL statement.\n >>> sql.update({'field1': 'new_value1', 'field2': 'new_value2'}, \"field3 = value1\")\n \"UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2' WHERE field3 = value1;\"\n \"\"\"", "test_class": "SQLGeneratorTestUpdate", "test_code": "class SQLGeneratorTestUpdate(unittest.TestCase):\n def test_update(self):\n sql = SQLGenerator('table1')\n result = sql.update({'field1': 'new_value1', 'field2': 'new_value2'}, \"field3 = value1\")\n self.assertEqual(result,\n \"UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2' WHERE field3 = value1;\")\n\n def test_update_2(self):\n sql = SQLGenerator('table1')\n result = sql.update({'field1': 'new_value1', 'field2': 'new_value2', 'field3': 'new_value3'},\n \"field4 = value1\")\n self.assertEqual(result,\n \"UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2', field3 = 'new_value3' WHERE field4 = value1;\")\n\n def test_update_3(self):\n sql = SQLGenerator('table1')\n result = sql.update({'field1': 'new_value1', 'field2': 'new_value2', 'field3': 'new_value3',\n 'field4': 'new_value4'}, \"field5 = value1\")\n self.assertEqual(result,\n \"UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2', field3 = 'new_value3', field4 = 'new_value4' WHERE field5 = value1;\")\n\n def test_update_4(self):\n sql = SQLGenerator('table1')\n result = sql.update({'field1': 'new_value1', 'field2': 'new_value2', 'field3': 'new_value3',\n 'field4': 'new_value4', 'field5': 'new_value5'}, \"field6 = value1\")\n self.assertEqual(result,\n \"UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2', field3 = 'new_value3', field4 = 'new_value4', field5 = 'new_value5' WHERE field6 = value1;\")\n\n def test_update_5(self):\n sql = SQLGenerator('table1')\n result = sql.update({'field1': 'new_value1', 'field2': 'new_value2', 'field3': 'new_value3',\n 'field4': 'new_value4', 'field5': 'new_value5', 'field6': 'new_value6'},\n \"field7 = value1\")\n self.assertEqual(result,\n \"UPDATE table1 SET field1 = 'new_value1', field2 = 'new_value2', field3 = 'new_value3', field4 = 'new_value4', field5 = 'new_value5', field6 = 'new_value6' WHERE field7 = value1;\")", "solution_code": "def update(self, data, condition):\n set_clause = \", \".join([f\"{field} = '{value}'\" for field, value in data.items()])\n sql = f\"UPDATE {self.table_name} SET {set_clause} WHERE {condition}\"\n return sql + \";\"", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.table_name" ], "method_dependencies": [] } }, { "method_name": "delete", "method_description": "def delete(self, condition):\n \"\"\"\n Generates a DELETE SQL statement based on the given condition.\n :param condition: str. The condition expression for the delete.\n :return: str. The generated SQL statement.\n >>> sql.delete(\"field1 = value1\")\n 'DELETE FROM table1 WHERE field1 = value1;'\n \"\"\"", "test_class": "SQLGeneratorTestDelete", "test_code": "class SQLGeneratorTestDelete(unittest.TestCase):\n def test_delete(self):\n sql = SQLGenerator('table1')\n result = sql.delete(\"field1 = value1\")\n self.assertEqual(result, \"DELETE FROM table1 WHERE field1 = value1;\")\n\n def test_delete_2(self):\n sql = SQLGenerator('table1')\n result = sql.delete(\"field1 = value1 AND field2 = value2\")\n self.assertEqual(result, \"DELETE FROM table1 WHERE field1 = value1 AND field2 = value2;\")\n\n def test_delete_3(self):\n sql = SQLGenerator('table1')\n result = sql.delete(\"field1 = value1 AND field2 = value2 AND field3 = value3\")\n self.assertEqual(result, \"DELETE FROM table1 WHERE field1 = value1 AND field2 = value2 AND field3 = value3;\")\n\n def test_delete_4(self):\n sql = SQLGenerator('table1')\n result = sql.delete(\"field1 = value1 AND field2 = value2 AND field3 = value3 AND field4 = value4\")\n self.assertEqual(result,\n \"DELETE FROM table1 WHERE field1 = value1 AND field2 = value2 AND field3 = value3 AND field4 = value4;\")\n\n def test_delete_5(self):\n sql = SQLGenerator('table1')\n result = sql.delete(\"field1 = value1 AND field2 = value2 AND field3 = value3 AND field4 = value4 AND field5 = value5\")\n self.assertEqual(result,\n \"DELETE FROM table1 WHERE field1 = value1 AND field2 = value2 AND field3 = value3 AND field4 = value4 AND field5 = value5;\")", "solution_code": "def delete(self, condition):\n sql = f\"DELETE FROM {self.table_name} WHERE {condition}\"\n return sql + \";\"", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.table_name" ], "method_dependencies": [] } }, { "method_name": "select_female_under_age", "method_description": "def select_female_under_age(self, age):\n \"\"\"\n Generates a SQL statement to select females under a specified age.\n :param age: int. The specified age.\n :return: str. The generated SQL statement.\n >>> sql.select_female_under_age(30)\n \"SELECT * FROM table1 WHERE age < 30 AND gender = 'female';\"\n \"\"\"", "test_class": "SQLGeneratorTestSelectFemaleUnderAge", "test_code": "class SQLGeneratorTestSelectFemaleUnderAge(unittest.TestCase):\n def test_select_female_under_age(self):\n sql = SQLGenerator('table1')\n result = sql.select_female_under_age(30)\n self.assertEqual(result, \"SELECT * FROM table1 WHERE age < 30 AND gender = 'female';\")\n\n def test_select_female_under_age_2(self):\n sql = SQLGenerator('table1')\n result = sql.select_female_under_age(40)\n self.assertEqual(result,\"SELECT * FROM table1 WHERE age < 40 AND gender = 'female';\")\n\n def test_select_female_under_age_3(self):\n sql = SQLGenerator('table1')\n result = sql.select_female_under_age(20)\n self.assertEqual(result,\"SELECT * FROM table1 WHERE age < 20 AND gender = 'female';\")\n\n def test_select_female_under_age_4(self):\n sql = SQLGenerator('table1')\n result = sql.select_female_under_age(10)\n self.assertEqual(result,\"SELECT * FROM table1 WHERE age < 10 AND gender = 'female';\")\n\n def test_select_female_under_age_5(self):\n sql = SQLGenerator('table1')\n result = sql.select_female_under_age(50)\n self.assertEqual(result,\"SELECT * FROM table1 WHERE age < 50 AND gender = 'female';\")", "solution_code": "def select_female_under_age(self, age):\n condition = f\"age < {age} AND gender = 'female'\"\n return self.select(condition=condition)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "select" ] } }, { "method_name": "select_by_age_range", "method_description": "def select_by_age_range(self, min_age, max_age):\n \"\"\"\n Generates a SQL statement to select records within a specified age range.\n :param min_age: int. The minimum age.\n :param max_age: int. The maximum age.\n :return: str. The generated SQL statement.\n >>> sql.select_by_age_range(20, 30)\n 'SELECT * FROM table1 WHERE age BETWEEN 20 AND 30;'\n \"\"\"", "test_class": "SQLGeneratorTestSelectByAgeRange", "test_code": "class SQLGeneratorTestSelectByAgeRange(unittest.TestCase):\n def test_select_by_age_range(self):\n sql = SQLGenerator('table1')\n result = sql.select_by_age_range(20, 30)\n self.assertEqual(result, \"SELECT * FROM table1 WHERE age BETWEEN 20 AND 30;\")\n\n def test_select_by_age_range_2(self):\n sql = SQLGenerator('table1')\n result = sql.select_by_age_range(10, 20)\n self.assertEqual(result, \"SELECT * FROM table1 WHERE age BETWEEN 10 AND 20;\")\n\n def test_select_by_age_range_3(self):\n sql = SQLGenerator('table1')\n result = sql.select_by_age_range(30, 40)\n self.assertEqual(result, \"SELECT * FROM table1 WHERE age BETWEEN 30 AND 40;\")\n\n def test_select_by_age_range_4(self):\n sql = SQLGenerator('table1')\n result = sql.select_by_age_range(40, 50)\n self.assertEqual(result, \"SELECT * FROM table1 WHERE age BETWEEN 40 AND 50;\")\n\n def test_select_by_age_range_5(self):\n sql = SQLGenerator('table1')\n result = sql.select_by_age_range(50, 60)\n self.assertEqual(result, \"SELECT * FROM table1 WHERE age BETWEEN 50 AND 60;\")", "solution_code": "def select_by_age_range(self, min_age, max_age):\n condition = f\"age BETWEEN {min_age} AND {max_age}\"\n return self.select(condition=condition)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "select" ] } } ] }, { "task_id": "ClassEval_80", "skeleton": "\nclass SQLQueryBuilder:\n \"\"\"\n This class provides to build SQL queries, including SELECT, INSERT, UPDATE, and DELETE statements. \n \"\"\"\n\n\n @staticmethod\n def select(table, columns='*', where=None):\n \"\"\"\n Generate the SELECT SQL statement from the given parameters.\n :param table: str, the query table in database.\n :param columns: list of str, ['col1', 'col2'].\n :param where: dict, {key1: value1, key2: value2 ...}. The query condition.\n return query: str, the SQL query statement.\n >>> SQLQueryBuilder.select('table1', columns = [\"col1\",\"col2\"], where = {\"age\": 15})\n \"SELECT col1, col2 FROM table1 WHERE age='15'\"\n \"\"\"\n\n @staticmethod\n def insert(table, data):\n \"\"\"\n Generate the INSERT SQL statement from the given parameters.\n :param table: str, the table to be inserted in database.\n :param data: dict, the key and value in SQL insert statement\n :return query: str, the SQL insert statement.\n >>> SQLQueryBuilder.insert('table1', {'name': 'Test', 'age': 14})\n \"INSERT INTO table1 (name, age) VALUES ('Test', '14')\"\n \"\"\"\n\n @staticmethod\n def delete(table, where=None):\n \"\"\"\n Generate the DELETE SQL statement from the given parameters.\n :param table: str, the table that will be excuted with DELETE operation in database\n :param where: dict, {key1: value1, key2: value2 ...}. The query condition.\n :return query: str, the SQL delete statement.\n >>> SQLQueryBuilder.delete('table1', {'name': 'Test', 'age': 14})\n \"DELETE FROM table1 WHERE name='Test' AND age='14'\"\n \"\"\"\n\n @staticmethod\n def update(table, data, where=None):\n \"\"\"\n Generate the UPDATE SQL statement from the given parameters.\n :param table: str, the table that will be excuted with UPDATE operation in database\n :param data: dict, the key and value in SQL update statement\n :param where: dict, {key1: value1, key2: value2 ...}. The query condition.\n >>> SQLQueryBuilder.update('table1', {'name': 'Test2', 'age': 15}, where = {'name':'Test'})\n \"UPDATE table1 SET name='Test2', age='15' WHERE name='Test'\"\n \"\"\"", "test": "import unittest\n\n\nclass SQLQueryBuilderTestSelect(unittest.TestCase):\n def test_select_1(self):\n self.assertEqual(\n SQLQueryBuilder.select('users', [\"id\", \"name\"], {'age': 30}),\n \"SELECT id, name FROM users WHERE age='30'\"\n )\n\n def test_select_2(self):\n self.assertEqual(\n SQLQueryBuilder.select('students', [\"id\", \"name\"], {'age': 18}),\n \"SELECT id, name FROM students WHERE age='18'\"\n )\n\n def test_select_3(self):\n self.assertEqual(\n SQLQueryBuilder.select('items', [\"id\", \"name\"], {'price': 1.0}),\n \"SELECT id, name FROM items WHERE price='1.0'\"\n )\n\n def test_select_4(self):\n self.assertEqual(\n SQLQueryBuilder.select('users', [\"id\"], {'age': 30}),\n \"SELECT id FROM users WHERE age='30'\"\n )\n\n def test_select_5(self):\n self.assertEqual(\n SQLQueryBuilder.select('users', [\"name\"], {'age': 30}),\n \"SELECT name FROM users WHERE age='30'\"\n )\n\n def test_select_6(self):\n self.assertEqual(\n SQLQueryBuilder.select('users', [\"name\"]),\n \"SELECT name FROM users\"\n )\n\n def test_select_7(self):\n self.assertEqual(\n SQLQueryBuilder.select('users', \"*\"),\n \"SELECT * FROM users\"\n )\n\n\nclass SQLQueryBuilderTestInsert(unittest.TestCase):\n def test_insert_1(self):\n self.assertEqual(\n SQLQueryBuilder.insert('users', {'name': 'Tom', 'age': 30}),\n \"INSERT INTO users (name, age) VALUES ('Tom', '30')\"\n )\n\n def test_insert_2(self):\n self.assertEqual(\n SQLQueryBuilder.insert('students', {'name': 'Tom', 'age': 18}),\n \"INSERT INTO students (name, age) VALUES ('Tom', '18')\"\n )\n\n def test_insert_3(self):\n self.assertEqual(\n SQLQueryBuilder.insert('items', {'name': 'apple', 'price': 1.0}),\n \"INSERT INTO items (name, price) VALUES ('apple', '1.0')\"\n )\n\n def test_insert_4(self):\n self.assertEqual(\n SQLQueryBuilder.insert('users', {'name': 'Tom'}),\n \"INSERT INTO users (name) VALUES ('Tom')\"\n )\n\n def test_insert_5(self):\n self.assertEqual(\n SQLQueryBuilder.insert('users', {'name': 'Tom', 'age': 30, 'region': 'USA'}),\n \"INSERT INTO users (name, age, region) VALUES ('Tom', '30', 'USA')\"\n )\n\n\nclass SQLQueryBuilderTestDetele(unittest.TestCase):\n def test_delete_1(self):\n self.assertEqual(\n SQLQueryBuilder.delete('users', {'name': 'Tom'}),\n \"DELETE FROM users WHERE name='Tom'\"\n )\n\n def test_delete_2(self):\n self.assertEqual(\n SQLQueryBuilder.delete('students', {'name': 'Tom'}),\n \"DELETE FROM students WHERE name='Tom'\"\n )\n\n def test_delete_3(self):\n self.assertEqual(\n SQLQueryBuilder.delete('items', {'name': 'apple'}),\n \"DELETE FROM items WHERE name='apple'\"\n )\n\n def test_delete_4(self):\n self.assertEqual(\n SQLQueryBuilder.delete('items', {'name': 'aaa'}),\n \"DELETE FROM items WHERE name='aaa'\"\n )\n\n def test_delete_5(self):\n self.assertEqual(\n SQLQueryBuilder.delete('items', {'name': 'bbb'}),\n \"DELETE FROM items WHERE name='bbb'\"\n )\n\n def test_delete_6(self):\n self.assertEqual(\n SQLQueryBuilder.delete('items'),\n \"DELETE FROM items\"\n )\n\n\nclass SQLQueryBuilderTestUpdate(unittest.TestCase):\n def test_update_1(self):\n self.assertEqual(\n SQLQueryBuilder.update('users', {'age': 35}, {'name': 'Tom'}),\n \"UPDATE users SET age='35' WHERE name='Tom'\"\n )\n\n def test_update_2(self):\n self.assertEqual(\n SQLQueryBuilder.update('students', {'age': 18}, {'name': 'Tom'}),\n \"UPDATE students SET age='18' WHERE name='Tom'\"\n )\n\n def test_update_3(self):\n self.assertEqual(\n SQLQueryBuilder.update('items', {'price': 1.0}, {'name': 'apple'}),\n \"UPDATE items SET price='1.0' WHERE name='apple'\"\n )\n\n def test_update_4(self):\n self.assertEqual(\n SQLQueryBuilder.update('items', {'price': 1.0}, {'name': 'aaa'}),\n \"UPDATE items SET price='1.0' WHERE name='aaa'\"\n )\n\n def test_update_5(self):\n self.assertEqual(\n SQLQueryBuilder.update('items', {'price': 1.0}, {'name': 'bbb'}),\n \"UPDATE items SET price='1.0' WHERE name='bbb'\"\n )\n\n def test_update_6(self):\n self.assertEqual(\n SQLQueryBuilder.update('items', {'price': 1.0}),\n \"UPDATE items SET price='1.0'\"\n )\n\n\nclass SQLQueryBuilderTestMain(unittest.TestCase):\n def test_main(self):\n self.assertEqual(\n SQLQueryBuilder.select('users', [\"id\", \"name\"], {'age': 30}),\n \"SELECT id, name FROM users WHERE age='30'\"\n )\n self.assertEqual(\n SQLQueryBuilder.insert('users', {'name': 'Tom', 'age': 30}),\n \"INSERT INTO users (name, age) VALUES ('Tom', '30')\"\n )\n self.assertEqual(\n SQLQueryBuilder.delete('users', {'name': 'Tom'}),\n \"DELETE FROM users WHERE name='Tom'\"\n )\n self.assertEqual(\n SQLQueryBuilder.update('users', {'age': 35}, {'name': 'Tom'}),\n \"UPDATE users SET age='35' WHERE name='Tom'\"\n )", "solution_code": "class SQLQueryBuilder:\n\n @staticmethod\n def select(table, columns='*', where=None):\n if columns != '*':\n columns = ', '.join(columns)\n query = f\"SELECT {columns} FROM {table}\"\n if where:\n query += \" WHERE \" + ' AND '.join(f\"{k}='{v}'\" for k, v in where.items())\n return query\n\n @staticmethod\n def insert(table, data):\n keys = ', '.join(data.keys())\n values = ', '.join(f\"'{v}'\" for v in data.values())\n return f\"INSERT INTO {table} ({keys}) VALUES ({values})\"\n\n @staticmethod\n def delete(table, where=None):\n query = f\"DELETE FROM {table}\"\n if where:\n query += \" WHERE \" + ' AND '.join(f\"{k}='{v}'\" for k, v in where.items())\n return query\n\n @staticmethod\n def update(table, data, where=None):\n update_str = ', '.join(f\"{k}='{v}'\" for k, v in data.items())\n query = f\"UPDATE {table} SET {update_str}\"\n if where:\n query += \" WHERE \" + ' AND '.join(f\"{k}='{v}'\" for k, v in where.items())\n return query", "import_statement": [], "class_description": " \"\"\"\n This class provides to build SQL queries, including SELECT, INSERT, UPDATE, and DELETE statements. \n \"\"\"\n", "class_name": "SQLQueryBuilder", "test_classes": [ "SQLQueryBuilderTestSelect", "SQLQueryBuilderTestInsert", "SQLQueryBuilderTestDetele", "SQLQueryBuilderTestUpdate", "SQLQueryBuilderTestMain" ], "class_constructor": "class SQLQueryBuilder: \n", "fields": [], "methods_info": [ { "method_name": "select", "method_description": "def select(table, columns='*', where=None):\n \"\"\"\n Generate the SELECT SQL statement from the given parameters.\n :param table: str, the query table in database.\n :param columns: list of str, ['col1', 'col2'].\n :param where: dict, {key1: value1, key2: value2 ...}. The query condition.\n return query: str, the SQL query statement.\n >>> SQLQueryBuilder.select('table1', columns = [\"col1\",\"col2\"], where = {\"age\": 15})\n \"SELECT col1, col2 FROM table1 WHERE age='15'\"\n \"\"\"", "test_class": "SQLQueryBuilderTestSelect", "test_code": "class SQLQueryBuilderTestSelect(unittest.TestCase):\n def test_select_1(self):\n self.assertEqual(\n SQLQueryBuilder.select('users', [\"id\", \"name\"], {'age': 30}),\n \"SELECT id, name FROM users WHERE age='30'\"\n )\n\n def test_select_2(self):\n self.assertEqual(\n SQLQueryBuilder.select('students', [\"id\", \"name\"], {'age': 18}),\n \"SELECT id, name FROM students WHERE age='18'\"\n )\n\n def test_select_3(self):\n self.assertEqual(\n SQLQueryBuilder.select('items', [\"id\", \"name\"], {'price': 1.0}),\n \"SELECT id, name FROM items WHERE price='1.0'\"\n )\n\n def test_select_4(self):\n self.assertEqual(\n SQLQueryBuilder.select('users', [\"id\"], {'age': 30}),\n \"SELECT id FROM users WHERE age='30'\"\n )\n\n def test_select_5(self):\n self.assertEqual(\n SQLQueryBuilder.select('users', [\"name\"], {'age': 30}),\n \"SELECT name FROM users WHERE age='30'\"\n )\n\n def test_select_6(self):\n self.assertEqual(\n SQLQueryBuilder.select('users', [\"name\"]),\n \"SELECT name FROM users\"\n )\n\n def test_select_7(self):\n self.assertEqual(\n SQLQueryBuilder.select('users', \"*\"),\n \"SELECT * FROM users\"\n )", "solution_code": "def select(table, columns='*', where=None):\n if columns != '*':\n columns = ', '.join(columns)\n query = f\"SELECT {columns} FROM {table}\"\n if where:\n query += \" WHERE \" + ' AND '.join(f\"{k}='{v}'\" for k, v in where.items())\n return query", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "insert", "method_description": "@staticmethod\n def insert(table, data):\n \"\"\"\n Generate the INSERT SQL statement from the given parameters.\n :param table: str, the table to be inserted in database.\n :param data: dict, the key and value in SQL insert statement\n :return query: str, the SQL insert statement.\n >>> SQLQueryBuilder.insert('table1', {'name': 'Test', 'age': 14})\n \"INSERT INTO table1 (name, age) VALUES ('Test', '14')\"\n \"\"\"", "test_class": "SQLQueryBuilderTestInsert", "test_code": "class SQLQueryBuilderTestInsert(unittest.TestCase):\n def test_insert_1(self):\n self.assertEqual(\n SQLQueryBuilder.insert('users', {'name': 'Tom', 'age': 30}),\n \"INSERT INTO users (name, age) VALUES ('Tom', '30')\"\n )\n\n def test_insert_2(self):\n self.assertEqual(\n SQLQueryBuilder.insert('students', {'name': 'Tom', 'age': 18}),\n \"INSERT INTO students (name, age) VALUES ('Tom', '18')\"\n )\n\n def test_insert_3(self):\n self.assertEqual(\n SQLQueryBuilder.insert('items', {'name': 'apple', 'price': 1.0}),\n \"INSERT INTO items (name, price) VALUES ('apple', '1.0')\"\n )\n\n def test_insert_4(self):\n self.assertEqual(\n SQLQueryBuilder.insert('users', {'name': 'Tom'}),\n \"INSERT INTO users (name) VALUES ('Tom')\"\n )\n\n def test_insert_5(self):\n self.assertEqual(\n SQLQueryBuilder.insert('users', {'name': 'Tom', 'age': 30, 'region': 'USA'}),\n \"INSERT INTO users (name, age, region) VALUES ('Tom', '30', 'USA')\"\n )", "solution_code": "@staticmethod\n def insert(table, data):\n keys = ', '.join(data.keys())\n values = ', '.join(f\"'{v}'\" for v in data.values())\n return f\"INSERT INTO {table} ({keys}) VALUES ({values})\"", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "delete", "method_description": "@staticmethod\n def delete(table, where=None):\n \"\"\"\n Generate the DELETE SQL statement from the given parameters.\n :param table: str, the table that will be excuted with DELETE operation in database\n :param where: dict, {key1: value1, key2: value2 ...}. The query condition.\n :return query: str, the SQL delete statement.\n >>> SQLQueryBuilder.delete('table1', {'name': 'Test', 'age': 14})\n \"DELETE FROM table1 WHERE name='Test' AND age='14'\"\n \"\"\"", "test_class": "SQLQueryBuilderTestDetele", "test_code": "class SQLQueryBuilderTestDetele(unittest.TestCase):\n def test_delete_1(self):\n self.assertEqual(\n SQLQueryBuilder.delete('users', {'name': 'Tom'}),\n \"DELETE FROM users WHERE name='Tom'\"\n )\n\n def test_delete_2(self):\n self.assertEqual(\n SQLQueryBuilder.delete('students', {'name': 'Tom'}),\n \"DELETE FROM students WHERE name='Tom'\"\n )\n\n def test_delete_3(self):\n self.assertEqual(\n SQLQueryBuilder.delete('items', {'name': 'apple'}),\n \"DELETE FROM items WHERE name='apple'\"\n )\n\n def test_delete_4(self):\n self.assertEqual(\n SQLQueryBuilder.delete('items', {'name': 'aaa'}),\n \"DELETE FROM items WHERE name='aaa'\"\n )\n\n def test_delete_5(self):\n self.assertEqual(\n SQLQueryBuilder.delete('items', {'name': 'bbb'}),\n \"DELETE FROM items WHERE name='bbb'\"\n )\n\n def test_delete_6(self):\n self.assertEqual(\n SQLQueryBuilder.delete('items'),\n \"DELETE FROM items\"\n )", "solution_code": "@staticmethod\n def delete(table, where=None):\n query = f\"DELETE FROM {table}\"\n if where:\n query += \" WHERE \" + ' AND '.join(f\"{k}='{v}'\" for k, v in where.items())\n return query", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "update", "method_description": "@staticmethod\n def update(table, data, where=None):\n \"\"\"\n Generate the UPDATE SQL statement from the given parameters.\n :param table: str, the table that will be excuted with UPDATE operation in database\n :param data: dict, the key and value in SQL update statement\n :param where: dict, {key1: value1, key2: value2 ...}. The query condition.\n >>> SQLQueryBuilder.update('table1', {'name': 'Test2', 'age': 15}, where = {'name':'Test'})\n \"UPDATE table1 SET name='Test2', age='15' WHERE name='Test'\"\n \"\"\"", "test_class": "SQLQueryBuilderTestUpdate", "test_code": "class SQLQueryBuilderTestUpdate(unittest.TestCase):\n def test_update_1(self):\n self.assertEqual(\n SQLQueryBuilder.update('users', {'age': 35}, {'name': 'Tom'}),\n \"UPDATE users SET age='35' WHERE name='Tom'\"\n )\n\n def test_update_2(self):\n self.assertEqual(\n SQLQueryBuilder.update('students', {'age': 18}, {'name': 'Tom'}),\n \"UPDATE students SET age='18' WHERE name='Tom'\"\n )\n\n def test_update_3(self):\n self.assertEqual(\n SQLQueryBuilder.update('items', {'price': 1.0}, {'name': 'apple'}),\n \"UPDATE items SET price='1.0' WHERE name='apple'\"\n )\n\n def test_update_4(self):\n self.assertEqual(\n SQLQueryBuilder.update('items', {'price': 1.0}, {'name': 'aaa'}),\n \"UPDATE items SET price='1.0' WHERE name='aaa'\"\n )\n\n def test_update_5(self):\n self.assertEqual(\n SQLQueryBuilder.update('items', {'price': 1.0}, {'name': 'bbb'}),\n \"UPDATE items SET price='1.0' WHERE name='bbb'\"\n )\n\n def test_update_6(self):\n self.assertEqual(\n SQLQueryBuilder.update('items', {'price': 1.0}),\n \"UPDATE items SET price='1.0'\"\n )", "solution_code": "@staticmethod\n def update(table, data, where=None):\n update_str = ', '.join(f\"{k}='{v}'\" for k, v in data.items())\n query = f\"UPDATE {table} SET {update_str}\"\n if where:\n query += \" WHERE \" + ' AND '.join(f\"{k}='{v}'\" for k, v in where.items())\n return query", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_81", "skeleton": "\nimport math\n\nclass Statistics3:\n \"\"\"\n This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics.\n \"\"\"\n\n @staticmethod\n def median(data):\n \"\"\"\n calculates the median of the given list.\n :param data: the given list, list.\n :return: the median of the given list, float.\n >>> statistics3 = Statistics3()\n >>> statistics3.median([1, 2, 3, 4])\n 2.5\n\n \"\"\"\n\n @staticmethod\n def mode(data):\n \"\"\"\n calculates the mode of the given list.\n :param data: the given list, list.\n :return: the mode of the given list, list.\n >>> statistics3 = Statistics3()\n >>> statistics3.mode([1, 2, 3, 3])\n [3]\n\n \"\"\"\n\n @staticmethod\n def correlation(x, y):\n \"\"\"\n calculates the correlation of the given list.\n :param x: the given list, list.\n :param y: the given list, list.\n :return: the correlation of the given list, float.\n >>> statistics3 = Statistics3()\n >>> statistics3.correlation([1, 2, 3], [4, 5, 6])\n 1.0\n\n \"\"\"\n\n @staticmethod\n def mean(data):\n \"\"\"\n calculates the mean of the given list.\n :param data: the given list, list.\n :return: the mean of the given list, float.\n >>> statistics3 = Statistics3()\n >>> statistics3.mean([1, 2, 3])\n 2.0\n\n \"\"\"\n\n @staticmethod\n def correlation_matrix(data):\n \"\"\"\n calculates the correlation matrix of the given list.\n :param data: the given list, list.\n :return: the correlation matrix of the given list, list.\n >>> statistics3 = Statistics3()\n >>> statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]\n\n \"\"\"\n\n @staticmethod\n def standard_deviation(data):\n \"\"\"\n calculates the standard deviation of the given list.\n :param data: the given list, list.\n :return: the standard deviation of the given list, float.\n >>> statistics3 = Statistics3()\n >>> statistics3.standard_deviation([1, 2, 3])\n 1.0\n\n \"\"\"\n\n @staticmethod\n def z_score(data):\n \"\"\"\n calculates the z-score of the given list.\n :param data: the given list, list.\n :return: the z-score of the given list, list.\n >>> statistics3 = Statistics3()\n >>> statistics3.z_score([1, 2, 3, 4])\n [-1.161895003862225, -0.3872983346207417, 0.3872983346207417, 1.161895003862225]\n\n \"\"\"", "test": "import unittest\n\nclass Statistics3TestMedian(unittest.TestCase):\n def test_median(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.median([1, 2, 3, 4]), 2.5)\n\n def test_median_2(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.median([1, 2, 3, 4, 5]), 3)\n\n def test_median_3(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.median([1, 2, 3, 4, 5, 6]), 3.5)\n\n def test_median_4(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.median([1, 2, 3, 4, 5, 6, 7]), 4)\n\n def test_median_5(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.median([1, 2, 3, 4, 5, 6, 7, 8]), 4.5)\n\nclass Statistics3TestMode(unittest.TestCase):\n def test_mode(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.mode([1, 2, 3, 3]), [3])\n\n def test_mode_2(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.mode([1, 2, 3, 3, 4, 4]), [3, 4])\n\n def test_mode_3(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.mode([1, 2, 3, 3, 4, 4, 5]), [3, 4])\n\n def test_mode_4(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.mode([1, 2, 3, 3, 4, 4, 5, 5]), [3, 4, 5])\n\n def test_mode_5(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.mode([1, 2, 3, 3, 4, 4, 5, 5, 6]), [3, 4, 5])\n\nclass Statistics3TestCorrelation(unittest.TestCase):\n def test_correlation(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.correlation([1, 2, 3], [4, 5, 6]), 1.0)\n\n def test_correlation_2(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.correlation([1, 2, 3, 4], [5, 6, 7, 8]), 1.0)\n\n def test_correlation_3(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.correlation([1, 2, 3], [1,2,3]), 1.0)\n\n def test_correlation_4(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.correlation([1, 1,1], [2,2,2]), None)\n\n def test_correlation_5(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.correlation([1, 1,1], [1,1,1]), None)\n\nclass Statistics3TestMean(unittest.TestCase):\n def test_mean(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.mean([1, 2, 3]), 2.0)\n\n def test_mean_2(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.mean([]), None)\n\n def test_mean_3(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.mean([1, 1, 1]), 1.0)\n\n def test_mean_4(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.mean([1, 1, 1, 1]), 1.0)\n\n def test_mean_5(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.mean([1, 1, 1, 1, 1]), 1.0)\n\nclass Statistics3TestCorrelationMatrix(unittest.TestCase):\n def test_correlation_matrix(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]])\n\n def test_correlation_matrix_2(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6]]), [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]])\n\n def test_correlation_matrix_3(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.correlation_matrix([[1, 2, 3]]), [[None, None, None], [None, None, None], [None, None, None]])\n\n def test_correlation_matrix_4(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11,12]]), [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]])\n\n def test_correlation_matrix_5(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11,12], [13, 14, 15]]), [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]])\n\nclass Statistics3TestStandardDeviation(unittest.TestCase):\n def test_standard_deviation(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.standard_deviation([1, 2, 3]), 1.0)\n\n def test_standard_deviation_2(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.standard_deviation([1, 1, 1]), 0.0)\n\n def test_standard_deviation_3(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.standard_deviation([1, 1]), 0.0)\n\n def test_standard_deviation_4(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.standard_deviation([1, 1, 1, 1]), 0.0)\n\n def test_standard_deviation_5(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.standard_deviation([1, 1, 2, 1, 4]), 1.3038404810405297)\n\n\nclass Statistics3TestZScore(unittest.TestCase):\n def test_z_score(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.z_score([1, 2, 3, 4]), [-1.161895003862225, -0.3872983346207417, 0.3872983346207417, 1.161895003862225])\n\n def test_z_score_2(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.z_score([1, 1, 1, 1]), None)\n\n def test_z_score_3(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.z_score([1]),None)\n\n def test_z_score_4(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.z_score([1, 1, 2, 3]), [-0.7833494518006403,-0.7833494518006403,0.26111648393354675,1.3055824196677337])\n\n def test_z_score_5(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.z_score([1, 1, 1, 1, 1]), None)\n\n\nclass Statistics3TestMain(unittest.TestCase):\n def test_main(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.median([1, 2, 3, 4]), 2.5)\n self.assertEqual(statistics3.mode([1, 2, 3, 3]), [3])\n self.assertEqual(statistics3.correlation([1, 2, 3], [4, 5, 6]), 1.0)\n self.assertEqual(statistics3.mean([1, 2, 3]), 2.0)\n self.assertEqual(statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]])\n self.assertEqual(statistics3.standard_deviation([1, 2, 3]), 1.0)\n self.assertEqual(statistics3.z_score([1, 2, 3, 4]), [-1.161895003862225, -0.3872983346207417, 0.3872983346207417, 1.161895003862225])", "solution_code": "import math\nclass Statistics3:\n @staticmethod\n def median(data):\n sorted_data = sorted(data)\n n = len(sorted_data)\n if n % 2 == 1:\n return sorted_data[n // 2]\n else:\n return (sorted_data[n // 2 - 1] + sorted_data[n // 2]) / 2\n\n @staticmethod\n def mode(data):\n counts = {}\n for value in data:\n counts[value] = counts.get(value, 0) + 1\n max_count = max(counts.values())\n mode_values = [value for value, count in counts.items() if count == max_count]\n return mode_values\n\n @staticmethod\n def correlation(x, y):\n n = len(x)\n mean_x = sum(x) / n\n mean_y = sum(y) / n\n numerator = sum((xi - mean_x) * (yi - mean_y) for xi, yi in zip(x, y))\n denominator = math.sqrt(sum((xi - mean_x) ** 2 for xi in x) * sum((yi - mean_y) ** 2 for yi in y))\n if denominator == 0:\n return None\n return numerator / denominator\n\n @staticmethod\n def mean(data):\n if len(data) == 0:\n return None\n return sum(data) / len(data)\n\n @staticmethod\n def correlation_matrix(data):\n matrix = []\n for i in range(len(data[0])):\n row = []\n for j in range(len(data[0])):\n column1 = [row[i] for row in data]\n column2 = [row[j] for row in data]\n correlation = Statistics3.correlation(column1, column2)\n row.append(correlation)\n matrix.append(row)\n return matrix\n\n @staticmethod\n def standard_deviation(data):\n n = len(data)\n if n < 2:\n return None\n mean_value = Statistics3.mean(data)\n variance = sum((x - mean_value) ** 2 for x in data) / (n - 1)\n return math.sqrt(variance)\n\n @staticmethod\n def z_score(data):\n mean = Statistics3.mean(data)\n std_deviation = Statistics3.standard_deviation(data)\n if std_deviation is None or std_deviation == 0:\n return None\n return [(x - mean) / std_deviation for x in data]", "import_statement": [ "import math" ], "class_description": " \"\"\"\n This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics.\n \"\"\"\n", "class_name": "Statistics3", "test_classes": [ "Statistics3TestMedian", "Statistics3TestMode", "Statistics3TestCorrelation", "Statistics3TestMean", "Statistics3TestCorrelationMatrix", "Statistics3TestStandardDeviation", "Statistics3TestZScore", "Statistics3TestMain" ], "class_constructor": "class Statistics3: \n", "fields": [], "methods_info": [ { "method_name": "median", "method_description": "def median(data):\n \"\"\"\n calculates the median of the given list.\n :param data: the given list, list.\n :return: the median of the given list, float.\n >>> statistics3 = Statistics3()\n >>> statistics3.median([1, 2, 3, 4])\n 2.5\n\n \"\"\"", "test_class": "Statistics3TestMedian", "test_code": "class Statistics3TestMedian(unittest.TestCase):\n def test_median(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.median([1, 2, 3, 4]), 2.5)\n\n def test_median_2(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.median([1, 2, 3, 4, 5]), 3)\n\n def test_median_3(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.median([1, 2, 3, 4, 5, 6]), 3.5)\n\n def test_median_4(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.median([1, 2, 3, 4, 5, 6, 7]), 4)\n\n def test_median_5(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.median([1, 2, 3, 4, 5, 6, 7, 8]), 4.5)", "solution_code": "def median(data):\n sorted_data = sorted(data)\n n = len(sorted_data)\n if n % 2 == 1:\n return sorted_data[n // 2]\n else:\n return (sorted_data[n // 2 - 1] + sorted_data[n // 2]) / 2", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "mode", "method_description": "@staticmethod\n def mode(data):\n \"\"\"\n calculates the mode of the given list.\n :param data: the given list, list.\n :return: the mode of the given list, list.\n >>> statistics3 = Statistics3()\n >>> statistics3.mode([1, 2, 3, 3])\n [3]\n\n \"\"\"", "test_class": "Statistics3TestMode", "test_code": "class Statistics3TestMode(unittest.TestCase):\n def test_mode(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.mode([1, 2, 3, 3]), [3])\n\n def test_mode_2(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.mode([1, 2, 3, 3, 4, 4]), [3, 4])\n\n def test_mode_3(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.mode([1, 2, 3, 3, 4, 4, 5]), [3, 4])\n\n def test_mode_4(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.mode([1, 2, 3, 3, 4, 4, 5, 5]), [3, 4, 5])\n\n def test_mode_5(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.mode([1, 2, 3, 3, 4, 4, 5, 5, 6]), [3, 4, 5])", "solution_code": "@staticmethod\n def mode(data):\n counts = {}\n for value in data:\n counts[value] = counts.get(value, 0) + 1\n max_count = max(counts.values())\n mode_values = [value for value, count in counts.items() if count == max_count]\n return mode_values", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "correlation", "method_description": "@staticmethod\n def correlation(x, y):\n \"\"\"\n calculates the correlation of the given list.\n :param x: the given list, list.\n :param y: the given list, list.\n :return: the correlation of the given list, float.\n >>> statistics3 = Statistics3()\n >>> statistics3.correlation([1, 2, 3], [4, 5, 6])\n 1.0\n\n \"\"\"", "test_class": "Statistics3TestCorrelation", "test_code": "class Statistics3TestCorrelation(unittest.TestCase):\n def test_correlation(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.correlation([1, 2, 3], [4, 5, 6]), 1.0)\n\n def test_correlation_2(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.correlation([1, 2, 3, 4], [5, 6, 7, 8]), 1.0)\n\n def test_correlation_3(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.correlation([1, 2, 3], [1,2,3]), 1.0)\n\n def test_correlation_4(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.correlation([1, 1,1], [2,2,2]), None)\n\n def test_correlation_5(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.correlation([1, 1,1], [1,1,1]), None)", "solution_code": "@staticmethod\n def correlation(x, y):\n n = len(x)\n mean_x = sum(x) / n\n mean_y = sum(y) / n\n numerator = sum((xi - mean_x) * (yi - mean_y) for xi, yi in zip(x, y))\n denominator = math.sqrt(sum((xi - mean_x) ** 2 for xi in x) * sum((yi - mean_y) ** 2 for yi in y))\n if denominator == 0:\n return None\n return numerator / denominator", "dependencies": { "Standalone": false, "lib_dependencies": [ "math" ], "field_dependencies": [], "method_dependencies": [ "mean" ] } }, { "method_name": "mean", "method_description": "@staticmethod\n def mean(data):\n \"\"\"\n calculates the mean of the given list.\n :param data: the given list, list.\n :return: the mean of the given list, float.\n >>> statistics3 = Statistics3()\n >>> statistics3.mean([1, 2, 3])\n 2.0\n\n \"\"\"", "test_class": "Statistics3TestMean", "test_code": "class Statistics3TestMean(unittest.TestCase):\n def test_mean(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.mean([1, 2, 3]), 2.0)\n\n def test_mean_2(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.mean([]), None)\n\n def test_mean_3(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.mean([1, 1, 1]), 1.0)\n\n def test_mean_4(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.mean([1, 1, 1, 1]), 1.0)\n\n def test_mean_5(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.mean([1, 1, 1, 1, 1]), 1.0)", "solution_code": "@staticmethod\n def mean(data):\n if len(data) == 0:\n return None\n return sum(data) / len(data)", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "correlation_matrix", "method_description": "@staticmethod\n def correlation_matrix(data):\n \"\"\"\n calculates the correlation matrix of the given list.\n :param data: the given list, list.\n :return: the correlation matrix of the given list, list.\n >>> statistics3 = Statistics3()\n >>> statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]\n\n \"\"\"", "test_class": "Statistics3TestCorrelationMatrix", "test_code": "class Statistics3TestCorrelationMatrix(unittest.TestCase):\n def test_correlation_matrix(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]])\n\n def test_correlation_matrix_2(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6]]), [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]])\n\n def test_correlation_matrix_3(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.correlation_matrix([[1, 2, 3]]), [[None, None, None], [None, None, None], [None, None, None]])\n\n def test_correlation_matrix_4(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11,12]]), [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]])\n\n def test_correlation_matrix_5(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.correlation_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11,12], [13, 14, 15]]), [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]])", "solution_code": "@staticmethod\n def correlation_matrix(data):\n matrix = []\n for i in range(len(data[0])):\n row = []\n for j in range(len(data[0])):\n column1 = [row[i] for row in data]\n column2 = [row[j] for row in data]\n correlation = Statistics3.correlation(column1, column2)\n row.append(correlation)\n matrix.append(row)\n return matrix", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "correlation" ] } }, { "method_name": "standard_deviation", "method_description": "@staticmethod\n def standard_deviation(data):\n \"\"\"\n calculates the standard deviation of the given list.\n :param data: the given list, list.\n :return: the standard deviation of the given list, float.\n >>> statistics3 = Statistics3()\n >>> statistics3.standard_deviation([1, 2, 3])\n 1.0\n\n \"\"\"", "test_class": "Statistics3TestStandardDeviation", "test_code": "class Statistics3TestStandardDeviation(unittest.TestCase):\n def test_standard_deviation(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.standard_deviation([1, 2, 3]), 1.0)\n\n def test_standard_deviation_2(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.standard_deviation([1, 1, 1]), 0.0)\n\n def test_standard_deviation_3(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.standard_deviation([1, 1]), 0.0)\n\n def test_standard_deviation_4(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.standard_deviation([1, 1, 1, 1]), 0.0)\n\n def test_standard_deviation_5(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.standard_deviation([1, 1, 2, 1, 4]), 1.3038404810405297)", "solution_code": "@staticmethod\n def standard_deviation(data):\n n = len(data)\n if n < 2:\n return None\n mean_value = Statistics3.mean(data)\n variance = sum((x - mean_value) ** 2 for x in data) / (n - 1)\n return math.sqrt(variance)", "dependencies": { "Standalone": false, "lib_dependencies": [ "math" ], "field_dependencies": [], "method_dependencies": [ "mean" ] } }, { "method_name": "z_score", "method_description": "@staticmethod\n def z_score(data):\n \"\"\"\n calculates the z-score of the given list.\n :param data: the given list, list.\n :return: the z-score of the given list, list.\n >>> statistics3 = Statistics3()\n >>> statistics3.z_score([1, 2, 3, 4])\n [-1.161895003862225, -0.3872983346207417, 0.3872983346207417, 1.161895003862225]\n\n \"\"\"", "test_class": "Statistics3TestZScore", "test_code": "class Statistics3TestZScore(unittest.TestCase):\n def test_z_score(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.z_score([1, 2, 3, 4]), [-1.161895003862225, -0.3872983346207417, 0.3872983346207417, 1.161895003862225])\n\n def test_z_score_2(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.z_score([1, 1, 1, 1]), None)\n\n def test_z_score_3(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.z_score([1]),None)\n\n def test_z_score_4(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.z_score([1, 1, 2, 3]), [-0.7833494518006403,-0.7833494518006403,0.26111648393354675,1.3055824196677337])\n\n def test_z_score_5(self):\n statistics3 = Statistics3()\n self.assertEqual(statistics3.z_score([1, 1, 1, 1, 1]), None)", "solution_code": "@staticmethod\n def z_score(data):\n mean = Statistics3.mean(data)\n std_deviation = Statistics3.standard_deviation(data)\n if std_deviation is None or std_deviation == 0:\n return None\n return [(x - mean) / std_deviation for x in data]", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "mean", "standard_deviation" ] } } ] }, { "task_id": "ClassEval_82", "skeleton": "\nclass StockPortfolioTracker:\n \"\"\"\n This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio.\n \"\"\"\n\n def __init__(self, cash_balance):\n \"\"\"\n Initialize the StockPortfolioTracker class with a cash balance and an empty portfolio.\n \"\"\"\n self.portfolio = []\n self.cash_balance = cash_balance\n\n def add_stock(self, stock):\n \"\"\"\n Add a stock to the portfolio.\n :param stock: a dictionary with keys \"name\", \"price\", and \"quantity\"\n >>> tracker = StockPortfolioTracker(10000.0)\n >>> tracker.add_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10})\n >>> tracker.portfolio\n [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n\n \"\"\"\n\n def remove_stock(self, stock):\n \"\"\"\n Remove a stock from the portfolio.\n :param stock: a dictionary with keys \"name\", \"price\", and \"quantity\"\n >>> tracker = StockPortfolioTracker(10000.0)\n >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n >>> tracker.remove_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10})\n True\n >>> tracker.portfolio\n []\n\n \"\"\"\n\n def buy_stock(self, stock):\n \"\"\"\n Buy a stock and add it to the portfolio.\n :param stock: a dictionary with keys \"name\", \"price\", and \"quantity\"\n :param quantity: the quantity of the stock to buy,int.\n :return: True if the stock was bought successfully, False if the cash balance is not enough.\n >>> tracker = StockPortfolioTracker(10000.0)\n >>> tracker.buy_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10})\n True\n >>> tracker.portfolio\n [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n\n \"\"\"\n\n def sell_stock(self, stock):\n \"\"\"\n Sell a stock and remove it from the portfolio and add the cash to the cash balance.\n :param stock: a dictionary with keys \"name\", \"price\", and \"quantity\"\n :param quantity: the quantity of the stock to sell,int.\n :return: True if the stock was sold successfully, False if the quantity of the stock is not enough.\n >>> tracker = StockPortfolioTracker(10000.0)\n >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n >>> tracker.sell_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10})\n True\n >>> tracker.portfolio\n []\n\n \"\"\"\n\n def calculate_portfolio_value(self):\n \"\"\"\n Calculate the total value of the portfolio.\n :return: the total value of the portfolio, float.\n >>> tracker = StockPortfolioTracker(10000.0)\n >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n >>> tracker.calculate_portfolio_value()\n 11500.0\n\n \"\"\"\n\n def get_portfolio_summary(self):\n \"\"\"\n Get a summary of the portfolio.\n :return: a tuple of the total value of the portfolio and a list of dictionaries with keys \"name\" and \"value\"\n >>> tracker = StockPortfolioTracker(10000.0)\n >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n >>> tracker.get_portfolio_summary()\n (11500.0, [{'name': 'AAPL', 'value': 1500.0}])\n\n \"\"\"\n\n def get_stock_value(self, stock):\n \"\"\"\n Get the value of a stock.\n :param stock: a dictionary with keys \"name\", \"price\", and \"quantity\"\n :return: the value of the stock, float.\n >>> tracker = StockPortfolioTracker(10000.0)\n >>> tracker.get_stock_value({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10})\n 1500.0\n\n \"\"\"", "test": "import unittest\n\n\nclass StockPortfolioTrackerTestAddStock(unittest.TestCase):\n def test_add_stock(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.add_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10})\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}])\n\n def test_add_stock_2(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n tracker.add_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10})\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 20}])\n\n def test_add_stock_3(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n tracker.add_stock({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 10})\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}])\n\n def test_add_stock_4(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n tracker.add_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10})\n tracker.add_stock({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 10})\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 20},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}])\n\n def test_add_stock_5(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n tracker.add_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10})\n tracker.add_stock({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 10})\n tracker.add_stock({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 10})\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 20},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 20}])\n\n\nclass StockPortfolioTrackerTestRemoveStock(unittest.TestCase):\n def test_remove_stock(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.remove_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}), True)\n self.assertEqual(tracker.portfolio, [])\n\n def test_remove_stock_2(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.remove_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}), True)\n self.assertEqual(tracker.portfolio, [{'name': 'MSFT', 'price': 150.0, 'quantity': 10}])\n\n def test_remove_stock_3(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.remove_stock({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 20}), False)\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}])\n\n def test_remove_stock_4(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.remove_stock({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 10}), False)\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}])\n\n def test_remove_stock_5(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.remove_stock({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 10}), True)\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}])\n\n\nclass StockPortfolioTrackerTestBuyStock(unittest.TestCase):\n def test_buy_stock(self):\n tracker = StockPortfolioTracker(10000.0)\n self.assertEqual(tracker.buy_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}), True)\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}])\n self.assertEqual(tracker.cash_balance, 8500.0)\n\n def test_buy_stock_2(self):\n tracker = StockPortfolioTracker(1000.0)\n self.assertEqual(tracker.buy_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}), False)\n self.assertEqual(tracker.portfolio, [])\n self.assertEqual(tracker.cash_balance, 1000.0)\n\n def test_buy_stock_3(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.buy_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}), True)\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 20}])\n self.assertEqual(tracker.cash_balance, 8500.0)\n\n def test_buy_stock_4(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.buy_stock({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 10}), True)\n self.assertEqual(tracker.buy_stock({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 10}), True)\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 20}])\n self.assertEqual(tracker.cash_balance, 7000.0)\n\n def test_buy_stock_5(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.buy_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}), True)\n self.assertEqual(tracker.buy_stock({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 10}), True)\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 20},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}])\n self.assertEqual(tracker.cash_balance, 7000.0)\n\n\nclass StockPortfolioTrackerTestSellStock(unittest.TestCase):\n def test_sell_stock(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.sell_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 9}), True)\n self.assertEqual(tracker.portfolio, [{\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 1}])\n self.assertEqual(tracker.cash_balance, 11350.0)\n\n def test_sell_stock_2(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.sell_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 20}), False)\n self.assertEqual(tracker.portfolio, [{\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}])\n self.assertEqual(tracker.cash_balance, 10000.0)\n\n def test_sell_stock_3(self):\n tracker = StockPortfolioTracker(10000.0)\n self.assertEqual(tracker.sell_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}), False)\n self.assertEqual(tracker.portfolio, [])\n self.assertEqual(tracker.cash_balance, 10000.0)\n\n def test_sell_stock_4(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 20}]\n self.assertEqual(tracker.sell_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 20}), True)\n self.assertEqual(tracker.portfolio, [])\n self.assertEqual(tracker.cash_balance, 13000.0)\n\n def test_sell_stock_5(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 20},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.sell_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 20}), True)\n self.assertEqual(tracker.portfolio, [{'name': 'MSFT', 'price': 150.0, 'quantity': 10}])\n self.assertEqual(tracker.cash_balance, 13000.0)\n\n\nclass StockPortfolioTrackerTestCalculatePortfolioValue(unittest.TestCase):\n def test_calculate_portfolio_value(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.calculate_portfolio_value(), 11500.0)\n\n def test_calculate_portfolio_value_2(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.calculate_portfolio_value(), 13000.0)\n\n def test_calculate_portfolio_value_3(self):\n tracker = StockPortfolioTracker(10000.0)\n self.assertEqual(tracker.calculate_portfolio_value(), 10000.0)\n\n def test_calculate_portfolio_value_4(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 0}]\n self.assertEqual(tracker.calculate_portfolio_value(), 10000.0)\n\n def test_calculate_portfolio_value_5(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 0.0, 'quantity': 10}]\n self.assertEqual(tracker.calculate_portfolio_value(), 10000.0)\n\n\nclass StockPortfolioTrackerTestGetPortfolioSummary(unittest.TestCase):\n def test_get_portfolio_summary(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.get_portfolio_summary(), (11500.0, [{'name': 'AAPL', 'value': 1500.0}]))\n\n def test_get_portfolio_summary_2(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.get_portfolio_summary(),\n (13000.0, [{'name': 'AAPL', 'value': 1500.0}, {'name': 'MSFT', 'value': 1500.0}]))\n\n def test_get_portfolio_summary_3(self):\n tracker = StockPortfolioTracker(10000.0)\n self.assertEqual(tracker.get_portfolio_summary(), (10000.0, []))\n\n def test_get_portfolio_summary_4(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 0}]\n self.assertEqual(tracker.get_portfolio_summary(), (10000.0, [{'name': 'AAPL', 'value': 0.0}]))\n\n def test_get_portfolio_summary_5(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 0.0, 'quantity': 10}]\n self.assertEqual(tracker.get_portfolio_summary(), (10000.0, [{'name': 'AAPL', 'value': 0.0}]))\n\n\nclass StockPortfolioTrackerTestGetStockValue(unittest.TestCase):\n def test_get_stock_value(self):\n tracker = StockPortfolioTracker(10000.0)\n self.assertEqual(tracker.get_stock_value({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}), 1500.0)\n\n def test_get_stock_value_2(self):\n tracker = StockPortfolioTracker(10000.0)\n self.assertEqual(tracker.get_stock_value({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 0}), 0.0)\n\n def test_get_stock_value_3(self):\n tracker = StockPortfolioTracker(10000.0)\n self.assertEqual(tracker.get_stock_value({\"name\": \"AAPL\", \"price\": 0.0, \"quantity\": 10}), 0.0)\n\n def test_get_stock_value_4(self):\n tracker = StockPortfolioTracker(10000.0)\n self.assertEqual(tracker.get_stock_value({\"name\": \"AAPL\", \"price\": 0.0, \"quantity\": 0}), 0.0)\n\n def test_get_stock_value_5(self):\n tracker = StockPortfolioTracker(10000.0)\n self.assertEqual(tracker.get_stock_value({\"name\": \"MSFL\", \"price\": 150.0, \"quantity\": 2}), 300.0)\n\n\nclass StockPortfolioTrackerTestMain(unittest.TestCase):\n def test_main(self):\n tracker = StockPortfolioTracker(10000.0)\n self.assertEqual(tracker.add_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}), None)\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}])\n self.assertEqual(tracker.buy_stock({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 10}), True)\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}])\n self.assertEqual(tracker.cash_balance, 8500.0)\n self.assertEqual(tracker.sell_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 9}), True)\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 1},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}])\n self.assertEqual(tracker.cash_balance, 9850.0)\n self.assertEqual(tracker.remove_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 1}), True)\n self.assertEqual(tracker.portfolio, [{'name': 'MSFT', 'price': 150.0, 'quantity': 10}])\n self.assertEqual(tracker.calculate_portfolio_value(), 11350.0)\n self.assertEqual(tracker.get_portfolio_summary(), (11350.0, [{'name': 'MSFT', 'value': 1500.0}]))\n self.assertEqual(tracker.get_stock_value({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 10}), 1500.0)\n\n def test_main_2(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.add_stock({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 10}), None)\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}])\n self.assertEqual(tracker.remove_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}), True)\n self.assertEqual(tracker.portfolio, [{'name': 'MSFT', 'price': 150.0, 'quantity': 10}])\n self.assertEqual(tracker.calculate_portfolio_value(), 11500.0)\n self.assertEqual(tracker.get_portfolio_summary(), (11500.0, [{'name': 'MSFT', 'value': 1500.0}]))\n self.assertEqual(tracker.get_stock_value({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 10}), 1500.0)\n self.assertEqual(tracker.buy_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}), True)\n self.assertEqual(tracker.portfolio, [{'name': 'MSFT', 'price': 150.0, 'quantity': 10},\n {'name': 'AAPL', 'price': 150.0, 'quantity': 10}])\n self.assertEqual(tracker.cash_balance, 8500.0)\n\n def test_main_3(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.get_stock_value({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 10}), 1500.0)\n self.assertEqual(tracker.buy_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}), True)\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 20},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}])\n self.assertEqual(tracker.cash_balance, 8500.0)\n self.assertEqual(tracker.sell_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}), True)\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}])\n self.assertEqual(tracker.cash_balance, 10000.0)\n self.assertEqual(tracker.remove_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}), True)\n self.assertEqual(tracker.portfolio, [{'name': 'MSFT', 'price': 150.0, 'quantity': 10}])\n self.assertEqual(tracker.calculate_portfolio_value(), 11500.0)\n self.assertEqual(tracker.get_portfolio_summary(), (11500.0, [{'name': 'MSFT', 'value': 1500.0}]))\n self.assertEqual(tracker.get_stock_value({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 10}), 1500.0)\n self.assertEqual(tracker.add_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}), None)\n self.assertEqual(tracker.portfolio, [{'name': 'MSFT', 'price': 150.0, 'quantity': 10},\n {'name': 'AAPL', 'price': 150.0, 'quantity': 10}])", "solution_code": "class StockPortfolioTracker:\n def __init__(self, cash_balance):\n self.portfolio = []\n self.cash_balance = cash_balance\n\n def add_stock(self, stock):\n for pf in self.portfolio:\n if pf['name'] == stock['name']:\n pf['quantity'] += stock['quantity']\n return\n\n self.portfolio.append(stock)\n\n def remove_stock(self, stock):\n for pf in self.portfolio:\n if pf['name'] == stock['name'] and pf['quantity'] >= stock['quantity']:\n pf['quantity'] -= stock['quantity']\n if pf['quantity'] == 0:\n self.portfolio.remove(pf)\n return True\n return False\n\n def buy_stock(self, stock):\n if stock['price'] * stock['quantity'] > self.cash_balance:\n return False\n else:\n self.add_stock(stock)\n self.cash_balance -= stock['price'] * stock['quantity']\n return True\n\n def sell_stock(self, stock):\n if self.remove_stock(stock) == False:\n return False\n self.cash_balance += stock['price'] * stock['quantity']\n return True\n\n def calculate_portfolio_value(self):\n total_value = self.cash_balance\n for stock in self.portfolio:\n total_value += stock['price'] * stock['quantity']\n return total_value\n\n def get_portfolio_summary(self):\n summary = []\n for stock in self.portfolio:\n value = self.get_stock_value(stock)\n summary.append({\"name\": stock[\"name\"], \"value\": value})\n portfolio_value = self.calculate_portfolio_value()\n return portfolio_value, summary\n\n def get_stock_value(self, stock):\n return stock['price'] * stock['quantity']", "import_statement": [], "class_description": " \"\"\"\n This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio.\n \"\"\"\n", "class_name": "StockPortfolioTracker", "test_classes": [ "StockPortfolioTrackerTestAddStock", "StockPortfolioTrackerTestRemoveStock", "StockPortfolioTrackerTestBuyStock", "StockPortfolioTrackerTestSellStock", "StockPortfolioTrackerTestCalculatePortfolioValue", "StockPortfolioTrackerTestGetPortfolioSummary", "StockPortfolioTrackerTestGetStockValue", "StockPortfolioTrackerTestMain" ], "class_constructor": "class StockPortfolioTracker: \n def __init__(self, cash_balance):\n \"\"\"\n Initialize the StockPortfolioTracker class with a cash balance and an empty portfolio.\n \"\"\"\n self.portfolio = []\n self.cash_balance = cash_balance\n\n", "fields": [ "self.cash_balance", "self.portfolio" ], "methods_info": [ { "method_name": "add_stock", "method_description": "def add_stock(self, stock):\n \"\"\"\n Add a stock to the portfolio.\n :param stock: a dictionary with keys \"name\", \"price\", and \"quantity\"\n >>> tracker = StockPortfolioTracker(10000.0)\n >>> tracker.add_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10})\n >>> tracker.portfolio\n [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n\n \"\"\"", "test_class": "StockPortfolioTrackerTestAddStock", "test_code": "class StockPortfolioTrackerTestAddStock(unittest.TestCase):\n def test_add_stock(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.add_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10})\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}])\n\n def test_add_stock_2(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n tracker.add_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10})\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 20}])\n\n def test_add_stock_3(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n tracker.add_stock({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 10})\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}])\n\n def test_add_stock_4(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n tracker.add_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10})\n tracker.add_stock({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 10})\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 20},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}])\n\n def test_add_stock_5(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n tracker.add_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10})\n tracker.add_stock({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 10})\n tracker.add_stock({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 10})\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 20},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 20}])", "solution_code": "def add_stock(self, stock):\n for pf in self.portfolio:\n if pf['name'] == stock['name']:\n pf['quantity'] += stock['quantity']\n return\n\n self.portfolio.append(stock)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.portfolio" ], "method_dependencies": [] } }, { "method_name": "remove_stock", "method_description": "def remove_stock(self, stock):\n \"\"\"\n Remove a stock from the portfolio.\n :param stock: a dictionary with keys \"name\", \"price\", and \"quantity\"\n >>> tracker = StockPortfolioTracker(10000.0)\n >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n >>> tracker.remove_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10})\n True\n >>> tracker.portfolio\n []\n\n \"\"\"", "test_class": "StockPortfolioTrackerTestRemoveStock", "test_code": "class StockPortfolioTrackerTestRemoveStock(unittest.TestCase):\n def test_remove_stock(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.remove_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}), True)\n self.assertEqual(tracker.portfolio, [])\n\n def test_remove_stock_2(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.remove_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}), True)\n self.assertEqual(tracker.portfolio, [{'name': 'MSFT', 'price': 150.0, 'quantity': 10}])\n\n def test_remove_stock_3(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.remove_stock({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 20}), False)\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}])\n\n def test_remove_stock_4(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.remove_stock({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 10}), False)\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}])\n\n def test_remove_stock_5(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.remove_stock({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 10}), True)\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}])", "solution_code": "def remove_stock(self, stock):\n for pf in self.portfolio:\n if pf['name'] == stock['name'] and pf['quantity'] >= stock['quantity']:\n pf['quantity'] -= stock['quantity']\n if pf['quantity'] == 0:\n self.portfolio.remove(pf)\n return True\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.portfolio" ], "method_dependencies": [] } }, { "method_name": "buy_stock", "method_description": "def buy_stock(self, stock):\n \"\"\"\n Buy a stock and add it to the portfolio.\n :param stock: a dictionary with keys \"name\", \"price\", and \"quantity\"\n :param quantity: the quantity of the stock to buy,int.\n :return: True if the stock was bought successfully, False if the cash balance is not enough.\n >>> tracker = StockPortfolioTracker(10000.0)\n >>> tracker.buy_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10})\n True\n >>> tracker.portfolio\n [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n\n \"\"\"", "test_class": "StockPortfolioTrackerTestBuyStock", "test_code": "class StockPortfolioTrackerTestBuyStock(unittest.TestCase):\n def test_buy_stock(self):\n tracker = StockPortfolioTracker(10000.0)\n self.assertEqual(tracker.buy_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}), True)\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}])\n self.assertEqual(tracker.cash_balance, 8500.0)\n\n def test_buy_stock_2(self):\n tracker = StockPortfolioTracker(1000.0)\n self.assertEqual(tracker.buy_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}), False)\n self.assertEqual(tracker.portfolio, [])\n self.assertEqual(tracker.cash_balance, 1000.0)\n\n def test_buy_stock_3(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.buy_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}), True)\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 20}])\n self.assertEqual(tracker.cash_balance, 8500.0)\n\n def test_buy_stock_4(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.buy_stock({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 10}), True)\n self.assertEqual(tracker.buy_stock({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 10}), True)\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 20}])\n self.assertEqual(tracker.cash_balance, 7000.0)\n\n def test_buy_stock_5(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.buy_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}), True)\n self.assertEqual(tracker.buy_stock({\"name\": \"MSFT\", \"price\": 150.0, \"quantity\": 10}), True)\n self.assertEqual(tracker.portfolio, [{'name': 'AAPL', 'price': 150.0, 'quantity': 20},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}])\n self.assertEqual(tracker.cash_balance, 7000.0)", "solution_code": "def buy_stock(self, stock):\n if stock['price'] * stock['quantity'] > self.cash_balance:\n return False\n else:\n self.add_stock(stock)\n self.cash_balance -= stock['price'] * stock['quantity']\n return True", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.cash_balance" ], "method_dependencies": [ "add_stock" ] } }, { "method_name": "sell_stock", "method_description": "def sell_stock(self, stock):\n \"\"\"\n Sell a stock and remove it from the portfolio and add the cash to the cash balance.\n :param stock: a dictionary with keys \"name\", \"price\", and \"quantity\"\n :param quantity: the quantity of the stock to sell,int.\n :return: True if the stock was sold successfully, False if the quantity of the stock is not enough.\n >>> tracker = StockPortfolioTracker(10000.0)\n >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n >>> tracker.sell_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10})\n True\n >>> tracker.portfolio\n []\n\n \"\"\"", "test_class": "StockPortfolioTrackerTestSellStock", "test_code": "class StockPortfolioTrackerTestSellStock(unittest.TestCase):\n def test_sell_stock(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.sell_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 9}), True)\n self.assertEqual(tracker.portfolio, [{\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 1}])\n self.assertEqual(tracker.cash_balance, 11350.0)\n\n def test_sell_stock_2(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.sell_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 20}), False)\n self.assertEqual(tracker.portfolio, [{\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}])\n self.assertEqual(tracker.cash_balance, 10000.0)\n\n def test_sell_stock_3(self):\n tracker = StockPortfolioTracker(10000.0)\n self.assertEqual(tracker.sell_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}), False)\n self.assertEqual(tracker.portfolio, [])\n self.assertEqual(tracker.cash_balance, 10000.0)\n\n def test_sell_stock_4(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 20}]\n self.assertEqual(tracker.sell_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 20}), True)\n self.assertEqual(tracker.portfolio, [])\n self.assertEqual(tracker.cash_balance, 13000.0)\n\n def test_sell_stock_5(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 20},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.sell_stock({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 20}), True)\n self.assertEqual(tracker.portfolio, [{'name': 'MSFT', 'price': 150.0, 'quantity': 10}])\n self.assertEqual(tracker.cash_balance, 13000.0)", "solution_code": "def sell_stock(self, stock):\n if self.remove_stock(stock) == False:\n return False\n self.cash_balance += stock['price'] * stock['quantity']\n return True", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.cash_balance" ], "method_dependencies": [ "remove_stock" ] } }, { "method_name": "calculate_portfolio_value", "method_description": "def calculate_portfolio_value(self):\n \"\"\"\n Calculate the total value of the portfolio.\n :return: the total value of the portfolio, float.\n >>> tracker = StockPortfolioTracker(10000.0)\n >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n >>> tracker.calculate_portfolio_value()\n 11500.0\n\n \"\"\"", "test_class": "StockPortfolioTrackerTestCalculatePortfolioValue", "test_code": "class StockPortfolioTrackerTestCalculatePortfolioValue(unittest.TestCase):\n def test_calculate_portfolio_value(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.calculate_portfolio_value(), 11500.0)\n\n def test_calculate_portfolio_value_2(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.calculate_portfolio_value(), 13000.0)\n\n def test_calculate_portfolio_value_3(self):\n tracker = StockPortfolioTracker(10000.0)\n self.assertEqual(tracker.calculate_portfolio_value(), 10000.0)\n\n def test_calculate_portfolio_value_4(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 0}]\n self.assertEqual(tracker.calculate_portfolio_value(), 10000.0)\n\n def test_calculate_portfolio_value_5(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 0.0, 'quantity': 10}]\n self.assertEqual(tracker.calculate_portfolio_value(), 10000.0)", "solution_code": "def calculate_portfolio_value(self):\n total_value = self.cash_balance\n for stock in self.portfolio:\n total_value += stock['price'] * stock['quantity']\n return total_value", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.cash_balance", "self.portfolio" ], "method_dependencies": [] } }, { "method_name": "get_portfolio_summary", "method_description": "def get_portfolio_summary(self):\n \"\"\"\n Get a summary of the portfolio.\n :return: a tuple of the total value of the portfolio and a list of dictionaries with keys \"name\" and \"value\"\n >>> tracker = StockPortfolioTracker(10000.0)\n >>> tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n >>> tracker.get_portfolio_summary()\n (11500.0, [{'name': 'AAPL', 'value': 1500.0}])\n\n \"\"\"", "test_class": "StockPortfolioTrackerTestGetPortfolioSummary", "test_code": "class StockPortfolioTrackerTestGetPortfolioSummary(unittest.TestCase):\n def test_get_portfolio_summary(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.get_portfolio_summary(), (11500.0, [{'name': 'AAPL', 'value': 1500.0}]))\n\n def test_get_portfolio_summary_2(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 10},\n {'name': 'MSFT', 'price': 150.0, 'quantity': 10}]\n self.assertEqual(tracker.get_portfolio_summary(),\n (13000.0, [{'name': 'AAPL', 'value': 1500.0}, {'name': 'MSFT', 'value': 1500.0}]))\n\n def test_get_portfolio_summary_3(self):\n tracker = StockPortfolioTracker(10000.0)\n self.assertEqual(tracker.get_portfolio_summary(), (10000.0, []))\n\n def test_get_portfolio_summary_4(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 150.0, 'quantity': 0}]\n self.assertEqual(tracker.get_portfolio_summary(), (10000.0, [{'name': 'AAPL', 'value': 0.0}]))\n\n def test_get_portfolio_summary_5(self):\n tracker = StockPortfolioTracker(10000.0)\n tracker.portfolio = [{'name': 'AAPL', 'price': 0.0, 'quantity': 10}]\n self.assertEqual(tracker.get_portfolio_summary(), (10000.0, [{'name': 'AAPL', 'value': 0.0}]))", "solution_code": "def get_portfolio_summary(self):\n summary = []\n for stock in self.portfolio:\n value = self.get_stock_value(stock)\n summary.append({\"name\": stock[\"name\"], \"value\": value})\n portfolio_value = self.calculate_portfolio_value()\n return portfolio_value, summary", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.portfolio" ], "method_dependencies": [ "calculate_portfolio_value", "get_stock_value" ] } }, { "method_name": "get_stock_value", "method_description": "def get_stock_value(self, stock):\n \"\"\"\n Get the value of a stock.\n :param stock: a dictionary with keys \"name\", \"price\", and \"quantity\"\n :return: the value of the stock, float.\n >>> tracker = StockPortfolioTracker(10000.0)\n >>> tracker.get_stock_value({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10})\n 1500.0\n\n \"\"\"", "test_class": "StockPortfolioTrackerTestGetStockValue", "test_code": "class StockPortfolioTrackerTestGetStockValue(unittest.TestCase):\n def test_get_stock_value(self):\n tracker = StockPortfolioTracker(10000.0)\n self.assertEqual(tracker.get_stock_value({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 10}), 1500.0)\n\n def test_get_stock_value_2(self):\n tracker = StockPortfolioTracker(10000.0)\n self.assertEqual(tracker.get_stock_value({\"name\": \"AAPL\", \"price\": 150.0, \"quantity\": 0}), 0.0)\n\n def test_get_stock_value_3(self):\n tracker = StockPortfolioTracker(10000.0)\n self.assertEqual(tracker.get_stock_value({\"name\": \"AAPL\", \"price\": 0.0, \"quantity\": 10}), 0.0)\n\n def test_get_stock_value_4(self):\n tracker = StockPortfolioTracker(10000.0)\n self.assertEqual(tracker.get_stock_value({\"name\": \"AAPL\", \"price\": 0.0, \"quantity\": 0}), 0.0)\n\n def test_get_stock_value_5(self):\n tracker = StockPortfolioTracker(10000.0)\n self.assertEqual(tracker.get_stock_value({\"name\": \"MSFL\", \"price\": 150.0, \"quantity\": 2}), 300.0)", "solution_code": "def get_stock_value(self, stock):\n return stock['price'] * stock['quantity']", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_83", "skeleton": "\nimport sqlite3\n\nclass StudentDatabaseProcessor:\n \"\"\"\n This is a class with database operation, including inserting student information, searching for student information by name, and deleting student information by name.\n \"\"\"\n\n def __init__(self, database_name):\n \"\"\"\n Initializes the StudentDatabaseProcessor object with the specified database name.\n :param database_name: str, the name of the SQLite database.\n \"\"\"\n self.database_name = database_name\n\n def create_student_table(self):\n \"\"\"\n Creates a \"students\" table in the database if it does not exist already.Fields include ID of type int, name of type str, age of type int, gender of type str, and grade of type int\n :return: None\n >>> processor = StudentDatabaseProcessor(\"students.db\")\n >>> processor.create_student_table()\n \"\"\"\n\n def insert_student(self, student_data):\n \"\"\"\n Inserts a new student into the \"students\" table.\n :param student_data: dict, a dictionary containing the student's information (name, age, gender, grade).\n :return: None\n >>> processor = StudentDatabaseProcessor(\"students.db\")\n >>> processor.create_student_table()\n >>> student_data = {'name': 'John', 'age': 15, 'gender': 'Male', 'grade': 9}\n >>> processor.insert_student(student_data)\n \"\"\"\n\n def search_student_by_name(self, name):\n \"\"\"\n Searches for a student in the \"students\" table by their name.\n :param name: str, the name of the student to search for.\n :return: list of tuples, the rows from the \"students\" table that match the search criteria.\n >>> processor = StudentDatabaseProcessor(\"students.db\")\n >>> processor.create_student_table()\n >>> result = processor.search_student_by_name(\"John\")\n \"\"\"\n\n def delete_student_by_name(self, name):\n \"\"\"\n Deletes a student from the \"students\" table by their name.\n :param name: str, the name of the student to delete.\n :return: None\n >>> processor = StudentDatabaseProcessor(\"students.db\")\n >>> processor.create_student_table()\n >>> student_data = {'name': 'John', 'age': 15, 'gender': 'Male', 'grade': 9}\n >>> processor.insert_student(student_data)\n >>> processor.delete_student_by_name(\"John\")\n \"\"\"", "test": "import unittest\n\n\nclass StudentDatabaseProcessorTestInsertStudent(unittest.TestCase):\n def setUp(self):\n self.processor = StudentDatabaseProcessor(\"test_database.db\")\n self.processor.create_student_table()\n\n def tearDown(self):\n conn = sqlite3.connect(\"test_database.db\")\n conn.execute(\"DROP TABLE IF EXISTS students\")\n conn.commit()\n conn.close()\n\n def test_insert_student_1(self):\n student_data = {\n 'name': 'Alice',\n 'age': 20,\n 'gender': 'female',\n 'grade': 90\n }\n self.processor.insert_student(student_data)\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('Alice',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'Alice')\n\n def test_insert_student_2(self):\n student_data = {\n 'name': 'aaa',\n 'age': 20,\n 'gender': 'female',\n 'grade': 90\n }\n self.processor.insert_student(student_data)\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('aaa',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'aaa')\n\n def test_insert_student_3(self):\n student_data = {\n 'name': 'bbb',\n 'age': 20,\n 'gender': 'female',\n 'grade': 90\n }\n self.processor.insert_student(student_data)\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('bbb',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'bbb')\n\n def test_insert_student_4(self):\n student_data = {\n 'name': 'ccc',\n 'age': 20,\n 'gender': 'female',\n 'grade': 90\n }\n self.processor.insert_student(student_data)\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('ccc',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'ccc')\n\n def test_insert_student_5(self):\n student_data = {\n 'name': 'ddd',\n 'age': 20,\n 'gender': 'female',\n 'grade': 90\n }\n self.processor.insert_student(student_data)\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('ddd',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'ddd')\n\n\nclass StudentDatabaseProcessorTestSearchStudentByName(unittest.TestCase):\n def setUp(self):\n self.processor = StudentDatabaseProcessor(\"test_database.db\")\n self.processor.create_student_table()\n\n def tearDown(self):\n conn = sqlite3.connect(\"test_database.db\")\n conn.execute(\"DROP TABLE IF EXISTS students\")\n conn.commit()\n conn.close()\n\n def test_search_student_by_name_1(self):\n student_data = {\n 'name': 'Bob',\n 'age': 19,\n 'gender': 'male',\n 'grade': 85\n }\n self.processor.insert_student(student_data)\n\n result = self.processor.search_student_by_name('Bob')\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'Bob')\n\n def test_search_student_by_name_2(self):\n student_data = {\n 'name': 'aaa',\n 'age': 19,\n 'gender': 'male',\n 'grade': 85\n }\n self.processor.insert_student(student_data)\n\n result = self.processor.search_student_by_name('aaa')\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'aaa')\n\n def test_search_student_by_name_3(self):\n student_data = {\n 'name': 'bbb',\n 'age': 19,\n 'gender': 'male',\n 'grade': 85\n }\n self.processor.insert_student(student_data)\n\n result = self.processor.search_student_by_name('bbb')\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'bbb')\n\n def test_search_student_by_name_4(self):\n student_data = {\n 'name': 'ccc',\n 'age': 19,\n 'gender': 'male',\n 'grade': 85\n }\n self.processor.insert_student(student_data)\n\n result = self.processor.search_student_by_name('ccc')\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'ccc')\n\n def test_search_student_by_name_5(self):\n student_data = {\n 'name': 'ddd',\n 'age': 19,\n 'gender': 'male',\n 'grade': 85\n }\n self.processor.insert_student(student_data)\n\n result = self.processor.search_student_by_name('ddd')\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'ddd')\n\n\nclass StudentDatabaseProcessorTestDeleteStudentByName(unittest.TestCase):\n def setUp(self):\n self.processor = StudentDatabaseProcessor(\"test_database.db\")\n self.processor.create_student_table()\n\n def tearDown(self):\n conn = sqlite3.connect(\"test_database.db\")\n conn.execute(\"DROP TABLE IF EXISTS students\")\n conn.commit()\n conn.close()\n\n def test_delete_student_by_name_1(self):\n student_data = {\n 'name': 'Charlie',\n 'age': 18,\n 'gender': 'male',\n 'grade': 95\n }\n self.processor.insert_student(student_data)\n\n self.processor.delete_student_by_name('Charlie')\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('Charlie',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 0)\n\n def test_delete_student_by_name_2(self):\n student_data = {\n 'name': 'aaa',\n 'age': 18,\n 'gender': 'male',\n 'grade': 95\n }\n self.processor.insert_student(student_data)\n\n self.processor.delete_student_by_name('aaa')\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('aaa',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 0)\n\n def test_delete_student_by_name_3(self):\n student_data = {\n 'name': 'bbb',\n 'age': 18,\n 'gender': 'male',\n 'grade': 95\n }\n self.processor.insert_student(student_data)\n\n self.processor.delete_student_by_name('bbb')\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('bbb',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 0)\n\n def test_delete_student_by_name_4(self):\n student_data = {\n 'name': 'ccc',\n 'age': 18,\n 'gender': 'male',\n 'grade': 95\n }\n self.processor.insert_student(student_data)\n\n self.processor.delete_student_by_name('ccc')\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('ccc',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 0)\n\n def test_delete_student_by_name_5(self):\n student_data = {\n 'name': 'ddd',\n 'age': 18,\n 'gender': 'male',\n 'grade': 95\n }\n self.processor.insert_student(student_data)\n\n self.processor.delete_student_by_name('ddd')\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('ddd',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 0)\n\n\nclass StudentDatabaseProcessorTest(unittest.TestCase):\n def setUp(self):\n self.processor = StudentDatabaseProcessor(\"test_database.db\")\n self.processor.create_student_table()\n\n def tearDown(self):\n conn = sqlite3.connect(\"test_database.db\")\n conn.execute(\"DROP TABLE IF EXISTS students\")\n conn.commit()\n conn.close()\n\n def test_StudentDatabaseProcessor(self):\n student_data = {\n 'name': 'Alice',\n 'age': 20,\n 'gender': 'female',\n 'grade': 90\n }\n self.processor.insert_student(student_data)\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('Alice',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'Alice')\n\n student_data = {\n 'name': 'Bob',\n 'age': 19,\n 'gender': 'male',\n 'grade': 85\n }\n self.processor.insert_student(student_data)\n\n result = self.processor.search_student_by_name('Bob')\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'Bob')\n\n student_data = {\n 'name': 'Charlie',\n 'age': 18,\n 'gender': 'male',\n 'grade': 95\n }\n self.processor.insert_student(student_data)\n\n self.processor.delete_student_by_name('Charlie')\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('Charlie',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 0)", "solution_code": "import sqlite3\n\n\nclass StudentDatabaseProcessor:\n\n def __init__(self, database_name):\n self.database_name = database_name\n\n def create_student_table(self):\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n\n create_table_query = \"\"\"\n CREATE TABLE IF NOT EXISTS students (\n id INTEGER PRIMARY KEY,\n name TEXT,\n age INTEGER,\n gender TEXT,\n grade INTEGER\n )\n \"\"\"\n cursor.execute(create_table_query)\n\n conn.commit()\n conn.close()\n\n def insert_student(self, student_data):\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n\n insert_query = \"\"\"\n INSERT INTO students (name, age, gender, grade)\n VALUES (?, ?, ?, ?)\n \"\"\"\n cursor.execute(insert_query,\n (student_data['name'], student_data['age'], student_data['gender'], student_data['grade']))\n\n conn.commit()\n conn.close()\n\n def search_student_by_name(self, name):\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n\n select_query = \"SELECT * FROM students WHERE name = ?\"\n cursor.execute(select_query, (name,))\n result = cursor.fetchall()\n\n conn.close()\n\n return result\n\n def delete_student_by_name(self, name):\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n\n delete_query = \"DELETE FROM students WHERE name = ?\"\n cursor.execute(delete_query, (name,))\n\n conn.commit()\n conn.close()", "import_statement": [ "import sqlite3" ], "class_description": " \"\"\"\n This is a class with database operation, including inserting student information, searching for student information by name, and deleting student information by name.\n \"\"\"\n", "class_name": "StudentDatabaseProcessor", "test_classes": [ "StudentDatabaseProcessorTestInsertStudent", "StudentDatabaseProcessorTestSearchStudentByName", "StudentDatabaseProcessorTestDeleteStudentByName", "StudentDatabaseProcessorTest" ], "class_constructor": "class StudentDatabaseProcessor: \n def __init__(self, database_name):\n \"\"\"\n Initializes the StudentDatabaseProcessor object with the specified database name.\n :param database_name: str, the name of the SQLite database.\n \"\"\"\n self.database_name = database_name\n\n", "fields": [ "self.database_name" ], "methods_info": [ { "method_name": "create_student_table", "method_description": "def create_student_table(self):\n \"\"\"\n Creates a \"students\" table in the database if it does not exist already.Fields include ID of type int, name of type str, age of type int, gender of type str, and grade of type int\n :return: None\n >>> processor = StudentDatabaseProcessor(\"students.db\")\n >>> processor.create_student_table()\n \"\"\"", "test_class": "StudentDatabaseProcessorTestInsertStudent", "test_code": "class StudentDatabaseProcessorTestInsertStudent(unittest.TestCase):\n def setUp(self):\n self.processor = StudentDatabaseProcessor(\"test_database.db\")\n self.processor.create_student_table()\n\n def tearDown(self):\n conn = sqlite3.connect(\"test_database.db\")\n conn.execute(\"DROP TABLE IF EXISTS students\")\n conn.commit()\n conn.close()\n\n def test_insert_student_1(self):\n student_data = {\n 'name': 'Alice',\n 'age': 20,\n 'gender': 'female',\n 'grade': 90\n }\n self.processor.insert_student(student_data)\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('Alice',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'Alice')\n\n def test_insert_student_2(self):\n student_data = {\n 'name': 'aaa',\n 'age': 20,\n 'gender': 'female',\n 'grade': 90\n }\n self.processor.insert_student(student_data)\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('aaa',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'aaa')\n\n def test_insert_student_3(self):\n student_data = {\n 'name': 'bbb',\n 'age': 20,\n 'gender': 'female',\n 'grade': 90\n }\n self.processor.insert_student(student_data)\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('bbb',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'bbb')\n\n def test_insert_student_4(self):\n student_data = {\n 'name': 'ccc',\n 'age': 20,\n 'gender': 'female',\n 'grade': 90\n }\n self.processor.insert_student(student_data)\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('ccc',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'ccc')\n\n def test_insert_student_5(self):\n student_data = {\n 'name': 'ddd',\n 'age': 20,\n 'gender': 'female',\n 'grade': 90\n }\n self.processor.insert_student(student_data)\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('ddd',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'ddd')", "solution_code": "def create_student_table(self):\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n\n create_table_query = \"\"\"\n CREATE TABLE IF NOT EXISTS students (\n id INTEGER PRIMARY KEY,\n name TEXT,\n age INTEGER,\n gender TEXT,\n grade INTEGER\n )\n \"\"\"\n cursor.execute(create_table_query)\n\n conn.commit()\n conn.close()", "dependencies": { "Standalone": false, "lib_dependencies": [ "sqlite3" ], "field_dependencies": [ "self.database_name" ], "method_dependencies": [] } }, { "method_name": "insert_student", "method_description": "def insert_student(self, student_data):\n \"\"\"\n Inserts a new student into the \"students\" table.\n :param student_data: dict, a dictionary containing the student's information (name, age, gender, grade).\n :return: None\n >>> processor = StudentDatabaseProcessor(\"students.db\")\n >>> processor.create_student_table()\n >>> student_data = {'name': 'John', 'age': 15, 'gender': 'Male', 'grade': 9}\n >>> processor.insert_student(student_data)\n \"\"\"", "test_class": "StudentDatabaseProcessorTestSearchStudentByName", "test_code": "class StudentDatabaseProcessorTestSearchStudentByName(unittest.TestCase):\n def setUp(self):\n self.processor = StudentDatabaseProcessor(\"test_database.db\")\n self.processor.create_student_table()\n\n def tearDown(self):\n conn = sqlite3.connect(\"test_database.db\")\n conn.execute(\"DROP TABLE IF EXISTS students\")\n conn.commit()\n conn.close()\n\n def test_search_student_by_name_1(self):\n student_data = {\n 'name': 'Bob',\n 'age': 19,\n 'gender': 'male',\n 'grade': 85\n }\n self.processor.insert_student(student_data)\n\n result = self.processor.search_student_by_name('Bob')\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'Bob')\n\n def test_search_student_by_name_2(self):\n student_data = {\n 'name': 'aaa',\n 'age': 19,\n 'gender': 'male',\n 'grade': 85\n }\n self.processor.insert_student(student_data)\n\n result = self.processor.search_student_by_name('aaa')\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'aaa')\n\n def test_search_student_by_name_3(self):\n student_data = {\n 'name': 'bbb',\n 'age': 19,\n 'gender': 'male',\n 'grade': 85\n }\n self.processor.insert_student(student_data)\n\n result = self.processor.search_student_by_name('bbb')\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'bbb')\n\n def test_search_student_by_name_4(self):\n student_data = {\n 'name': 'ccc',\n 'age': 19,\n 'gender': 'male',\n 'grade': 85\n }\n self.processor.insert_student(student_data)\n\n result = self.processor.search_student_by_name('ccc')\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'ccc')\n\n def test_search_student_by_name_5(self):\n student_data = {\n 'name': 'ddd',\n 'age': 19,\n 'gender': 'male',\n 'grade': 85\n }\n self.processor.insert_student(student_data)\n\n result = self.processor.search_student_by_name('ddd')\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'ddd')", "solution_code": "def insert_student(self, student_data):\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n\n insert_query = \"\"\"\n INSERT INTO students (name, age, gender, grade)\n VALUES (?, ?, ?, ?)\n \"\"\"\n cursor.execute(insert_query,\n (student_data['name'], student_data['age'], student_data['gender'], student_data['grade']))\n\n conn.commit()\n conn.close()", "dependencies": { "Standalone": false, "lib_dependencies": [ "sqlite3" ], "field_dependencies": [ "self.database_name" ], "method_dependencies": [] } }, { "method_name": "search_student_by_name", "method_description": "def search_student_by_name(self, name):\n \"\"\"\n Searches for a student in the \"students\" table by their name.\n :param name: str, the name of the student to search for.\n :return: list of tuples, the rows from the \"students\" table that match the search criteria.\n >>> processor = StudentDatabaseProcessor(\"students.db\")\n >>> processor.create_student_table()\n >>> result = processor.search_student_by_name(\"John\")\n \"\"\"", "test_class": "StudentDatabaseProcessorTestDeleteStudentByName", "test_code": "class StudentDatabaseProcessorTestDeleteStudentByName(unittest.TestCase):\n def setUp(self):\n self.processor = StudentDatabaseProcessor(\"test_database.db\")\n self.processor.create_student_table()\n\n def tearDown(self):\n conn = sqlite3.connect(\"test_database.db\")\n conn.execute(\"DROP TABLE IF EXISTS students\")\n conn.commit()\n conn.close()\n\n def test_delete_student_by_name_1(self):\n student_data = {\n 'name': 'Charlie',\n 'age': 18,\n 'gender': 'male',\n 'grade': 95\n }\n self.processor.insert_student(student_data)\n\n self.processor.delete_student_by_name('Charlie')\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('Charlie',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 0)\n\n def test_delete_student_by_name_2(self):\n student_data = {\n 'name': 'aaa',\n 'age': 18,\n 'gender': 'male',\n 'grade': 95\n }\n self.processor.insert_student(student_data)\n\n self.processor.delete_student_by_name('aaa')\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('aaa',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 0)\n\n def test_delete_student_by_name_3(self):\n student_data = {\n 'name': 'bbb',\n 'age': 18,\n 'gender': 'male',\n 'grade': 95\n }\n self.processor.insert_student(student_data)\n\n self.processor.delete_student_by_name('bbb')\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('bbb',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 0)\n\n def test_delete_student_by_name_4(self):\n student_data = {\n 'name': 'ccc',\n 'age': 18,\n 'gender': 'male',\n 'grade': 95\n }\n self.processor.insert_student(student_data)\n\n self.processor.delete_student_by_name('ccc')\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('ccc',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 0)\n\n def test_delete_student_by_name_5(self):\n student_data = {\n 'name': 'ddd',\n 'age': 18,\n 'gender': 'male',\n 'grade': 95\n }\n self.processor.insert_student(student_data)\n\n self.processor.delete_student_by_name('ddd')\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('ddd',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 0)", "solution_code": "def search_student_by_name(self, name):\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n\n select_query = \"SELECT * FROM students WHERE name = ?\"\n cursor.execute(select_query, (name,))\n result = cursor.fetchall()\n\n conn.close()\n\n return result", "dependencies": { "Standalone": false, "lib_dependencies": [ "sqlite3" ], "field_dependencies": [ "self.database_name" ], "method_dependencies": [] } }, { "method_name": "delete_student_by_name", "method_description": "def delete_student_by_name(self, name):\n \"\"\"\n Deletes a student from the \"students\" table by their name.\n :param name: str, the name of the student to delete.\n :return: None\n >>> processor = StudentDatabaseProcessor(\"students.db\")\n >>> processor.create_student_table()\n >>> student_data = {'name': 'John', 'age': 15, 'gender': 'Male', 'grade': 9}\n >>> processor.insert_student(student_data)\n >>> processor.delete_student_by_name(\"John\")\n \"\"\"", "test_class": "StudentDatabaseProcessorTest", "test_code": "class StudentDatabaseProcessorTest(unittest.TestCase):\n def setUp(self):\n self.processor = StudentDatabaseProcessor(\"test_database.db\")\n self.processor.create_student_table()\n\n def tearDown(self):\n conn = sqlite3.connect(\"test_database.db\")\n conn.execute(\"DROP TABLE IF EXISTS students\")\n conn.commit()\n conn.close()\n\n def test_StudentDatabaseProcessor(self):\n student_data = {\n 'name': 'Alice',\n 'age': 20,\n 'gender': 'female',\n 'grade': 90\n }\n self.processor.insert_student(student_data)\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('Alice',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'Alice')\n\n student_data = {\n 'name': 'Bob',\n 'age': 19,\n 'gender': 'male',\n 'grade': 85\n }\n self.processor.insert_student(student_data)\n\n result = self.processor.search_student_by_name('Bob')\n\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0][1], 'Bob')\n\n student_data = {\n 'name': 'Charlie',\n 'age': 18,\n 'gender': 'male',\n 'grade': 95\n }\n self.processor.insert_student(student_data)\n\n self.processor.delete_student_by_name('Charlie')\n\n conn = sqlite3.connect(\"test_database.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM students WHERE name=?\", ('Charlie',))\n result = cursor.fetchall()\n conn.close()\n\n self.assertEqual(len(result), 0)", "solution_code": "def delete_student_by_name(self, name):\n conn = sqlite3.connect(self.database_name)\n cursor = conn.cursor()\n\n delete_query = \"DELETE FROM students WHERE name = ?\"\n cursor.execute(delete_query, (name,))\n\n conn.commit()\n conn.close()", "dependencies": { "Standalone": false, "lib_dependencies": [ "sqlite3" ], "field_dependencies": [ "self.database_name" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_84", "skeleton": "\nimport json\n\nclass TextFileProcessor:\n \"\"\"\n The class handles reading, writing, and processing text files. It can read the file as JSON, read the raw text, write content to the file, and process the file by removing non-alphabetic characters.\n \"\"\"\n\n def __init__(self, file_path):\n \"\"\"\n Initialize the file path.\n :param file_path: str\n \"\"\"\n self.file_path = file_path\n\n def read_file_as_json(self):\n \"\"\"\n Read the self.file_path file as json format.\n if the file content doesn't obey json format, the code will raise error.\n :return data: dict if the file is stored as json format, or str/int/float.. according to the file content otherwise.\n >>> textFileProcessor = TextFileProcessor('test.json')\n >>> textFileProcessor.read_file_as_json()\n {'name': 'test', 'age': 12}\n >>> type(textFileProcessor.read_file_as_json())\n \n \"\"\"\n\n def read_file(self):\n \"\"\"\n Read the return the content of self.file_path file.\n :return: the same return as the read() method\n >>> textFileProcessor = TextFileProcessor('test.json')\n >>> textFileProcessor.read_file()\n '{\\n \"name\": \"test\",\\n \"age\": 12\\n}'\n \"\"\"\n\n def write_file(self, content):\n \"\"\"\n Write content into the self.file_path file, and overwrite if the file has already existed.\n :param content: any content\n >>> textFileProcessor = TextFileProcessor('test.json')\n >>> textFileProcessor.write_file('Hello world!')\n >>> textFileProcessor.read_file()\n 'Hello world!'\n \"\"\"\n\n def process_file(self):\n \"\"\"\n Read the self.file_path file and filter out non-alphabetic characters from the content string.\n Overwrite the after-processed data into the same self.file_path file.\n >>> textFileProcessor = TextFileProcessor('test.json')\n >>> textFileProcessor.read_file()\n '{\\n \"name\": \"test\",\\n \"age\": 12\\n}'\n >>> textFileProcessor.process_file()\n 'nametestage'\n \"\"\"", "test": "import unittest\nimport json\nfrom unittest.mock import MagicMock\nimport os\n\n\nclass TextFileProcessorTestReadFileAsJson(unittest.TestCase):\n def setUp(self):\n self.files = ['test_1.txt', 'test_2.txt', 'test_3.txt', 'test_4.txt', 'test_5.txt']\n self.contents = ['{\\n \"name\": \"test\",\\n \"age\": 12\\n}', '12345', '\\\"hello\\\"', '\\\"aaa\\\"', '\\\"bbb\\\"']\n for index, file in enumerate(self.files):\n with open(file, 'w') as f:\n f.write(self.contents[index])\n\n # the dict type\n def test_read_file_as_json_1(self):\n textFileProcessor = TextFileProcessor(self.files[0])\n data = textFileProcessor.read_file_as_json()\n expected = {\"name\": \"test\", \"age\": 12}\n self.assertEqual(dict, type(data))\n self.assertEqual(expected, data)\n\n # the int type\n def test_read_file_as_json_2(self):\n textFileProcessor = TextFileProcessor(self.files[1])\n data = textFileProcessor.read_file_as_json()\n expected = 12345\n self.assertEqual(int, type(data))\n self.assertEqual(expected, data)\n\n # the str type\n def test_read_file_as_json_3(self):\n textFileProcessor = TextFileProcessor(self.files[2])\n data = textFileProcessor.read_file_as_json()\n expected = 'hello'\n self.assertEqual(str, type(data))\n self.assertEqual(expected, data)\n\n def test_read_file_as_json_4(self):\n textFileProcessor = TextFileProcessor(self.files[3])\n data = textFileProcessor.read_file_as_json()\n expected = 'aaa'\n self.assertEqual(str, type(data))\n self.assertEqual(expected, data)\n\n def test_read_file_as_json_5(self):\n textFileProcessor = TextFileProcessor(self.files[4])\n data = textFileProcessor.read_file_as_json()\n expected = 'bbb'\n self.assertEqual(str, type(data))\n self.assertEqual(expected, data)\n\n\nclass TextFileProcessorTestReadFile(unittest.TestCase):\n def setUp(self) -> None:\n self.files = ['test_1.txt', 'test_2.txt', 'test_3.txt', 'test_4.txt', 'test_5.txt']\n self.contents = ['123aac\\n&^(*&43)', '12345', 'aaa', 'bbb', 'ccc']\n for index, file in enumerate(self.files):\n with open(file, 'w') as f:\n f.write(self.contents[index])\n\n def test_read_file_1(self):\n textFileProcessor = TextFileProcessor(self.files[0])\n data = textFileProcessor.read_file()\n self.assertEqual(str, type(data))\n self.assertEqual(data, self.contents[0])\n\n def test_read_file_2(self):\n textFileProcessor = TextFileProcessor(self.files[1])\n data = textFileProcessor.read_file()\n self.assertEqual(str, type(data))\n self.assertEqual(data, self.contents[1])\n\n def test_read_file_3(self):\n textFileProcessor = TextFileProcessor(self.files[2])\n data = textFileProcessor.read_file()\n self.assertEqual(str, type(data))\n self.assertEqual(data, self.contents[2])\n\n def test_read_file_4(self):\n textFileProcessor = TextFileProcessor(self.files[3])\n data = textFileProcessor.read_file()\n self.assertEqual(str, type(data))\n self.assertEqual(data, self.contents[3])\n\n def test_read_file_5(self):\n textFileProcessor = TextFileProcessor(self.files[4])\n data = textFileProcessor.read_file()\n self.assertEqual(str, type(data))\n self.assertEqual(data, self.contents[4])\n\n\nclass TextFileProcessorTestWriteFile(unittest.TestCase):\n def setUp(self) -> None:\n self.files = ['test_1.txt', 'test_2.txt', 'test_3.txt', 'test_4.txt', 'test_5.txt']\n self.contents = ['123aac\\n&^(*&43)', '12345', 'aaa', 'bbb', 'ccc']\n\n def tearDown(self) -> None:\n for file in self.files:\n if os.path.exists(file):\n os.remove(file)\n\n def test_write_file_1(self):\n textFileProcessor = TextFileProcessor(self.files[0])\n textFileProcessor.write_file(self.contents[0])\n with open(self.files[0], 'r') as f:\n data = f.read()\n self.assertEqual(data, self.contents[0])\n\n def test_write_file_2(self):\n textFileProcessor = TextFileProcessor(self.files[1])\n textFileProcessor.write_file(self.contents[1])\n with open(self.files[1], 'r') as f:\n data = f.read()\n self.assertEqual(data, self.contents[1])\n\n def test_write_file_3(self):\n textFileProcessor = TextFileProcessor(self.files[2])\n textFileProcessor.write_file(self.contents[2])\n with open(self.files[2], 'r') as f:\n data = f.read()\n self.assertEqual(data, self.contents[2])\n\n def test_write_file_4(self):\n textFileProcessor = TextFileProcessor(self.files[3])\n textFileProcessor.write_file(self.contents[3])\n with open(self.files[3], 'r') as f:\n data = f.read()\n self.assertEqual(data, self.contents[3])\n\n def test_write_file_5(self):\n textFileProcessor = TextFileProcessor(self.files[4])\n textFileProcessor.write_file(self.contents[4])\n with open(self.files[4], 'r') as f:\n data = f.read()\n self.assertEqual(data, self.contents[4])\n\n\nclass TextFileProcessorTestProcessFile(unittest.TestCase):\n def test_process_file_1(self):\n self.file = 'test.txt'\n self.content = 'Hello, 123 World!'\n self.expected_result = 'HelloWorld'\n\n textFileProcessor = TextFileProcessor(self.file)\n textFileProcessor.read_file = MagicMock(return_value=self.content)\n textFileProcessor.write_file = MagicMock()\n\n result = textFileProcessor.process_file()\n self.assertEqual(result, self.expected_result)\n textFileProcessor.read_file.assert_called_once()\n textFileProcessor.write_file.assert_called_once_with(self.expected_result)\n\n def test_process_file_2(self):\n self.file = 'test.txt'\n self.content = 'Hello, abc World!'\n self.expected_result = 'HelloabcWorld'\n\n textFileProcessor = TextFileProcessor(self.file)\n textFileProcessor.read_file = MagicMock(return_value=self.content)\n textFileProcessor.write_file = MagicMock()\n\n result = textFileProcessor.process_file()\n self.assertEqual(result, self.expected_result)\n textFileProcessor.read_file.assert_called_once()\n textFileProcessor.write_file.assert_called_once_with(self.expected_result)\n\n def test_process_file_3(self):\n self.file = 'test.txt'\n self.content = ', 123 !'\n self.expected_result = ''\n\n textFileProcessor = TextFileProcessor(self.file)\n textFileProcessor.read_file = MagicMock(return_value=self.content)\n textFileProcessor.write_file = MagicMock()\n\n result = textFileProcessor.process_file()\n self.assertEqual(result, self.expected_result)\n textFileProcessor.read_file.assert_called_once()\n textFileProcessor.write_file.assert_called_once_with(self.expected_result)\n\n def test_process_file_4(self):\n self.file = 'test.txt'\n self.content = 'Hello, World!'\n self.expected_result = 'HelloWorld'\n\n textFileProcessor = TextFileProcessor(self.file)\n textFileProcessor.read_file = MagicMock(return_value=self.content)\n textFileProcessor.write_file = MagicMock()\n\n result = textFileProcessor.process_file()\n self.assertEqual(result, self.expected_result)\n textFileProcessor.read_file.assert_called_once()\n textFileProcessor.write_file.assert_called_once_with(self.expected_result)\n\n def test_process_file_5(self):\n self.file = 'test.txt'\n self.content = 'Hello, 123a World!'\n self.expected_result = 'HelloaWorld'\n\n textFileProcessor = TextFileProcessor(self.file)\n textFileProcessor.read_file = MagicMock(return_value=self.content)\n textFileProcessor.write_file = MagicMock()\n\n result = textFileProcessor.process_file()\n self.assertEqual(result, self.expected_result)\n textFileProcessor.read_file.assert_called_once()\n textFileProcessor.write_file.assert_called_once_with(self.expected_result)\n\n\nclass TextFileProcessorTestMain(unittest.TestCase):\n def setUp(self) -> None:\n self.file = 'test.txt'\n self.content = '{\\n \"name\": \"test\",\\n \"age\": 12\\n}'\n with open(self.file, 'w') as f:\n f.write(self.content)\n\n def test_main(self):\n textFileProcessor = TextFileProcessor(self.file)\n data1 = textFileProcessor.read_file_as_json()\n expected1 = {\"name\": \"test\", \"age\": 12}\n self.assertEqual(dict, type(data1))\n self.assertEqual(expected1, data1)\n\n textFileProcessor.write_file(self.content)\n data2 = textFileProcessor.read_file()\n self.assertEqual(str, type(data2))\n self.assertEqual(self.content, data2)\n\n data3 = textFileProcessor.process_file()\n self.assertEqual(str, type(data3))\n expected2 = 'nametestage'\n self.assertEqual(expected2, data3)", "solution_code": "import json\n\n\nclass TextFileProcessor:\n def __init__(self, file_path):\n self.file_path = file_path\n\n def read_file_as_json(self):\n with open(self.file_path, 'r') as file:\n data = json.load(file)\n\n return data\n\n def read_file(self):\n with open(self.file_path, 'r') as file:\n return file.read()\n\n def write_file(self, content):\n with open(self.file_path, 'w') as file:\n file.write(content)\n\n def process_file(self):\n content = self.read_file()\n content = ''.join([char for char in content if char.isalpha()])\n self.write_file(content)\n return content", "import_statement": [ "import json" ], "class_description": " \"\"\"\n The class handles reading, writing, and processing text files. It can read the file as JSON, read the raw text, write content to the file, and process the file by removing non-alphabetic characters.\n \"\"\"\n", "class_name": "TextFileProcessor", "test_classes": [ "TextFileProcessorTestReadFileAsJson", "TextFileProcessorTestReadFile", "TextFileProcessorTestWriteFile", "TextFileProcessorTestProcessFile", "TextFileProcessorTestMain" ], "class_constructor": "class TextFileProcessor: \n def __init__(self, file_path):\n \"\"\"\n Initialize the file path.\n :param file_path: str\n \"\"\"\n self.file_path = file_path\n\n", "fields": [ "self.file_path" ], "methods_info": [ { "method_name": "read_file_as_json", "method_description": "def read_file_as_json(self):\n \"\"\"\n Read the self.file_path file as json format.\n if the file content doesn't obey json format, the code will raise error.\n :return data: dict if the file is stored as json format, or str/int/float.. according to the file content otherwise.\n >>> textFileProcessor = TextFileProcessor('test.json')\n >>> textFileProcessor.read_file_as_json()\n {'name': 'test', 'age': 12}\n >>> type(textFileProcessor.read_file_as_json())\n \n \"\"\"", "test_class": "TextFileProcessorTestReadFileAsJson", "test_code": "class TextFileProcessorTestReadFileAsJson(unittest.TestCase):\n def setUp(self):\n self.files = ['test_1.txt', 'test_2.txt', 'test_3.txt', 'test_4.txt', 'test_5.txt']\n self.contents = ['{\\n \"name\": \"test\",\\n \"age\": 12\\n}', '12345', '\\\"hello\\\"', '\\\"aaa\\\"', '\\\"bbb\\\"']\n for index, file in enumerate(self.files):\n with open(file, 'w') as f:\n f.write(self.contents[index])\n\n # the dict type\n def test_read_file_as_json_1(self):\n textFileProcessor = TextFileProcessor(self.files[0])\n data = textFileProcessor.read_file_as_json()\n expected = {\"name\": \"test\", \"age\": 12}\n self.assertEqual(dict, type(data))\n self.assertEqual(expected, data)\n\n # the int type\n def test_read_file_as_json_2(self):\n textFileProcessor = TextFileProcessor(self.files[1])\n data = textFileProcessor.read_file_as_json()\n expected = 12345\n self.assertEqual(int, type(data))\n self.assertEqual(expected, data)\n\n # the str type\n def test_read_file_as_json_3(self):\n textFileProcessor = TextFileProcessor(self.files[2])\n data = textFileProcessor.read_file_as_json()\n expected = 'hello'\n self.assertEqual(str, type(data))\n self.assertEqual(expected, data)\n\n def test_read_file_as_json_4(self):\n textFileProcessor = TextFileProcessor(self.files[3])\n data = textFileProcessor.read_file_as_json()\n expected = 'aaa'\n self.assertEqual(str, type(data))\n self.assertEqual(expected, data)\n\n def test_read_file_as_json_5(self):\n textFileProcessor = TextFileProcessor(self.files[4])\n data = textFileProcessor.read_file_as_json()\n expected = 'bbb'\n self.assertEqual(str, type(data))\n self.assertEqual(expected, data)", "solution_code": "def read_file_as_json(self):\n with open(self.file_path, 'r') as file:\n data = json.load(file)\n\n return data", "dependencies": { "Standalone": false, "lib_dependencies": [ "json" ], "field_dependencies": [ "self.file_path" ], "method_dependencies": [] } }, { "method_name": "read_file", "method_description": "def read_file(self):\n \"\"\"\n Read the return the content of self.file_path file.\n :return: the same return as the read() method\n >>> textFileProcessor = TextFileProcessor('test.json')\n >>> textFileProcessor.read_file()\n '{\\n \"name\": \"test\",\\n \"age\": 12\\n}'\n \"\"\"", "test_class": "TextFileProcessorTestReadFile", "test_code": "class TextFileProcessorTestReadFile(unittest.TestCase):\n def setUp(self) -> None:\n self.files = ['test_1.txt', 'test_2.txt', 'test_3.txt', 'test_4.txt', 'test_5.txt']\n self.contents = ['123aac\\n&^(*&43)', '12345', 'aaa', 'bbb', 'ccc']\n for index, file in enumerate(self.files):\n with open(file, 'w') as f:\n f.write(self.contents[index])\n\n def test_read_file_1(self):\n textFileProcessor = TextFileProcessor(self.files[0])\n data = textFileProcessor.read_file()\n self.assertEqual(str, type(data))\n self.assertEqual(data, self.contents[0])\n\n def test_read_file_2(self):\n textFileProcessor = TextFileProcessor(self.files[1])\n data = textFileProcessor.read_file()\n self.assertEqual(str, type(data))\n self.assertEqual(data, self.contents[1])\n\n def test_read_file_3(self):\n textFileProcessor = TextFileProcessor(self.files[2])\n data = textFileProcessor.read_file()\n self.assertEqual(str, type(data))\n self.assertEqual(data, self.contents[2])\n\n def test_read_file_4(self):\n textFileProcessor = TextFileProcessor(self.files[3])\n data = textFileProcessor.read_file()\n self.assertEqual(str, type(data))\n self.assertEqual(data, self.contents[3])\n\n def test_read_file_5(self):\n textFileProcessor = TextFileProcessor(self.files[4])\n data = textFileProcessor.read_file()\n self.assertEqual(str, type(data))\n self.assertEqual(data, self.contents[4])", "solution_code": "def read_file(self):\n with open(self.file_path, 'r') as file:\n return file.read()", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.file_path" ], "method_dependencies": [] } }, { "method_name": "write_file", "method_description": "def write_file(self, content):\n \"\"\"\n Write content into the self.file_path file, and overwrite if the file has already existed.\n :param content: any content\n >>> textFileProcessor = TextFileProcessor('test.json')\n >>> textFileProcessor.write_file('Hello world!')\n >>> textFileProcessor.read_file()\n 'Hello world!'\n \"\"\"", "test_class": "TextFileProcessorTestWriteFile", "test_code": "class TextFileProcessorTestWriteFile(unittest.TestCase):\n def setUp(self) -> None:\n self.files = ['test_1.txt', 'test_2.txt', 'test_3.txt', 'test_4.txt', 'test_5.txt']\n self.contents = ['123aac\\n&^(*&43)', '12345', 'aaa', 'bbb', 'ccc']\n\n def tearDown(self) -> None:\n for file in self.files:\n if os.path.exists(file):\n os.remove(file)\n\n def test_write_file_1(self):\n textFileProcessor = TextFileProcessor(self.files[0])\n textFileProcessor.write_file(self.contents[0])\n with open(self.files[0], 'r') as f:\n data = f.read()\n self.assertEqual(data, self.contents[0])\n\n def test_write_file_2(self):\n textFileProcessor = TextFileProcessor(self.files[1])\n textFileProcessor.write_file(self.contents[1])\n with open(self.files[1], 'r') as f:\n data = f.read()\n self.assertEqual(data, self.contents[1])\n\n def test_write_file_3(self):\n textFileProcessor = TextFileProcessor(self.files[2])\n textFileProcessor.write_file(self.contents[2])\n with open(self.files[2], 'r') as f:\n data = f.read()\n self.assertEqual(data, self.contents[2])\n\n def test_write_file_4(self):\n textFileProcessor = TextFileProcessor(self.files[3])\n textFileProcessor.write_file(self.contents[3])\n with open(self.files[3], 'r') as f:\n data = f.read()\n self.assertEqual(data, self.contents[3])\n\n def test_write_file_5(self):\n textFileProcessor = TextFileProcessor(self.files[4])\n textFileProcessor.write_file(self.contents[4])\n with open(self.files[4], 'r') as f:\n data = f.read()\n self.assertEqual(data, self.contents[4])", "solution_code": "def write_file(self, content):\n with open(self.file_path, 'w') as file:\n file.write(content)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.file_path" ], "method_dependencies": [] } }, { "method_name": "process_file", "method_description": "def process_file(self):\n \"\"\"\n Read the self.file_path file and filter out non-alphabetic characters from the content string.\n Overwrite the after-processed data into the same self.file_path file.\n >>> textFileProcessor = TextFileProcessor('test.json')\n >>> textFileProcessor.read_file()\n '{\\n \"name\": \"test\",\\n \"age\": 12\\n}'\n >>> textFileProcessor.process_file()\n 'nametestage'\n \"\"\"", "test_class": "TextFileProcessorTestProcessFile", "test_code": "class TextFileProcessorTestProcessFile(unittest.TestCase):\n def test_process_file_1(self):\n self.file = 'test.txt'\n self.content = 'Hello, 123 World!'\n self.expected_result = 'HelloWorld'\n\n textFileProcessor = TextFileProcessor(self.file)\n textFileProcessor.read_file = MagicMock(return_value=self.content)\n textFileProcessor.write_file = MagicMock()\n\n result = textFileProcessor.process_file()\n self.assertEqual(result, self.expected_result)\n textFileProcessor.read_file.assert_called_once()\n textFileProcessor.write_file.assert_called_once_with(self.expected_result)\n\n def test_process_file_2(self):\n self.file = 'test.txt'\n self.content = 'Hello, abc World!'\n self.expected_result = 'HelloabcWorld'\n\n textFileProcessor = TextFileProcessor(self.file)\n textFileProcessor.read_file = MagicMock(return_value=self.content)\n textFileProcessor.write_file = MagicMock()\n\n result = textFileProcessor.process_file()\n self.assertEqual(result, self.expected_result)\n textFileProcessor.read_file.assert_called_once()\n textFileProcessor.write_file.assert_called_once_with(self.expected_result)\n\n def test_process_file_3(self):\n self.file = 'test.txt'\n self.content = ', 123 !'\n self.expected_result = ''\n\n textFileProcessor = TextFileProcessor(self.file)\n textFileProcessor.read_file = MagicMock(return_value=self.content)\n textFileProcessor.write_file = MagicMock()\n\n result = textFileProcessor.process_file()\n self.assertEqual(result, self.expected_result)\n textFileProcessor.read_file.assert_called_once()\n textFileProcessor.write_file.assert_called_once_with(self.expected_result)\n\n def test_process_file_4(self):\n self.file = 'test.txt'\n self.content = 'Hello, World!'\n self.expected_result = 'HelloWorld'\n\n textFileProcessor = TextFileProcessor(self.file)\n textFileProcessor.read_file = MagicMock(return_value=self.content)\n textFileProcessor.write_file = MagicMock()\n\n result = textFileProcessor.process_file()\n self.assertEqual(result, self.expected_result)\n textFileProcessor.read_file.assert_called_once()\n textFileProcessor.write_file.assert_called_once_with(self.expected_result)\n\n def test_process_file_5(self):\n self.file = 'test.txt'\n self.content = 'Hello, 123a World!'\n self.expected_result = 'HelloaWorld'\n\n textFileProcessor = TextFileProcessor(self.file)\n textFileProcessor.read_file = MagicMock(return_value=self.content)\n textFileProcessor.write_file = MagicMock()\n\n result = textFileProcessor.process_file()\n self.assertEqual(result, self.expected_result)\n textFileProcessor.read_file.assert_called_once()\n textFileProcessor.write_file.assert_called_once_with(self.expected_result)", "solution_code": "def process_file(self):\n content = self.read_file()\n content = ''.join([char for char in content if char.isalpha()])\n self.write_file(content)\n return content", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "read_file", "write_file" ] } } ] }, { "task_id": "ClassEval_85", "skeleton": "\nimport time\n\nclass Thermostat:\n \"\"\"\n The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation.\n \"\"\"\n\n def __init__(self, current_temperature, target_temperature, mode):\n \"\"\"\n initialize instances of the Thermostat class, including the current temperature, target temperature, and operating mode.\n :param current_temperature: float\n :param target_temperature: float\n :param mode: str, the work mode\n \"\"\"\n self.current_temperature = current_temperature\n self.target_temperature = target_temperature\n self.mode = mode\n\n def get_target_temperature(self):\n \"\"\"\n Get the target temperature of an instance of the Thermostat class.\n :return self.current_temperature: int\n >>> thermostat.get_target_temperature()\n 37.5\n \"\"\"\n\n def set_target_temperature(self, temperature):\n \"\"\"\n Set the target temperature\n :param temperature: float, the target temperature\n >>> thermostat.set_target_temperature(37.6)\n >>> thermostat.target_temperature\n 37.6\n \"\"\"\n\n def get_mode(self):\n \"\"\"\n Get the current work mode\n :return mode: str, working mode. only ['heat', 'cool']\n \"\"\"\n\n def set_mode(self, mode):\n \"\"\"\n Get the current work mode\n :param mode: str, working mode. only ['heat', 'cool']\n >>> thermostat.set_mode('cool')\n >>> thermostat.mode\n 'cool'\n \"\"\"\n\n def auto_set_mode(self):\n \"\"\"\n Automatically set the operating mode by comparing with the current temperature and target temperature. If the current temperature is lower than the target temperature, the operating mode is set to 'heat', otherwise it is set to 'cool'.\n >>> thermostat = Thermostat(20.4, 37.5, 'cool')\n >>> thermostat.auto_set_mode()\n >>> thermostat.mode\n 'heat'\n \"\"\"\n\n def auto_check_conflict(self):\n \"\"\"\n Check if there is a conflict between the operating mode and the relationship between the current temperature and the target temperature.\n If there is a conflict, the operating mode will be adjusted automatically.\n :return: True if mode isn't conflict with the relationship between the current temperature and the target temperature, or False otherwise.\n >>> thermostat = Thermostat(20.4, 37.5, 'cool')\n >>> thermostat.auto_check_conflict()\n False\n >>> thermostat.mode\n 'heat'\n \"\"\"\n\n def simulate_operation(self):\n \"\"\"\n simulate the operation of Thermostat. It will automatically start the auto_set_mode method to set the operating mode,\n and then automatically adjust the current temperature according to the operating mode until the target temperature is reached.\n :return time: int, the time it took to complete the simulation.\n >>> thermostat = Thermostat(20.4, 37.5, 'cool')\n >>> thermostat.simulate_operation()\n 18\n \"\"\"", "test": "import unittest\n\nclass ThermostatTestGetTargetTemperature(unittest.TestCase):\n def test_get_target_temperature_1(self):\n t = Thermostat(20, 25, 'heat')\n self.assertEqual(t.get_target_temperature(), 25)\n\n def test_get_target_temperature_2(self):\n t = Thermostat(20, 25, 'cool')\n self.assertEqual(t.get_target_temperature(), 25)\n\n def test_get_target_temperature_3(self):\n t = Thermostat(20, 25, 'test')\n self.assertEqual(t.get_target_temperature(), 25)\n\n def test_get_target_temperature_4(self):\n t = Thermostat(25, 25, 'cool')\n self.assertEqual(t.get_target_temperature(), 25)\n\n def test_get_target_temperature_5(self):\n t = Thermostat(25, 25, 'heat')\n self.assertEqual(t.get_target_temperature(), 25)\n\n\nclass ThermostatTestSetTargetTemperature(unittest.TestCase):\n def test_set_target_temperature_1(self):\n t = Thermostat(20, 25, 'heat')\n t.set_target_temperature(30)\n self.assertEqual(t.get_target_temperature(), 30)\n\n def test_set_target_temperature_2(self):\n t = Thermostat(20, 25, 'cool')\n t.set_target_temperature(10)\n self.assertEqual(t.get_target_temperature(), 10)\n\n def test_set_target_temperature_3(self):\n t = Thermostat(20, 25, 'test')\n t.set_target_temperature(10)\n self.assertEqual(t.get_target_temperature(), 10)\n\n def test_set_target_temperature_4(self):\n t = Thermostat(25, 25, 'cool')\n t.set_target_temperature(10)\n self.assertEqual(t.get_target_temperature(), 10)\n\n def test_set_target_temperature_5(self):\n t = Thermostat(25, 25, 'heat')\n t.set_target_temperature(10)\n self.assertEqual(t.get_target_temperature(), 10)\n\n\nclass ThermostatTestGetMode(unittest.TestCase):\n def test_get_mode_1(self):\n t = Thermostat(20, 25, 'heat')\n self.assertEqual(t.get_mode(), 'heat')\n\n def test_get_mode_2(self):\n t = Thermostat(20, 25, 'cool')\n self.assertEqual(t.get_mode(), 'cool')\n\n def test_get_mode_3(self):\n t = Thermostat(20, 25, 'test')\n self.assertEqual(t.get_mode(), 'test')\n\n def test_get_mode_4(self):\n t = Thermostat(25, 25, 'cool')\n self.assertEqual(t.get_mode(), 'cool')\n\n def test_get_mode_5(self):\n t = Thermostat(25, 25, 'heat')\n self.assertEqual(t.get_mode(), 'heat')\n\n\nclass ThermostatTestSetMode(unittest.TestCase):\n def test_set_mode_1(self):\n t = Thermostat(20, 25, 'heat')\n t.set_mode('cool')\n self.assertEqual(t.get_mode(), 'cool')\n\n # use mode that not in ['heat', 'cool']\n def test_set_mode_2(self):\n t = Thermostat(20, 25, 'heat')\n self.assertFalse(t.set_mode('test'))\n\n def test_set_mode_3(self):\n t = Thermostat(20, 25, 'cool')\n t.set_mode('heat')\n self.assertEqual(t.get_mode(), 'heat')\n\n def test_set_mode_4(self):\n t = Thermostat(20, 25, 'test')\n t.set_mode('heat')\n self.assertEqual(t.get_mode(), 'heat')\n\n def test_set_mode_5(self):\n t = Thermostat(25, 25, 'cool')\n t.set_mode('heat')\n self.assertEqual(t.get_mode(), 'heat')\n\n\nclass ThermostatTestAutoSetMode(unittest.TestCase):\n def test_auto_set_mode_1(self):\n t = Thermostat(20, 25, 'heat')\n t.auto_set_mode()\n self.assertEqual(t.get_mode(), 'heat')\n\n def test_auto_set_mode_2(self):\n t = Thermostat(25, 20, 'heat')\n t.auto_set_mode()\n self.assertEqual(t.get_mode(), 'cool')\n\n def test_auto_set_mode_3(self):\n t = Thermostat(25, 20, 'cool')\n t.auto_set_mode()\n self.assertEqual(t.get_mode(), 'cool')\n\n def test_auto_set_mode_4(self):\n t = Thermostat(20, 25, 'cool')\n t.auto_set_mode()\n self.assertEqual(t.get_mode(), 'heat')\n\n def test_auto_set_mode_5(self):\n t = Thermostat(25, 25, 'cool')\n t.auto_set_mode()\n self.assertEqual(t.get_mode(), 'cool')\n\nclass ThermostatTestAutoCheckConflict(unittest.TestCase):\n def test_auto_check_conflict_1(self):\n t = Thermostat(30, 25, 'cool')\n self.assertTrue(t.auto_check_conflict())\n\n def test_auto_check_conflict_2(self):\n t = Thermostat(30, 25, 'heat')\n self.assertFalse(t.auto_check_conflict())\n self.assertEqual(t.mode, 'cool')\n\n def test_auto_check_conflict_3(self):\n t = Thermostat(25, 30, 'heat')\n self.assertTrue(t.auto_check_conflict())\n\n def test_auto_check_conflict_4(self):\n t = Thermostat(25, 30, 'cool')\n self.assertFalse(t.auto_check_conflict())\n self.assertEqual(t.mode, 'heat')\n\n def test_auto_check_conflict_5(self):\n t = Thermostat(25, 25, 'cool')\n self.assertFalse(t.auto_check_conflict())\n self.assertEqual(t.mode, 'cool')\n\n\nclass ThermostatTestSimulateOperation(unittest.TestCase):\n def test_simulate_operation_1(self):\n t = Thermostat(20, 25, 'heat')\n self.assertEqual(t.simulate_operation(), 5)\n self.assertEqual(t.get_mode(), 'heat')\n self.assertEqual(t.current_temperature, 25)\n\n def test_simulate_operation_2(self):\n t = Thermostat(25.7, 20, 'cool')\n self.assertEqual(t.simulate_operation(), 6)\n self.assertEqual(t.get_mode(), 'cool')\n self.assertEqual(t.current_temperature, 19.7)\n\n def test_simulate_operation_3(self):\n t = Thermostat(25, 25, 'heat')\n self.assertEqual(t.simulate_operation(), 0)\n self.assertEqual(t.get_mode(), 'cool')\n self.assertEqual(t.current_temperature, 25)\n\n def test_simulate_operation_4(self):\n t = Thermostat(25, 25, 'cool')\n self.assertEqual(t.simulate_operation(), 0)\n self.assertEqual(t.get_mode(), 'cool')\n self.assertEqual(t.current_temperature, 25)\n\n def test_simulate_operation_5(self):\n t = Thermostat(25, 25, 'test')\n self.assertEqual(t.simulate_operation(), 0)\n self.assertEqual(t.get_mode(), 'cool')\n self.assertEqual(t.current_temperature, 25)\n\nclass ThermostatTestMain(unittest.TestCase):\n def test_main(self):\n t = Thermostat(20, 37.5, 'cool')\n self.assertEqual(t.get_target_temperature(), 37.5)\n\n t.set_target_temperature(37.6)\n self.assertEqual(t.target_temperature, 37.6)\n\n self.assertEqual(t.get_mode(), 'cool')\n self.assertFalse(t.set_mode('test'))\n\n self.assertFalse(t.auto_check_conflict())\n self.assertEqual(t.get_mode(), 'heat')\n self.assertEqual(t.simulate_operation(), 18)", "solution_code": "import time\n\nclass Thermostat:\n def __init__(self, current_temperature, target_temperature, mode):\n self.current_temperature = current_temperature\n self.target_temperature = target_temperature\n self.mode = mode\n\n def get_target_temperature(self):\n return self.target_temperature\n\n def set_target_temperature(self, temperature):\n self.target_temperature = temperature\n\n def get_mode(self):\n return self.mode\n\n def set_mode(self, mode):\n if mode in ['heat', 'cool']:\n self.mode = mode\n else:\n return False\n\n def auto_set_mode(self):\n if self.current_temperature < self.target_temperature:\n self.mode = 'heat'\n else:\n self.mode = 'cool'\n\n def auto_check_conflict(self):\n if self.current_temperature > self.target_temperature:\n if self.mode == 'cool':\n return True\n else:\n self.auto_set_mode()\n return False\n else:\n if self.mode == 'heat':\n return True\n else:\n self.auto_set_mode()\n return False\n\n def simulate_operation(self):\n self.auto_set_mode()\n use_time = 0\n if self.mode == 'heat':\n while(self.current_temperature < self.target_temperature):\n self.current_temperature += 1\n use_time += 1\n else:\n while(self.current_temperature > self.target_temperature):\n self.current_temperature -= 1\n use_time += 1\n return use_time", "import_statement": [ "import time" ], "class_description": " \"\"\"\n The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation.\n \"\"\"\n", "class_name": "Thermostat", "test_classes": [ "ThermostatTestGetTargetTemperature", "ThermostatTestSetTargetTemperature", "ThermostatTestGetMode", "ThermostatTestSetMode", "ThermostatTestAutoSetMode", "ThermostatTestAutoCheckConflict", "ThermostatTestSimulateOperation", "ThermostatTestMain" ], "class_constructor": "class Thermostat: \n def __init__(self, current_temperature, target_temperature, mode):\n \"\"\"\n initialize instances of the Thermostat class, including the current temperature, target temperature, and operating mode.\n :param current_temperature: float\n :param target_temperature: float\n :param mode: str, the work mode\n \"\"\"\n self.current_temperature = current_temperature\n self.target_temperature = target_temperature\n self.mode = mode\n\n", "fields": [ "self.current_temperature", "self.mode", "self.target_temperature" ], "methods_info": [ { "method_name": "get_target_temperature", "method_description": "def get_target_temperature(self):\n \"\"\"\n Get the target temperature of an instance of the Thermostat class.\n :return self.current_temperature: int\n >>> thermostat.get_target_temperature()\n 37.5\n \"\"\"", "test_class": "ThermostatTestGetTargetTemperature", "test_code": "class ThermostatTestGetTargetTemperature(unittest.TestCase):\n def test_get_target_temperature_1(self):\n t = Thermostat(20, 25, 'heat')\n self.assertEqual(t.get_target_temperature(), 25)\n\n def test_get_target_temperature_2(self):\n t = Thermostat(20, 25, 'cool')\n self.assertEqual(t.get_target_temperature(), 25)\n\n def test_get_target_temperature_3(self):\n t = Thermostat(20, 25, 'test')\n self.assertEqual(t.get_target_temperature(), 25)\n\n def test_get_target_temperature_4(self):\n t = Thermostat(25, 25, 'cool')\n self.assertEqual(t.get_target_temperature(), 25)\n\n def test_get_target_temperature_5(self):\n t = Thermostat(25, 25, 'heat')\n self.assertEqual(t.get_target_temperature(), 25)", "solution_code": "def get_target_temperature(self):\n return self.target_temperature", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.target_temperature" ], "method_dependencies": [] } }, { "method_name": "set_target_temperature", "method_description": "def set_target_temperature(self, temperature):\n \"\"\"\n Set the target temperature\n :param temperature: float, the target temperature\n >>> thermostat.set_target_temperature(37.6)\n >>> thermostat.target_temperature\n 37.6\n \"\"\"", "test_class": "ThermostatTestSetTargetTemperature", "test_code": "class ThermostatTestSetTargetTemperature(unittest.TestCase):\n def test_set_target_temperature_1(self):\n t = Thermostat(20, 25, 'heat')\n t.set_target_temperature(30)\n self.assertEqual(t.get_target_temperature(), 30)\n\n def test_set_target_temperature_2(self):\n t = Thermostat(20, 25, 'cool')\n t.set_target_temperature(10)\n self.assertEqual(t.get_target_temperature(), 10)\n\n def test_set_target_temperature_3(self):\n t = Thermostat(20, 25, 'test')\n t.set_target_temperature(10)\n self.assertEqual(t.get_target_temperature(), 10)\n\n def test_set_target_temperature_4(self):\n t = Thermostat(25, 25, 'cool')\n t.set_target_temperature(10)\n self.assertEqual(t.get_target_temperature(), 10)\n\n def test_set_target_temperature_5(self):\n t = Thermostat(25, 25, 'heat')\n t.set_target_temperature(10)\n self.assertEqual(t.get_target_temperature(), 10)", "solution_code": "def set_target_temperature(self, temperature):\n self.target_temperature = temperature", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.target_temperature" ], "method_dependencies": [] } }, { "method_name": "get_mode", "method_description": "def get_mode(self):\n \"\"\"\n Get the current work mode\n :return mode: str, working mode. only ['heat', 'cool']\n \"\"\"", "test_class": "ThermostatTestGetMode", "test_code": "class ThermostatTestGetMode(unittest.TestCase):\n def test_get_mode_1(self):\n t = Thermostat(20, 25, 'heat')\n self.assertEqual(t.get_mode(), 'heat')\n\n def test_get_mode_2(self):\n t = Thermostat(20, 25, 'cool')\n self.assertEqual(t.get_mode(), 'cool')\n\n def test_get_mode_3(self):\n t = Thermostat(20, 25, 'test')\n self.assertEqual(t.get_mode(), 'test')\n\n def test_get_mode_4(self):\n t = Thermostat(25, 25, 'cool')\n self.assertEqual(t.get_mode(), 'cool')\n\n def test_get_mode_5(self):\n t = Thermostat(25, 25, 'heat')\n self.assertEqual(t.get_mode(), 'heat')", "solution_code": "def get_mode(self):\n return self.mode", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.mode" ], "method_dependencies": [] } }, { "method_name": "set_mode", "method_description": "def set_mode(self, mode):\n \"\"\"\n Get the current work mode\n :param mode: str, working mode. only ['heat', 'cool']\n >>> thermostat.set_mode('cool')\n >>> thermostat.mode\n 'cool'\n \"\"\"", "test_class": "ThermostatTestSetMode", "test_code": "class ThermostatTestSetMode(unittest.TestCase):\n def test_set_mode_1(self):\n t = Thermostat(20, 25, 'heat')\n t.set_mode('cool')\n self.assertEqual(t.get_mode(), 'cool')\n\n # use mode that not in ['heat', 'cool']\n def test_set_mode_2(self):\n t = Thermostat(20, 25, 'heat')\n self.assertFalse(t.set_mode('test'))\n\n def test_set_mode_3(self):\n t = Thermostat(20, 25, 'cool')\n t.set_mode('heat')\n self.assertEqual(t.get_mode(), 'heat')\n\n def test_set_mode_4(self):\n t = Thermostat(20, 25, 'test')\n t.set_mode('heat')\n self.assertEqual(t.get_mode(), 'heat')\n\n def test_set_mode_5(self):\n t = Thermostat(25, 25, 'cool')\n t.set_mode('heat')\n self.assertEqual(t.get_mode(), 'heat')", "solution_code": "def set_mode(self, mode):\n if mode in ['heat', 'cool']:\n self.mode = mode\n else:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.mode" ], "method_dependencies": [] } }, { "method_name": "auto_set_mode", "method_description": "def auto_set_mode(self):\n \"\"\"\n Automatically set the operating mode by comparing with the current temperature and target temperature. If the current temperature is lower than the target temperature, the operating mode is set to 'heat', otherwise it is set to 'cool'.\n >>> thermostat = Thermostat(20.4, 37.5, 'cool')\n >>> thermostat.auto_set_mode()\n >>> thermostat.mode\n 'heat'\n \"\"\"", "test_class": "ThermostatTestAutoSetMode", "test_code": "class ThermostatTestAutoSetMode(unittest.TestCase):\n def test_auto_set_mode_1(self):\n t = Thermostat(20, 25, 'heat')\n t.auto_set_mode()\n self.assertEqual(t.get_mode(), 'heat')\n\n def test_auto_set_mode_2(self):\n t = Thermostat(25, 20, 'heat')\n t.auto_set_mode()\n self.assertEqual(t.get_mode(), 'cool')\n\n def test_auto_set_mode_3(self):\n t = Thermostat(25, 20, 'cool')\n t.auto_set_mode()\n self.assertEqual(t.get_mode(), 'cool')\n\n def test_auto_set_mode_4(self):\n t = Thermostat(20, 25, 'cool')\n t.auto_set_mode()\n self.assertEqual(t.get_mode(), 'heat')\n\n def test_auto_set_mode_5(self):\n t = Thermostat(25, 25, 'cool')\n t.auto_set_mode()\n self.assertEqual(t.get_mode(), 'cool')", "solution_code": "def auto_set_mode(self):\n if self.current_temperature < self.target_temperature:\n self.mode = 'heat'\n else:\n self.mode = 'cool'", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.current_temperature", "self.mode", "self.target_temperature" ], "method_dependencies": [] } }, { "method_name": "auto_check_conflict", "method_description": "def auto_check_conflict(self):\n \"\"\"\n Check if there is a conflict between the operating mode and the relationship between the current temperature and the target temperature.\n If there is a conflict, the operating mode will be adjusted automatically.\n :return: True if mode isn't conflict with the relationship between the current temperature and the target temperature, or False otherwise.\n >>> thermostat = Thermostat(20.4, 37.5, 'cool')\n >>> thermostat.auto_check_conflict()\n False\n >>> thermostat.mode\n 'heat'\n \"\"\"", "test_class": "ThermostatTestAutoCheckConflict", "test_code": "class ThermostatTestAutoCheckConflict(unittest.TestCase):\n def test_auto_check_conflict_1(self):\n t = Thermostat(30, 25, 'cool')\n self.assertTrue(t.auto_check_conflict())\n\n def test_auto_check_conflict_2(self):\n t = Thermostat(30, 25, 'heat')\n self.assertFalse(t.auto_check_conflict())\n self.assertEqual(t.mode, 'cool')\n\n def test_auto_check_conflict_3(self):\n t = Thermostat(25, 30, 'heat')\n self.assertTrue(t.auto_check_conflict())\n\n def test_auto_check_conflict_4(self):\n t = Thermostat(25, 30, 'cool')\n self.assertFalse(t.auto_check_conflict())\n self.assertEqual(t.mode, 'heat')\n\n def test_auto_check_conflict_5(self):\n t = Thermostat(25, 25, 'cool')\n self.assertFalse(t.auto_check_conflict())\n self.assertEqual(t.mode, 'cool')", "solution_code": "def auto_check_conflict(self):\n if self.current_temperature > self.target_temperature:\n if self.mode == 'cool':\n return True\n else:\n self.auto_set_mode()\n return False\n else:\n if self.mode == 'heat':\n return True\n else:\n self.auto_set_mode()\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.current_temperature", "self.mode", "self.target_temperature" ], "method_dependencies": [ "set_mode", "auto_set_mode" ] } }, { "method_name": "simulate_operation", "method_description": "def simulate_operation(self):\n \"\"\"\n simulate the operation of Thermostat. It will automatically start the auto_set_mode method to set the operating mode,\n and then automatically adjust the current temperature according to the operating mode until the target temperature is reached.\n :return time: int, the time it took to complete the simulation.\n >>> thermostat = Thermostat(20.4, 37.5, 'cool')\n >>> thermostat.simulate_operation()\n 18\n \"\"\"", "test_class": "ThermostatTestSimulateOperation", "test_code": "class ThermostatTestSimulateOperation(unittest.TestCase):\n def test_simulate_operation_1(self):\n t = Thermostat(20, 25, 'heat')\n self.assertEqual(t.simulate_operation(), 5)\n self.assertEqual(t.get_mode(), 'heat')\n self.assertEqual(t.current_temperature, 25)\n\n def test_simulate_operation_2(self):\n t = Thermostat(25.7, 20, 'cool')\n self.assertEqual(t.simulate_operation(), 6)\n self.assertEqual(t.get_mode(), 'cool')\n self.assertEqual(t.current_temperature, 19.7)\n\n def test_simulate_operation_3(self):\n t = Thermostat(25, 25, 'heat')\n self.assertEqual(t.simulate_operation(), 0)\n self.assertEqual(t.get_mode(), 'cool')\n self.assertEqual(t.current_temperature, 25)\n\n def test_simulate_operation_4(self):\n t = Thermostat(25, 25, 'cool')\n self.assertEqual(t.simulate_operation(), 0)\n self.assertEqual(t.get_mode(), 'cool')\n self.assertEqual(t.current_temperature, 25)\n\n def test_simulate_operation_5(self):\n t = Thermostat(25, 25, 'test')\n self.assertEqual(t.simulate_operation(), 0)\n self.assertEqual(t.get_mode(), 'cool')\n self.assertEqual(t.current_temperature, 25)", "solution_code": "def simulate_operation(self):\n self.auto_set_mode()\n use_time = 0\n if self.mode == 'heat':\n while(self.current_temperature < self.target_temperature):\n self.current_temperature += 1\n use_time += 1\n else:\n while(self.current_temperature > self.target_temperature):\n self.current_temperature -= 1\n use_time += 1\n return use_time", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.current_temperature", "self.mode", "self.target_temperature" ], "method_dependencies": [ "set_mode", "auto_set_mode" ] } } ] }, { "task_id": "ClassEval_86", "skeleton": "\nclass TicTacToe:\n \"\"\"\n The class represents a game of Tic-Tac-Toe and its functions include making a move on the board, checking for a winner, and determining if the board is full.\n \"\"\"\n\n def __init__(self, N=3):\n \"\"\"\n Initialize a 3x3 game board with all empty spaces and current symble player, default is 'X'.\n \"\"\"\n self.board = [[' ' for _ in range(N)] for _ in range(3)]\n self.current_player = 'X'\n\n def make_move(self, row, col):\n \"\"\"\n Place the current player's mark at the specified position on the board and switch the mark.\n :param row: int, the row index of the position\n :param col: int, the column index of the position\n :return: bool, indicating whether the move was successful or not\n >>> ttt.current_player\n 'X'\n >>> ttt.make_move(1, 1)\n >>> ttt.current_player\n 'O'\n \"\"\"\n\n def check_winner(self):\n \"\"\"\n Check if there is a winner on the board in rows, columns and diagonals three directions\n :return: str or None, the mark of the winner ('X' or 'O'), or None if there is no winner yet\n >>> moves = [(1, 0), (2, 0), (1, 1), (2, 1), (1, 2)]\n >>> for move in moves:\n ... ttt.make_move(move[0], move[1])\n >>> ttt.check_winner()\n 'X'\n \"\"\"\n\n def is_board_full(self):\n \"\"\"\n Check if the game board is completely filled.\n :return: bool, indicating whether the game board is full or not\n >>> ttt.is_board_full()\n False\n \"\"\"", "test": "import unittest\n\nclass TicTacToeTestMakeMove(unittest.TestCase):\n def test_make_move_1(self):\n ttt = TicTacToe()\n self.assertEqual(ttt.current_player, 'X')\n self.assertTrue(ttt.make_move(0, 0))\n self.assertEqual(ttt.current_player, 'O')\n\n # move invalid\n def test_make_move_2(self):\n ttt = TicTacToe()\n self.assertEqual(ttt.current_player, 'X')\n self.assertTrue(ttt.make_move(0, 0))\n self.assertTrue(ttt.make_move(0, 1))\n self.assertFalse(ttt.make_move(0, 0))\n self.assertEqual(ttt.current_player, 'X')\n\n def test_make_move_3(self):\n ttt = TicTacToe()\n self.assertEqual(ttt.current_player, 'X')\n self.assertTrue(ttt.make_move(0, 0))\n self.assertTrue(ttt.make_move(0, 1))\n self.assertTrue(ttt.make_move(1, 1))\n self.assertEqual(ttt.current_player, 'O')\n\n def test_make_move_4(self):\n ttt = TicTacToe()\n self.assertEqual(ttt.current_player, 'X')\n self.assertTrue(ttt.make_move(0, 0))\n self.assertTrue(ttt.make_move(0, 1))\n self.assertTrue(ttt.make_move(1, 1))\n self.assertTrue(ttt.make_move(1, 2))\n self.assertEqual(ttt.current_player, 'X')\n\n def test_make_move_5(self):\n ttt = TicTacToe()\n self.assertEqual(ttt.current_player, 'X')\n self.assertTrue(ttt.make_move(0, 0))\n self.assertTrue(ttt.make_move(0, 1))\n self.assertTrue(ttt.make_move(1, 1))\n self.assertTrue(ttt.make_move(1, 2))\n self.assertTrue(ttt.make_move(2, 2))\n self.assertEqual(ttt.current_player, 'O')\n\n\nclass TicTacToeTestCheckWinner(unittest.TestCase):\n # rows\n def test_check_winner_1(self):\n ttt = TicTacToe()\n moves = [(1, 0), (2, 0), (1, 1), (2, 1), (1, 2)]\n for move in moves:\n ttt.make_move(move[0], move[1])\n self.assertEqual(ttt.check_winner(), 'X')\n\n # columns\n def test_check_winner_2(self):\n ttt = TicTacToe()\n moves = [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0)]\n for move in moves:\n ttt.make_move(move[0], move[1])\n self.assertEqual(ttt.check_winner(), 'X')\n\n # main diagonals \n def test_check_winner_3(self):\n ttt = TicTacToe()\n moves = [(0, 0), (0, 1), (1, 1), (0, 2), (2, 2)]\n for move in moves:\n ttt.make_move(move[0], move[1])\n self.assertEqual(ttt.check_winner(), 'X')\n\n # secondary diagonals \n def test_check_winner_4(self):\n ttt = TicTacToe()\n moves = [(0, 2), (0, 1), (1, 1), (1, 0), (2, 0)]\n for move in moves:\n ttt.make_move(move[0], move[1])\n self.assertEqual(ttt.check_winner(), 'X')\n\n def test_check_winner_5(self):\n ttt = TicTacToe()\n moves = [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0)]\n for move in moves:\n ttt.make_move(move[0], move[1])\n self.assertEqual(ttt.check_winner(), None)\n\n\nclass TicTacToeTestIsBoardFull(unittest.TestCase):\n # not full\n def test_is_board_full_1(self):\n ttt = TicTacToe()\n self.assertFalse(ttt.is_board_full())\n\n # full\n def test_is_board_full_2(self):\n ttt = TicTacToe()\n moves = [(1, 1), (0, 2), (2, 2), (0, 0), (0, 1), (2, 1), (1, 0), (1, 2), (2, 0)]\n for move in moves:\n ttt.make_move(move[0], move[1])\n self.assertTrue(ttt.is_board_full())\n\n def test_is_board_full_3(self):\n ttt = TicTacToe()\n moves = [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0)]\n for move in moves:\n ttt.make_move(move[0], move[1])\n self.assertFalse(ttt.is_board_full())\n\n def test_is_board_full_4(self):\n ttt = TicTacToe()\n moves = [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (0, 2), (1, 2), (2, 1), (2, 2)]\n for move in moves:\n ttt.make_move(move[0], move[1])\n self.assertTrue(ttt.is_board_full())\n\n def test_is_board_full_5(self):\n ttt = TicTacToe()\n moves = [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (0, 2), (1, 2), (2, 1)]\n for move in moves:\n ttt.make_move(move[0], move[1])\n self.assertFalse(ttt.is_board_full())\n\n\nclass TicTacToeTestMain(unittest.TestCase):\n def test_main(self):\n # A draw down way\n ttt = TicTacToe()\n moves = [(1, 1), (0, 2), (2, 2), (0, 0), (0, 1), (2, 1), (1, 0), (1, 2), (2, 0)]\n for move in moves:\n self.assertTrue(ttt.make_move(move[0], move[1]))\n # no winner in this case\n self.assertFalse(ttt.check_winner())\n if move != (2, 0):\n self.assertFalse(ttt.is_board_full())\n self.assertTrue(ttt.is_board_full())", "solution_code": "class TicTacToe:\n def __init__(self, N=3):\n self.board = [[' ' for _ in range(N)] for _ in range(3)]\n self.current_player = 'X'\n\n def make_move(self, row, col):\n if self.board[row][col] == ' ':\n self.board[row][col] = self.current_player\n self.current_player = 'O' if self.current_player == 'X' else 'X'\n return True\n else:\n return False\n\n def check_winner(self):\n for row in self.board:\n if row[0] == row[1] == row[2] != ' ':\n return row[0]\n for col in range(3):\n if self.board[0][col] == self.board[1][col] == self.board[2][col] != ' ':\n return self.board[0][col]\n if self.board[0][0] == self.board[1][1] == self.board[2][2] != ' ':\n return self.board[0][0]\n if self.board[0][2] == self.board[1][1] == self.board[2][0] != ' ':\n return self.board[0][2]\n return None\n\n def is_board_full(self):\n for row in self.board:\n if ' ' in row:\n return False\n return True", "import_statement": [], "class_description": " \"\"\"\n The class represents a game of Tic-Tac-Toe and its functions include making a move on the board, checking for a winner, and determining if the board is full.\n \"\"\"\n", "class_name": "TicTacToe", "test_classes": [ "TicTacToeTestMakeMove", "TicTacToeTestCheckWinner", "TicTacToeTestIsBoardFull", "TicTacToeTestMain" ], "class_constructor": "class TicTacToe: \n def __init__(self, N=3):\n \"\"\"\n Initialize a 3x3 game board with all empty spaces and current symble player, default is 'X'.\n \"\"\"\n self.board = [[' ' for _ in range(N)] for _ in range(3)]\n self.current_player = 'X'\n\n", "fields": [ "self.board", "self.current_player" ], "methods_info": [ { "method_name": "make_move", "method_description": "def make_move(self, row, col):\n \"\"\"\n Place the current player's mark at the specified position on the board and switch the mark.\n :param row: int, the row index of the position\n :param col: int, the column index of the position\n :return: bool, indicating whether the move was successful or not\n >>> ttt.current_player\n 'X'\n >>> ttt.make_move(1, 1)\n >>> ttt.current_player\n 'O'\n \"\"\"", "test_class": "TicTacToeTestMakeMove", "test_code": "class TicTacToeTestMakeMove(unittest.TestCase):\n def test_make_move_1(self):\n ttt = TicTacToe()\n self.assertEqual(ttt.current_player, 'X')\n self.assertTrue(ttt.make_move(0, 0))\n self.assertEqual(ttt.current_player, 'O')\n\n # move invalid\n def test_make_move_2(self):\n ttt = TicTacToe()\n self.assertEqual(ttt.current_player, 'X')\n self.assertTrue(ttt.make_move(0, 0))\n self.assertTrue(ttt.make_move(0, 1))\n self.assertFalse(ttt.make_move(0, 0))\n self.assertEqual(ttt.current_player, 'X')\n\n def test_make_move_3(self):\n ttt = TicTacToe()\n self.assertEqual(ttt.current_player, 'X')\n self.assertTrue(ttt.make_move(0, 0))\n self.assertTrue(ttt.make_move(0, 1))\n self.assertTrue(ttt.make_move(1, 1))\n self.assertEqual(ttt.current_player, 'O')\n\n def test_make_move_4(self):\n ttt = TicTacToe()\n self.assertEqual(ttt.current_player, 'X')\n self.assertTrue(ttt.make_move(0, 0))\n self.assertTrue(ttt.make_move(0, 1))\n self.assertTrue(ttt.make_move(1, 1))\n self.assertTrue(ttt.make_move(1, 2))\n self.assertEqual(ttt.current_player, 'X')\n\n def test_make_move_5(self):\n ttt = TicTacToe()\n self.assertEqual(ttt.current_player, 'X')\n self.assertTrue(ttt.make_move(0, 0))\n self.assertTrue(ttt.make_move(0, 1))\n self.assertTrue(ttt.make_move(1, 1))\n self.assertTrue(ttt.make_move(1, 2))\n self.assertTrue(ttt.make_move(2, 2))\n self.assertEqual(ttt.current_player, 'O')", "solution_code": "def make_move(self, row, col):\n if self.board[row][col] == ' ':\n self.board[row][col] = self.current_player\n self.current_player = 'O' if self.current_player == 'X' else 'X'\n return True\n else:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.board", "self.current_player" ], "method_dependencies": [] } }, { "method_name": "check_winner", "method_description": "def check_winner(self):\n \"\"\"\n Check if there is a winner on the board in rows, columns and diagonals three directions\n :return: str or None, the mark of the winner ('X' or 'O'), or None if there is no winner yet\n >>> moves = [(1, 0), (2, 0), (1, 1), (2, 1), (1, 2)]\n >>> for move in moves:\n ... ttt.make_move(move[0], move[1])\n >>> ttt.check_winner()\n 'X'\n \"\"\"", "test_class": "TicTacToeTestCheckWinner", "test_code": "class TicTacToeTestCheckWinner(unittest.TestCase):\n # rows\n def test_check_winner_1(self):\n ttt = TicTacToe()\n moves = [(1, 0), (2, 0), (1, 1), (2, 1), (1, 2)]\n for move in moves:\n ttt.make_move(move[0], move[1])\n self.assertEqual(ttt.check_winner(), 'X')\n\n # columns\n def test_check_winner_2(self):\n ttt = TicTacToe()\n moves = [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0)]\n for move in moves:\n ttt.make_move(move[0], move[1])\n self.assertEqual(ttt.check_winner(), 'X')\n\n # main diagonals \n def test_check_winner_3(self):\n ttt = TicTacToe()\n moves = [(0, 0), (0, 1), (1, 1), (0, 2), (2, 2)]\n for move in moves:\n ttt.make_move(move[0], move[1])\n self.assertEqual(ttt.check_winner(), 'X')\n\n # secondary diagonals \n def test_check_winner_4(self):\n ttt = TicTacToe()\n moves = [(0, 2), (0, 1), (1, 1), (1, 0), (2, 0)]\n for move in moves:\n ttt.make_move(move[0], move[1])\n self.assertEqual(ttt.check_winner(), 'X')\n\n def test_check_winner_5(self):\n ttt = TicTacToe()\n moves = [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0)]\n for move in moves:\n ttt.make_move(move[0], move[1])\n self.assertEqual(ttt.check_winner(), None)", "solution_code": "def check_winner(self):\n for row in self.board:\n if row[0] == row[1] == row[2] != ' ':\n return row[0]\n for col in range(3):\n if self.board[0][col] == self.board[1][col] == self.board[2][col] != ' ':\n return self.board[0][col]\n if self.board[0][0] == self.board[1][1] == self.board[2][2] != ' ':\n return self.board[0][0]\n if self.board[0][2] == self.board[1][1] == self.board[2][0] != ' ':\n return self.board[0][2]\n return None", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.board" ], "method_dependencies": [] } }, { "method_name": "is_board_full", "method_description": "def is_board_full(self):\n \"\"\"\n Check if the game board is completely filled.\n :return: bool, indicating whether the game board is full or not\n >>> ttt.is_board_full()\n False\n \"\"\"", "test_class": "TicTacToeTestIsBoardFull", "test_code": "class TicTacToeTestIsBoardFull(unittest.TestCase):\n # not full\n def test_is_board_full_1(self):\n ttt = TicTacToe()\n self.assertFalse(ttt.is_board_full())\n\n # full\n def test_is_board_full_2(self):\n ttt = TicTacToe()\n moves = [(1, 1), (0, 2), (2, 2), (0, 0), (0, 1), (2, 1), (1, 0), (1, 2), (2, 0)]\n for move in moves:\n ttt.make_move(move[0], move[1])\n self.assertTrue(ttt.is_board_full())\n\n def test_is_board_full_3(self):\n ttt = TicTacToe()\n moves = [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0)]\n for move in moves:\n ttt.make_move(move[0], move[1])\n self.assertFalse(ttt.is_board_full())\n\n def test_is_board_full_4(self):\n ttt = TicTacToe()\n moves = [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (0, 2), (1, 2), (2, 1), (2, 2)]\n for move in moves:\n ttt.make_move(move[0], move[1])\n self.assertTrue(ttt.is_board_full())\n\n def test_is_board_full_5(self):\n ttt = TicTacToe()\n moves = [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (0, 2), (1, 2), (2, 1)]\n for move in moves:\n ttt.make_move(move[0], move[1])\n self.assertFalse(ttt.is_board_full())", "solution_code": "def is_board_full(self):\n for row in self.board:\n if ' ' in row:\n return False\n return True", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.board" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_87", "skeleton": "\nimport datetime\nimport time\n\nclass TimeUtils:\n \"\"\"\n This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object.\n \"\"\"\n\n\n def __init__(self):\n \"\"\"\n Get the current datetime\n \"\"\"\n self.datetime = datetime.datetime.now()\n\n def get_current_time(self):\n \"\"\"\n Return the current time in the format of '%H:%M:%S'\n :return: string\n >>> timeutils = TimeUtils()\n >>> timeutils.get_current_time()\n \"19:19:22\"\n \"\"\"\n\n def get_current_date(self):\n \"\"\"\n Return the current date in the format of \"%Y-%m-%d\"\n :return: string\n >>> timeutils.get_current_date()\n \"2023-06-14\"\n \"\"\"\n\n def add_seconds(self, seconds):\n \"\"\"\n Add the specified number of seconds to the current time\n :param seconds: int, number of seconds to add\n :return: string, time after adding the specified number of seconds in the format '%H:%M:%S'\n >>> timeutils.add_seconds(600)\n \"19:29:22\"\n \"\"\"\n\n def string_to_datetime(self, string):\n \"\"\"\n Convert the time string to a datetime instance\n :param string: string, string before converting format\n :return: datetime instance\n >>> timeutils.string_to_datetime(\"2001-7-18 1:1:1\")\n 2001-07-18 01:01:01\n \"\"\"\n\n def datetime_to_string(self, datetime):\n \"\"\"\n Convert a datetime instance to a string\n :param datetime: the datetime instance to convert\n :return: string, converted time string\n >>> timeutils.datetime_to_string(timeutils.datetime)\n \"2023-06-14 19:30:03\"\n \"\"\"\n\n def get_minutes(self, string_time1, string_time2):\n \"\"\"\n Calculate how many minutes have passed between two times, and round the results to the nearest\n :return: int, the number of minutes between two times, rounded off\n >>> timeutils.get_minutes(\"2001-7-18 1:1:1\", \"2001-7-18 2:1:1\")\n 60\n \"\"\"\n\n def get_format_time(self, year, month, day, hour, minute, second):\n \"\"\"\n get format time\n :param year: int\n :param month: int\n :param day: int\n :param hour: int\n :param minute: int\n :param second: int\n :return: formatted time string\n >>> timeutils.get_format_time(2001, 7, 18, 1, 1, 1)\n \"2001-07-18 01:01:01\"\n \"\"\"", "test": "import unittest\n\n\nclass TimeUtilsTestGetCurrentTime(unittest.TestCase):\n def test_get_current_time_1(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_current_time(), timeutils.datetime.strftime(\"%H:%M:%S\"))\n\n def test_get_current_time_2(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_current_time(), timeutils.datetime.strftime(\"%H:%M:%S\"))\n\n def test_get_current_time_3(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_current_time(), timeutils.datetime.strftime(\"%H:%M:%S\"))\n\n def test_get_current_time_4(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_current_time(), timeutils.datetime.strftime(\"%H:%M:%S\"))\n\n def test_get_current_time_5(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_current_time(), timeutils.datetime.strftime(\"%H:%M:%S\"))\n\n\nclass TimeUtilsTestGetCurrentDate(unittest.TestCase):\n def test_get_current_date_1(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_current_date(), timeutils.datetime.strftime(\"%Y-%m-%d\"))\n\n def test_get_current_date_2(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_current_date(), timeutils.datetime.strftime(\"%Y-%m-%d\"))\n\n def test_get_current_date_3(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_current_date(), timeutils.datetime.strftime(\"%Y-%m-%d\"))\n\n def test_get_current_date_4(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_current_date(), timeutils.datetime.strftime(\"%Y-%m-%d\"))\n\n def test_get_current_date_5(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_current_date(), timeutils.datetime.strftime(\"%Y-%m-%d\"))\n\n\nclass TimeUtilsTestAddSeconds(unittest.TestCase):\n def test_add_seconds_1(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.add_seconds(600),\n (timeutils.datetime + datetime.timedelta(seconds=600)).strftime(\"%H:%M:%S\"))\n\n def test_add_seconds_2(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.add_seconds(500),\n (timeutils.datetime + datetime.timedelta(seconds=500)).strftime(\"%H:%M:%S\"))\n\n def test_add_seconds_3(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.add_seconds(400),\n (timeutils.datetime + datetime.timedelta(seconds=400)).strftime(\"%H:%M:%S\"))\n\n def test_add_seconds_4(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.add_seconds(300),\n (timeutils.datetime + datetime.timedelta(seconds=300)).strftime(\"%H:%M:%S\"))\n\n def test_add_seconds_5(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.add_seconds(200),\n (timeutils.datetime + datetime.timedelta(seconds=200)).strftime(\"%H:%M:%S\"))\n\n\nclass TimeUtilsTestStringToDatetime(unittest.TestCase):\n def test_string_to_datetime_1(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.string_to_datetime('2001-7-18 1:1:1'), datetime.datetime(2001, 7, 18, 1, 1, 1))\n\n def test_string_to_datetime_2(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.string_to_datetime('2001-7-17 1:1:1'), datetime.datetime(2001, 7, 17, 1, 1, 1))\n\n def test_string_to_datetime_3(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.string_to_datetime('2001-7-16 1:1:1'), datetime.datetime(2001, 7, 16, 1, 1, 1))\n\n def test_string_to_datetime_4(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.string_to_datetime('2001-7-15 1:1:1'), datetime.datetime(2001, 7, 15, 1, 1, 1))\n\n def test_string_to_datetime_5(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.string_to_datetime('2001-7-14 1:1:1'), datetime.datetime(2001, 7, 14, 1, 1, 1))\n\n\nclass TimeUtilsTestDatetimeToString(unittest.TestCase):\n def test_datetime_to_string_1(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.datetime_to_string(timeutils.datetime),\n timeutils.datetime.strftime(\"%Y-%m-%d %H:%M:%S\"))\n\n def test_datetime_to_string_2(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.datetime_to_string(timeutils.datetime),\n timeutils.datetime.strftime(\"%Y-%m-%d %H:%M:%S\"))\n\n def test_datetime_to_string_3(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.datetime_to_string(timeutils.datetime),\n timeutils.datetime.strftime(\"%Y-%m-%d %H:%M:%S\"))\n\n def test_datetime_to_string_4(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.datetime_to_string(timeutils.datetime),\n timeutils.datetime.strftime(\"%Y-%m-%d %H:%M:%S\"))\n\n def test_datetime_to_string_5(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.datetime_to_string(timeutils.datetime),\n timeutils.datetime.strftime(\"%Y-%m-%d %H:%M:%S\"))\n\n\nclass TimeUtilsTestGetMinutes(unittest.TestCase):\n def test_get_minutes_1(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_minutes(\"2001-7-18 1:1:1\", \"2001-7-18 2:1:1\"), 60)\n\n def test_get_minutes_2(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_minutes(\"2001-7-18 1:1:1\", \"2001-7-18 3:1:1\"), 120)\n\n def test_get_minutes_3(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_minutes(\"2001-7-18 1:1:1\", \"2001-7-18 4:1:1\"), 180)\n\n def test_get_minutes_4(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_minutes(\"2001-7-18 1:1:1\", \"2001-7-18 5:1:1\"), 240)\n\n def test_get_minutes_5(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_minutes(\"2001-7-18 1:1:1\", \"2001-7-18 6:1:1\"), 300)\n\n\nclass TimeUtilsTestGetFormatTime(unittest.TestCase):\n def test_get_format_time_1(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_format_time(2001, 7, 18, 1, 1, 1), \"2001-07-18 01:01:01\")\n\n def test_get_format_time_2(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_format_time(2001, 7, 17, 1, 1, 1), \"2001-07-17 01:01:01\")\n\n def test_get_format_time_3(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_format_time(2001, 7, 16, 1, 1, 1), \"2001-07-16 01:01:01\")\n\n def test_get_format_time_4(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_format_time(2001, 7, 15, 1, 1, 1), \"2001-07-15 01:01:01\")\n\n def test_get_format_time_5(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_format_time(2001, 7, 14, 1, 1, 1), \"2001-07-14 01:01:01\")\n\n\nclass TimeUtilsTest(unittest.TestCase):\n def test_timeutils(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_current_time(), timeutils.datetime.strftime(\"%H:%M:%S\"))\n self.assertEqual(timeutils.get_current_date(), timeutils.datetime.strftime(\"%Y-%m-%d\"))\n self.assertEqual(timeutils.add_seconds(600),\n (timeutils.datetime + datetime.timedelta(seconds=600)).strftime(\"%H:%M:%S\"))\n self.assertEqual(timeutils.string_to_datetime('2001-7-18 1:1:1'), datetime.datetime(2001, 7, 18, 1, 1, 1))\n self.assertEqual(timeutils.datetime_to_string(timeutils.datetime),\n timeutils.datetime.strftime(\"%Y-%m-%d %H:%M:%S\"))\n self.assertEqual(timeutils.get_minutes(\"2001-7-18 1:1:1\", \"2001-7-18 2:1:1\"), 60)\n self.assertEqual(timeutils.get_format_time(2001, 7, 18, 1, 1, 1), \"2001-07-18 01:01:01\")", "solution_code": "import datetime\nimport time\n\nclass TimeUtils:\n\n def __init__(self):\n self.datetime = datetime.datetime.now()\n\n def get_current_time(self):\n format = \"%H:%M:%S\"\n return self.datetime.strftime(format)\n\n def get_current_date(self):\n format = \"%Y-%m-%d\"\n return self.datetime.strftime(format)\n\n def add_seconds(self, seconds):\n new_datetime = self.datetime + datetime.timedelta(seconds=seconds)\n format = \"%H:%M:%S\"\n return new_datetime.strftime(format)\n\n def string_to_datetime(self, string):\n return datetime.datetime.strptime(string, \"%Y-%m-%d %H:%M:%S\")\n\n def datetime_to_string(self, datetime):\n return datetime.strftime(\"%Y-%m-%d %H:%M:%S\")\n\n def get_minutes(self, string_time1, string_time2):\n time1 = self.string_to_datetime(string_time1)\n time2 = self.string_to_datetime(string_time2)\n return round((time2 - time1).seconds / 60)\n\n def get_format_time(self, year, month, day, hour, minute, second):\n format = \"%Y-%m-%d %H:%M:%S\"\n time_item = datetime.datetime(year, month, day, hour, minute, second)\n return time_item.strftime(format)", "import_statement": [ "import datetime", "import time" ], "class_description": " \"\"\"\n This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object.\n \"\"\"\n", "class_name": "TimeUtils", "test_classes": [ "TimeUtilsTestGetCurrentTime", "TimeUtilsTestGetCurrentDate", "TimeUtilsTestAddSeconds", "TimeUtilsTestStringToDatetime", "TimeUtilsTestDatetimeToString", "TimeUtilsTestGetMinutes", "TimeUtilsTestGetFormatTime", "TimeUtilsTest" ], "class_constructor": "class TimeUtils: \n def __init__(self):\n \"\"\"\n Get the current datetime\n \"\"\"\n self.datetime = datetime.datetime.now()\n\n", "fields": [ "self.datetime" ], "methods_info": [ { "method_name": "get_current_time", "method_description": "def get_current_time(self):\n \"\"\"\n Return the current time in the format of '%H:%M:%S'\n :return: string\n >>> timeutils = TimeUtils()\n >>> timeutils.get_current_time()\n \"19:19:22\"\n \"\"\"", "test_class": "TimeUtilsTestGetCurrentTime", "test_code": "class TimeUtilsTestGetCurrentTime(unittest.TestCase):\n def test_get_current_time_1(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_current_time(), timeutils.datetime.strftime(\"%H:%M:%S\"))\n\n def test_get_current_time_2(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_current_time(), timeutils.datetime.strftime(\"%H:%M:%S\"))\n\n def test_get_current_time_3(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_current_time(), timeutils.datetime.strftime(\"%H:%M:%S\"))\n\n def test_get_current_time_4(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_current_time(), timeutils.datetime.strftime(\"%H:%M:%S\"))\n\n def test_get_current_time_5(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_current_time(), timeutils.datetime.strftime(\"%H:%M:%S\"))", "solution_code": "def get_current_time(self):\n format = \"%H:%M:%S\"\n return self.datetime.strftime(format)", "dependencies": { "Standalone": false, "lib_dependencies": [ "datetime", "time" ], "field_dependencies": [ "self.datetime" ], "method_dependencies": [] } }, { "method_name": "get_current_date", "method_description": "def get_current_date(self):\n \"\"\"\n Return the current date in the format of \"%Y-%m-%d\"\n :return: string\n >>> timeutils.get_current_date()\n \"2023-06-14\"\n \"\"\"", "test_class": "TimeUtilsTestGetCurrentDate", "test_code": "class TimeUtilsTestGetCurrentDate(unittest.TestCase):\n def test_get_current_date_1(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_current_date(), timeutils.datetime.strftime(\"%Y-%m-%d\"))\n\n def test_get_current_date_2(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_current_date(), timeutils.datetime.strftime(\"%Y-%m-%d\"))\n\n def test_get_current_date_3(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_current_date(), timeutils.datetime.strftime(\"%Y-%m-%d\"))\n\n def test_get_current_date_4(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_current_date(), timeutils.datetime.strftime(\"%Y-%m-%d\"))\n\n def test_get_current_date_5(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_current_date(), timeutils.datetime.strftime(\"%Y-%m-%d\"))", "solution_code": "def get_current_date(self):\n format = \"%Y-%m-%d\"\n return self.datetime.strftime(format)", "dependencies": { "Standalone": false, "lib_dependencies": [ "datetime", "time" ], "field_dependencies": [ "self.datetime" ], "method_dependencies": [] } }, { "method_name": "add_seconds", "method_description": "def add_seconds(self, seconds):\n \"\"\"\n Add the specified number of seconds to the current time\n :param seconds: int, number of seconds to add\n :return: string, time after adding the specified number of seconds in the format '%H:%M:%S'\n >>> timeutils.add_seconds(600)\n \"19:29:22\"\n \"\"\"", "test_class": "TimeUtilsTestAddSeconds", "test_code": "class TimeUtilsTestAddSeconds(unittest.TestCase):\n def test_add_seconds_1(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.add_seconds(600),\n (timeutils.datetime + datetime.timedelta(seconds=600)).strftime(\"%H:%M:%S\"))\n\n def test_add_seconds_2(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.add_seconds(500),\n (timeutils.datetime + datetime.timedelta(seconds=500)).strftime(\"%H:%M:%S\"))\n\n def test_add_seconds_3(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.add_seconds(400),\n (timeutils.datetime + datetime.timedelta(seconds=400)).strftime(\"%H:%M:%S\"))\n\n def test_add_seconds_4(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.add_seconds(300),\n (timeutils.datetime + datetime.timedelta(seconds=300)).strftime(\"%H:%M:%S\"))\n\n def test_add_seconds_5(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.add_seconds(200),\n (timeutils.datetime + datetime.timedelta(seconds=200)).strftime(\"%H:%M:%S\"))", "solution_code": "def add_seconds(self, seconds):\n new_datetime = self.datetime + datetime.timedelta(seconds=seconds)\n format = \"%H:%M:%S\"\n return new_datetime.strftime(format)", "dependencies": { "Standalone": false, "lib_dependencies": [ "datetime", "time" ], "field_dependencies": [ "self.datetime" ], "method_dependencies": [] } }, { "method_name": "string_to_datetime", "method_description": "def string_to_datetime(self, string):\n \"\"\"\n Convert the time string to a datetime instance\n :param string: string, string before converting format\n :return: datetime instance\n >>> timeutils.string_to_datetime(\"2001-7-18 1:1:1\")\n 2001-07-18 01:01:01\n \"\"\"", "test_class": "TimeUtilsTestStringToDatetime", "test_code": "class TimeUtilsTestStringToDatetime(unittest.TestCase):\n def test_string_to_datetime_1(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.string_to_datetime('2001-7-18 1:1:1'), datetime.datetime(2001, 7, 18, 1, 1, 1))\n\n def test_string_to_datetime_2(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.string_to_datetime('2001-7-17 1:1:1'), datetime.datetime(2001, 7, 17, 1, 1, 1))\n\n def test_string_to_datetime_3(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.string_to_datetime('2001-7-16 1:1:1'), datetime.datetime(2001, 7, 16, 1, 1, 1))\n\n def test_string_to_datetime_4(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.string_to_datetime('2001-7-15 1:1:1'), datetime.datetime(2001, 7, 15, 1, 1, 1))\n\n def test_string_to_datetime_5(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.string_to_datetime('2001-7-14 1:1:1'), datetime.datetime(2001, 7, 14, 1, 1, 1))", "solution_code": "def string_to_datetime(self, string):\n return datetime.datetime.strptime(string, \"%Y-%m-%d %H:%M:%S\")", "dependencies": { "Standalone": false, "lib_dependencies": [ "datetime", "time" ], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "datetime_to_string", "method_description": "def datetime_to_string(self, datetime):\n \"\"\"\n Convert a datetime instance to a string\n :param datetime: the datetime instance to convert\n :return: string, converted time string\n >>> timeutils.datetime_to_string(timeutils.datetime)\n \"2023-06-14 19:30:03\"\n \"\"\"", "test_class": "TimeUtilsTestDatetimeToString", "test_code": "class TimeUtilsTestDatetimeToString(unittest.TestCase):\n def test_datetime_to_string_1(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.datetime_to_string(timeutils.datetime),\n timeutils.datetime.strftime(\"%Y-%m-%d %H:%M:%S\"))\n\n def test_datetime_to_string_2(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.datetime_to_string(timeutils.datetime),\n timeutils.datetime.strftime(\"%Y-%m-%d %H:%M:%S\"))\n\n def test_datetime_to_string_3(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.datetime_to_string(timeutils.datetime),\n timeutils.datetime.strftime(\"%Y-%m-%d %H:%M:%S\"))\n\n def test_datetime_to_string_4(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.datetime_to_string(timeutils.datetime),\n timeutils.datetime.strftime(\"%Y-%m-%d %H:%M:%S\"))\n\n def test_datetime_to_string_5(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.datetime_to_string(timeutils.datetime),\n timeutils.datetime.strftime(\"%Y-%m-%d %H:%M:%S\"))", "solution_code": "def datetime_to_string(self, datetime):\n return datetime.strftime(\"%Y-%m-%d %H:%M:%S\")", "dependencies": { "Standalone": false, "lib_dependencies": [ "datetime", "time" ], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "get_minutes", "method_description": "def get_minutes(self, string_time1, string_time2):\n \"\"\"\n Calculate how many minutes have passed between two times, and round the results to the nearest\n :return: int, the number of minutes between two times, rounded off\n >>> timeutils.get_minutes(\"2001-7-18 1:1:1\", \"2001-7-18 2:1:1\")\n 60\n \"\"\"", "test_class": "TimeUtilsTestGetMinutes", "test_code": "class TimeUtilsTestGetMinutes(unittest.TestCase):\n def test_get_minutes_1(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_minutes(\"2001-7-18 1:1:1\", \"2001-7-18 2:1:1\"), 60)\n\n def test_get_minutes_2(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_minutes(\"2001-7-18 1:1:1\", \"2001-7-18 3:1:1\"), 120)\n\n def test_get_minutes_3(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_minutes(\"2001-7-18 1:1:1\", \"2001-7-18 4:1:1\"), 180)\n\n def test_get_minutes_4(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_minutes(\"2001-7-18 1:1:1\", \"2001-7-18 5:1:1\"), 240)\n\n def test_get_minutes_5(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_minutes(\"2001-7-18 1:1:1\", \"2001-7-18 6:1:1\"), 300)", "solution_code": "def get_minutes(self, string_time1, string_time2):\n time1 = self.string_to_datetime(string_time1)\n time2 = self.string_to_datetime(string_time2)\n return round((time2 - time1).seconds / 60)", "dependencies": { "Standalone": false, "lib_dependencies": [ "datetime", "time" ], "field_dependencies": [], "method_dependencies": [ "string_to_datetime" ] } }, { "method_name": "get_format_time", "method_description": "def get_format_time(self, year, month, day, hour, minute, second):\n \"\"\"\n get format time\n :param year: int\n :param month: int\n :param day: int\n :param hour: int\n :param minute: int\n :param second: int\n :return: formatted time string\n >>> timeutils.get_format_time(2001, 7, 18, 1, 1, 1)\n \"2001-07-18 01:01:01\"\n \"\"\"", "test_class": "TimeUtilsTestGetFormatTime", "test_code": "class TimeUtilsTestGetFormatTime(unittest.TestCase):\n def test_get_format_time_1(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_format_time(2001, 7, 18, 1, 1, 1), \"2001-07-18 01:01:01\")\n\n def test_get_format_time_2(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_format_time(2001, 7, 17, 1, 1, 1), \"2001-07-17 01:01:01\")\n\n def test_get_format_time_3(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_format_time(2001, 7, 16, 1, 1, 1), \"2001-07-16 01:01:01\")\n\n def test_get_format_time_4(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_format_time(2001, 7, 15, 1, 1, 1), \"2001-07-15 01:01:01\")\n\n def test_get_format_time_5(self):\n timeutils = TimeUtils()\n self.assertEqual(timeutils.get_format_time(2001, 7, 14, 1, 1, 1), \"2001-07-14 01:01:01\")", "solution_code": "def get_format_time(self, year, month, day, hour, minute, second):\n format = \"%Y-%m-%d %H:%M:%S\"\n time_item = datetime.datetime(year, month, day, hour, minute, second)\n return time_item.strftime(format)", "dependencies": { "Standalone": false, "lib_dependencies": [ "datetime", "time" ], "field_dependencies": [], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_88", "skeleton": "\nfrom math import pi, fabs\n\nclass TriCalculator:\n \"\"\"\n The class allows to calculate trigonometric values, including cosine, sine, and tangent, using Taylor series approximations.\n \"\"\"\n\n\n def __init__(self):\n pass\n\n def cos(self, x):\n \"\"\"\n Calculate the cos value of the x-degree angle\n :param x:float\n :return:float\n >>> tricalculator = TriCalculator()\n >>> tricalculator.cos(60)\n 0.5\n \"\"\"\n\n def factorial(self, a):\n \"\"\"\n Calculate the factorial of a\n :param a: int\n :return: int\n >>> tricalculator.factorial(5)\n 120\n \"\"\"\n\n def taylor(self, x, n):\n \"\"\"\n Finding the n-order Taylor expansion value of cos (x/180 * pi)\n :param x: int\n :param n: int\n :return: float\n >>> tricalculator.taylor(60, 50)\n 0.5000000000000001\n \"\"\"\n\n def sin(self, x):\n \"\"\"\n Calculate the sin value of the x-degree angle\n :param x: float\n :return: float\n >>> tricalculator.sin(30)\n 0.5\n \"\"\"\n\n\n def tan(self, x):\n \"\"\"\n Calculate the tan value of the x-degree angle\n :param x: float\n :return: float\n >>> tricalculator.tan(45)\n 1.0\n \"\"\"", "test": "import unittest\n\n\nclass TriCalculatorTestCos(unittest.TestCase):\n def test_cos_1(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.cos(60), 0.5)\n\n def test_cos_2(self):\n tricalculator = TriCalculator()\n self.assertAlmostEqual(tricalculator.cos(30), 0.8660254038)\n\n def test_cos_3(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.cos(0), 1.0)\n\n def test_cos_4(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.cos(90), 0.0)\n\n def test_cos_5(self):\n tricalculator = TriCalculator()\n self.assertAlmostEqual(tricalculator.cos(45), 0.7071067812)\n\n\nclass TriCalculatorTestFactorial(unittest.TestCase):\n def test_factorial_1(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.factorial(5), 120)\n\n def test_factorial_2(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.factorial(4), 24)\n\n def test_factorial_3(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.factorial(3), 6)\n\n def test_factorial_4(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.factorial(2), 2)\n\n def test_factorial_5(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.factorial(1), 1)\n\n\nclass TriCalculatorTestTaylor(unittest.TestCase):\n def test_taylor_1(self):\n tricalculator = TriCalculator()\n self.assertAlmostEqual(tricalculator.taylor(60, 50), 0.5)\n\n def test_taylor_2(self):\n tricalculator = TriCalculator()\n self.assertAlmostEqual(tricalculator.taylor(30, 50), 0.8660254037844386)\n\n def test_taylor_3(self):\n tricalculator = TriCalculator()\n self.assertAlmostEqual(tricalculator.taylor(90, 50), 0.0)\n\n def test_taylor_4(self):\n tricalculator = TriCalculator()\n self.assertAlmostEqual(tricalculator.taylor(0, 50), 1.0)\n\n def test_taylor_5(self):\n tricalculator = TriCalculator()\n self.assertAlmostEqual(tricalculator.taylor(45, 50), 0.7071067811865475)\n\n\nclass TriCalculatorTestSin(unittest.TestCase):\n def test_sin_1(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.sin(30), 0.5)\n\n def test_sin_2(self):\n tricalculator = TriCalculator()\n self.assertAlmostEqual(tricalculator.sin(60), 0.8660254038)\n\n def test_sin_3(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.sin(0), 0.0)\n\n def test_sin_4(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.sin(90), 1.0)\n\n def test_sin_5(self):\n tricalculator = TriCalculator()\n self.assertAlmostEqual(tricalculator.sin(45), 0.7071067812)\n\n\nclass TriCalculatorTestTan(unittest.TestCase):\n def test_tan_1(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.tan(45), 1.0)\n\n def test_tan_2(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.tan(90), False)\n\n def test_tan_3(self):\n tricalculator = TriCalculator()\n self.assertAlmostEqual(tricalculator.tan(30), 0.5773502692)\n\n def test_tan_4(self):\n tricalculator = TriCalculator()\n self.assertAlmostEqual(tricalculator.tan(60), 1.7320508076)\n\n def test_tan_5(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.tan(0), 0.0)\n\n\nclass TriCalculatorTest(unittest.TestCase):\n def test_tricalculator(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.cos(60), 0.5)\n self.assertAlmostEqual(tricalculator.taylor(60, 50), 0.5)\n self.assertEqual(tricalculator.sin(30), 0.5)\n self.assertEqual(tricalculator.tan(45), 1.0)\n self.assertEqual(tricalculator.tan(90), False)", "solution_code": "from math import pi, fabs\n\n\nclass TriCalculator:\n\n def __init__(self):\n pass\n\n def cos(self, x):\n return round(self.taylor(x, 50), 10)\n\n def factorial(self, a):\n b = 1\n while a != 1:\n b *= a\n a -= 1\n return b\n\n def taylor(self, x, n):\n a = 1\n x = x / 180 * pi\n count = 1\n for k in range(1, n):\n if count % 2 != 0:\n a -= (x ** (2 * k)) / self.factorial(2 * k)\n else:\n a += (x ** (2 * k)) / self.factorial(2 * k)\n count += 1\n return a\n\n def sin(self, x):\n x = x / 180 * pi\n g = 0\n t = x\n n = 1\n\n while fabs(t) >= 1e-15:\n g += t\n n += 1\n t = -t * x * x / (2 * n - 1) / (2 * n - 2)\n return round(g, 10)\n\n def tan(self, x):\n if self.cos(x) != 0:\n result = self.sin(x) / self.cos(x)\n return round(result, 10)\n else:\n return False", "import_statement": [ "from math import pi, fabs" ], "class_description": " \"\"\"\n The class allows to calculate trigonometric values, including cosine, sine, and tangent, using Taylor series approximations.\n \"\"\"\n", "class_name": "TriCalculator", "test_classes": [ "TriCalculatorTestCos", "TriCalculatorTestFactorial", "TriCalculatorTestTaylor", "TriCalculatorTestSin", "TriCalculatorTestTan", "TriCalculatorTest" ], "class_constructor": "class TriCalculator: \n def __init__(self):\n pass\n\n", "fields": [], "methods_info": [ { "method_name": "cos", "method_description": "def cos(self, x):\n \"\"\"\n Calculate the cos value of the x-degree angle\n :param x:float\n :return:float\n >>> tricalculator = TriCalculator()\n >>> tricalculator.cos(60)\n 0.5\n \"\"\"", "test_class": "TriCalculatorTestCos", "test_code": "class TriCalculatorTestCos(unittest.TestCase):\n def test_cos_1(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.cos(60), 0.5)\n\n def test_cos_2(self):\n tricalculator = TriCalculator()\n self.assertAlmostEqual(tricalculator.cos(30), 0.8660254038)\n\n def test_cos_3(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.cos(0), 1.0)\n\n def test_cos_4(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.cos(90), 0.0)\n\n def test_cos_5(self):\n tricalculator = TriCalculator()\n self.assertAlmostEqual(tricalculator.cos(45), 0.7071067812)", "solution_code": "def cos(self, x):\n return round(self.taylor(x, 50), 10)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "taylor" ] } }, { "method_name": "factorial", "method_description": "def factorial(self, a):\n \"\"\"\n Calculate the factorial of a\n :param a: int\n :return: int\n >>> tricalculator.factorial(5)\n 120\n \"\"\"", "test_class": "TriCalculatorTestFactorial", "test_code": "class TriCalculatorTestFactorial(unittest.TestCase):\n def test_factorial_1(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.factorial(5), 120)\n\n def test_factorial_2(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.factorial(4), 24)\n\n def test_factorial_3(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.factorial(3), 6)\n\n def test_factorial_4(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.factorial(2), 2)\n\n def test_factorial_5(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.factorial(1), 1)", "solution_code": "def factorial(self, a):\n b = 1\n while a != 1:\n b *= a\n a -= 1\n return b", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "taylor", "method_description": "def taylor(self, x, n):\n \"\"\"\n Finding the n-order Taylor expansion value of cos (x/180 * pi)\n :param x: int\n :param n: int\n :return: float\n >>> tricalculator.taylor(60, 50)\n 0.5000000000000001\n \"\"\"", "test_class": "TriCalculatorTestTaylor", "test_code": "class TriCalculatorTestTaylor(unittest.TestCase):\n def test_taylor_1(self):\n tricalculator = TriCalculator()\n self.assertAlmostEqual(tricalculator.taylor(60, 50), 0.5)\n\n def test_taylor_2(self):\n tricalculator = TriCalculator()\n self.assertAlmostEqual(tricalculator.taylor(30, 50), 0.8660254037844386)\n\n def test_taylor_3(self):\n tricalculator = TriCalculator()\n self.assertAlmostEqual(tricalculator.taylor(90, 50), 0.0)\n\n def test_taylor_4(self):\n tricalculator = TriCalculator()\n self.assertAlmostEqual(tricalculator.taylor(0, 50), 1.0)\n\n def test_taylor_5(self):\n tricalculator = TriCalculator()\n self.assertAlmostEqual(tricalculator.taylor(45, 50), 0.7071067811865475)", "solution_code": "def taylor(self, x, n):\n a = 1\n x = x / 180 * pi\n count = 1\n for k in range(1, n):\n if count % 2 != 0:\n a -= (x ** (2 * k)) / self.factorial(2 * k)\n else:\n a += (x ** (2 * k)) / self.factorial(2 * k)\n count += 1\n return a", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "factorial" ] } }, { "method_name": "sin", "method_description": "def sin(self, x):\n \"\"\"\n Calculate the sin value of the x-degree angle\n :param x: float\n :return: float\n >>> tricalculator.sin(30)\n 0.5\n \"\"\"", "test_class": "TriCalculatorTestSin", "test_code": "class TriCalculatorTestSin(unittest.TestCase):\n def test_sin_1(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.sin(30), 0.5)\n\n def test_sin_2(self):\n tricalculator = TriCalculator()\n self.assertAlmostEqual(tricalculator.sin(60), 0.8660254038)\n\n def test_sin_3(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.sin(0), 0.0)\n\n def test_sin_4(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.sin(90), 1.0)\n\n def test_sin_5(self):\n tricalculator = TriCalculator()\n self.assertAlmostEqual(tricalculator.sin(45), 0.7071067812)", "solution_code": "def sin(self, x):\n x = x / 180 * pi\n g = 0\n t = x\n n = 1\n\n while fabs(t) >= 1e-15:\n g += t\n n += 1\n t = -t * x * x / (2 * n - 1) / (2 * n - 2)\n return round(g, 10)", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "tan", "method_description": "def tan(self, x):\n \"\"\"\n Calculate the tan value of the x-degree angle\n :param x: float\n :return: float\n >>> tricalculator.tan(45)\n 1.0\n \"\"\"", "test_class": "TriCalculatorTestTan", "test_code": "class TriCalculatorTestTan(unittest.TestCase):\n def test_tan_1(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.tan(45), 1.0)\n\n def test_tan_2(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.tan(90), False)\n\n def test_tan_3(self):\n tricalculator = TriCalculator()\n self.assertAlmostEqual(tricalculator.tan(30), 0.5773502692)\n\n def test_tan_4(self):\n tricalculator = TriCalculator()\n self.assertAlmostEqual(tricalculator.tan(60), 1.7320508076)\n\n def test_tan_5(self):\n tricalculator = TriCalculator()\n self.assertEqual(tricalculator.tan(0), 0.0)", "solution_code": "def tan(self, x):\n if self.cos(x) != 0:\n result = self.sin(x) / self.cos(x)\n return round(result, 10)\n else:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "cos", "sin" ] } } ] }, { "task_id": "ClassEval_89", "skeleton": "\nimport random\n\nclass TwentyFourPointGame:\n \"\"\"\n This ia a game of twenty-four points, which provides to generate four numbers and check whether player's expression is equal to 24.\n \"\"\"\n\n def __init__(self) -> None:\n self.nums = []\n\n\n def _generate_cards(self):\n \"\"\"\n Generate random numbers between 1 and 9 for the cards.\n \"\"\"\n\n\n def get_my_cards(self):\n \"\"\"\n Get a list of four random numbers between 1 and 9 representing the player's cards.\n :return: list of integers, representing the player's cards\n >>> game = TwentyFourPointGame()\n >>> game.get_my_cards()\n\n \"\"\"\n\n\n def answer(self, expression):\n \"\"\"\n Check if a given mathematical expression using the cards can evaluate to 24.\n :param expression: string, mathematical expression using the cards\n :return: bool, True if the expression evaluates to 24, False otherwise\n >>> game = TwentyFourPointGame()\n >>> game.nums = [4, 3, 6, 6]\n >>> ans = \"4*3+6+6\"\n >>> ret = game.answer(ans)\n True\n \"\"\"\n\n\n def evaluate_expression(self, expression):\n \"\"\"\n Evaluate a mathematical expression and check if the result is 24.\n :param expression: string, mathematical expression\n :return: bool, True if the expression evaluates to 24, False otherwise\n >>> game = TwentyFourPointGame()\n >>> nums = [4, 3, 6, 6]\n >>> ans = \"4*3+6+6\"\n >>> ret = game.evaluate_expression(ans)\n True\n \"\"\"", "test": "import unittest\n\n\nclass TwentyFourPointGameTestGetMyCards(unittest.TestCase):\n def test_get_my_cards_1(self):\n game = TwentyFourPointGame()\n cards = game.get_my_cards()\n self.assertEqual(len(cards), 4)\n for card in cards:\n self.assertIn(card, [1, 2, 3, 4, 5, 6, 7, 8, 9])\n\n def test_get_my_cards_2(self):\n game = TwentyFourPointGame()\n cards = game.get_my_cards()\n self.assertEqual(len(cards), 4)\n for card in cards:\n self.assertIn(card, [1, 2, 3, 4, 5, 6, 7, 8, 9])\n\n def test_get_my_cards_3(self):\n game = TwentyFourPointGame()\n cards = game.get_my_cards()\n self.assertEqual(len(cards), 4)\n for card in cards:\n self.assertIn(card, [1, 2, 3, 4, 5, 6, 7, 8, 9])\n\n def test_get_my_cards_4(self):\n game = TwentyFourPointGame()\n cards = game.get_my_cards()\n self.assertEqual(len(cards), 4)\n for card in cards:\n self.assertIn(card, [1, 2, 3, 4, 5, 6, 7, 8, 9])\n\n def test_get_my_cards_5(self):\n game = TwentyFourPointGame()\n cards = game.get_my_cards()\n self.assertEqual(len(cards), 4)\n for card in cards:\n self.assertIn(card, [1, 2, 3, 4, 5, 6, 7, 8, 9])\n\n\nclass TwentyFourPointGameTestAnswer(unittest.TestCase):\n def test_answer_1(self):\n game = TwentyFourPointGame()\n cards = game.answer('pass')\n self.assertEqual(len(cards), 4)\n\n def test_answer_2(self):\n game = TwentyFourPointGame()\n result = game.answer('4*3+6+6')\n self.assertTrue(result)\n\n def test_answer_3(self):\n game = TwentyFourPointGame()\n result = game.answer('1+1+1+1')\n self.assertFalse(result)\n\n def test_answer_4(self):\n game = TwentyFourPointGame()\n result = game.answer('1+')\n self.assertFalse(result)\n\n def test_answer_5(self):\n game = TwentyFourPointGame()\n result = game.answer('abc')\n self.assertFalse(result)\n\n def test_answer_6(self):\n game = TwentyFourPointGame()\n game.nums = [1, 1, 1, 1]\n result = game.answer('1+1+1+2')\n self.assertFalse(result)\n\n def test_answer_7(self):\n game = TwentyFourPointGame()\n game.nums = [1, 1, 1, 1]\n result = game.answer('1+1+1+1+1')\n self.assertFalse(result)\n\n\nclass TwentyFourPointGameTestEvaluateExpression(unittest.TestCase):\n def test_evaluate_expression_1(self):\n game = TwentyFourPointGame()\n result = game.evaluate_expression('4+3+6+6')\n self.assertFalse(result)\n\n def test_evaluate_expression_2(self):\n game = TwentyFourPointGame()\n result = game.evaluate_expression('4*3+6+6')\n self.assertTrue(result)\n\n def test_evaluate_expression_3(self):\n game = TwentyFourPointGame()\n result = game.evaluate_expression('1+1+1+1')\n self.assertFalse(result)\n\n def test_evaluate_expression_4(self):\n game = TwentyFourPointGame()\n result = game.evaluate_expression('1+')\n self.assertFalse(result)\n\n def test_evaluate_expression_5(self):\n game = TwentyFourPointGame()\n result = game.evaluate_expression('abc')\n self.assertFalse(result)\n\n\nclass TwentyFourPointGameTest(unittest.TestCase):\n def test_TwentyFourPointGame(self):\n game = TwentyFourPointGame()\n cards = game.get_my_cards()\n self.assertEqual(len(cards), 4)\n for card in cards:\n self.assertIn(card, [1, 2, 3, 4, 5, 6, 7, 8, 9])\n game.nums = [4, 3, 6, 6]\n result = game.answer('4*3+6+6')\n self.assertTrue(result)\n result = game.evaluate_expression('4*3+6+6')\n self.assertTrue(result)", "solution_code": "import random\n\n\nclass TwentyFourPointGame:\n def __init__(self) -> None:\n self.nums = []\n\n def _generate_cards(self):\n for i in range(4):\n self.nums.append(random.randint(1, 9))\n assert len(self.nums) == 4\n\n def get_my_cards(self):\n self.nums = []\n self._generate_cards()\n return self.nums\n\n def answer(self, expression):\n if expression == 'pass':\n return self.get_my_cards()\n statistic = {}\n for c in expression:\n if c.isdigit() and int(c) in self.nums:\n statistic[c] = statistic.get(c, 0) + 1\n\n nums_used = statistic.copy()\n\n for num in self.nums:\n if nums_used.get(str(num), -100) != -100 and nums_used[str(num)] > 0:\n nums_used[str(num)] -= 1\n else:\n return False\n\n if all(count == 0 for count in nums_used.values()) == True:\n return self.evaluate_expression(expression)\n else:\n return False\n\n def evaluate_expression(self, expression):\n try:\n if eval(expression) == 24:\n return True\n else:\n return False\n except Exception as e:\n return False", "import_statement": [ "import random" ], "class_description": " \"\"\"\n This ia a game of twenty-four points, which provides to generate four numbers and check whether player's expression is equal to 24.\n \"\"\"\n", "class_name": "TwentyFourPointGame", "test_classes": [ "TwentyFourPointGameTestGetMyCards", "TwentyFourPointGameTestAnswer", "TwentyFourPointGameTestEvaluateExpression", "TwentyFourPointGameTest" ], "class_constructor": "class TwentyFourPointGame: \n def __init__(self) -> None:\n self.nums = []\n\n\n", "fields": [ "self.nums" ], "methods_info": [ { "method_name": "_generate_cards", "method_description": "def _generate_cards(self):\n \"\"\"\n Generate random numbers between 1 and 9 for the cards.\n \"\"\"", "test_class": "TwentyFourPointGameTestGetMyCards", "test_code": "class TwentyFourPointGameTestGetMyCards(unittest.TestCase):\n def test_get_my_cards_1(self):\n game = TwentyFourPointGame()\n cards = game.get_my_cards()\n self.assertEqual(len(cards), 4)\n for card in cards:\n self.assertIn(card, [1, 2, 3, 4, 5, 6, 7, 8, 9])\n\n def test_get_my_cards_2(self):\n game = TwentyFourPointGame()\n cards = game.get_my_cards()\n self.assertEqual(len(cards), 4)\n for card in cards:\n self.assertIn(card, [1, 2, 3, 4, 5, 6, 7, 8, 9])\n\n def test_get_my_cards_3(self):\n game = TwentyFourPointGame()\n cards = game.get_my_cards()\n self.assertEqual(len(cards), 4)\n for card in cards:\n self.assertIn(card, [1, 2, 3, 4, 5, 6, 7, 8, 9])\n\n def test_get_my_cards_4(self):\n game = TwentyFourPointGame()\n cards = game.get_my_cards()\n self.assertEqual(len(cards), 4)\n for card in cards:\n self.assertIn(card, [1, 2, 3, 4, 5, 6, 7, 8, 9])\n\n def test_get_my_cards_5(self):\n game = TwentyFourPointGame()\n cards = game.get_my_cards()\n self.assertEqual(len(cards), 4)\n for card in cards:\n self.assertIn(card, [1, 2, 3, 4, 5, 6, 7, 8, 9])", "solution_code": "def _generate_cards(self):\n for i in range(4):\n self.nums.append(random.randint(1, 9))\n assert len(self.nums) == 4", "dependencies": { "Standalone": false, "lib_dependencies": [ "random" ], "field_dependencies": [ "self.nums" ], "method_dependencies": [] } }, { "method_name": "get_my_cards", "method_description": "def get_my_cards(self):\n \"\"\"\n Get a list of four random numbers between 1 and 9 representing the player's cards.\n :return: list of integers, representing the player's cards\n >>> game = TwentyFourPointGame()\n >>> game.get_my_cards()\n\n \"\"\"", "test_class": "TwentyFourPointGameTestAnswer", "test_code": "class TwentyFourPointGameTestAnswer(unittest.TestCase):\n def test_answer_1(self):\n game = TwentyFourPointGame()\n cards = game.answer('pass')\n self.assertEqual(len(cards), 4)\n\n def test_answer_2(self):\n game = TwentyFourPointGame()\n result = game.answer('4*3+6+6')\n self.assertTrue(result)\n\n def test_answer_3(self):\n game = TwentyFourPointGame()\n result = game.answer('1+1+1+1')\n self.assertFalse(result)\n\n def test_answer_4(self):\n game = TwentyFourPointGame()\n result = game.answer('1+')\n self.assertFalse(result)\n\n def test_answer_5(self):\n game = TwentyFourPointGame()\n result = game.answer('abc')\n self.assertFalse(result)\n\n def test_answer_6(self):\n game = TwentyFourPointGame()\n game.nums = [1, 1, 1, 1]\n result = game.answer('1+1+1+2')\n self.assertFalse(result)\n\n def test_answer_7(self):\n game = TwentyFourPointGame()\n game.nums = [1, 1, 1, 1]\n result = game.answer('1+1+1+1+1')\n self.assertFalse(result)", "solution_code": "def get_my_cards(self):\n self.nums = []\n self._generate_cards()\n return self.nums", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.nums" ], "method_dependencies": [ "_generate_cards" ] } }, { "method_name": "answer", "method_description": "def answer(self, expression):\n \"\"\"\n Check if a given mathematical expression using the cards can evaluate to 24.\n :param expression: string, mathematical expression using the cards\n :return: bool, True if the expression evaluates to 24, False otherwise\n >>> game = TwentyFourPointGame()\n >>> game.nums = [4, 3, 6, 6]\n >>> ans = \"4*3+6+6\"\n >>> ret = game.answer(ans)\n True\n \"\"\"", "test_class": "TwentyFourPointGameTestEvaluateExpression", "test_code": "class TwentyFourPointGameTestEvaluateExpression(unittest.TestCase):\n def test_evaluate_expression_1(self):\n game = TwentyFourPointGame()\n result = game.evaluate_expression('4+3+6+6')\n self.assertFalse(result)\n\n def test_evaluate_expression_2(self):\n game = TwentyFourPointGame()\n result = game.evaluate_expression('4*3+6+6')\n self.assertTrue(result)\n\n def test_evaluate_expression_3(self):\n game = TwentyFourPointGame()\n result = game.evaluate_expression('1+1+1+1')\n self.assertFalse(result)\n\n def test_evaluate_expression_4(self):\n game = TwentyFourPointGame()\n result = game.evaluate_expression('1+')\n self.assertFalse(result)\n\n def test_evaluate_expression_5(self):\n game = TwentyFourPointGame()\n result = game.evaluate_expression('abc')\n self.assertFalse(result)", "solution_code": "def answer(self, expression):\n if expression == 'pass':\n return self.get_my_cards()\n statistic = {}\n for c in expression:\n if c.isdigit() and int(c) in self.nums:\n statistic[c] = statistic.get(c, 0) + 1\n\n nums_used = statistic.copy()\n\n for num in self.nums:\n if nums_used.get(str(num), -100) != -100 and nums_used[str(num)] > 0:\n nums_used[str(num)] -= 1\n else:\n return False\n\n if all(count == 0 for count in nums_used.values()) == True:\n return self.evaluate_expression(expression)\n else:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.nums" ], "method_dependencies": [ "get_my_cards", "evaluate_expression" ] } }, { "method_name": "evaluate_expression", "method_description": "def evaluate_expression(self, expression):\n \"\"\"\n Evaluate a mathematical expression and check if the result is 24.\n :param expression: string, mathematical expression\n :return: bool, True if the expression evaluates to 24, False otherwise\n >>> game = TwentyFourPointGame()\n >>> nums = [4, 3, 6, 6]\n >>> ans = \"4*3+6+6\"\n >>> ret = game.evaluate_expression(ans)\n True\n \"\"\"", "test_class": "TwentyFourPointGameTest", "test_code": "class TwentyFourPointGameTest(unittest.TestCase):\n def test_TwentyFourPointGame(self):\n game = TwentyFourPointGame()\n cards = game.get_my_cards()\n self.assertEqual(len(cards), 4)\n for card in cards:\n self.assertIn(card, [1, 2, 3, 4, 5, 6, 7, 8, 9])\n game.nums = [4, 3, 6, 6]\n result = game.answer('4*3+6+6')\n self.assertTrue(result)\n result = game.evaluate_expression('4*3+6+6')\n self.assertTrue(result)", "solution_code": "def evaluate_expression(self, expression):\n try:\n if eval(expression) == 24:\n return True\n else:\n return False\n except Exception as e:\n return False", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_90", "skeleton": "\nclass URLHandler:\n \"\"\"\n The class supports to handle URLs, including extracting the scheme, host, path, query parameters, and fragment.\n \"\"\"\n\n def __init__(self, url):\n \"\"\"\n Initialize URLHandler's URL\n \"\"\"\n self.url = url\n\n def get_scheme(self):\n \"\"\"\n get the scheme of the URL\n :return: string, If successful, return the scheme of the URL\n >>> urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\n >>> urlhandler.get_scheme()\n \"https\"\n \"\"\"\n\n\n def get_host(self):\n \"\"\"\n Get the second part of the URL, which is the host domain name\n :return: string, If successful, return the host domain name of the URL\n >>> urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\n >>> urlhandler.get_host()\n \"www.baidu.com\"\n \"\"\"\n\n\n def get_path(self):\n \"\"\"\n Get the third part of the URL, which is the address of the resource\n :return: string, If successful, return the address of the resource of the URL\n >>> urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\n >>> urlhandler.get_path()\n \"/s?wd=aaa&rsv_spt=1#page\"\n \"\"\"\n\n\n def get_query_params(self):\n \"\"\"\n Get the request parameters for the URL\n :return: dict, If successful, return the request parameters of the URL\n >>> urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\n >>> urlhandler.get_query_params()\n {\"wd\": \"aaa\", \"rsv_spt\": \"1\"}\n \"\"\"\n\n\n def get_fragment(self):\n \"\"\"\n Get the fragment after '#' in the URL\n :return: string, If successful, return the fragment after '#' of the URL\n >>> urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\n >>> urlhandler.get_fragment()\n \"page\"\n \"\"\"", "test": "import unittest\n\n\nclass URLHandlerTestGetScheme(unittest.TestCase):\n def test_get_scheme_1(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\n temp = urlhandler.get_scheme()\n self.assertEqual(temp, \"https\")\n\n def test_get_scheme_2(self):\n urlhandler = URLHandler(\n \"https://www.bing.com/search?pglt=41&q=humaneval&cvid=4dc2da2bb4bc429eb498c85245ae5253&aqs=edge.0.0l7j69i61j69i60.10008j0j1&FORM=ANNTA1&PC=U531&mkt=zh-CN\")\n temp = urlhandler.get_scheme()\n self.assertEqual(temp, \"https\")\n\n def test_get_scheme_3(self):\n urlhandler = URLHandler(\"https://github.com/openai/human-eval\")\n temp = urlhandler.get_scheme()\n self.assertEqual(temp, \"https\")\n\n def test_get_scheme_4(self):\n urlhandler = URLHandler(\"aaa://github.com/openai/human-eval\")\n temp = urlhandler.get_scheme()\n self.assertEqual(temp, \"aaa\")\n\n def test_get_scheme_5(self):\n urlhandler = URLHandler(\"bbb://github.com/openai/human-eval\")\n temp = urlhandler.get_scheme()\n self.assertEqual(temp, \"bbb\")\n\n def test_get_scheme_6(self):\n urlhandler = URLHandler(\"abcdefg\")\n temp = urlhandler.get_scheme()\n self.assertIsNone(temp)\n\n\nclass URLHandlerTestGetHost(unittest.TestCase):\n def test_get_host_1(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\n temp = urlhandler.get_host()\n self.assertEqual(temp, \"www.baidu.com\")\n\n def test_get_host_2(self):\n urlhandler = URLHandler(\n \"https://www.bing.com/search?pglt=41&q=humaneval&cvid=4dc2da2bb4bc429eb498c85245ae5253&aqs=edge.0.0l7j69i61j69i60.10008j0j1&FORM=ANNTA1&PC=U531&mkt=zh-CN\")\n temp = urlhandler.get_host()\n self.assertEqual(temp, \"www.bing.com\")\n\n def test_get_host_3(self):\n urlhandler = URLHandler(\"https://github.com/openai/human-eval\")\n temp = urlhandler.get_host()\n self.assertEqual(temp, \"github.com\")\n\n def test_get_host_4(self):\n urlhandler = URLHandler(\"https://aaa.com/openai/human-eval\")\n temp = urlhandler.get_host()\n self.assertEqual(temp, \"aaa.com\")\n\n def test_get_host_5(self):\n urlhandler = URLHandler(\"https://bbb.com/openai/human-eval\")\n temp = urlhandler.get_host()\n self.assertEqual(temp, \"bbb.com\")\n\n def test_get_host_6(self):\n urlhandler = URLHandler(\"abcdefg\")\n temp = urlhandler.get_host()\n self.assertIsNone(temp)\n\n def test_get_host_7(self):\n urlhandler = URLHandler(\"https://bbb.com\")\n temp = urlhandler.get_host()\n self.assertEqual(temp, \"bbb.com\")\n\n def test_get_host_8(self):\n urlhandler = URLHandler(\"https://bbb.com/\")\n temp = urlhandler.get_host()\n self.assertEqual(temp, \"bbb.com\")\n\n\nclass URLHandlerTestGetPath(unittest.TestCase):\n def test_get_path_1(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\n temp = urlhandler.get_path()\n self.assertEqual(temp, \"/s?wd=aaa&rsv_spt=1#page\")\n\n def test_get_path_2(self):\n urlhandler = URLHandler(\n \"https://www.bing.com/search?pglt=41&q=humaneval&cvid=4dc2da2bb4bc429eb498c85245ae5253&aqs=edge.0.0l7j69i61j69i60.10008j0j1&FORM=ANNTA1&PC=U531&mkt=zh-CN\")\n temp = urlhandler.get_path()\n self.assertEqual(temp,\n \"/search?pglt=41&q=humaneval&cvid=4dc2da2bb4bc429eb498c85245ae5253&aqs=edge.0.0l7j69i61j69i60.10008j0j1&FORM=ANNTA1&PC=U531&mkt=zh-CN\")\n\n def test_get_path_3(self):\n urlhandler = URLHandler(\"https://github.com/openai/human-eval\")\n temp = urlhandler.get_path()\n self.assertEqual(temp, \"/openai/human-eval\")\n\n def test_get_path_4(self):\n urlhandler = URLHandler(\"https://github.com/aaa/human-eval\")\n temp = urlhandler.get_path()\n self.assertEqual(temp, \"/aaa/human-eval\")\n\n def test_get_path_5(self):\n urlhandler = URLHandler(\"https://github.com/bbb/human-eval\")\n temp = urlhandler.get_path()\n self.assertEqual(temp, \"/bbb/human-eval\")\n\n def test_get_path_6(self):\n urlhandler = URLHandler(\"abcdefg\")\n temp = urlhandler.get_path()\n self.assertIsNone(temp)\n\n\nclass URLHandlerTestGetQueryParams(unittest.TestCase):\n def test_get_query_params_1(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\n temp = urlhandler.get_query_params()\n self.assertEqual(temp, {\"wd\": \"aaa\", \"rsv_spt\": \"1\"})\n\n def test_get_query_params_2(self):\n urlhandler = URLHandler(\n \"https://www.bing.com/search?pglt=41&q=humaneval&cvid=4dc2da2bb4bc429eb498c85245ae5253&aqs=edge.0.0l7j69i61j69i60.10008j0j1&FORM=ANNTA1&PC=U531#\")\n temp = urlhandler.get_query_params()\n self.assertEqual(temp, {\"pglt\": \"41\", \"q\": \"humaneval\", \"cvid\": \"4dc2da2bb4bc429eb498c85245ae5253\",\n \"aqs\": \"edge.0.0l7j69i61j69i60.10008j0j1\", \"FORM\": \"ANNTA1\", \"PC\": \"U531\"})\n\n def test_get_query_params_3(self):\n urlhandler = URLHandler(\"https://github.com/openai/human-eval\")\n temp = urlhandler.get_query_params()\n self.assertEqual(temp, None)\n\n def test_get_query_params_4(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?wd=bbb&rsv_spt=1#page\")\n temp = urlhandler.get_query_params()\n self.assertEqual(temp, {\"wd\": \"bbb\", \"rsv_spt\": \"1\"})\n\n def test_get_query_params_5(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?wd=ccc&rsv_spt=1#page\")\n temp = urlhandler.get_query_params()\n self.assertEqual(temp, {\"wd\": \"ccc\", \"rsv_spt\": \"1\"})\n\n def test_get_query_params_6(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?&#page\")\n temp = urlhandler.get_query_params()\n self.assertEqual(temp, {})\n\n\nclass URLHandlerTestGetFragment(unittest.TestCase):\n def test_get_fragment_1(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\n temp = urlhandler.get_fragment()\n self.assertEqual(temp, \"page\")\n\n def test_get_fragment_2(self):\n urlhandler = URLHandler(\n \"https://www.bing.com/search?pglt=41&q=humaneval&cvid=4dc2da2bb4bc429eb498c85245ae5253&aqs=edge.0.0l7j69i61j69i60.10008j0j1&FORM=ANNTA1&PC=U531&mkt=zh-CN\")\n temp = urlhandler.get_fragment()\n self.assertEqual(temp, None)\n\n def test_get_fragment_3(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#aaa\")\n temp = urlhandler.get_fragment()\n self.assertEqual(temp, \"aaa\")\n\n def test_get_fragment_4(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#bbb\")\n temp = urlhandler.get_fragment()\n self.assertEqual(temp, \"bbb\")\n\n def test_get_fragment_5(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#ccc\")\n temp = urlhandler.get_fragment()\n self.assertEqual(temp, \"ccc\")\n\n\nclass URLHandlerTest(unittest.TestCase):\n def test_urlhandler(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\n temp = urlhandler.get_scheme()\n self.assertEqual(temp, \"https\")\n temp = urlhandler.get_host()\n self.assertEqual(temp, \"www.baidu.com\")\n temp = urlhandler.get_path()\n self.assertEqual(temp, \"/s?wd=aaa&rsv_spt=1#page\")\n temp = urlhandler.get_query_params()\n self.assertEqual(temp, {\"wd\": \"aaa\", \"rsv_spt\": \"1\"})\n temp = urlhandler.get_fragment()\n self.assertEqual(temp, \"page\")", "solution_code": "class URLHandler:\n def __init__(self, url):\n self.url = url\n\n def get_scheme(self):\n scheme_end = self.url.find(\"://\")\n if scheme_end != -1:\n return self.url[:scheme_end]\n return None\n\n def get_host(self):\n scheme_end = self.url.find(\"://\")\n if scheme_end != -1:\n url_without_scheme = self.url[scheme_end + 3:]\n host_end = url_without_scheme.find(\"/\")\n if host_end != -1:\n return url_without_scheme[:host_end]\n return url_without_scheme\n return None\n\n def get_path(self):\n scheme_end = self.url.find(\"://\")\n if scheme_end != -1:\n url_without_scheme = self.url[scheme_end + 3:]\n host_end = url_without_scheme.find(\"/\")\n if host_end != -1:\n return url_without_scheme[host_end:]\n return None\n\n def get_query_params(self):\n query_start = self.url.find(\"?\")\n fragment_start = self.url.find(\"#\")\n if query_start != -1:\n query_string = self.url[query_start + 1:fragment_start]\n params = {}\n if len(query_string) > 0:\n param_pairs = query_string.split(\"&\")\n for pair in param_pairs:\n key_value = pair.split(\"=\")\n if len(key_value) == 2:\n key, value = key_value\n params[key] = value\n return params\n return None\n\n def get_fragment(self):\n fragment_start = self.url.find(\"#\")\n if fragment_start != -1:\n return self.url[fragment_start + 1:]\n return None", "import_statement": [], "class_description": " \"\"\"\n The class supports to handle URLs, including extracting the scheme, host, path, query parameters, and fragment.\n \"\"\"\n", "class_name": "URLHandler", "test_classes": [ "URLHandlerTestGetScheme", "URLHandlerTestGetHost", "URLHandlerTestGetPath", "URLHandlerTestGetQueryParams", "URLHandlerTestGetFragment", "URLHandlerTest" ], "class_constructor": "class URLHandler: \n def __init__(self, url):\n \"\"\"\n Initialize URLHandler's URL\n \"\"\"\n self.url = url\n\n", "fields": [ "self.url" ], "methods_info": [ { "method_name": "get_scheme", "method_description": "def get_scheme(self):\n \"\"\"\n get the scheme of the URL\n :return: string, If successful, return the scheme of the URL\n >>> urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\n >>> urlhandler.get_scheme()\n \"https\"\n \"\"\"", "test_class": "URLHandlerTestGetScheme", "test_code": "class URLHandlerTestGetScheme(unittest.TestCase):\n def test_get_scheme_1(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\n temp = urlhandler.get_scheme()\n self.assertEqual(temp, \"https\")\n\n def test_get_scheme_2(self):\n urlhandler = URLHandler(\n \"https://www.bing.com/search?pglt=41&q=humaneval&cvid=4dc2da2bb4bc429eb498c85245ae5253&aqs=edge.0.0l7j69i61j69i60.10008j0j1&FORM=ANNTA1&PC=U531&mkt=zh-CN\")\n temp = urlhandler.get_scheme()\n self.assertEqual(temp, \"https\")\n\n def test_get_scheme_3(self):\n urlhandler = URLHandler(\"https://github.com/openai/human-eval\")\n temp = urlhandler.get_scheme()\n self.assertEqual(temp, \"https\")\n\n def test_get_scheme_4(self):\n urlhandler = URLHandler(\"aaa://github.com/openai/human-eval\")\n temp = urlhandler.get_scheme()\n self.assertEqual(temp, \"aaa\")\n\n def test_get_scheme_5(self):\n urlhandler = URLHandler(\"bbb://github.com/openai/human-eval\")\n temp = urlhandler.get_scheme()\n self.assertEqual(temp, \"bbb\")\n\n def test_get_scheme_6(self):\n urlhandler = URLHandler(\"abcdefg\")\n temp = urlhandler.get_scheme()\n self.assertIsNone(temp)", "solution_code": "def get_scheme(self):\n scheme_end = self.url.find(\"://\")\n if scheme_end != -1:\n return self.url[:scheme_end]\n return None", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.url" ], "method_dependencies": [] } }, { "method_name": "get_host", "method_description": "def get_host(self):\n \"\"\"\n Get the second part of the URL, which is the host domain name\n :return: string, If successful, return the host domain name of the URL\n >>> urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\n >>> urlhandler.get_host()\n \"www.baidu.com\"\n \"\"\"", "test_class": "URLHandlerTestGetHost", "test_code": "class URLHandlerTestGetHost(unittest.TestCase):\n def test_get_host_1(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\n temp = urlhandler.get_host()\n self.assertEqual(temp, \"www.baidu.com\")\n\n def test_get_host_2(self):\n urlhandler = URLHandler(\n \"https://www.bing.com/search?pglt=41&q=humaneval&cvid=4dc2da2bb4bc429eb498c85245ae5253&aqs=edge.0.0l7j69i61j69i60.10008j0j1&FORM=ANNTA1&PC=U531&mkt=zh-CN\")\n temp = urlhandler.get_host()\n self.assertEqual(temp, \"www.bing.com\")\n\n def test_get_host_3(self):\n urlhandler = URLHandler(\"https://github.com/openai/human-eval\")\n temp = urlhandler.get_host()\n self.assertEqual(temp, \"github.com\")\n\n def test_get_host_4(self):\n urlhandler = URLHandler(\"https://aaa.com/openai/human-eval\")\n temp = urlhandler.get_host()\n self.assertEqual(temp, \"aaa.com\")\n\n def test_get_host_5(self):\n urlhandler = URLHandler(\"https://bbb.com/openai/human-eval\")\n temp = urlhandler.get_host()\n self.assertEqual(temp, \"bbb.com\")\n\n def test_get_host_6(self):\n urlhandler = URLHandler(\"abcdefg\")\n temp = urlhandler.get_host()\n self.assertIsNone(temp)\n\n def test_get_host_7(self):\n urlhandler = URLHandler(\"https://bbb.com\")\n temp = urlhandler.get_host()\n self.assertEqual(temp, \"bbb.com\")\n\n def test_get_host_8(self):\n urlhandler = URLHandler(\"https://bbb.com/\")\n temp = urlhandler.get_host()\n self.assertEqual(temp, \"bbb.com\")", "solution_code": "def get_host(self):\n scheme_end = self.url.find(\"://\")\n if scheme_end != -1:\n url_without_scheme = self.url[scheme_end + 3:]\n host_end = url_without_scheme.find(\"/\")\n if host_end != -1:\n return url_without_scheme[:host_end]\n return url_without_scheme\n return None", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.url" ], "method_dependencies": [] } }, { "method_name": "get_path", "method_description": "def get_path(self):\n \"\"\"\n Get the third part of the URL, which is the address of the resource\n :return: string, If successful, return the address of the resource of the URL\n >>> urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\n >>> urlhandler.get_path()\n \"/s?wd=aaa&rsv_spt=1#page\"\n \"\"\"", "test_class": "URLHandlerTestGetPath", "test_code": "class URLHandlerTestGetPath(unittest.TestCase):\n def test_get_path_1(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\n temp = urlhandler.get_path()\n self.assertEqual(temp, \"/s?wd=aaa&rsv_spt=1#page\")\n\n def test_get_path_2(self):\n urlhandler = URLHandler(\n \"https://www.bing.com/search?pglt=41&q=humaneval&cvid=4dc2da2bb4bc429eb498c85245ae5253&aqs=edge.0.0l7j69i61j69i60.10008j0j1&FORM=ANNTA1&PC=U531&mkt=zh-CN\")\n temp = urlhandler.get_path()\n self.assertEqual(temp,\n \"/search?pglt=41&q=humaneval&cvid=4dc2da2bb4bc429eb498c85245ae5253&aqs=edge.0.0l7j69i61j69i60.10008j0j1&FORM=ANNTA1&PC=U531&mkt=zh-CN\")\n\n def test_get_path_3(self):\n urlhandler = URLHandler(\"https://github.com/openai/human-eval\")\n temp = urlhandler.get_path()\n self.assertEqual(temp, \"/openai/human-eval\")\n\n def test_get_path_4(self):\n urlhandler = URLHandler(\"https://github.com/aaa/human-eval\")\n temp = urlhandler.get_path()\n self.assertEqual(temp, \"/aaa/human-eval\")\n\n def test_get_path_5(self):\n urlhandler = URLHandler(\"https://github.com/bbb/human-eval\")\n temp = urlhandler.get_path()\n self.assertEqual(temp, \"/bbb/human-eval\")\n\n def test_get_path_6(self):\n urlhandler = URLHandler(\"abcdefg\")\n temp = urlhandler.get_path()\n self.assertIsNone(temp)", "solution_code": "def get_path(self):\n scheme_end = self.url.find(\"://\")\n if scheme_end != -1:\n url_without_scheme = self.url[scheme_end + 3:]\n host_end = url_without_scheme.find(\"/\")\n if host_end != -1:\n return url_without_scheme[host_end:]\n return None", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.url" ], "method_dependencies": [] } }, { "method_name": "get_query_params", "method_description": "def get_query_params(self):\n \"\"\"\n Get the request parameters for the URL\n :return: dict, If successful, return the request parameters of the URL\n >>> urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\n >>> urlhandler.get_query_params()\n {\"wd\": \"aaa\", \"rsv_spt\": \"1\"}\n \"\"\"", "test_class": "URLHandlerTestGetQueryParams", "test_code": "class URLHandlerTestGetQueryParams(unittest.TestCase):\n def test_get_query_params_1(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\n temp = urlhandler.get_query_params()\n self.assertEqual(temp, {\"wd\": \"aaa\", \"rsv_spt\": \"1\"})\n\n def test_get_query_params_2(self):\n urlhandler = URLHandler(\n \"https://www.bing.com/search?pglt=41&q=humaneval&cvid=4dc2da2bb4bc429eb498c85245ae5253&aqs=edge.0.0l7j69i61j69i60.10008j0j1&FORM=ANNTA1&PC=U531#\")\n temp = urlhandler.get_query_params()\n self.assertEqual(temp, {\"pglt\": \"41\", \"q\": \"humaneval\", \"cvid\": \"4dc2da2bb4bc429eb498c85245ae5253\",\n \"aqs\": \"edge.0.0l7j69i61j69i60.10008j0j1\", \"FORM\": \"ANNTA1\", \"PC\": \"U531\"})\n\n def test_get_query_params_3(self):\n urlhandler = URLHandler(\"https://github.com/openai/human-eval\")\n temp = urlhandler.get_query_params()\n self.assertEqual(temp, None)\n\n def test_get_query_params_4(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?wd=bbb&rsv_spt=1#page\")\n temp = urlhandler.get_query_params()\n self.assertEqual(temp, {\"wd\": \"bbb\", \"rsv_spt\": \"1\"})\n\n def test_get_query_params_5(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?wd=ccc&rsv_spt=1#page\")\n temp = urlhandler.get_query_params()\n self.assertEqual(temp, {\"wd\": \"ccc\", \"rsv_spt\": \"1\"})\n\n def test_get_query_params_6(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?&#page\")\n temp = urlhandler.get_query_params()\n self.assertEqual(temp, {})", "solution_code": "def get_query_params(self):\n query_start = self.url.find(\"?\")\n fragment_start = self.url.find(\"#\")\n if query_start != -1:\n query_string = self.url[query_start + 1:fragment_start]\n params = {}\n if len(query_string) > 0:\n param_pairs = query_string.split(\"&\")\n for pair in param_pairs:\n key_value = pair.split(\"=\")\n if len(key_value) == 2:\n key, value = key_value\n params[key] = value\n return params\n return None", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.url" ], "method_dependencies": [] } }, { "method_name": "get_fragment", "method_description": "def get_fragment(self):\n \"\"\"\n Get the fragment after '#' in the URL\n :return: string, If successful, return the fragment after '#' of the URL\n >>> urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\n >>> urlhandler.get_fragment()\n \"page\"\n \"\"\"", "test_class": "URLHandlerTestGetFragment", "test_code": "class URLHandlerTestGetFragment(unittest.TestCase):\n def test_get_fragment_1(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#page\")\n temp = urlhandler.get_fragment()\n self.assertEqual(temp, \"page\")\n\n def test_get_fragment_2(self):\n urlhandler = URLHandler(\n \"https://www.bing.com/search?pglt=41&q=humaneval&cvid=4dc2da2bb4bc429eb498c85245ae5253&aqs=edge.0.0l7j69i61j69i60.10008j0j1&FORM=ANNTA1&PC=U531&mkt=zh-CN\")\n temp = urlhandler.get_fragment()\n self.assertEqual(temp, None)\n\n def test_get_fragment_3(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#aaa\")\n temp = urlhandler.get_fragment()\n self.assertEqual(temp, \"aaa\")\n\n def test_get_fragment_4(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#bbb\")\n temp = urlhandler.get_fragment()\n self.assertEqual(temp, \"bbb\")\n\n def test_get_fragment_5(self):\n urlhandler = URLHandler(\"https://www.baidu.com/s?wd=aaa&rsv_spt=1#ccc\")\n temp = urlhandler.get_fragment()\n self.assertEqual(temp, \"ccc\")", "solution_code": "def get_fragment(self):\n fragment_start = self.url.find(\"#\")\n if fragment_start != -1:\n return self.url[fragment_start + 1:]\n return None", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.url" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_91", "skeleton": "\nimport urllib.parse\n\nclass UrlPath:\n \"\"\"\n The class is a utility for encapsulating and manipulating the path component of a URL, including adding nodes, parsing path strings, and building path strings with optional encoding.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initializes the UrlPath object with an empty list of segments and a flag indicating the presence of an end tag.\n \"\"\"\n self.segments = []\n self.with_end_tag = False\n\n def add(self, segment):\n \"\"\"\n Adds a segment to the list of segments in the UrlPath.\n :param segment: str, the segment to add.\n >>> url_path = UrlPath()\n >>> url_path.add('foo')\n >>> url_path.add('bar')\n\n url_path.segments = ['foo', 'bar']\n \"\"\"\n\n\n def parse(self, path, charset):\n \"\"\"\n Parses a given path string and populates the list of segments in the UrlPath.\n :param path: str, the path string to parse.\n :param charset: str, the character encoding of the path string.\n >>> url_path = UrlPath()\n >>> url_path.parse('/foo/bar/', 'utf-8')\n\n url_path.segments = ['foo', 'bar']\n \"\"\"\n\n\n @staticmethod\n def fix_path(path):\n \"\"\"\n Fixes the given path string by removing leading and trailing slashes.\n :param path: str, the path string to fix.\n :return: str, the fixed path string.\n >>> url_path = UrlPath()\n >>> url_path.fix_path('/foo/bar/')\n 'foo/bar'\n\n \"\"\"", "test": "import unittest\n\n\nclass UrlPathTestAdd(unittest.TestCase):\n def test_add_1(self):\n url_path = UrlPath()\n url_path.add('foo')\n url_path.add('bar')\n self.assertEqual(url_path.segments, ['foo', 'bar'])\n\n def test_add_2(self):\n url_path = UrlPath()\n url_path.add('aaa')\n url_path.add('bbb')\n self.assertEqual(url_path.segments, ['aaa', 'bbb'])\n\n def test_add_3(self):\n url_path = UrlPath()\n url_path.add('123')\n self.assertEqual(url_path.segments, ['123'])\n\n def test_add_4(self):\n url_path = UrlPath()\n url_path.add('ddd')\n self.assertEqual(url_path.segments, ['ddd'])\n\n def test_add_5(self):\n url_path = UrlPath()\n url_path.add('eee')\n self.assertEqual(url_path.segments, ['eee'])\n\n\nclass UrlPathTestParse(unittest.TestCase):\n def test_parse_1(self):\n url_path = UrlPath()\n url_path.parse('/foo/bar/', 'utf-8')\n self.assertEqual(url_path.segments, ['foo', 'bar'])\n self.assertEqual(url_path.with_end_tag, True)\n\n def test_parse_2(self):\n url_path = UrlPath()\n url_path.parse('aaa/bbb', 'utf-8')\n self.assertEqual(url_path.segments, ['aaa', 'bbb'])\n self.assertEqual(url_path.with_end_tag, False)\n\n def test_parse_3(self):\n url_path = UrlPath()\n url_path.parse('/123/456/', 'utf-8')\n self.assertEqual(url_path.segments, ['123', '456'])\n self.assertEqual(url_path.with_end_tag, True)\n\n def test_parse_4(self):\n url_path = UrlPath()\n url_path.parse('/123/456/789', 'utf-8')\n self.assertEqual(url_path.segments, ['123', '456', '789'])\n self.assertEqual(url_path.with_end_tag, False)\n\n def test_parse_5(self):\n url_path = UrlPath()\n url_path.parse('/foo/bar', 'utf-8')\n self.assertEqual(url_path.segments, ['foo', 'bar'])\n self.assertEqual(url_path.with_end_tag, False)\n\n def test_parse_6(self):\n url_path = UrlPath()\n url_path.parse('', 'utf-8')\n self.assertEqual(url_path.segments, [])\n self.assertEqual(url_path.with_end_tag, False)\n\n def test_parse_7(self):\n url_path = UrlPath()\n url_path.parse('//', 'utf-8')\n self.assertEqual(url_path.segments, [])\n self.assertEqual(url_path.with_end_tag, True)\n\n\nclass UrlPathTestFixPath(unittest.TestCase):\n def test_fix_path_1(self):\n fixed_path = UrlPath.fix_path('/foo/bar/')\n self.assertEqual(fixed_path, 'foo/bar')\n\n def test_fix_path_2(self):\n fixed_path = UrlPath.fix_path('/aaa/bbb/')\n self.assertEqual(fixed_path, 'aaa/bbb')\n\n def test_fix_path_3(self):\n fixed_path = UrlPath.fix_path('/a/b/')\n self.assertEqual(fixed_path, 'a/b')\n\n def test_fix_path_4(self):\n fixed_path = UrlPath.fix_path('/111/222/')\n self.assertEqual(fixed_path, '111/222')\n\n def test_fix_path_5(self):\n fixed_path = UrlPath.fix_path('/a/')\n self.assertEqual(fixed_path, 'a')\n\n def test_fix_path_6(self):\n fixed_path = UrlPath.fix_path('')\n self.assertEqual(fixed_path, '')\n\n\nclass UrlPathTest(unittest.TestCase):\n def test_urlpath(self):\n url_path = UrlPath()\n url_path.add('foo')\n url_path.add('bar')\n self.assertEqual(url_path.segments, ['foo', 'bar'])\n\n url_path = UrlPath()\n url_path.parse('/foo/bar/', 'utf-8')\n self.assertEqual(url_path.segments, ['foo', 'bar'])\n self.assertEqual(url_path.with_end_tag, True)\n\n fixed_path = UrlPath.fix_path('/foo/bar/')\n self.assertEqual(fixed_path, 'foo/bar')", "solution_code": "import urllib.parse\n\n\nclass UrlPath:\n def __init__(self):\n self.segments = []\n self.with_end_tag = False\n\n def add(self, segment):\n self.segments.append(self.fix_path(segment))\n\n def parse(self, path, charset):\n if path:\n if path.endswith('/'):\n self.with_end_tag = True\n\n path = self.fix_path(path)\n if path:\n split = path.split('/')\n for seg in split:\n decoded_seg = urllib.parse.unquote(seg, encoding=charset)\n self.segments.append(decoded_seg)\n\n @staticmethod\n def fix_path(path):\n if not path:\n return ''\n\n segment_str = path.strip('/')\n return segment_str", "import_statement": [ "import urllib.parse" ], "class_description": " \"\"\"\n The class is a utility for encapsulating and manipulating the path component of a URL, including adding nodes, parsing path strings, and building path strings with optional encoding.\n \"\"\"\n", "class_name": "UrlPath", "test_classes": [ "UrlPathTestAdd", "UrlPathTestParse", "UrlPathTestFixPath", "UrlPathTest" ], "class_constructor": "class UrlPath: \n def __init__(self):\n \"\"\"\n Initializes the UrlPath object with an empty list of segments and a flag indicating the presence of an end tag.\n \"\"\"\n self.segments = []\n self.with_end_tag = False\n\n", "fields": [ "self.segments", "self.with_end_tag" ], "methods_info": [ { "method_name": "add", "method_description": "def add(self, segment):\n \"\"\"\n Adds a segment to the list of segments in the UrlPath.\n :param segment: str, the segment to add.\n >>> url_path = UrlPath()\n >>> url_path.add('foo')\n >>> url_path.add('bar')\n\n url_path.segments = ['foo', 'bar']\n \"\"\"", "test_class": "UrlPathTestAdd", "test_code": "class UrlPathTestAdd(unittest.TestCase):\n def test_add_1(self):\n url_path = UrlPath()\n url_path.add('foo')\n url_path.add('bar')\n self.assertEqual(url_path.segments, ['foo', 'bar'])\n\n def test_add_2(self):\n url_path = UrlPath()\n url_path.add('aaa')\n url_path.add('bbb')\n self.assertEqual(url_path.segments, ['aaa', 'bbb'])\n\n def test_add_3(self):\n url_path = UrlPath()\n url_path.add('123')\n self.assertEqual(url_path.segments, ['123'])\n\n def test_add_4(self):\n url_path = UrlPath()\n url_path.add('ddd')\n self.assertEqual(url_path.segments, ['ddd'])\n\n def test_add_5(self):\n url_path = UrlPath()\n url_path.add('eee')\n self.assertEqual(url_path.segments, ['eee'])", "solution_code": "def add(self, segment):\n self.segments.append(self.fix_path(segment))", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.segments" ], "method_dependencies": [ "fix_path" ] } }, { "method_name": "parse", "method_description": "def parse(self, path, charset):\n \"\"\"\n Parses a given path string and populates the list of segments in the UrlPath.\n :param path: str, the path string to parse.\n :param charset: str, the character encoding of the path string.\n >>> url_path = UrlPath()\n >>> url_path.parse('/foo/bar/', 'utf-8')\n\n url_path.segments = ['foo', 'bar']\n \"\"\"", "test_class": "UrlPathTestParse", "test_code": "class UrlPathTestParse(unittest.TestCase):\n def test_parse_1(self):\n url_path = UrlPath()\n url_path.parse('/foo/bar/', 'utf-8')\n self.assertEqual(url_path.segments, ['foo', 'bar'])\n self.assertEqual(url_path.with_end_tag, True)\n\n def test_parse_2(self):\n url_path = UrlPath()\n url_path.parse('aaa/bbb', 'utf-8')\n self.assertEqual(url_path.segments, ['aaa', 'bbb'])\n self.assertEqual(url_path.with_end_tag, False)\n\n def test_parse_3(self):\n url_path = UrlPath()\n url_path.parse('/123/456/', 'utf-8')\n self.assertEqual(url_path.segments, ['123', '456'])\n self.assertEqual(url_path.with_end_tag, True)\n\n def test_parse_4(self):\n url_path = UrlPath()\n url_path.parse('/123/456/789', 'utf-8')\n self.assertEqual(url_path.segments, ['123', '456', '789'])\n self.assertEqual(url_path.with_end_tag, False)\n\n def test_parse_5(self):\n url_path = UrlPath()\n url_path.parse('/foo/bar', 'utf-8')\n self.assertEqual(url_path.segments, ['foo', 'bar'])\n self.assertEqual(url_path.with_end_tag, False)\n\n def test_parse_6(self):\n url_path = UrlPath()\n url_path.parse('', 'utf-8')\n self.assertEqual(url_path.segments, [])\n self.assertEqual(url_path.with_end_tag, False)\n\n def test_parse_7(self):\n url_path = UrlPath()\n url_path.parse('//', 'utf-8')\n self.assertEqual(url_path.segments, [])\n self.assertEqual(url_path.with_end_tag, True)", "solution_code": "def parse(self, path, charset):\n if path:\n if path.endswith('/'):\n self.with_end_tag = True\n\n path = self.fix_path(path)\n if path:\n split = path.split('/')\n for seg in split:\n decoded_seg = urllib.parse.unquote(seg, encoding=charset)\n self.segments.append(decoded_seg)", "dependencies": { "Standalone": false, "lib_dependencies": [ "urllib.parse" ], "field_dependencies": [ "self.segments", "self.with_end_tag" ], "method_dependencies": [ "fix_path" ] } }, { "method_name": "fix_path", "method_description": "@staticmethod\n def fix_path(path):\n \"\"\"\n Fixes the given path string by removing leading and trailing slashes.\n :param path: str, the path string to fix.\n :return: str, the fixed path string.\n >>> url_path = UrlPath()\n >>> url_path.fix_path('/foo/bar/')\n 'foo/bar'\n\n \"\"\"", "test_class": "UrlPathTestFixPath", "test_code": "class UrlPathTestFixPath(unittest.TestCase):\n def test_fix_path_1(self):\n fixed_path = UrlPath.fix_path('/foo/bar/')\n self.assertEqual(fixed_path, 'foo/bar')\n\n def test_fix_path_2(self):\n fixed_path = UrlPath.fix_path('/aaa/bbb/')\n self.assertEqual(fixed_path, 'aaa/bbb')\n\n def test_fix_path_3(self):\n fixed_path = UrlPath.fix_path('/a/b/')\n self.assertEqual(fixed_path, 'a/b')\n\n def test_fix_path_4(self):\n fixed_path = UrlPath.fix_path('/111/222/')\n self.assertEqual(fixed_path, '111/222')\n\n def test_fix_path_5(self):\n fixed_path = UrlPath.fix_path('/a/')\n self.assertEqual(fixed_path, 'a')\n\n def test_fix_path_6(self):\n fixed_path = UrlPath.fix_path('')\n self.assertEqual(fixed_path, '')", "solution_code": "@staticmethod\n def fix_path(path):\n if not path:\n return ''\n\n segment_str = path.strip('/')\n return segment_str", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_92", "skeleton": "\nclass UserLoginDB:\n \"\"\"\n This is a database management class for user login verification, providing functions for inserting user information, searching user information, deleting user information, and validating user login.\n \"\"\"\n\n def __init__(self, db_name):\n \"\"\"\n Initializes the UserLoginDB object with the specified database name.\n :param db_name: str, the name of the SQLite database.\n \"\"\"\n self.connection = sqlite3.connect(db_name)\n self.cursor = self.connection.cursor()\n\n def insert_user(self, username, password):\n \"\"\"\n Inserts a new user into the \"users\" table.\n :param username: str, the username of the user.\n :param password: str, the password of the user.\n :return: None\n >>> user_db = UserLoginDB(\"user_database.db\")\n >>> user_db.create_table()\n >>> user_db.insert_user('user1', 'pass1')\n \"\"\"\n\n\n def search_user_by_username(self, username):\n \"\"\"\n Searches for users in the \"users\" table by username.\n :param username: str, the username of the user to search for.\n :return:list of tuples, the rows from the \"users\" table that match the search criteria.\n >>> user_db = UserLoginDB(\"user_database.db\")\n >>> user_db.create_table()\n >>> user_db.insert_user('user1', 'pass1')\n >>> result = user_db.search_user_by_username('user1')\n len(result) = 1\n \"\"\"\n\n\n def delete_user_by_username(self, username):\n \"\"\"\n Deletes a user from the \"users\" table by username.\n :param username: str, the username of the user to delete.\n :return: None\n >>> user_db = UserLoginDB(\"user_database.db\")\n >>> user_db.create_table()\n >>> user_db.insert_user('user1', 'pass1')\n >>> user_db.delete_user_by_username('user1')\n \"\"\"\n\n\n def validate_user_login(self, username, password):\n \"\"\"\n Determine whether the user can log in, that is, the user is in the database and the password is correct\n :param username:str, the username of the user to validate.\n :param password:str, the password of the user to validate.\n :return:bool, representing whether the user can log in correctly\n >>> user_db = UserLoginDB(\"user_database.db\")\n >>> user_db.create_table()\n >>> user_db.insert_user('user1', 'pass1')\n >>> user_db.validate_user_login('user1', 'pass1')\n True\n \"\"\"", "test": "import unittest\nimport os\nfrom tempfile import gettempdir\n\n\nclass UserLoginDBTestInsertUser(unittest.TestCase):\n def setUp(self):\n self.db_path = os.path.join(gettempdir(), 'test_db.db')\n conn = sqlite3.connect(self.db_path)\n cursor = conn.cursor()\n create_table_query = \"\"\"\n CREATE TABLE IF NOT EXISTS users (\n username TEXT,\n password TEXT\n )\n \"\"\"\n cursor.execute(create_table_query)\n\n conn.commit()\n conn.close()\n self.db = UserLoginDB(self.db_path)\n\n def tearDown(self):\n self.db.connection.close()\n os.unlink(self.db_path)\n\n def test_insert_user_1(self):\n self.db.insert_user('user1', 'pass1')\n user = self.db.search_user_by_username('user1')\n self.assertIsNotNone(user)\n self.assertEqual(user[0], 'user1')\n self.assertEqual(user[1], 'pass1')\n\n def test_insert_user_2(self):\n self.db.insert_user('user2', 'pass2')\n user = self.db.search_user_by_username('user2')\n self.assertIsNotNone(user)\n self.assertEqual(user[0], 'user2')\n self.assertEqual(user[1], 'pass2')\n\n def test_insert_user_3(self):\n self.db.insert_user('user3', 'pass3')\n user = self.db.search_user_by_username('user3')\n self.assertIsNotNone(user)\n self.assertEqual(user[0], 'user3')\n self.assertEqual(user[1], 'pass3')\n\n def test_insert_user_4(self):\n self.db.insert_user('user4', 'pass4')\n user = self.db.search_user_by_username('user4')\n self.assertIsNotNone(user)\n self.assertEqual(user[0], 'user4')\n self.assertEqual(user[1], 'pass4')\n\n def test_insert_user_5(self):\n self.db.insert_user('user5', 'pass5')\n user = self.db.search_user_by_username('user5')\n self.assertIsNotNone(user)\n self.assertEqual(user[0], 'user5')\n self.assertEqual(user[1], 'pass5')\n\n\nclass UserLoginDBTestSearchUserByUsername(unittest.TestCase):\n def setUp(self):\n self.db_path = os.path.join(gettempdir(), 'test_db.db')\n conn = sqlite3.connect(self.db_path)\n cursor = conn.cursor()\n create_table_query = \"\"\"\n CREATE TABLE IF NOT EXISTS users (\n username TEXT,\n password TEXT\n )\n \"\"\"\n cursor.execute(create_table_query)\n\n conn.commit()\n conn.close()\n self.db = UserLoginDB(self.db_path)\n\n def tearDown(self):\n self.db.connection.close()\n os.unlink(self.db_path)\n\n def test_search_user_by_username_1(self):\n self.db.insert_user('user1', 'pass1')\n user = self.db.search_user_by_username('user1')\n self.assertIsNotNone(user)\n self.assertEqual(user[0], 'user1')\n self.assertEqual(user[1], 'pass1')\n\n def test_search_user_by_username_2(self):\n self.db.insert_user('user2', 'pass2')\n user = self.db.search_user_by_username('user2')\n self.assertIsNotNone(user)\n self.assertEqual(user[0], 'user2')\n self.assertEqual(user[1], 'pass2')\n\n def test_search_user_by_username_3(self):\n self.db.insert_user('user3', 'pass3')\n user = self.db.search_user_by_username('user3')\n self.assertIsNotNone(user)\n self.assertEqual(user[0], 'user3')\n self.assertEqual(user[1], 'pass3')\n\n def test_search_user_by_username_4(self):\n self.db.insert_user('user4', 'pass4')\n user = self.db.search_user_by_username('user4')\n self.assertIsNotNone(user)\n self.assertEqual(user[0], 'user4')\n self.assertEqual(user[1], 'pass4')\n\n def test_search_user_by_username_5(self):\n self.db.insert_user('user5', 'pass5')\n user = self.db.search_user_by_username('user5')\n self.assertIsNotNone(user)\n self.assertEqual(user[0], 'user5')\n self.assertEqual(user[1], 'pass5')\n\n\nclass UserLoginDBTestDeleteUserByUsername(unittest.TestCase):\n def setUp(self):\n self.db_path = os.path.join(gettempdir(), 'test_db.db')\n conn = sqlite3.connect(self.db_path)\n cursor = conn.cursor()\n create_table_query = \"\"\"\n CREATE TABLE IF NOT EXISTS users (\n username TEXT,\n password TEXT\n )\n \"\"\"\n cursor.execute(create_table_query)\n\n conn.commit()\n conn.close()\n self.db = UserLoginDB(self.db_path)\n\n def tearDown(self):\n self.db.connection.close()\n os.unlink(self.db_path)\n\n def test_delete_user_by_username_1(self):\n self.db.insert_user('user1', 'pass1')\n self.db.delete_user_by_username('user1')\n user = self.db.search_user_by_username('user1')\n self.assertIsNone(user)\n\n def test_delete_user_by_username_2(self):\n self.db.insert_user('user2', 'pass2')\n self.db.delete_user_by_username('user2')\n user = self.db.search_user_by_username('user2')\n self.assertIsNone(user)\n\n def test_delete_user_by_username_3(self):\n self.db.insert_user('user3', 'pass3')\n self.db.delete_user_by_username('user3')\n user = self.db.search_user_by_username('user3')\n self.assertIsNone(user)\n\n def test_delete_user_by_username_4(self):\n self.db.insert_user('user4', 'pass4')\n self.db.delete_user_by_username('user4')\n user = self.db.search_user_by_username('user4')\n self.assertIsNone(user)\n\n def test_delete_user_by_username_5(self):\n self.db.insert_user('user5', 'pass5')\n self.db.delete_user_by_username('user5')\n user = self.db.search_user_by_username('user5')\n self.assertIsNone(user)\n\n\nclass UserLoginDBTestValidateUserLogin(unittest.TestCase):\n def setUp(self):\n self.db_path = os.path.join(gettempdir(), 'test_db.db')\n conn = sqlite3.connect(self.db_path)\n cursor = conn.cursor()\n create_table_query = \"\"\"\n CREATE TABLE IF NOT EXISTS users (\n username TEXT,\n password TEXT\n )\n \"\"\"\n cursor.execute(create_table_query)\n\n conn.commit()\n conn.close()\n self.db = UserLoginDB(self.db_path)\n\n def tearDown(self):\n self.db.connection.close()\n os.unlink(self.db_path)\n\n def test_validate_user_login_1(self):\n self.db.insert_user('user1', 'pass1')\n valid = self.db.validate_user_login('user1', 'pass1')\n self.assertTrue(valid)\n\n def test_validate_user_login_2(self):\n self.db.insert_user('user1', 'pass1')\n invalid = self.db.validate_user_login('user1', 'wrongpass')\n self.assertFalse(invalid)\n\n def test_validate_user_login_3(self):\n valid = self.db.validate_user_login('nonexistentuser', 'somepass')\n self.assertFalse(valid)\n\n def test_validate_user_login_4(self):\n self.db.insert_user('user2', 'pass2')\n valid = self.db.validate_user_login('user2', 'pass2')\n self.assertTrue(valid)\n\n def test_validate_user_login_5(self):\n self.db.insert_user('user3', 'pass3')\n valid = self.db.validate_user_login('user3', 'pass3')\n self.assertTrue(valid)\n\n\nclass UserLoginDBTest(unittest.TestCase):\n def setUp(self):\n self.db_path = os.path.join(gettempdir(), 'test_db.db')\n conn = sqlite3.connect(self.db_path)\n cursor = conn.cursor()\n create_table_query = \"\"\"\n CREATE TABLE IF NOT EXISTS users (\n username TEXT,\n password TEXT\n )\n \"\"\"\n cursor.execute(create_table_query)\n\n conn.commit()\n conn.close()\n self.db = UserLoginDB(self.db_path)\n\n def tearDown(self):\n self.db.connection.close()\n os.unlink(self.db_path)\n\n def test_UserLoginDB(self):\n self.db.insert_user('user1', 'pass1')\n user = self.db.search_user_by_username('user1')\n self.assertIsNotNone(user)\n self.assertEqual(user[0], 'user1')\n self.assertEqual(user[1], 'pass1')\n self.db.delete_user_by_username('user1')\n user = self.db.search_user_by_username('user1')\n self.assertIsNone(user)\n self.db.insert_user('user1', 'pass1')\n valid = self.db.validate_user_login('user1', 'pass1')\n self.assertTrue(valid)", "solution_code": "import sqlite3\n\n\nclass UserLoginDB:\n def __init__(self, db_name):\n self.connection = sqlite3.connect(db_name)\n self.cursor = self.connection.cursor()\n\n def insert_user(self, username, password):\n self.cursor.execute('''\n INSERT INTO users (username, password)\n VALUES (?, ?)\n ''', (username, password))\n self.connection.commit()\n\n def search_user_by_username(self, username):\n self.cursor.execute('''\n SELECT * FROM users WHERE username = ?\n ''', (username,))\n user = self.cursor.fetchone()\n return user\n\n def delete_user_by_username(self, username):\n self.cursor.execute('''\n DELETE FROM users WHERE username = ?\n ''', (username,))\n self.connection.commit()\n\n def validate_user_login(self, username, password):\n user = self.search_user_by_username(username)\n if user is not None and user[1] == password:\n return True\n return False", "import_statement": [ "import sqlite3" ], "class_description": " \"\"\"\n This is a database management class for user login verification, providing functions for inserting user information, searching user information, deleting user information, and validating user login.\n \"\"\"\n", "class_name": "UserLoginDB", "test_classes": [ "UserLoginDBTestInsertUser", "UserLoginDBTestSearchUserByUsername", "UserLoginDBTestDeleteUserByUsername", "UserLoginDBTestValidateUserLogin", "UserLoginDBTest" ], "class_constructor": "class UserLoginDB: \n def __init__(self, db_name):\n \"\"\"\n Initializes the UserLoginDB object with the specified database name.\n :param db_name: str, the name of the SQLite database.\n \"\"\"\n self.connection = sqlite3.connect(db_name)\n self.cursor = self.connection.cursor()\n\n", "fields": [ "self.connection", "self.cursor" ], "methods_info": [ { "method_name": "insert_user", "method_description": "def insert_user(self, username, password):\n \"\"\"\n Inserts a new user into the \"users\" table.\n :param username: str, the username of the user.\n :param password: str, the password of the user.\n :return: None\n >>> user_db = UserLoginDB(\"user_database.db\")\n >>> user_db.create_table()\n >>> user_db.insert_user('user1', 'pass1')\n \"\"\"", "test_class": "UserLoginDBTestInsertUser", "test_code": "class UserLoginDBTestInsertUser(unittest.TestCase):\n def setUp(self):\n self.db_path = os.path.join(gettempdir(), 'test_db.db')\n conn = sqlite3.connect(self.db_path)\n cursor = conn.cursor()\n create_table_query = \"\"\"\n CREATE TABLE IF NOT EXISTS users (\n username TEXT,\n password TEXT\n )\n \"\"\"\n cursor.execute(create_table_query)\n\n conn.commit()\n conn.close()\n self.db = UserLoginDB(self.db_path)\n\n def tearDown(self):\n self.db.connection.close()\n os.unlink(self.db_path)\n\n def test_insert_user_1(self):\n self.db.insert_user('user1', 'pass1')\n user = self.db.search_user_by_username('user1')\n self.assertIsNotNone(user)\n self.assertEqual(user[0], 'user1')\n self.assertEqual(user[1], 'pass1')\n\n def test_insert_user_2(self):\n self.db.insert_user('user2', 'pass2')\n user = self.db.search_user_by_username('user2')\n self.assertIsNotNone(user)\n self.assertEqual(user[0], 'user2')\n self.assertEqual(user[1], 'pass2')\n\n def test_insert_user_3(self):\n self.db.insert_user('user3', 'pass3')\n user = self.db.search_user_by_username('user3')\n self.assertIsNotNone(user)\n self.assertEqual(user[0], 'user3')\n self.assertEqual(user[1], 'pass3')\n\n def test_insert_user_4(self):\n self.db.insert_user('user4', 'pass4')\n user = self.db.search_user_by_username('user4')\n self.assertIsNotNone(user)\n self.assertEqual(user[0], 'user4')\n self.assertEqual(user[1], 'pass4')\n\n def test_insert_user_5(self):\n self.db.insert_user('user5', 'pass5')\n user = self.db.search_user_by_username('user5')\n self.assertIsNotNone(user)\n self.assertEqual(user[0], 'user5')\n self.assertEqual(user[1], 'pass5')", "solution_code": "def insert_user(self, username, password):\n self.cursor.execute('''\n INSERT INTO users (username, password)\n VALUES (?, ?)\n ''', (username, password))\n self.connection.commit()", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.connection", "self.cursor" ], "method_dependencies": [] } }, { "method_name": "search_user_by_username", "method_description": "def search_user_by_username(self, username):\n \"\"\"\n Searches for users in the \"users\" table by username.\n :param username: str, the username of the user to search for.\n :return:list of tuples, the rows from the \"users\" table that match the search criteria.\n >>> user_db = UserLoginDB(\"user_database.db\")\n >>> user_db.create_table()\n >>> user_db.insert_user('user1', 'pass1')\n >>> result = user_db.search_user_by_username('user1')\n len(result) = 1\n \"\"\"", "test_class": "UserLoginDBTestSearchUserByUsername", "test_code": "class UserLoginDBTestSearchUserByUsername(unittest.TestCase):\n def setUp(self):\n self.db_path = os.path.join(gettempdir(), 'test_db.db')\n conn = sqlite3.connect(self.db_path)\n cursor = conn.cursor()\n create_table_query = \"\"\"\n CREATE TABLE IF NOT EXISTS users (\n username TEXT,\n password TEXT\n )\n \"\"\"\n cursor.execute(create_table_query)\n\n conn.commit()\n conn.close()\n self.db = UserLoginDB(self.db_path)\n\n def tearDown(self):\n self.db.connection.close()\n os.unlink(self.db_path)\n\n def test_search_user_by_username_1(self):\n self.db.insert_user('user1', 'pass1')\n user = self.db.search_user_by_username('user1')\n self.assertIsNotNone(user)\n self.assertEqual(user[0], 'user1')\n self.assertEqual(user[1], 'pass1')\n\n def test_search_user_by_username_2(self):\n self.db.insert_user('user2', 'pass2')\n user = self.db.search_user_by_username('user2')\n self.assertIsNotNone(user)\n self.assertEqual(user[0], 'user2')\n self.assertEqual(user[1], 'pass2')\n\n def test_search_user_by_username_3(self):\n self.db.insert_user('user3', 'pass3')\n user = self.db.search_user_by_username('user3')\n self.assertIsNotNone(user)\n self.assertEqual(user[0], 'user3')\n self.assertEqual(user[1], 'pass3')\n\n def test_search_user_by_username_4(self):\n self.db.insert_user('user4', 'pass4')\n user = self.db.search_user_by_username('user4')\n self.assertIsNotNone(user)\n self.assertEqual(user[0], 'user4')\n self.assertEqual(user[1], 'pass4')\n\n def test_search_user_by_username_5(self):\n self.db.insert_user('user5', 'pass5')\n user = self.db.search_user_by_username('user5')\n self.assertIsNotNone(user)\n self.assertEqual(user[0], 'user5')\n self.assertEqual(user[1], 'pass5')", "solution_code": "def search_user_by_username(self, username):\n self.cursor.execute('''\n SELECT * FROM users WHERE username = ?\n ''', (username,))\n user = self.cursor.fetchone()\n return user", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.cursor" ], "method_dependencies": [] } }, { "method_name": "delete_user_by_username", "method_description": "def delete_user_by_username(self, username):\n \"\"\"\n Deletes a user from the \"users\" table by username.\n :param username: str, the username of the user to delete.\n :return: None\n >>> user_db = UserLoginDB(\"user_database.db\")\n >>> user_db.create_table()\n >>> user_db.insert_user('user1', 'pass1')\n >>> user_db.delete_user_by_username('user1')\n \"\"\"", "test_class": "UserLoginDBTestDeleteUserByUsername", "test_code": "class UserLoginDBTestDeleteUserByUsername(unittest.TestCase):\n def setUp(self):\n self.db_path = os.path.join(gettempdir(), 'test_db.db')\n conn = sqlite3.connect(self.db_path)\n cursor = conn.cursor()\n create_table_query = \"\"\"\n CREATE TABLE IF NOT EXISTS users (\n username TEXT,\n password TEXT\n )\n \"\"\"\n cursor.execute(create_table_query)\n\n conn.commit()\n conn.close()\n self.db = UserLoginDB(self.db_path)\n\n def tearDown(self):\n self.db.connection.close()\n os.unlink(self.db_path)\n\n def test_delete_user_by_username_1(self):\n self.db.insert_user('user1', 'pass1')\n self.db.delete_user_by_username('user1')\n user = self.db.search_user_by_username('user1')\n self.assertIsNone(user)\n\n def test_delete_user_by_username_2(self):\n self.db.insert_user('user2', 'pass2')\n self.db.delete_user_by_username('user2')\n user = self.db.search_user_by_username('user2')\n self.assertIsNone(user)\n\n def test_delete_user_by_username_3(self):\n self.db.insert_user('user3', 'pass3')\n self.db.delete_user_by_username('user3')\n user = self.db.search_user_by_username('user3')\n self.assertIsNone(user)\n\n def test_delete_user_by_username_4(self):\n self.db.insert_user('user4', 'pass4')\n self.db.delete_user_by_username('user4')\n user = self.db.search_user_by_username('user4')\n self.assertIsNone(user)\n\n def test_delete_user_by_username_5(self):\n self.db.insert_user('user5', 'pass5')\n self.db.delete_user_by_username('user5')\n user = self.db.search_user_by_username('user5')\n self.assertIsNone(user)", "solution_code": "def delete_user_by_username(self, username):\n self.cursor.execute('''\n DELETE FROM users WHERE username = ?\n ''', (username,))\n self.connection.commit()", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.connection", "self.cursor" ], "method_dependencies": [] } }, { "method_name": "validate_user_login", "method_description": "def validate_user_login(self, username, password):\n \"\"\"\n Determine whether the user can log in, that is, the user is in the database and the password is correct\n :param username:str, the username of the user to validate.\n :param password:str, the password of the user to validate.\n :return:bool, representing whether the user can log in correctly\n >>> user_db = UserLoginDB(\"user_database.db\")\n >>> user_db.create_table()\n >>> user_db.insert_user('user1', 'pass1')\n >>> user_db.validate_user_login('user1', 'pass1')\n True\n \"\"\"", "test_class": "UserLoginDBTestValidateUserLogin", "test_code": "class UserLoginDBTestValidateUserLogin(unittest.TestCase):\n def setUp(self):\n self.db_path = os.path.join(gettempdir(), 'test_db.db')\n conn = sqlite3.connect(self.db_path)\n cursor = conn.cursor()\n create_table_query = \"\"\"\n CREATE TABLE IF NOT EXISTS users (\n username TEXT,\n password TEXT\n )\n \"\"\"\n cursor.execute(create_table_query)\n\n conn.commit()\n conn.close()\n self.db = UserLoginDB(self.db_path)\n\n def tearDown(self):\n self.db.connection.close()\n os.unlink(self.db_path)\n\n def test_validate_user_login_1(self):\n self.db.insert_user('user1', 'pass1')\n valid = self.db.validate_user_login('user1', 'pass1')\n self.assertTrue(valid)\n\n def test_validate_user_login_2(self):\n self.db.insert_user('user1', 'pass1')\n invalid = self.db.validate_user_login('user1', 'wrongpass')\n self.assertFalse(invalid)\n\n def test_validate_user_login_3(self):\n valid = self.db.validate_user_login('nonexistentuser', 'somepass')\n self.assertFalse(valid)\n\n def test_validate_user_login_4(self):\n self.db.insert_user('user2', 'pass2')\n valid = self.db.validate_user_login('user2', 'pass2')\n self.assertTrue(valid)\n\n def test_validate_user_login_5(self):\n self.db.insert_user('user3', 'pass3')\n valid = self.db.validate_user_login('user3', 'pass3')\n self.assertTrue(valid)", "solution_code": "def validate_user_login(self, username, password):\n user = self.search_user_by_username(username)\n if user is not None and user[1] == password:\n return True\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [ "search_user_by_username" ] } } ] }, { "task_id": "ClassEval_93", "skeleton": "\nimport numpy as np\nfrom gensim import matutils\nfrom numpy import dot, array\n\nclass VectorUtil:\n \"\"\"\n The class provides vector operations, including calculating similarity, cosine similarities, average similarity, and IDF weights.\n \"\"\"\n\n @staticmethod\n def similarity(vector_1, vector_2):\n \"\"\"\n Compute the cosine similarity between one vector and another vector.\n :param vector_1: numpy.ndarray, Vector from which similarities are to be computed, expected shape (dim,).\n :param vector_2: numpy.ndarray, Vector from which similarities are to be computed, expected shape (dim,).\n :return: numpy.ndarray, Contains cosine distance between `vector_1` and `vector_2`\n >>> vector_1 = np.array([1, 1])\n >>> vector_2 = np.array([1, 0])\n >>> VectorUtil.similarity(vector_1, vector_2)\n 0.7071067811865475\n \"\"\"\n\n\n @staticmethod\n def cosine_similarities(vector_1, vectors_all):\n \"\"\"\n Compute cosine similarities between one vector and a set of other vectors.\n :param vector_1: numpy.ndarray, Vector from which similarities are to be computed, expected shape (dim,).\n :param vectors_all: list of numpy.ndarray, For each row in vectors_all, distance from vector_1 is computed, expected shape (num_vectors, dim).\n :return: numpy.ndarray, Contains cosine distance between `vector_1` and each row in `vectors_all`, shape (num_vectors,).\n >>> vector1 = np.array([1, 2, 3])\n >>> vectors_all = [np.array([4, 5, 6]), np.array([7, 8, 9])]\n >>> VectorUtil.cosine_similarities(vector1, vectors_all)\n [0.97463185 0.95941195]\n \"\"\"\n\n\n @staticmethod\n def n_similarity(vector_list_1, vector_list_2):\n \"\"\"\n Compute cosine similarity between two sets of vectors.\n :param vector_list_1: list of numpy vector\n :param vector_list_2: list of numpy vector\n :return: numpy.ndarray, Similarities between vector_list_1 and vector_list_2.\n >>> vector_list1 = [np.array([1, 2, 3]), np.array([4, 5, 6])]\n >>> vector_list2 = [np.array([7, 8, 9]), np.array([10, 11, 12])]\n >>> VectorUtil.n_similarity(vector_list1, vector_list2)\n 0.9897287473881233\n \"\"\"\n\n\n @staticmethod\n def compute_idf_weight_dict(total_num, number_dict):\n \"\"\"\n Calculate log(total_num+1/count+1) for each count in number_dict\n :param total_num: int\n :param number_dict: dict\n :return: dict\n >>> num_dict = {'key1':0.1, 'key2':0.5}\n >>> VectorUtil.compute_idf_weight_dict(2, num_dict)\n {'key1': 1.0033021088637848, 'key2': 0.6931471805599453}\n \"\"\"", "test": "import unittest\n\n\nclass VectorUtilTestSimilarity(unittest.TestCase):\n def test_similarity_1(self):\n vector_1 = np.array([1, 1])\n vector_2 = np.array([1, 0])\n similarity = VectorUtil.similarity(vector_1, vector_2)\n self.assertAlmostEqual(similarity, 0.7071067811865475)\n\n def test_similarity_2(self):\n vector_1 = np.array([1, 1])\n vector_2 = np.array([0, 0])\n similarity = VectorUtil.similarity(vector_1, vector_2)\n self.assertAlmostEqual(similarity, 0.0)\n\n def test_similarity_3(self):\n vector_1 = np.array([1, 1])\n vector_2 = np.array([1, 1])\n similarity = VectorUtil.similarity(vector_1, vector_2)\n self.assertAlmostEqual(similarity, 1.0)\n\n def test_similarity_4(self):\n vector_1 = np.array([1, 1, 0, 1, 0, 1, 0, 1])\n vector_2 = np.array([1, 0, 0, 1, 0, 1, 0, 1])\n similarity = VectorUtil.similarity(vector_1, vector_2)\n self.assertAlmostEqual(similarity, 0.8944271909999159)\n\n def test_similarity_5(self):\n vector_1 = np.array([1, 1, 1, 1, 1, 1, 1, 1])\n vector_2 = np.array([0, 0, 0, 0, 0, 0, 0, 0])\n similarity = VectorUtil.similarity(vector_1, vector_2)\n self.assertAlmostEqual(similarity, 0.0)\n\n\nclass VectorUtilTestCosineSimilarities(unittest.TestCase):\n def test_cosine_similarities_1(self):\n vector1 = np.array([1, 1])\n vectors_all = [np.array([1, 0]), np.array([1, 1])]\n similarities = VectorUtil.cosine_similarities(vector1, vectors_all)\n res = [0.7071067811865475, 1.0]\n for index, item in enumerate(similarities):\n self.assertAlmostEqual(item, res[index])\n\n def test_cosine_similarities_2(self):\n vector1 = np.array([1, 1, 0, 0, 1, 0, 1, 0])\n vectors_all = [np.array([1, 0, 0, 0, 1, 0, 1, 0]), np.array([1, 1, 0, 1, 1, 1, 1, 0])]\n similarities = VectorUtil.cosine_similarities(vector1, vectors_all)\n res = [0.8660254037844387, 0.8164965809277261]\n for index, item in enumerate(similarities):\n self.assertAlmostEqual(item, res[index])\n\n def test_cosine_similarities_3(self):\n vector1 = np.array([1, 1, 0, 0, 1, 0, 1, 0])\n vectors_all = [np.array([1, 0, 0, 0, 1, 0, 1, 0]), np.array([1, 1, 1, 1, 1, 1, 1, 0])]\n similarities = VectorUtil.cosine_similarities(vector1, vectors_all)\n res = [0.8660254037844387, 0.7559289460184544]\n for index, item in enumerate(similarities):\n self.assertAlmostEqual(item, res[index])\n\n def test_cosine_similarities_4(self):\n vector1 = np.array([1, 1, 0, 0, 1, 0, 1, 0])\n vectors_all = [np.array([1, 0, 0, 0, 1, 0, 1, 0]), np.array([1, 1, 1, 1, 1, 1, 1, 1])]\n similarities = VectorUtil.cosine_similarities(vector1, vectors_all)\n res = [0.8660254037844387, 0.7071067811865475]\n for index, item in enumerate(similarities):\n self.assertAlmostEqual(item, res[index])\n\n def test_cosine_similarities_5(self):\n vector1 = np.array([1, 1, 0, 0, 1, 0, 1, 0])\n vectors_all = [np.array([1, 0, 0, 0, 1, 0, 1, 0]), np.array([0, 1, 1, 1, 1, 1, 1, 1])]\n similarities = VectorUtil.cosine_similarities(vector1, vectors_all)\n res = [0.8660254037844387, 0.5669467095138409]\n for index, item in enumerate(similarities):\n self.assertAlmostEqual(item, res[index])\n\n\nclass VectorUtilTestNSimilarity(unittest.TestCase):\n def test_n_similarity_1(self):\n vector_list1 = [np.array([1, 0]), np.array([0, 1])]\n vector_list2 = [np.array([0, 0]), np.array([1, 1])]\n similarity = VectorUtil.n_similarity(vector_list1, vector_list2)\n self.assertAlmostEqual(similarity, 1.0)\n\n def test_n_similarity_2(self):\n vector_list1 = [np.array([1, 1]), np.array([0, 1])]\n vector_list2 = [np.array([0, 0]), np.array([1, 1])]\n similarity = VectorUtil.n_similarity(vector_list1, vector_list2)\n self.assertAlmostEqual(similarity, 0.9486832980505137)\n\n def test_n_similarity_3(self):\n vector_list1 = [np.array([1, 0]), np.array([1, 1])]\n vector_list2 = [np.array([0, 0]), np.array([1, 1])]\n similarity = VectorUtil.n_similarity(vector_list1, vector_list2)\n self.assertAlmostEqual(similarity, 0.9486832980505137)\n\n def test_n_similarity_4(self):\n vector_list1 = [np.array([1, 0]), np.array([0, 1])]\n vector_list2 = [np.array([1, 0]), np.array([1, 1])]\n similarity = VectorUtil.n_similarity(vector_list1, vector_list2)\n self.assertAlmostEqual(similarity, 0.9486832980505137)\n\n def test_n_similarity_5(self):\n vector_list1 = [np.array([1, 0]), np.array([0, 1])]\n vector_list2 = [np.array([0, 1]), np.array([1, 1])]\n similarity = VectorUtil.n_similarity(vector_list1, vector_list2)\n self.assertAlmostEqual(similarity, 0.9486832980505137)\n\n def test_n_similarity_6(self):\n try:\n vector_list1 = []\n vector_list2 = []\n similarity = VectorUtil.n_similarity(vector_list1, vector_list2)\n except:\n pass\n\n\nclass VectorUtilTestComputeIdfWeightDict(unittest.TestCase):\n def test_compute_idf_weight_dict_1(self):\n num_dict = {'key1': 0.1, 'key2': 0.5}\n res = VectorUtil.compute_idf_weight_dict(2, num_dict)\n self.assertAlmostEqual(res['key1'], 1.0033021088637848)\n self.assertAlmostEqual(res['key2'], 0.6931471805599453)\n\n def test_compute_idf_weight_dict_2(self):\n num_dict = {'key1': 0.2, 'key2': 0.5}\n res = VectorUtil.compute_idf_weight_dict(2, num_dict)\n self.assertAlmostEqual(res['key1'], 0.9162907318741551)\n self.assertAlmostEqual(res['key2'], 0.6931471805599453)\n\n def test_compute_idf_weight_dict_3(self):\n num_dict = {'key1': 0.3, 'key2': 0.5}\n res = VectorUtil.compute_idf_weight_dict(2, num_dict)\n self.assertAlmostEqual(res['key1'], 0.8362480242006185)\n self.assertAlmostEqual(res['key2'], 0.6931471805599453)\n\n def test_compute_idf_weight_dict_4(self):\n num_dict = {'key1': 0.4, 'key2': 0.5}\n res = VectorUtil.compute_idf_weight_dict(2, num_dict)\n self.assertAlmostEqual(res['key1'], 0.7621400520468967)\n self.assertAlmostEqual(res['key2'], 0.6931471805599453)\n\n def test_compute_idf_weight_dict_5(self):\n num_dict = {'key1': 0.5, 'key2': 0.5}\n res = VectorUtil.compute_idf_weight_dict(2, num_dict)\n self.assertAlmostEqual(res['key1'], 0.6931471805599453)\n self.assertAlmostEqual(res['key2'], 0.6931471805599453)\n\n\nclass VectorUtilTest(unittest.TestCase):\n def test_vectorutil(self):\n vector_1 = np.array([1, 1])\n vector_2 = np.array([1, 0])\n similarity = VectorUtil.similarity(vector_1, vector_2)\n self.assertAlmostEqual(similarity, 0.7071067811865475)\n\n vector1 = np.array([1, 1])\n vectors_all = [np.array([1, 0]), np.array([1, 1])]\n similarities = VectorUtil.cosine_similarities(vector1, vectors_all)\n res = [0.7071067811865475, 1.0]\n for index, item in enumerate(similarities):\n self.assertAlmostEqual(item, res[index])\n\n vector_list1 = [np.array([1, 0]), np.array([0, 1])]\n vector_list2 = [np.array([0, 0]), np.array([1, 1])]\n similarity = VectorUtil.n_similarity(vector_list1, vector_list2)\n self.assertAlmostEqual(similarity, 1.0)\n\n num_dict = {'key1': 0.1, 'key2': 0.5}\n res = VectorUtil.compute_idf_weight_dict(2, num_dict)\n self.assertAlmostEqual(res['key1'], 1.0033021088637848)\n self.assertAlmostEqual(res['key2'], 0.6931471805599453)", "solution_code": "import numpy as np\nfrom gensim import matutils\nfrom numpy import dot, array\n\n\nclass VectorUtil:\n @staticmethod\n def similarity(vector_1, vector_2):\n return dot(matutils.unitvec(vector_1), matutils.unitvec(vector_2))\n\n @staticmethod\n def cosine_similarities(vector_1, vectors_all):\n norm = np.linalg.norm(vector_1)\n all_norms = np.linalg.norm(vectors_all, axis=1)\n dot_products = dot(vectors_all, vector_1)\n similarities = dot_products / (norm * all_norms)\n return similarities\n\n @staticmethod\n def n_similarity(vector_list_1, vector_list_2):\n if not (len(vector_list_1) and len(vector_list_2)):\n raise ZeroDivisionError('At least one of the passed list is empty.')\n\n return dot(matutils.unitvec(array(vector_list_1).mean(axis=0)),\n matutils.unitvec(array(vector_list_2).mean(axis=0)))\n\n @staticmethod\n def compute_idf_weight_dict(total_num, number_dict):\n index_2_key_map = {}\n\n index = 0\n\n count_list = []\n for key, count in number_dict.items():\n index_2_key_map[index] = key\n count_list.append(count)\n index = index + 1\n\n a = np.array(count_list)\n ## smooth, in case the divide by zero error\n a = np.log((total_num + 1) / (a + 1))\n result = {}\n\n for index, w in enumerate(a):\n key = index_2_key_map[index]\n result[key] = w\n\n return result", "import_statement": [ "import numpy as np", "from gensim import matutils", "from numpy import dot, array" ], "class_description": " \"\"\"\n The class provides vector operations, including calculating similarity, cosine similarities, average similarity, and IDF weights.\n \"\"\"\n", "class_name": "VectorUtil", "test_classes": [ "VectorUtilTestSimilarity", "VectorUtilTestCosineSimilarities", "VectorUtilTestNSimilarity", "VectorUtilTestComputeIdfWeightDict", "VectorUtilTest" ], "class_constructor": "class VectorUtil: \n", "fields": [], "methods_info": [ { "method_name": "similarity", "method_description": "def similarity(vector_1, vector_2):\n \"\"\"\n Compute the cosine similarity between one vector and another vector.\n :param vector_1: numpy.ndarray, Vector from which similarities are to be computed, expected shape (dim,).\n :param vector_2: numpy.ndarray, Vector from which similarities are to be computed, expected shape (dim,).\n :return: numpy.ndarray, Contains cosine distance between `vector_1` and `vector_2`\n >>> vector_1 = np.array([1, 1])\n >>> vector_2 = np.array([1, 0])\n >>> VectorUtil.similarity(vector_1, vector_2)\n 0.7071067811865475\n \"\"\"", "test_class": "VectorUtilTestSimilarity", "test_code": "class VectorUtilTestSimilarity(unittest.TestCase):\n def test_similarity_1(self):\n vector_1 = np.array([1, 1])\n vector_2 = np.array([1, 0])\n similarity = VectorUtil.similarity(vector_1, vector_2)\n self.assertAlmostEqual(similarity, 0.7071067811865475)\n\n def test_similarity_2(self):\n vector_1 = np.array([1, 1])\n vector_2 = np.array([0, 0])\n similarity = VectorUtil.similarity(vector_1, vector_2)\n self.assertAlmostEqual(similarity, 0.0)\n\n def test_similarity_3(self):\n vector_1 = np.array([1, 1])\n vector_2 = np.array([1, 1])\n similarity = VectorUtil.similarity(vector_1, vector_2)\n self.assertAlmostEqual(similarity, 1.0)\n\n def test_similarity_4(self):\n vector_1 = np.array([1, 1, 0, 1, 0, 1, 0, 1])\n vector_2 = np.array([1, 0, 0, 1, 0, 1, 0, 1])\n similarity = VectorUtil.similarity(vector_1, vector_2)\n self.assertAlmostEqual(similarity, 0.8944271909999159)\n\n def test_similarity_5(self):\n vector_1 = np.array([1, 1, 1, 1, 1, 1, 1, 1])\n vector_2 = np.array([0, 0, 0, 0, 0, 0, 0, 0])\n similarity = VectorUtil.similarity(vector_1, vector_2)\n self.assertAlmostEqual(similarity, 0.0)", "solution_code": "def similarity(vector_1, vector_2):\n return dot(matutils.unitvec(vector_1), matutils.unitvec(vector_2))", "dependencies": { "Standalone": false, "lib_dependencies": [ "matutils" ], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "cosine_similarities", "method_description": "@staticmethod\n def cosine_similarities(vector_1, vectors_all):\n \"\"\"\n Compute cosine similarities between one vector and a set of other vectors.\n :param vector_1: numpy.ndarray, Vector from which similarities are to be computed, expected shape (dim,).\n :param vectors_all: list of numpy.ndarray, For each row in vectors_all, distance from vector_1 is computed, expected shape (num_vectors, dim).\n :return: numpy.ndarray, Contains cosine distance between `vector_1` and each row in `vectors_all`, shape (num_vectors,).\n >>> vector1 = np.array([1, 2, 3])\n >>> vectors_all = [np.array([4, 5, 6]), np.array([7, 8, 9])]\n >>> VectorUtil.cosine_similarities(vector1, vectors_all)\n [0.97463185 0.95941195]\n \"\"\"", "test_class": "VectorUtilTestCosineSimilarities", "test_code": "class VectorUtilTestCosineSimilarities(unittest.TestCase):\n def test_cosine_similarities_1(self):\n vector1 = np.array([1, 1])\n vectors_all = [np.array([1, 0]), np.array([1, 1])]\n similarities = VectorUtil.cosine_similarities(vector1, vectors_all)\n res = [0.7071067811865475, 1.0]\n for index, item in enumerate(similarities):\n self.assertAlmostEqual(item, res[index])\n\n def test_cosine_similarities_2(self):\n vector1 = np.array([1, 1, 0, 0, 1, 0, 1, 0])\n vectors_all = [np.array([1, 0, 0, 0, 1, 0, 1, 0]), np.array([1, 1, 0, 1, 1, 1, 1, 0])]\n similarities = VectorUtil.cosine_similarities(vector1, vectors_all)\n res = [0.8660254037844387, 0.8164965809277261]\n for index, item in enumerate(similarities):\n self.assertAlmostEqual(item, res[index])\n\n def test_cosine_similarities_3(self):\n vector1 = np.array([1, 1, 0, 0, 1, 0, 1, 0])\n vectors_all = [np.array([1, 0, 0, 0, 1, 0, 1, 0]), np.array([1, 1, 1, 1, 1, 1, 1, 0])]\n similarities = VectorUtil.cosine_similarities(vector1, vectors_all)\n res = [0.8660254037844387, 0.7559289460184544]\n for index, item in enumerate(similarities):\n self.assertAlmostEqual(item, res[index])\n\n def test_cosine_similarities_4(self):\n vector1 = np.array([1, 1, 0, 0, 1, 0, 1, 0])\n vectors_all = [np.array([1, 0, 0, 0, 1, 0, 1, 0]), np.array([1, 1, 1, 1, 1, 1, 1, 1])]\n similarities = VectorUtil.cosine_similarities(vector1, vectors_all)\n res = [0.8660254037844387, 0.7071067811865475]\n for index, item in enumerate(similarities):\n self.assertAlmostEqual(item, res[index])\n\n def test_cosine_similarities_5(self):\n vector1 = np.array([1, 1, 0, 0, 1, 0, 1, 0])\n vectors_all = [np.array([1, 0, 0, 0, 1, 0, 1, 0]), np.array([0, 1, 1, 1, 1, 1, 1, 1])]\n similarities = VectorUtil.cosine_similarities(vector1, vectors_all)\n res = [0.8660254037844387, 0.5669467095138409]\n for index, item in enumerate(similarities):\n self.assertAlmostEqual(item, res[index])", "solution_code": "@staticmethod\n def cosine_similarities(vector_1, vectors_all):\n norm = np.linalg.norm(vector_1)\n all_norms = np.linalg.norm(vectors_all, axis=1)\n dot_products = dot(vectors_all, vector_1)\n similarities = dot_products / (norm * all_norms)\n return similarities", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "n_similarity", "method_description": "@staticmethod\n def n_similarity(vector_list_1, vector_list_2):\n \"\"\"\n Compute cosine similarity between two sets of vectors.\n :param vector_list_1: list of numpy vector\n :param vector_list_2: list of numpy vector\n :return: numpy.ndarray, Similarities between vector_list_1 and vector_list_2.\n >>> vector_list1 = [np.array([1, 2, 3]), np.array([4, 5, 6])]\n >>> vector_list2 = [np.array([7, 8, 9]), np.array([10, 11, 12])]\n >>> VectorUtil.n_similarity(vector_list1, vector_list2)\n 0.9897287473881233\n \"\"\"", "test_class": "VectorUtilTestNSimilarity", "test_code": "class VectorUtilTestNSimilarity(unittest.TestCase):\n def test_n_similarity_1(self):\n vector_list1 = [np.array([1, 0]), np.array([0, 1])]\n vector_list2 = [np.array([0, 0]), np.array([1, 1])]\n similarity = VectorUtil.n_similarity(vector_list1, vector_list2)\n self.assertAlmostEqual(similarity, 1.0)\n\n def test_n_similarity_2(self):\n vector_list1 = [np.array([1, 1]), np.array([0, 1])]\n vector_list2 = [np.array([0, 0]), np.array([1, 1])]\n similarity = VectorUtil.n_similarity(vector_list1, vector_list2)\n self.assertAlmostEqual(similarity, 0.9486832980505137)\n\n def test_n_similarity_3(self):\n vector_list1 = [np.array([1, 0]), np.array([1, 1])]\n vector_list2 = [np.array([0, 0]), np.array([1, 1])]\n similarity = VectorUtil.n_similarity(vector_list1, vector_list2)\n self.assertAlmostEqual(similarity, 0.9486832980505137)\n\n def test_n_similarity_4(self):\n vector_list1 = [np.array([1, 0]), np.array([0, 1])]\n vector_list2 = [np.array([1, 0]), np.array([1, 1])]\n similarity = VectorUtil.n_similarity(vector_list1, vector_list2)\n self.assertAlmostEqual(similarity, 0.9486832980505137)\n\n def test_n_similarity_5(self):\n vector_list1 = [np.array([1, 0]), np.array([0, 1])]\n vector_list2 = [np.array([0, 1]), np.array([1, 1])]\n similarity = VectorUtil.n_similarity(vector_list1, vector_list2)\n self.assertAlmostEqual(similarity, 0.9486832980505137)\n\n def test_n_similarity_6(self):\n try:\n vector_list1 = []\n vector_list2 = []\n similarity = VectorUtil.n_similarity(vector_list1, vector_list2)\n except:\n pass", "solution_code": "@staticmethod\n def n_similarity(vector_list_1, vector_list_2):\n if not (len(vector_list_1) and len(vector_list_2)):\n raise ZeroDivisionError('At least one of the passed list is empty.')\n\n return dot(matutils.unitvec(array(vector_list_1).mean(axis=0)),\n matutils.unitvec(array(vector_list_2).mean(axis=0)))", "dependencies": { "Standalone": false, "lib_dependencies": [ "matutils" ], "field_dependencies": [], "method_dependencies": [] } }, { "method_name": "compute_idf_weight_dict", "method_description": "@staticmethod\n def compute_idf_weight_dict(total_num, number_dict):\n \"\"\"\n Calculate log(total_num+1/count+1) for each count in number_dict\n :param total_num: int\n :param number_dict: dict\n :return: dict\n >>> num_dict = {'key1':0.1, 'key2':0.5}\n >>> VectorUtil.compute_idf_weight_dict(2, num_dict)\n {'key1': 1.0033021088637848, 'key2': 0.6931471805599453}\n \"\"\"", "test_class": "VectorUtilTestComputeIdfWeightDict", "test_code": "class VectorUtilTestComputeIdfWeightDict(unittest.TestCase):\n def test_compute_idf_weight_dict_1(self):\n num_dict = {'key1': 0.1, 'key2': 0.5}\n res = VectorUtil.compute_idf_weight_dict(2, num_dict)\n self.assertAlmostEqual(res['key1'], 1.0033021088637848)\n self.assertAlmostEqual(res['key2'], 0.6931471805599453)\n\n def test_compute_idf_weight_dict_2(self):\n num_dict = {'key1': 0.2, 'key2': 0.5}\n res = VectorUtil.compute_idf_weight_dict(2, num_dict)\n self.assertAlmostEqual(res['key1'], 0.9162907318741551)\n self.assertAlmostEqual(res['key2'], 0.6931471805599453)\n\n def test_compute_idf_weight_dict_3(self):\n num_dict = {'key1': 0.3, 'key2': 0.5}\n res = VectorUtil.compute_idf_weight_dict(2, num_dict)\n self.assertAlmostEqual(res['key1'], 0.8362480242006185)\n self.assertAlmostEqual(res['key2'], 0.6931471805599453)\n\n def test_compute_idf_weight_dict_4(self):\n num_dict = {'key1': 0.4, 'key2': 0.5}\n res = VectorUtil.compute_idf_weight_dict(2, num_dict)\n self.assertAlmostEqual(res['key1'], 0.7621400520468967)\n self.assertAlmostEqual(res['key2'], 0.6931471805599453)\n\n def test_compute_idf_weight_dict_5(self):\n num_dict = {'key1': 0.5, 'key2': 0.5}\n res = VectorUtil.compute_idf_weight_dict(2, num_dict)\n self.assertAlmostEqual(res['key1'], 0.6931471805599453)\n self.assertAlmostEqual(res['key2'], 0.6931471805599453)", "solution_code": "@staticmethod\n def compute_idf_weight_dict(total_num, number_dict):\n index_2_key_map = {}\n\n index = 0\n\n count_list = []\n for key, count in number_dict.items():\n index_2_key_map[index] = key\n count_list.append(count)\n index = index + 1\n\n a = np.array(count_list)\n ## smooth, in case the divide by zero error\n a = np.log((total_num + 1) / (a + 1))\n result = {}\n\n for index, w in enumerate(a):\n key = index_2_key_map[index]\n result[key] = w\n\n return result", "dependencies": { "Standalone": true, "lib_dependencies": [], "field_dependencies": [], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_94", "skeleton": "\nclass VendingMachine:\n \"\"\"\n This is a class to simulate a vending machine, including adding products, inserting coins, purchasing products, viewing balance, replenishing product inventory, and displaying product information.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initializes the vending machine's inventory and balance.\n \"\"\"\n self.inventory = {}\n self.balance = 0\n\n def add_item(self, item_name, price, quantity):\n \"\"\"\n Adds a product to the vending machine's inventory.\n :param item_name: The name of the product to be added, str.\n :param price: The price of the product to be added, float.\n :param quantity: The quantity of the product to be added, int.\n :return: None\n >>> vendingMachine = VendingMachine()\n >>> vendingMachine.add_item('Coke', 1.25, 10)\n >>> vendingMachine.inventory\n {'Coke': {'price': 1.25, 'quantity': 10}}\n\n \"\"\"\n\n def insert_coin(self, amount):\n \"\"\"\n Inserts coins into the vending machine.\n :param amount: The amount of coins to be inserted, float.\n :return: The balance of the vending machine after the coins are inserted, float.\n >>> vendingMachine = VendingMachine()\n >>> vendingMachine.insert_coin(1.25)\n 1.25\n\n \"\"\"\n\n def purchase_item(self, item_name):\n \"\"\"\n Purchases a product from the vending machine and returns the balance after the purchase and display purchase unsuccessful if the product is out of stock.\n :param item_name: The name of the product to be purchased, str.\n :return: If successful, returns the balance of the vending machine after the product is purchased, float,otherwise,returns False.\n >>> vendingMachine = VendingMachine()\n >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}}\n >>> vendingMachine.balance = 1.25\n >>> vendingMachine.purchase_item('Coke')\n 0.0\n >>> vendingMachine.purchase_item('Pizza')\n False\n\n \"\"\"\n\n def restock_item(self, item_name, quantity):\n \"\"\"\n Replenishes the inventory of a product already in the vending machine.\n :param item_name: The name of the product to be replenished, str.\n :param quantity: The quantity of the product to be replenished, int.\n :return: If the product is already in the vending machine, returns True, otherwise, returns False.\n >>> vendingMachine = VendingMachine()\n >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}}\n >>> vendingMachine.restock_item('Coke', 10)\n True\n >>> vendingMachine.restock_item('Pizza', 10)\n False\n\n \"\"\"\n\n def display_items(self):\n \"\"\"\n Displays the products in the vending machine.\n :return: If the vending machine is empty, returns False, otherwise, returns a list of the products in the vending machine, list.\n >>> vendingMachine = VendingMachine()\n >>> vendingMachine.display_items()\n False\n >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10} }\n >>> vendingMachine.display_items()\n 'Coke - $1.25 [10]'\n\n \"\"\"", "test": "import unittest\nclass VendingMachineTestAddItem(unittest.TestCase):\n def test_add_item(self):\n vendingMachine = VendingMachine()\n vendingMachine.add_item('Coke', 1.25, 10)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}})\n\n def test_add_item_2(self):\n vendingMachine = VendingMachine()\n vendingMachine.add_item('Coke', 1.25, 10)\n vendingMachine.add_item('Coke', 1.25, 10)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 20}})\n\n def test_add_item_3(self):\n vendingMachine = VendingMachine()\n vendingMachine.add_item('Coke', 1.25, 10)\n vendingMachine.add_item('Pizza', 1.25, 10)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 10}})\n\n def test_add_item_4(self):\n vendingMachine = VendingMachine()\n vendingMachine.add_item('Coke', 1.25, 10)\n vendingMachine.add_item('Pizza', 1.25, 10)\n vendingMachine.add_item('Pizza', 1.25, 10)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 20}})\n\n def test_add_item_5(self):\n vendingMachine = VendingMachine()\n vendingMachine.add_item('Coke', 1.25, 10)\n vendingMachine.add_item('Pizza', 1.25, 10)\n vendingMachine.add_item('Pizza', 1.25, 10)\n vendingMachine.add_item('Coke', 1.25, 10)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 20}, 'Pizza': {'price': 1.25, 'quantity': 20}})\n\nclass VendingMachineTestInsertCoin(unittest.TestCase):\n def test_insert_coin(self):\n vendingMachine = VendingMachine()\n self.assertEqual(vendingMachine.insert_coin(1.25), 1.25)\n\n def test_insert_coin_2(self):\n vendingMachine = VendingMachine()\n self.assertEqual(vendingMachine.insert_coin(2.5), 2.5)\n\n def test_insert_coin_3(self):\n vendingMachine = VendingMachine()\n vendingMachine.insert_coin(1.25)\n vendingMachine.insert_coin(1.25)\n self.assertEqual(vendingMachine.balance, 2.50)\n\n def test_insert_coin_4(self):\n vendingMachine = VendingMachine()\n vendingMachine.balance = 1.25\n vendingMachine.insert_coin(1.25)\n vendingMachine.insert_coin(1.25)\n vendingMachine.insert_coin(1.25)\n self.assertEqual(vendingMachine.balance, 5.0)\n\n def test_insert_coin_5(self):\n vendingMachine = VendingMachine()\n vendingMachine.balance = 1.25\n vendingMachine.insert_coin(1.25)\n vendingMachine.insert_coin(1.25)\n vendingMachine.insert_coin(1.25)\n vendingMachine.insert_coin(1.25)\n self.assertEqual(vendingMachine.balance, 6.25)\n\nclass VendingMachineTestPurchaseItem(unittest.TestCase):\n def test_purchase_item(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}}\n vendingMachine.balance = 1.25\n self.assertEqual(vendingMachine.purchase_item('Coke'), 0.0)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 9}})\n\n def test_purchase_item_2(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}}\n vendingMachine.balance = 1.25\n self.assertEqual(vendingMachine.purchase_item('Pizza'), False)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}})\n\n def test_purchase_item_3(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}}\n vendingMachine.balance = 0\n self.assertEqual(vendingMachine.purchase_item('Coke'), False)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}})\n\n def test_purchase_item_4(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 0}}\n vendingMachine.balance = 1.25\n self.assertEqual(vendingMachine.purchase_item('Coke'), False)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 0}})\n\n def test_purchase_item_5(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 10}}\n vendingMachine.balance = 1.25\n self.assertEqual(vendingMachine.purchase_item('Pizza'), 0.0)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 9}})\n\nclass VendingMachineTestRestockItem(unittest.TestCase):\n def test_restock_item(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}}\n self.assertEqual(vendingMachine.restock_item('Coke', 10), True)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 20}})\n\n def test_restock_item_2(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}}\n self.assertEqual(vendingMachine.restock_item('Pizza', 10), False)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}})\n\n def test_restock_item_3(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 0}}\n self.assertEqual(vendingMachine.restock_item('Coke', 10), True)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}})\n\n def test_restock_item_4(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 10}}\n self.assertEqual(vendingMachine.restock_item('Pizza', 10), True)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 20}})\n\n def test_restock_item_5(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 10}}\n self.assertEqual(vendingMachine.restock_item('Pizza', 0), True)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 10}})\nclass VendingMachineTestDisplayItems(unittest.TestCase):\n def test_display_items(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}}\n self.assertEqual(vendingMachine.display_items(), 'Coke - $1.25 [10]')\n\n def test_display_items_2(self):\n vendingMachine = VendingMachine()\n self.assertEqual(vendingMachine.display_items(), False)\n\n def test_display_items_3(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 10}}\n self.assertEqual(vendingMachine.display_items(),\"Coke - $1.25 [10]\\nPizza - $1.25 [10]\")\n\n def test_display_items_4(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 0}}\n self.assertEqual(vendingMachine.display_items(), 'Coke - $1.25 [0]')\n\n def test_display_items_5(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 0}, 'Pizza': {'price': 1.25, 'quantity': 10}}\n self.assertEqual(vendingMachine.display_items(), 'Coke - $1.25 [0]\\nPizza - $1.25 [10]')\n\nclass VendingMachineTestMain(unittest.TestCase):\n def test_main(self):\n vendingMachine = VendingMachine()\n self.assertEqual(vendingMachine.display_items(), False)\n vendingMachine.add_item('Coke', 1.25, 10)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}})\n self.assertEqual(vendingMachine.insert_coin(1.25), 1.25)\n self.assertEqual(vendingMachine.purchase_item('Coke'), 0.0)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 9}})\n self.assertEqual(vendingMachine.purchase_item('Pizza'), False)\n self.assertEqual(vendingMachine.restock_item('Coke', 10), True)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 19}})\n self.assertEqual(vendingMachine.restock_item('Pizza', 10), False)\n self.assertEqual(vendingMachine.display_items(), 'Coke - $1.25 [19]')\n\n def test_main_2(self):\n vendingMachine = VendingMachine()\n self.assertEqual(vendingMachine.purchase_item('Coke'), False)\n vendingMachine.add_item('Coke', 1.25, 10)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}})\n self.assertEqual(vendingMachine.restock_item('Pizza', 10), False)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}})\n self.assertEqual(vendingMachine.insert_coin(1.25), 1.25)\n self.assertEqual(vendingMachine.purchase_item('Coke'), 0.0)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 9}})\n self.assertEqual(vendingMachine.display_items(), 'Coke - $1.25 [9]')", "solution_code": "class VendingMachine:\n def __init__(self):\n self.inventory = {}\n self.balance = 0\n\n def add_item(self, item_name, price, quantity):\n if not self.restock_item(item_name, quantity):\n self.inventory[item_name] = {'price': price, 'quantity': quantity}\n\n def insert_coin(self, amount):\n self.balance += amount\n return self.balance\n\n def purchase_item(self, item_name):\n if item_name in self.inventory:\n item = self.inventory[item_name]\n if item['quantity'] > 0 and self.balance >= item['price']:\n self.balance -= item['price']\n item['quantity'] -= 1\n return self.balance\n else:\n return False\n else:\n return False\n\n def restock_item(self, item_name, quantity):\n if item_name in self.inventory:\n self.inventory[item_name]['quantity'] += quantity\n return True\n else:\n return False\n\n def display_items(self):\n if not self.inventory:\n return False\n else:\n items = []\n for item_name, item_info in self.inventory.items():\n items.append(f\"{item_name} - ${item_info['price']} [{item_info['quantity']}]\")\n return \"\\n\".join(items)", "import_statement": [], "class_description": " \"\"\"\n This is a class to simulate a vending machine, including adding products, inserting coins, purchasing products, viewing balance, replenishing product inventory, and displaying product information.\n \"\"\"\n", "class_name": "VendingMachine", "test_classes": [ "VendingMachineTestAddItem", "VendingMachineTestInsertCoin", "VendingMachineTestPurchaseItem", "VendingMachineTestRestockItem", "VendingMachineTestDisplayItems", "VendingMachineTestMain" ], "class_constructor": "class VendingMachine: \n def __init__(self):\n \"\"\"\n Initializes the vending machine's inventory and balance.\n \"\"\"\n self.inventory = {}\n self.balance = 0\n\n", "fields": [ "self.balance", "self.inventory" ], "methods_info": [ { "method_name": "add_item", "method_description": "def add_item(self, item_name, price, quantity):\n \"\"\"\n Adds a product to the vending machine's inventory.\n :param item_name: The name of the product to be added, str.\n :param price: The price of the product to be added, float.\n :param quantity: The quantity of the product to be added, int.\n :return: None\n >>> vendingMachine = VendingMachine()\n >>> vendingMachine.add_item('Coke', 1.25, 10)\n >>> vendingMachine.inventory\n {'Coke': {'price': 1.25, 'quantity': 10}}\n\n \"\"\"", "test_class": "VendingMachineTestAddItem", "test_code": "class VendingMachineTestAddItem(unittest.TestCase):\n def test_add_item(self):\n vendingMachine = VendingMachine()\n vendingMachine.add_item('Coke', 1.25, 10)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}})\n\n def test_add_item_2(self):\n vendingMachine = VendingMachine()\n vendingMachine.add_item('Coke', 1.25, 10)\n vendingMachine.add_item('Coke', 1.25, 10)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 20}})\n\n def test_add_item_3(self):\n vendingMachine = VendingMachine()\n vendingMachine.add_item('Coke', 1.25, 10)\n vendingMachine.add_item('Pizza', 1.25, 10)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 10}})\n\n def test_add_item_4(self):\n vendingMachine = VendingMachine()\n vendingMachine.add_item('Coke', 1.25, 10)\n vendingMachine.add_item('Pizza', 1.25, 10)\n vendingMachine.add_item('Pizza', 1.25, 10)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 20}})\n\n def test_add_item_5(self):\n vendingMachine = VendingMachine()\n vendingMachine.add_item('Coke', 1.25, 10)\n vendingMachine.add_item('Pizza', 1.25, 10)\n vendingMachine.add_item('Pizza', 1.25, 10)\n vendingMachine.add_item('Coke', 1.25, 10)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 20}, 'Pizza': {'price': 1.25, 'quantity': 20}})", "solution_code": "def add_item(self, item_name, price, quantity):\n if not self.restock_item(item_name, quantity):\n self.inventory[item_name] = {'price': price, 'quantity': quantity}", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.inventory" ], "method_dependencies": [ "restock_item" ] } }, { "method_name": "insert_coin", "method_description": "def insert_coin(self, amount):\n \"\"\"\n Inserts coins into the vending machine.\n :param amount: The amount of coins to be inserted, float.\n :return: The balance of the vending machine after the coins are inserted, float.\n >>> vendingMachine = VendingMachine()\n >>> vendingMachine.insert_coin(1.25)\n 1.25\n\n \"\"\"", "test_class": "VendingMachineTestInsertCoin", "test_code": "class VendingMachineTestInsertCoin(unittest.TestCase):\n def test_insert_coin(self):\n vendingMachine = VendingMachine()\n self.assertEqual(vendingMachine.insert_coin(1.25), 1.25)\n\n def test_insert_coin_2(self):\n vendingMachine = VendingMachine()\n self.assertEqual(vendingMachine.insert_coin(2.5), 2.5)\n\n def test_insert_coin_3(self):\n vendingMachine = VendingMachine()\n vendingMachine.insert_coin(1.25)\n vendingMachine.insert_coin(1.25)\n self.assertEqual(vendingMachine.balance, 2.50)\n\n def test_insert_coin_4(self):\n vendingMachine = VendingMachine()\n vendingMachine.balance = 1.25\n vendingMachine.insert_coin(1.25)\n vendingMachine.insert_coin(1.25)\n vendingMachine.insert_coin(1.25)\n self.assertEqual(vendingMachine.balance, 5.0)\n\n def test_insert_coin_5(self):\n vendingMachine = VendingMachine()\n vendingMachine.balance = 1.25\n vendingMachine.insert_coin(1.25)\n vendingMachine.insert_coin(1.25)\n vendingMachine.insert_coin(1.25)\n vendingMachine.insert_coin(1.25)\n self.assertEqual(vendingMachine.balance, 6.25)", "solution_code": "def insert_coin(self, amount):\n self.balance += amount\n return self.balance", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.balance" ], "method_dependencies": [] } }, { "method_name": "purchase_item", "method_description": "def purchase_item(self, item_name):\n \"\"\"\n Purchases a product from the vending machine and returns the balance after the purchase and display purchase unsuccessful if the product is out of stock.\n :param item_name: The name of the product to be purchased, str.\n :return: If successful, returns the balance of the vending machine after the product is purchased, float,otherwise,returns False.\n >>> vendingMachine = VendingMachine()\n >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}}\n >>> vendingMachine.balance = 1.25\n >>> vendingMachine.purchase_item('Coke')\n 0.0\n >>> vendingMachine.purchase_item('Pizza')\n False\n\n \"\"\"", "test_class": "VendingMachineTestPurchaseItem", "test_code": "class VendingMachineTestPurchaseItem(unittest.TestCase):\n def test_purchase_item(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}}\n vendingMachine.balance = 1.25\n self.assertEqual(vendingMachine.purchase_item('Coke'), 0.0)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 9}})\n\n def test_purchase_item_2(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}}\n vendingMachine.balance = 1.25\n self.assertEqual(vendingMachine.purchase_item('Pizza'), False)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}})\n\n def test_purchase_item_3(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}}\n vendingMachine.balance = 0\n self.assertEqual(vendingMachine.purchase_item('Coke'), False)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}})\n\n def test_purchase_item_4(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 0}}\n vendingMachine.balance = 1.25\n self.assertEqual(vendingMachine.purchase_item('Coke'), False)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 0}})\n\n def test_purchase_item_5(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 10}}\n vendingMachine.balance = 1.25\n self.assertEqual(vendingMachine.purchase_item('Pizza'), 0.0)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 9}})", "solution_code": "def purchase_item(self, item_name):\n if item_name in self.inventory:\n item = self.inventory[item_name]\n if item['quantity'] > 0 and self.balance >= item['price']:\n self.balance -= item['price']\n item['quantity'] -= 1\n return self.balance\n else:\n return False\n else:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.balance", "self.inventory" ], "method_dependencies": [] } }, { "method_name": "restock_item", "method_description": "def restock_item(self, item_name, quantity):\n \"\"\"\n Replenishes the inventory of a product already in the vending machine.\n :param item_name: The name of the product to be replenished, str.\n :param quantity: The quantity of the product to be replenished, int.\n :return: If the product is already in the vending machine, returns True, otherwise, returns False.\n >>> vendingMachine = VendingMachine()\n >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}}\n >>> vendingMachine.restock_item('Coke', 10)\n True\n >>> vendingMachine.restock_item('Pizza', 10)\n False\n\n \"\"\"", "test_class": "VendingMachineTestRestockItem", "test_code": "class VendingMachineTestRestockItem(unittest.TestCase):\n def test_restock_item(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}}\n self.assertEqual(vendingMachine.restock_item('Coke', 10), True)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 20}})\n\n def test_restock_item_2(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}}\n self.assertEqual(vendingMachine.restock_item('Pizza', 10), False)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}})\n\n def test_restock_item_3(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 0}}\n self.assertEqual(vendingMachine.restock_item('Coke', 10), True)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}})\n\n def test_restock_item_4(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 10}}\n self.assertEqual(vendingMachine.restock_item('Pizza', 10), True)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 20}})\n\n def test_restock_item_5(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 10}}\n self.assertEqual(vendingMachine.restock_item('Pizza', 0), True)\n self.assertEqual(vendingMachine.inventory, {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 10}})", "solution_code": "def restock_item(self, item_name, quantity):\n if item_name in self.inventory:\n self.inventory[item_name]['quantity'] += quantity\n return True\n else:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.inventory" ], "method_dependencies": [] } }, { "method_name": "display_items", "method_description": "def display_items(self):\n \"\"\"\n Displays the products in the vending machine.\n :return: If the vending machine is empty, returns False, otherwise, returns a list of the products in the vending machine, list.\n >>> vendingMachine = VendingMachine()\n >>> vendingMachine.display_items()\n False\n >>> vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10} }\n >>> vendingMachine.display_items()\n 'Coke - $1.25 [10]'\n\n \"\"\"", "test_class": "VendingMachineTestDisplayItems", "test_code": "class VendingMachineTestDisplayItems(unittest.TestCase):\n def test_display_items(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}}\n self.assertEqual(vendingMachine.display_items(), 'Coke - $1.25 [10]')\n\n def test_display_items_2(self):\n vendingMachine = VendingMachine()\n self.assertEqual(vendingMachine.display_items(), False)\n\n def test_display_items_3(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 10}, 'Pizza': {'price': 1.25, 'quantity': 10}}\n self.assertEqual(vendingMachine.display_items(),\"Coke - $1.25 [10]\\nPizza - $1.25 [10]\")\n\n def test_display_items_4(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 0}}\n self.assertEqual(vendingMachine.display_items(), 'Coke - $1.25 [0]')\n\n def test_display_items_5(self):\n vendingMachine = VendingMachine()\n vendingMachine.inventory = {'Coke': {'price': 1.25, 'quantity': 0}, 'Pizza': {'price': 1.25, 'quantity': 10}}\n self.assertEqual(vendingMachine.display_items(), 'Coke - $1.25 [0]\\nPizza - $1.25 [10]')", "solution_code": "def display_items(self):\n if not self.inventory:\n return False\n else:\n items = []\n for item_name, item_info in self.inventory.items():\n items.append(f\"{item_name} - ${item_info['price']} [{item_info['quantity']}]\")\n return \"\\n\".join(items)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.inventory" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_95", "skeleton": "\nclass Warehouse:\n \"\"\"\n The class manages inventory and orders, including adding products, updating product quantities, retrieving product quantities, creating orders, changing order statuses, and tracking orders.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialize two fields.\n self.inventory is a dict that stores the products.\n self.inventory = {Product ID: Product}\n self.orders is a dict that stores the products in a order.\n self.orders = {Order ID: Order}\n \"\"\"\n self.inventory = {} # Product ID: Product\n self.orders = {} # Order ID: Order\n\n def add_product(self, product_id, name, quantity):\n \"\"\"\n Add product to inventory and plus the quantity if it has existed in inventory.\n Or just add new product to dict otherwise.\n :param product_id: int\n :param name: str, product name\n :param quantity: int, product quantity\n >>> warehouse.add_product(1, \"product1\", 3)\n >>> warehouse.inventory\n {1: {'name': 'product1', 'quantity': 3}}\n \"\"\"\n\n def update_product_quantity(self, product_id, quantity):\n \"\"\"\n According to product_id, add the quantity to the corresponding product in inventory.\n >>> warehouse.add_product(1, \"product1\", 3)\n >>> warehouse.update_product_quantity(1, -1)\n >>> warehouse.inventory\n {1: {'name': 'product1', 'quantity': 2}}\n \"\"\"\n\n def get_product_quantity(self, product_id):\n \"\"\"\n Get the quantity of specific product by product_id.\n :param product_id, int\n :return: if the product_id is in inventory then return the corresponding quantity,\n or False otherwise.\n >>> warehouse.add_product(1, \"product1\", 3)\n >>> warehouse.get_product_quantity(1)\n 3\n >>> warehouse.get_product_quantity(2)\n False\n \"\"\"\n\n def create_order(self, order_id, product_id, quantity):\n \"\"\"\n Create a order which includes the infomation of product, like id and quantity.\n And put the new order into self.orders.\n The default value of status is 'Shipped'.\n :param order_id: int\n :param product_id: int\n :param quantity: the quantity of product that be selected.\n :return False: only if product_id is not in inventory or the quantity is not adequate\n >>> warehouse.add_product(1, \"product1\", 3)\n >>> warehouse.create_order(1, 1, 2)\n >>> warehouse.orders\n {1: {'product_id': 1, 'quantity': 2, 'status': 'Shipped'}}\n >>> warehouse.create_order(1, 2, 2)\n False\n \"\"\"\n\n def change_order_status(self, order_id, status):\n \"\"\"\n Change the status of order if the input order_id is in self.orders.\n :param order_id: int\n :param status: str, the state that is going to change to\n :return False: only if the order_id is not in self.orders\n >>> warehouse.add_product(1, \"product1\", 3)\n >>> warehouse.create_order(1, 1, 2)\n >>> warehouse.change_order_status(1, \"done\")\n >>> warehouse.orders\n {1: {'product_id': 1, 'quantity': 2, 'status': 'done'}}\n \"\"\"\n\n def track_order(self, order_id):\n \"\"\"\n Get the status of specific order.\n :param order_id: int\n :return False: only if the order_id is not in self.orders.\n >>> warehouse.add_product(1, \"product1\", 3)\n >>> warehouse.create_order(1, 1, 2)\n >>> warehouse.track_order(1)\n 'Shipped'\n \"\"\"", "test": "import unittest\n\n\nclass WarehouseTestAddProduct(unittest.TestCase):\n def test_add_product_1(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n self.assertEqual(warehouse.inventory, {1: {'name': 'product 1', 'quantity': 10}})\n\n def test_add_product_2(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n warehouse.add_product(2, 'product 2', 5)\n self.assertEqual(warehouse.inventory,\n {1: {'name': 'product 1', 'quantity': 10}, 2: {'name': 'product 2', 'quantity': 5}})\n\n def test_add_product_3(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 3', 10)\n self.assertEqual(warehouse.inventory, {1: {'name': 'product 3', 'quantity': 10}})\n\n def test_add_product_4(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 4', 10)\n self.assertEqual(warehouse.inventory, {1: {'name': 'product 4', 'quantity': 10}})\n\n def test_add_product_5(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 5', 10)\n self.assertEqual(warehouse.inventory, {1: {'name': 'product 5', 'quantity': 10}})\n\n def test_add_product_6(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 5', 10)\n warehouse.add_product(1, 'product 5', 10)\n self.assertEqual(warehouse.inventory, {1: {'name': 'product 5', 'quantity': 20}})\n\n\nclass WarehouseTestUpdateProductQuantity(unittest.TestCase):\n def test_update_product_quantity_1(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n warehouse.update_product_quantity(1, 5)\n self.assertEqual(warehouse.inventory, {1: {'name': 'product 1', 'quantity': 15}})\n\n # quantity is negative\n def test_update_product_quantity_2(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n warehouse.update_product_quantity(1, -5)\n self.assertEqual(warehouse.inventory, {1: {'name': 'product 1', 'quantity': 5}})\n\n def test_update_product_quantity_3(self):\n warehouse = Warehouse()\n warehouse.update_product_quantity(1, -5)\n self.assertEqual(warehouse.inventory, {})\n\n def test_update_product_quantity_4(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n warehouse.update_product_quantity(1, 1)\n self.assertEqual(warehouse.inventory, {1: {'name': 'product 1', 'quantity': 11}})\n\n def test_update_product_quantity_5(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n warehouse.update_product_quantity(1, -9)\n self.assertEqual(warehouse.inventory, {1: {'name': 'product 1', 'quantity': 1}})\n\n\nclass WarehouseTestGetProductQuantity(unittest.TestCase):\n def test_get_product_quantity_1(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n self.assertEqual(warehouse.get_product_quantity(1), 10)\n\n def test_get_product_quantity_2(self):\n warehouse = Warehouse()\n self.assertEqual(warehouse.get_product_quantity(1), False)\n\n def test_get_product_quantity_3(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 5)\n self.assertEqual(warehouse.get_product_quantity(1), 5)\n\n def test_get_product_quantity_4(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 100)\n self.assertEqual(warehouse.get_product_quantity(1), 100)\n\n def test_get_product_quantity_5(self):\n warehouse = Warehouse()\n warehouse.add_product(5, 'product 1', 10)\n self.assertEqual(warehouse.get_product_quantity(5), 10)\n\n\nclass WarehouseTestCreateOrder(unittest.TestCase):\n def test_create_order_1(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n warehouse.create_order(1, 1, 5)\n self.assertEqual(warehouse.orders, {1: {'product_id': 1, 'quantity': 5, 'status': 'Shipped'}})\n\n def test_create_order_2(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n result = warehouse.create_order(1, 1, 15)\n self.assertFalse(result)\n\n def test_create_order_3(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 1)\n warehouse.create_order(1, 1, 1)\n self.assertEqual(warehouse.orders, {1: {'product_id': 1, 'quantity': 1, 'status': 'Shipped'}})\n\n def test_create_order_4(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 4', 5)\n warehouse.create_order(1, 1, 5)\n self.assertEqual(warehouse.orders, {1: {'product_id': 1, 'quantity': 5, 'status': 'Shipped'}})\n\n def test_create_order_5(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 5', 100)\n warehouse.create_order(1, 1, 50)\n self.assertEqual(warehouse.orders, {1: {'product_id': 1, 'quantity': 50, 'status': 'Shipped'}})\n\n\nclass WarehouseTestChangeOrderStatus(unittest.TestCase):\n def test_change_order_status_1(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n warehouse.create_order(1, 1, 5)\n warehouse.change_order_status(1, 'Delivered')\n self.assertEqual(warehouse.orders, {1: {'product_id': 1, 'quantity': 5, 'status': 'Delivered'}})\n\n def test_change_order_status_2(self):\n warehouse = Warehouse()\n result = warehouse.change_order_status(1, 'Delivered')\n self.assertFalse(result)\n\n def test_change_order_status_3(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 3', 5)\n warehouse.create_order(1, 1, 5)\n warehouse.change_order_status(1, 'Delivered')\n self.assertEqual(warehouse.orders, {1: {'product_id': 1, 'quantity': 5, 'status': 'Delivered'}})\n\n def test_change_order_status_4(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 4', 100)\n warehouse.create_order(1, 1, 50)\n warehouse.change_order_status(1, 'Delivered')\n self.assertEqual(warehouse.orders, {1: {'product_id': 1, 'quantity': 50, 'status': 'Delivered'}})\n\n def test_change_order_status_5(self):\n warehouse = Warehouse()\n result = warehouse.change_order_status(2, 'Delivered')\n self.assertFalse(result)\n\n\nclass WarehouseTestTrackOrder(unittest.TestCase):\n def test_track_order_1(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n warehouse.create_order(1, 1, 5)\n self.assertEqual(warehouse.track_order(1), 'Shipped')\n\n def test_track_order_2(self):\n warehouse = Warehouse()\n result = warehouse.track_order(1)\n self.assertFalse(result)\n\n def test_track_order_3(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 3', 10)\n warehouse.create_order(1, 1, 1)\n self.assertEqual(warehouse.track_order(1), 'Shipped')\n\n def test_track_order_4(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 4', 100)\n warehouse.create_order(1, 1, 50)\n self.assertEqual(warehouse.track_order(1), 'Shipped')\n\n def test_track_order_5(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 5', 100)\n warehouse.create_order(1, 1, 10)\n self.assertEqual(warehouse.track_order(1), 'Shipped')\n\n\nclass WarehouseTestMain(unittest.TestCase):\n def test_main(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n self.assertEqual({1: {'name': 'product 1', 'quantity': 10}}, warehouse.inventory)\n\n warehouse.update_product_quantity(1, -5)\n self.assertEqual({1: {'name': 'product 1', 'quantity': 5}}, warehouse.inventory)\n\n self.assertEqual(warehouse.get_product_quantity(1), 5)\n\n warehouse.create_order(1, 1, 3)\n self.assertEqual({1: {'product_id': 1, 'quantity': 3, 'status': 'Shipped'}}, warehouse.orders)\n\n warehouse.change_order_status(1, 'Delivered')\n self.assertEqual({1: {'product_id': 1, 'quantity': 3, 'status': 'Delivered'}}, warehouse.orders)\n\n self.assertEqual('Delivered', warehouse.track_order(1))", "solution_code": "class Warehouse:\n def __init__(self):\n self.inventory = {} # Product ID: Product\n self.orders = {} # Order ID: Order\n\n def add_product(self, product_id, name, quantity):\n if product_id not in self.inventory:\n self.inventory[product_id] = {'name': name, 'quantity': quantity}\n else:\n self.inventory[product_id]['quantity'] += quantity\n\n def update_product_quantity(self, product_id, quantity):\n if product_id in self.inventory:\n self.inventory[product_id]['quantity'] += quantity\n\n def get_product_quantity(self, product_id):\n if product_id in self.inventory:\n return self.inventory[product_id]['quantity']\n else:\n return False\n\n def create_order(self, order_id, product_id, quantity):\n if self.get_product_quantity(product_id) >= quantity:\n self.update_product_quantity(product_id, -quantity)\n self.orders[order_id] = {'product_id': product_id, 'quantity': quantity, 'status': 'Shipped'}\n else:\n return False\n\n def change_order_status(self, order_id, status):\n if order_id in self.orders:\n self.orders[order_id]['status'] = status\n else:\n return False\n\n def track_order(self, order_id):\n if order_id in self.orders:\n return self.orders[order_id]['status']\n else:\n return False", "import_statement": [], "class_description": " \"\"\"\n The class manages inventory and orders, including adding products, updating product quantities, retrieving product quantities, creating orders, changing order statuses, and tracking orders.\n \"\"\"\n", "class_name": "Warehouse", "test_classes": [ "WarehouseTestAddProduct", "WarehouseTestUpdateProductQuantity", "WarehouseTestGetProductQuantity", "WarehouseTestCreateOrder", "WarehouseTestChangeOrderStatus", "WarehouseTestTrackOrder", "WarehouseTestMain" ], "class_constructor": "class Warehouse: \n def __init__(self):\n \"\"\"\n Initialize two fields.\n self.inventory is a dict that stores the products.\n self.inventory = {Product ID: Product}\n self.orders is a dict that stores the products in a order.\n self.orders = {Order ID: Order}\n \"\"\"\n self.inventory = {} # Product ID: Product\n self.orders = {} # Order ID: Order\n\n", "fields": [ "self.inventory", "self.orders" ], "methods_info": [ { "method_name": "add_product", "method_description": "def add_product(self, product_id, name, quantity):\n \"\"\"\n Add product to inventory and plus the quantity if it has existed in inventory.\n Or just add new product to dict otherwise.\n :param product_id: int\n :param name: str, product name\n :param quantity: int, product quantity\n >>> warehouse.add_product(1, \"product1\", 3)\n >>> warehouse.inventory\n {1: {'name': 'product1', 'quantity': 3}}\n \"\"\"", "test_class": "WarehouseTestAddProduct", "test_code": "class WarehouseTestAddProduct(unittest.TestCase):\n def test_add_product_1(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n self.assertEqual(warehouse.inventory, {1: {'name': 'product 1', 'quantity': 10}})\n\n def test_add_product_2(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n warehouse.add_product(2, 'product 2', 5)\n self.assertEqual(warehouse.inventory,\n {1: {'name': 'product 1', 'quantity': 10}, 2: {'name': 'product 2', 'quantity': 5}})\n\n def test_add_product_3(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 3', 10)\n self.assertEqual(warehouse.inventory, {1: {'name': 'product 3', 'quantity': 10}})\n\n def test_add_product_4(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 4', 10)\n self.assertEqual(warehouse.inventory, {1: {'name': 'product 4', 'quantity': 10}})\n\n def test_add_product_5(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 5', 10)\n self.assertEqual(warehouse.inventory, {1: {'name': 'product 5', 'quantity': 10}})\n\n def test_add_product_6(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 5', 10)\n warehouse.add_product(1, 'product 5', 10)\n self.assertEqual(warehouse.inventory, {1: {'name': 'product 5', 'quantity': 20}})", "solution_code": "def add_product(self, product_id, name, quantity):\n if product_id not in self.inventory:\n self.inventory[product_id] = {'name': name, 'quantity': quantity}\n else:\n self.inventory[product_id]['quantity'] += quantity", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.inventory" ], "method_dependencies": [] } }, { "method_name": "update_product_quantity", "method_description": "def update_product_quantity(self, product_id, quantity):\n \"\"\"\n According to product_id, add the quantity to the corresponding product in inventory.\n >>> warehouse.add_product(1, \"product1\", 3)\n >>> warehouse.update_product_quantity(1, -1)\n >>> warehouse.inventory\n {1: {'name': 'product1', 'quantity': 2}}\n \"\"\"", "test_class": "WarehouseTestUpdateProductQuantity", "test_code": "class WarehouseTestUpdateProductQuantity(unittest.TestCase):\n def test_update_product_quantity_1(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n warehouse.update_product_quantity(1, 5)\n self.assertEqual(warehouse.inventory, {1: {'name': 'product 1', 'quantity': 15}})\n\n # quantity is negative\n def test_update_product_quantity_2(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n warehouse.update_product_quantity(1, -5)\n self.assertEqual(warehouse.inventory, {1: {'name': 'product 1', 'quantity': 5}})\n\n def test_update_product_quantity_3(self):\n warehouse = Warehouse()\n warehouse.update_product_quantity(1, -5)\n self.assertEqual(warehouse.inventory, {})\n\n def test_update_product_quantity_4(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n warehouse.update_product_quantity(1, 1)\n self.assertEqual(warehouse.inventory, {1: {'name': 'product 1', 'quantity': 11}})\n\n def test_update_product_quantity_5(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n warehouse.update_product_quantity(1, -9)\n self.assertEqual(warehouse.inventory, {1: {'name': 'product 1', 'quantity': 1}})", "solution_code": "def update_product_quantity(self, product_id, quantity):\n if product_id in self.inventory:\n self.inventory[product_id]['quantity'] += quantity", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.inventory" ], "method_dependencies": [] } }, { "method_name": "get_product_quantity", "method_description": "def get_product_quantity(self, product_id):\n \"\"\"\n Get the quantity of specific product by product_id.\n :param product_id, int\n :return: if the product_id is in inventory then return the corresponding quantity,\n or False otherwise.\n >>> warehouse.add_product(1, \"product1\", 3)\n >>> warehouse.get_product_quantity(1)\n 3\n >>> warehouse.get_product_quantity(2)\n False\n \"\"\"", "test_class": "WarehouseTestGetProductQuantity", "test_code": "class WarehouseTestGetProductQuantity(unittest.TestCase):\n def test_get_product_quantity_1(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n self.assertEqual(warehouse.get_product_quantity(1), 10)\n\n def test_get_product_quantity_2(self):\n warehouse = Warehouse()\n self.assertEqual(warehouse.get_product_quantity(1), False)\n\n def test_get_product_quantity_3(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 5)\n self.assertEqual(warehouse.get_product_quantity(1), 5)\n\n def test_get_product_quantity_4(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 100)\n self.assertEqual(warehouse.get_product_quantity(1), 100)\n\n def test_get_product_quantity_5(self):\n warehouse = Warehouse()\n warehouse.add_product(5, 'product 1', 10)\n self.assertEqual(warehouse.get_product_quantity(5), 10)", "solution_code": "def get_product_quantity(self, product_id):\n if product_id in self.inventory:\n return self.inventory[product_id]['quantity']\n else:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.inventory" ], "method_dependencies": [] } }, { "method_name": "create_order", "method_description": "def create_order(self, order_id, product_id, quantity):\n \"\"\"\n Create a order which includes the infomation of product, like id and quantity.\n And put the new order into self.orders.\n The default value of status is 'Shipped'.\n :param order_id: int\n :param product_id: int\n :param quantity: the quantity of product that be selected.\n :return False: only if product_id is not in inventory or the quantity is not adequate\n >>> warehouse.add_product(1, \"product1\", 3)\n >>> warehouse.create_order(1, 1, 2)\n >>> warehouse.orders\n {1: {'product_id': 1, 'quantity': 2, 'status': 'Shipped'}}\n >>> warehouse.create_order(1, 2, 2)\n False\n \"\"\"", "test_class": "WarehouseTestCreateOrder", "test_code": "class WarehouseTestCreateOrder(unittest.TestCase):\n def test_create_order_1(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n warehouse.create_order(1, 1, 5)\n self.assertEqual(warehouse.orders, {1: {'product_id': 1, 'quantity': 5, 'status': 'Shipped'}})\n\n def test_create_order_2(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n result = warehouse.create_order(1, 1, 15)\n self.assertFalse(result)\n\n def test_create_order_3(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 1)\n warehouse.create_order(1, 1, 1)\n self.assertEqual(warehouse.orders, {1: {'product_id': 1, 'quantity': 1, 'status': 'Shipped'}})\n\n def test_create_order_4(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 4', 5)\n warehouse.create_order(1, 1, 5)\n self.assertEqual(warehouse.orders, {1: {'product_id': 1, 'quantity': 5, 'status': 'Shipped'}})\n\n def test_create_order_5(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 5', 100)\n warehouse.create_order(1, 1, 50)\n self.assertEqual(warehouse.orders, {1: {'product_id': 1, 'quantity': 50, 'status': 'Shipped'}})", "solution_code": "def create_order(self, order_id, product_id, quantity):\n if self.get_product_quantity(product_id) >= quantity:\n self.update_product_quantity(product_id, -quantity)\n self.orders[order_id] = {'product_id': product_id, 'quantity': quantity, 'status': 'Shipped'}\n else:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.orders" ], "method_dependencies": [ "update_product_quantity", "get_product_quantity" ] } }, { "method_name": "change_order_status", "method_description": "def change_order_status(self, order_id, status):\n \"\"\"\n Change the status of order if the input order_id is in self.orders.\n :param order_id: int\n :param status: str, the state that is going to change to\n :return False: only if the order_id is not in self.orders\n >>> warehouse.add_product(1, \"product1\", 3)\n >>> warehouse.create_order(1, 1, 2)\n >>> warehouse.change_order_status(1, \"done\")\n >>> warehouse.orders\n {1: {'product_id': 1, 'quantity': 2, 'status': 'done'}}\n \"\"\"", "test_class": "WarehouseTestChangeOrderStatus", "test_code": "class WarehouseTestChangeOrderStatus(unittest.TestCase):\n def test_change_order_status_1(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n warehouse.create_order(1, 1, 5)\n warehouse.change_order_status(1, 'Delivered')\n self.assertEqual(warehouse.orders, {1: {'product_id': 1, 'quantity': 5, 'status': 'Delivered'}})\n\n def test_change_order_status_2(self):\n warehouse = Warehouse()\n result = warehouse.change_order_status(1, 'Delivered')\n self.assertFalse(result)\n\n def test_change_order_status_3(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 3', 5)\n warehouse.create_order(1, 1, 5)\n warehouse.change_order_status(1, 'Delivered')\n self.assertEqual(warehouse.orders, {1: {'product_id': 1, 'quantity': 5, 'status': 'Delivered'}})\n\n def test_change_order_status_4(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 4', 100)\n warehouse.create_order(1, 1, 50)\n warehouse.change_order_status(1, 'Delivered')\n self.assertEqual(warehouse.orders, {1: {'product_id': 1, 'quantity': 50, 'status': 'Delivered'}})\n\n def test_change_order_status_5(self):\n warehouse = Warehouse()\n result = warehouse.change_order_status(2, 'Delivered')\n self.assertFalse(result)", "solution_code": "def change_order_status(self, order_id, status):\n if order_id in self.orders:\n self.orders[order_id]['status'] = status\n else:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.orders" ], "method_dependencies": [] } }, { "method_name": "track_order", "method_description": "def track_order(self, order_id):\n \"\"\"\n Get the status of specific order.\n :param order_id: int\n :return False: only if the order_id is not in self.orders.\n >>> warehouse.add_product(1, \"product1\", 3)\n >>> warehouse.create_order(1, 1, 2)\n >>> warehouse.track_order(1)\n 'Shipped'\n \"\"\"", "test_class": "WarehouseTestTrackOrder", "test_code": "class WarehouseTestTrackOrder(unittest.TestCase):\n def test_track_order_1(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 1', 10)\n warehouse.create_order(1, 1, 5)\n self.assertEqual(warehouse.track_order(1), 'Shipped')\n\n def test_track_order_2(self):\n warehouse = Warehouse()\n result = warehouse.track_order(1)\n self.assertFalse(result)\n\n def test_track_order_3(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 3', 10)\n warehouse.create_order(1, 1, 1)\n self.assertEqual(warehouse.track_order(1), 'Shipped')\n\n def test_track_order_4(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 4', 100)\n warehouse.create_order(1, 1, 50)\n self.assertEqual(warehouse.track_order(1), 'Shipped')\n\n def test_track_order_5(self):\n warehouse = Warehouse()\n warehouse.add_product(1, 'product 5', 100)\n warehouse.create_order(1, 1, 10)\n self.assertEqual(warehouse.track_order(1), 'Shipped')", "solution_code": "def track_order(self, order_id):\n if order_id in self.orders:\n return self.orders[order_id]['status']\n else:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.orders" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_96", "skeleton": "\nclass WeatherSystem:\n \"\"\"\n This is a class representing a weather system that provides functionality to query weather information for a specific city and convert temperature units between Celsius and Fahrenheit.\n \"\"\"\n\n def __init__(self, city) -> None:\n \"\"\"\n Initialize the weather system with a city name.\n \"\"\"\n self.temperature = None\n self.weather = None\n self.city = city\n self.weather_list = {}\n\n def query(self, weather_list, tmp_units = 'celsius'):\n \"\"\"\n Query the weather system for the weather and temperature of the city,and convert the temperature units based on the input parameter.\n :param weather_list: a dictionary of weather information for different cities,dict.\n :param tmp_units: the temperature units to convert to, str.\n :return: the temperature and weather of the city, tuple.\n >>> weatherSystem = WeatherSystem('New York')\n >>> weather_list = {'New York': {'weather': 'sunny','temperature': 27,'temperature units': 'celsius'},'Beijing': {'weather': 'cloudy','temperature': 23,'temperature units': 'celsius'}}\n >>> weatherSystem.query(weather_list)\n (27, 'sunny')\n\n \"\"\"\n\n def set_city(self, city):\n \"\"\"\n Set the city of the weather system.\n :param city: the city to set, str.\n :return: None\n >>> weatherSystem = WeatherSystem('New York')\n >>> weatherSystem.set_city('Beijing')\n >>> weatherSystem.city\n 'Beijing'\n\n \"\"\"\n\n def celsius_to_fahrenheit(self):\n \"\"\"\n Convert the temperature from Celsius to Fahrenheit.\n :return: the temperature in Fahrenheit, float.\n >>> weatherSystem = WeatherSystem('New York')\n >>> weatherSystem.temperature = 27\n >>> weatherSystem.celsius_to_fahrenheit()\n 80.6\n\n \"\"\"\n\n def fahrenheit_to_celsius(self):\n \"\"\"\n Convert the temperature from Fahrenheit to Celsius.\n :return: the temperature in Celsius, float.\n >>> weatherSystem = WeatherSystem('New York')\n >>> weatherSystem.temperature = 80.6\n >>> weatherSystem.fahrenheit_to_celsius()\n 26.999999999999996\n\n \"\"\"", "test": "import unittest\n\n\nclass WeatherSystemTestQuery(unittest.TestCase):\n def test_query(self):\n weatherSystem = WeatherSystem('New York')\n weather_list = {\n 'New York': {\n 'weather': 'sunny',\n 'temperature': 27,\n 'temperature units': 'celsius'\n },\n 'Beijing': {\n 'weather': 'cloudy',\n 'temperature': 23,\n 'temperature units': 'celsius'\n }\n }\n self.assertEqual(weatherSystem.query(weather_list), (27, 'sunny'))\n\n def test_query_2(self):\n weatherSystem = WeatherSystem('Shanghai')\n weather_list = {\n 'New York': {\n 'weather': 'sunny',\n 'temperature': 27,\n 'temperature units': 'celsius'\n },\n 'Beijing': {\n 'weather': 'cloudy',\n 'temperature': 23,\n 'temperature units': 'celsius'\n }\n }\n self.assertEqual(weatherSystem.query(weather_list), False)\n\n def test_query_3(self):\n weatherSystem = WeatherSystem('Beijing')\n weather_list = {\n 'New York': {\n 'weather': 'sunny',\n 'temperature': 27,\n 'temperature units': 'celsius'\n },\n 'Beijing': {\n 'weather': 'cloudy',\n 'temperature': 23,\n 'temperature units': 'celsius'\n }\n }\n self.assertEqual(weatherSystem.query(weather_list, 'fahrenheit'), (73.4, 'cloudy'))\n\n def test_query_4(self):\n weatherSystem = WeatherSystem('Beijing')\n weather_list = {\n 'New York': {\n 'weather': 'sunny',\n 'temperature': 73.47,\n 'temperature units': 'fahrenheit'\n },\n 'Beijing': {\n 'weather': 'cloudy',\n 'temperature': 73.4,\n 'temperature units': 'fahrenheit'\n }\n }\n self.assertEqual(weatherSystem.query(weather_list, 'celsius'), (23.000000000000004, 'cloudy'))\n\n def test_query_5(self):\n weatherSystem = WeatherSystem('New York')\n weather_list = {\n 'New York': {\n 'weather': 'sunny',\n 'temperature': 80.6,\n 'temperature units': 'fahrenheit'\n },\n 'Beijing': {\n 'weather': 'cloudy',\n 'temperature': 23,\n 'temperature units': 'celsius'\n }\n }\n self.assertEqual(weatherSystem.query(weather_list, tmp_units='celsius'), (26.999999999999996, 'sunny'))\n\n def test_query_6(self):\n weatherSystem = WeatherSystem('New York')\n weather_list = {\n 'New York': {\n 'weather': 'sunny',\n 'temperature': 27,\n 'temperature units': 'celsius'\n },\n 'Beijing': {\n 'weather': 'cloudy',\n 'temperature': 23,\n 'temperature units': 'celsius'\n }\n }\n self.assertEqual(weatherSystem.query(weather_list, tmp_units='fahrenheit'), (80.6, 'sunny'))\n\n\nclass WeatherSystemTestSetCity(unittest.TestCase):\n def test_set_city(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.set_city('Beijing')\n self.assertEqual(weatherSystem.city, 'Beijing')\n\n def test_set_city_2(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.set_city('Shanghai')\n self.assertEqual(weatherSystem.city, 'Shanghai')\n\n def test_set_city_3(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.set_city('Shanghai')\n self.assertNotEqual(weatherSystem.city, 'Beijing')\n\n def test_set_city_4(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.set_city('Shanghai')\n self.assertNotEqual(weatherSystem.city, 'New York')\n\n def test_set_city_5(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.set_city('Shanghai')\n self.assertNotEqual(weatherSystem.city, 'Tokyo')\n\n\nclass WeatherSystemTestCelsiusToFahrenheit(unittest.TestCase):\n def test_celsius_to_fahrenheit(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.temperature = 27\n self.assertEqual(weatherSystem.celsius_to_fahrenheit(), 80.6)\n\n def test_celsius_to_fahrenheit_2(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.temperature = 23\n self.assertEqual(weatherSystem.celsius_to_fahrenheit(), 73.4)\n\n def test_celsius_to_fahrenheit_3(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.temperature = 23\n self.assertNotEqual(weatherSystem.celsius_to_fahrenheit(), 80.6)\n\n def test_celsius_to_fahrenheit_4(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.temperature = 27\n self.assertNotEqual(weatherSystem.celsius_to_fahrenheit(), 73.4)\n\n def test_celsius_to_fahrenheit_5(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.temperature = 27\n self.assertNotEqual(weatherSystem.celsius_to_fahrenheit(), 23)\n\n\nclass WeatherSystemTestFahrenheitToCelsius(unittest.TestCase):\n def test_fahrenheit_to_celsius(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.temperature = 80.6\n self.assertEqual(weatherSystem.fahrenheit_to_celsius(), 26.999999999999996)\n\n def test_fahrenheit_to_celsius_2(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.temperature = 73.4\n self.assertEqual(weatherSystem.fahrenheit_to_celsius(), 23.000000000000004)\n\n def test_fahrenheit_to_celsius_3(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.temperature = 80\n self.assertNotEqual(weatherSystem.fahrenheit_to_celsius(), 23)\n\n def test_fahrenheit_to_celsius_4(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.temperature = 73\n self.assertNotEqual(weatherSystem.fahrenheit_to_celsius(), 27)\n\n def test_fahrenheit_to_celsius_5(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.temperature = 80\n self.assertNotEqual(weatherSystem.fahrenheit_to_celsius(), 27)\n\n\nclass WeatherSystemTestMain(unittest.TestCase):\n def test_main(self):\n weatherSystem = WeatherSystem('New York')\n weather_list = {\n 'New York': {\n 'weather': 'sunny',\n 'temperature': 27,\n 'temperature units': 'celsius'\n },\n 'Beijing': {\n 'weather': 'cloudy',\n 'temperature': 23,\n 'temperature units': 'celsius'\n }\n }\n self.assertEqual(weatherSystem.query(weather_list), (27, 'sunny'))\n weatherSystem.set_city('Beijing')\n self.assertEqual(weatherSystem.city, 'Beijing')\n weatherSystem.temperature = 27\n self.assertEqual(weatherSystem.celsius_to_fahrenheit(), 80.6)\n weatherSystem.temperature = 80.6\n self.assertEqual(weatherSystem.fahrenheit_to_celsius(), 26.999999999999996)", "solution_code": "class WeatherSystem:\n def __init__(self, city) -> None:\n self.temperature = None\n self.weather = None\n self.city = city\n self.weather_list = {}\n \n def query(self, weather_list, tmp_units = 'celsius'):\n self.weather_list = weather_list\n if self.city not in weather_list:\n return False\n else:\n self.temperature = self.weather_list[self.city]['temperature']\n self.weather = self.weather_list[self.city]['weather']\n if self.weather_list[self.city]['temperature units'] != tmp_units:\n if tmp_units == 'celsius':\n return self.fahrenheit_to_celsius(), self.weather\n elif tmp_units == 'fahrenheit':\n return self.celsius_to_fahrenheit(), self.weather\n else:\n return self.temperature, self.weather\n \n def set_city(self, city):\n self.city = city\n\n def celsius_to_fahrenheit(self):\n return (self.temperature * 9/5) + 32\n\n def fahrenheit_to_celsius(self):\n return (self.temperature - 32) * 5/9", "import_statement": [], "class_description": " \"\"\"\n This is a class representing a weather system that provides functionality to query weather information for a specific city and convert temperature units between Celsius and Fahrenheit.\n \"\"\"\n", "class_name": "WeatherSystem", "test_classes": [ "WeatherSystemTestQuery", "WeatherSystemTestSetCity", "WeatherSystemTestCelsiusToFahrenheit", "WeatherSystemTestFahrenheitToCelsius", "WeatherSystemTestMain" ], "class_constructor": "class WeatherSystem: \n def __init__(self, city) -> None:\n \"\"\"\n Initialize the weather system with a city name.\n \"\"\"\n self.temperature = None\n self.weather = None\n self.city = city\n self.weather_list = {}\n\n", "fields": [ "self.city", "self.temperature", "self.weather", "self.weather_list" ], "methods_info": [ { "method_name": "query", "method_description": "def query(self, weather_list, tmp_units = 'celsius'):\n \"\"\"\n Query the weather system for the weather and temperature of the city,and convert the temperature units based on the input parameter.\n :param weather_list: a dictionary of weather information for different cities,dict.\n :param tmp_units: the temperature units to convert to, str.\n :return: the temperature and weather of the city, tuple.\n >>> weatherSystem = WeatherSystem('New York')\n >>> weather_list = {'New York': {'weather': 'sunny','temperature': 27,'temperature units': 'celsius'},'Beijing': {'weather': 'cloudy','temperature': 23,'temperature units': 'celsius'}}\n >>> weatherSystem.query(weather_list)\n (27, 'sunny')\n\n \"\"\"", "test_class": "WeatherSystemTestQuery", "test_code": "class WeatherSystemTestQuery(unittest.TestCase):\n def test_query(self):\n weatherSystem = WeatherSystem('New York')\n weather_list = {\n 'New York': {\n 'weather': 'sunny',\n 'temperature': 27,\n 'temperature units': 'celsius'\n },\n 'Beijing': {\n 'weather': 'cloudy',\n 'temperature': 23,\n 'temperature units': 'celsius'\n }\n }\n self.assertEqual(weatherSystem.query(weather_list), (27, 'sunny'))\n\n def test_query_2(self):\n weatherSystem = WeatherSystem('Shanghai')\n weather_list = {\n 'New York': {\n 'weather': 'sunny',\n 'temperature': 27,\n 'temperature units': 'celsius'\n },\n 'Beijing': {\n 'weather': 'cloudy',\n 'temperature': 23,\n 'temperature units': 'celsius'\n }\n }\n self.assertEqual(weatherSystem.query(weather_list), False)\n\n def test_query_3(self):\n weatherSystem = WeatherSystem('Beijing')\n weather_list = {\n 'New York': {\n 'weather': 'sunny',\n 'temperature': 27,\n 'temperature units': 'celsius'\n },\n 'Beijing': {\n 'weather': 'cloudy',\n 'temperature': 23,\n 'temperature units': 'celsius'\n }\n }\n self.assertEqual(weatherSystem.query(weather_list, 'fahrenheit'), (73.4, 'cloudy'))\n\n def test_query_4(self):\n weatherSystem = WeatherSystem('Beijing')\n weather_list = {\n 'New York': {\n 'weather': 'sunny',\n 'temperature': 73.47,\n 'temperature units': 'fahrenheit'\n },\n 'Beijing': {\n 'weather': 'cloudy',\n 'temperature': 73.4,\n 'temperature units': 'fahrenheit'\n }\n }\n self.assertEqual(weatherSystem.query(weather_list, 'celsius'), (23.000000000000004, 'cloudy'))\n\n def test_query_5(self):\n weatherSystem = WeatherSystem('New York')\n weather_list = {\n 'New York': {\n 'weather': 'sunny',\n 'temperature': 80.6,\n 'temperature units': 'fahrenheit'\n },\n 'Beijing': {\n 'weather': 'cloudy',\n 'temperature': 23,\n 'temperature units': 'celsius'\n }\n }\n self.assertEqual(weatherSystem.query(weather_list, tmp_units='celsius'), (26.999999999999996, 'sunny'))\n\n def test_query_6(self):\n weatherSystem = WeatherSystem('New York')\n weather_list = {\n 'New York': {\n 'weather': 'sunny',\n 'temperature': 27,\n 'temperature units': 'celsius'\n },\n 'Beijing': {\n 'weather': 'cloudy',\n 'temperature': 23,\n 'temperature units': 'celsius'\n }\n }\n self.assertEqual(weatherSystem.query(weather_list, tmp_units='fahrenheit'), (80.6, 'sunny'))", "solution_code": "def query(self, weather_list, tmp_units = 'celsius'):\n self.weather_list = weather_list\n if self.city not in weather_list:\n return False\n else:\n self.temperature = self.weather_list[self.city]['temperature']\n self.weather = self.weather_list[self.city]['weather']\n if self.weather_list[self.city]['temperature units'] != tmp_units:\n if tmp_units == 'celsius':\n return self.fahrenheit_to_celsius(), self.weather\n elif tmp_units == 'fahrenheit':\n return self.celsius_to_fahrenheit(), self.weather\n else:\n return self.temperature, self.weather", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.city", "self.temperature", "self.weather", "self.weather_list" ], "method_dependencies": [ "celsius_to_fahrenheit", "fahrenheit_to_celsius" ] } }, { "method_name": "set_city", "method_description": "def set_city(self, city):\n \"\"\"\n Set the city of the weather system.\n :param city: the city to set, str.\n :return: None\n >>> weatherSystem = WeatherSystem('New York')\n >>> weatherSystem.set_city('Beijing')\n >>> weatherSystem.city\n 'Beijing'\n\n \"\"\"", "test_class": "WeatherSystemTestSetCity", "test_code": "class WeatherSystemTestSetCity(unittest.TestCase):\n def test_set_city(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.set_city('Beijing')\n self.assertEqual(weatherSystem.city, 'Beijing')\n\n def test_set_city_2(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.set_city('Shanghai')\n self.assertEqual(weatherSystem.city, 'Shanghai')\n\n def test_set_city_3(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.set_city('Shanghai')\n self.assertNotEqual(weatherSystem.city, 'Beijing')\n\n def test_set_city_4(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.set_city('Shanghai')\n self.assertNotEqual(weatherSystem.city, 'New York')\n\n def test_set_city_5(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.set_city('Shanghai')\n self.assertNotEqual(weatherSystem.city, 'Tokyo')", "solution_code": "def set_city(self, city):\n self.city = city", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.city" ], "method_dependencies": [] } }, { "method_name": "celsius_to_fahrenheit", "method_description": "def celsius_to_fahrenheit(self):\n \"\"\"\n Convert the temperature from Celsius to Fahrenheit.\n :return: the temperature in Fahrenheit, float.\n >>> weatherSystem = WeatherSystem('New York')\n >>> weatherSystem.temperature = 27\n >>> weatherSystem.celsius_to_fahrenheit()\n 80.6\n\n \"\"\"", "test_class": "WeatherSystemTestCelsiusToFahrenheit", "test_code": "class WeatherSystemTestCelsiusToFahrenheit(unittest.TestCase):\n def test_celsius_to_fahrenheit(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.temperature = 27\n self.assertEqual(weatherSystem.celsius_to_fahrenheit(), 80.6)\n\n def test_celsius_to_fahrenheit_2(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.temperature = 23\n self.assertEqual(weatherSystem.celsius_to_fahrenheit(), 73.4)\n\n def test_celsius_to_fahrenheit_3(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.temperature = 23\n self.assertNotEqual(weatherSystem.celsius_to_fahrenheit(), 80.6)\n\n def test_celsius_to_fahrenheit_4(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.temperature = 27\n self.assertNotEqual(weatherSystem.celsius_to_fahrenheit(), 73.4)\n\n def test_celsius_to_fahrenheit_5(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.temperature = 27\n self.assertNotEqual(weatherSystem.celsius_to_fahrenheit(), 23)", "solution_code": "def celsius_to_fahrenheit(self):\n return (self.temperature * 9/5) + 32", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.temperature" ], "method_dependencies": [] } }, { "method_name": "fahrenheit_to_celsius", "method_description": "def fahrenheit_to_celsius(self):\n \"\"\"\n Convert the temperature from Fahrenheit to Celsius.\n :return: the temperature in Celsius, float.\n >>> weatherSystem = WeatherSystem('New York')\n >>> weatherSystem.temperature = 80.6\n >>> weatherSystem.fahrenheit_to_celsius()\n 26.999999999999996\n\n \"\"\"", "test_class": "WeatherSystemTestFahrenheitToCelsius", "test_code": "class WeatherSystemTestFahrenheitToCelsius(unittest.TestCase):\n def test_fahrenheit_to_celsius(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.temperature = 80.6\n self.assertEqual(weatherSystem.fahrenheit_to_celsius(), 26.999999999999996)\n\n def test_fahrenheit_to_celsius_2(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.temperature = 73.4\n self.assertEqual(weatherSystem.fahrenheit_to_celsius(), 23.000000000000004)\n\n def test_fahrenheit_to_celsius_3(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.temperature = 80\n self.assertNotEqual(weatherSystem.fahrenheit_to_celsius(), 23)\n\n def test_fahrenheit_to_celsius_4(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.temperature = 73\n self.assertNotEqual(weatherSystem.fahrenheit_to_celsius(), 27)\n\n def test_fahrenheit_to_celsius_5(self):\n weatherSystem = WeatherSystem('New York')\n weatherSystem.temperature = 80\n self.assertNotEqual(weatherSystem.fahrenheit_to_celsius(), 27)", "solution_code": "def fahrenheit_to_celsius(self):\n return (self.temperature - 32) * 5/9", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.temperature" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_97", "skeleton": "\nclass Words2Numbers:\n \"\"\"\n The class provides a text-to-number conversion utility, allowing conversion of written numbers (in words) to their numerical representation.\n \"\"\"\n\n\n def __init__(self):\n \"\"\"\n Initialize the word lists and dictionaries required for conversion\n \"\"\"\n self.numwords = {}\n self.units = [\n \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\",\n \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\",\n ]\n self.tens = [\"\", \"\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\n self.scales = [\"hundred\", \"thousand\", \"million\", \"billion\", \"trillion\"]\n\n self.numwords[\"and\"] = (1, 0)\n for idx, word in enumerate(self.units):\n self.numwords[word] = (1, idx)\n for idx, word in enumerate(self.tens):\n self.numwords[word] = (1, idx * 10)\n for idx, word in enumerate(self.scales):\n self.numwords[word] = (10 ** (idx * 3 or 2), 0)\n\n self.ordinal_words = {'first': 1, 'second': 2, 'third': 3, 'fifth': 5, 'eighth': 8, 'ninth': 9, 'twelfth': 12}\n self.ordinal_endings = [('ieth', 'y'), ('th', '')]\n\n\n def text2int(self, textnum):\n \"\"\"\n Convert the word string to the corresponding integer string\n :param textnum: string, the word string to be converted\n :return: string, the final converted integer string\n >>> w2n = Words2Numbers()\n >>> w2n.text2int(\"thirty-two\")\n \"32\"\n \"\"\"\n\n def is_valid_input(self, textnum):\n \"\"\"\n Check if the input text contains only valid words that can be converted into numbers.\n :param textnum: The input text containing words representing numbers.\n :return: True if input is valid, False otherwise.\n >>> w2n = Words2Numbers()\n >>> w2n.is_valid_input(\"thirty-two\")\n False\n \"\"\"", "test": "import unittest\n\n\nclass Words2NumbersTestText2Int(unittest.TestCase):\n def test_text2int(self):\n w2n = Words2Numbers()\n self.assertEqual(w2n.text2int(\"thirty-two\"), \"32\")\n\n def test_text2int2(self):\n w2n = Words2Numbers()\n self.assertEqual(w2n.text2int(\"one hundred and twenty-three\"), \"123\")\n\n def test_text2int3(self):\n w2n = Words2Numbers()\n self.assertEqual(w2n.text2int(\"two thousand and nineteen\"), \"2019\")\n\n def test_text2int4(self):\n w2n = Words2Numbers()\n self.assertEqual(w2n.text2int(\"one hundred and one\"), \"101\")\n\n def test_text2int5(self):\n w2n = Words2Numbers()\n self.assertEqual(w2n.text2int(\"one million and eleven\"), \"1000011\")\n\n def test_text2int6(self):\n w2n = Words2Numbers()\n self.assertEqual(w2n.text2int(\"one million one hundred sixty-ninth\"), \"1000169\")\n\nclass Words2NumbersTestIsValidInput(unittest.TestCase):\n def test_is_valid_input(self):\n w2n = Words2Numbers()\n self.assertTrue(w2n.is_valid_input(\"twenty-five thousand three hundred and forty-two\"))\n\n def test_is_valid_input2(self):\n w2n = Words2Numbers()\n self.assertTrue(w2n.is_valid_input(\"second hundred and third\"))\n\n def test_is_valid_input3(self):\n w2n = Words2Numbers()\n self.assertTrue(w2n.is_valid_input(\"twenty-fifth thousand three hundred and forty-second\"))\n\n def test_is_valid_input4(self):\n w2n = Words2Numbers()\n self.assertFalse(w2n.is_valid_input(\"eleventy thousand and five\"))\n\n def test_is_valid_input5(self):\n w2n = Words2Numbers()\n self.assertTrue(w2n.is_valid_input(\"seventy two thousand and hundred eleven\"))\n\n def test_is_valid_input6(self):\n w2n = Words2Numbers()\n self.assertTrue(w2n.is_valid_input(\"fifteenth hundred\"))\n\nclass Words2NumbersTestMain(unittest.TestCase):\n def test_main(self):\n w2n = Words2Numbers()\n self.assertEqual(w2n.is_valid_input(\"seventy two thousand and hundred eleven\"), True)\n self.assertEqual(w2n.text2int(\"seventy two thousand and hundred eleven\"), \"72011\")", "solution_code": "class Words2Numbers:\n\n def __init__(self):\n self.numwords = {}\n self.units = [\n \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\",\n \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\",\n ]\n self.tens = [\"\", \"\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\n self.scales = [\"hundred\", \"thousand\", \"million\", \"billion\", \"trillion\"]\n\n self.numwords[\"and\"] = (1, 0)\n for idx, word in enumerate(self.units):\n self.numwords[word] = (1, idx)\n for idx, word in enumerate(self.tens):\n self.numwords[word] = (1, idx * 10)\n for idx, word in enumerate(self.scales):\n self.numwords[word] = (10 ** (idx * 3 or 2), 0)\n\n self.ordinal_words = {'first': 1, 'second': 2, 'third': 3, 'fifth': 5, 'eighth': 8, 'ninth': 9, 'twelfth': 12}\n self.ordinal_endings = [('ieth', 'y'), ('th', '')]\n\n def text2int(self, textnum):\n textnum = textnum.replace('-', ' ')\n\n current = result = 0\n curstring = \"\"\n onnumber = False\n for word in textnum.split():\n if word in self.ordinal_words:\n scale, increment = (1, self.ordinal_words[word])\n current = current * scale + increment\n onnumber = True\n else:\n for ending, replacement in self.ordinal_endings:\n if word.endswith(ending):\n word = \"%s%s\" % (word[:-len(ending)], replacement)\n\n if word not in self.numwords:\n if onnumber:\n curstring += repr(result + current) + \" \"\n curstring += word + \" \"\n result = current = 0\n onnumber = False\n else:\n scale, increment = self.numwords[word]\n current = current * scale + increment\n if scale > 100:\n result += current\n current = 0\n onnumber = True\n\n if onnumber:\n curstring += repr(result + current)\n\n return curstring\n\n def is_valid_input(self, textnum):\n\n textnum = textnum.replace('-', ' ')\n\n for word in textnum.split():\n if word in self.ordinal_words:\n continue\n else:\n for ending, replacement in self.ordinal_endings:\n if word.endswith(ending):\n word = \"%s%s\" % (word[:-len(ending)], replacement)\n\n if word not in self.numwords:\n return False\n\n return True", "import_statement": [], "class_description": " \"\"\"\n The class provides a text-to-number conversion utility, allowing conversion of written numbers (in words) to their numerical representation.\n \"\"\"\n", "class_name": "Words2Numbers", "test_classes": [ "Words2NumbersTestText2Int", "Words2NumbersTestIsValidInput", " Words2NumbersTestMain" ], "class_constructor": "class Words2Numbers: \n def __init__(self):\n \"\"\"\n Initialize the word lists and dictionaries required for conversion\n \"\"\"\n self.numwords = {}\n self.units = [\n \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\",\n \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\",\n ]\n self.tens = [\"\", \"\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\n self.scales = [\"hundred\", \"thousand\", \"million\", \"billion\", \"trillion\"]\n\n self.numwords[\"and\"] = (1, 0)\n for idx, word in enumerate(self.units):\n self.numwords[word] = (1, idx)\n for idx, word in enumerate(self.tens):\n self.numwords[word] = (1, idx * 10)\n for idx, word in enumerate(self.scales):\n self.numwords[word] = (10 ** (idx * 3 or 2), 0)\n\n self.ordinal_words = {'first': 1, 'second': 2, 'third': 3, 'fifth': 5, 'eighth': 8, 'ninth': 9, 'twelfth': 12}\n self.ordinal_endings = [('ieth', 'y'), ('th', '')]\n\n\n", "fields": [ "self.numwords", "self.ordinal_endings", "self.ordinal_words", "self.scales", "self.tens", "self.units" ], "methods_info": [ { "method_name": "text2int", "method_description": "def text2int(self, textnum):\n \"\"\"\n Convert the word string to the corresponding integer string\n :param textnum: string, the word string to be converted\n :return: string, the final converted integer string\n >>> w2n = Words2Numbers()\n >>> w2n.text2int(\"thirty-two\")\n \"32\"\n \"\"\"", "test_class": "Words2NumbersTestText2Int", "test_code": "class Words2NumbersTestText2Int(unittest.TestCase):\n def test_text2int(self):\n w2n = Words2Numbers()\n self.assertEqual(w2n.text2int(\"thirty-two\"), \"32\")\n\n def test_text2int2(self):\n w2n = Words2Numbers()\n self.assertEqual(w2n.text2int(\"one hundred and twenty-three\"), \"123\")\n\n def test_text2int3(self):\n w2n = Words2Numbers()\n self.assertEqual(w2n.text2int(\"two thousand and nineteen\"), \"2019\")\n\n def test_text2int4(self):\n w2n = Words2Numbers()\n self.assertEqual(w2n.text2int(\"one hundred and one\"), \"101\")\n\n def test_text2int5(self):\n w2n = Words2Numbers()\n self.assertEqual(w2n.text2int(\"one million and eleven\"), \"1000011\")\n\n def test_text2int6(self):\n w2n = Words2Numbers()\n self.assertEqual(w2n.text2int(\"one million one hundred sixty-ninth\"), \"1000169\")", "solution_code": "def text2int(self, textnum):\n textnum = textnum.replace('-', ' ')\n\n current = result = 0\n curstring = \"\"\n onnumber = False\n for word in textnum.split():\n if word in self.ordinal_words:\n scale, increment = (1, self.ordinal_words[word])\n current = current * scale + increment\n onnumber = True\n else:\n for ending, replacement in self.ordinal_endings:\n if word.endswith(ending):\n word = \"%s%s\" % (word[:-len(ending)], replacement)\n\n if word not in self.numwords:\n if onnumber:\n curstring += repr(result + current) + \" \"\n curstring += word + \" \"\n result = current = 0\n onnumber = False\n else:\n scale, increment = self.numwords[word]\n current = current * scale + increment\n if scale > 100:\n result += current\n current = 0\n onnumber = True\n\n if onnumber:\n curstring += repr(result + current)\n\n return curstring", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.numwords", "self.ordinal_endings", "self.ordinal_words" ], "method_dependencies": [] } }, { "method_name": "is_valid_input", "method_description": "def is_valid_input(self, textnum):\n \"\"\"\n Check if the input text contains only valid words that can be converted into numbers.\n :param textnum: The input text containing words representing numbers.\n :return: True if input is valid, False otherwise.\n >>> w2n = Words2Numbers()\n >>> w2n.is_valid_input(\"thirty-two\")\n False\n \"\"\"", "test_class": "Words2NumbersTestIsValidInput", "test_code": "class Words2NumbersTestIsValidInput(unittest.TestCase):\n def test_is_valid_input(self):\n w2n = Words2Numbers()\n self.assertTrue(w2n.is_valid_input(\"twenty-five thousand three hundred and forty-two\"))\n\n def test_is_valid_input2(self):\n w2n = Words2Numbers()\n self.assertTrue(w2n.is_valid_input(\"second hundred and third\"))\n\n def test_is_valid_input3(self):\n w2n = Words2Numbers()\n self.assertTrue(w2n.is_valid_input(\"twenty-fifth thousand three hundred and forty-second\"))\n\n def test_is_valid_input4(self):\n w2n = Words2Numbers()\n self.assertFalse(w2n.is_valid_input(\"eleventy thousand and five\"))\n\n def test_is_valid_input5(self):\n w2n = Words2Numbers()\n self.assertTrue(w2n.is_valid_input(\"seventy two thousand and hundred eleven\"))\n\n def test_is_valid_input6(self):\n w2n = Words2Numbers()\n self.assertTrue(w2n.is_valid_input(\"fifteenth hundred\"))", "solution_code": "def is_valid_input(self, textnum):\n\n textnum = textnum.replace('-', ' ')\n\n for word in textnum.split():\n if word in self.ordinal_words:\n continue\n else:\n for ending, replacement in self.ordinal_endings:\n if word.endswith(ending):\n word = \"%s%s\" % (word[:-len(ending)], replacement)\n\n if word not in self.numwords:\n return False\n\n return True", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.numwords", "self.ordinal_endings", "self.ordinal_words" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_98", "skeleton": "\nimport xml.etree.ElementTree as ET\n\n\nclass XMLProcessor:\n \"\"\"\n This is a class as XML files handler, including reading, writing, processing as well as finding elements in a XML file.\n \"\"\"\n\n def __init__(self, file_name):\n \"\"\"\n Initialize the XMLProcessor object with the given file name.\n :param file_name:string, the name of the XML file to be processed.\n \"\"\"\n self.file_name = file_name\n self.root = None\n\n def read_xml(self):\n \"\"\"\n Reads the XML file and returns the root element.\n :return: Element, the root element of the XML file.\n >>> xml_processor = XMLProcessor('test.xml')\n >>> root_element = xml_processor.read_xml()\n >>> print(root_element)\n \n \"\"\"\n\n\n def write_xml(self, file_name):\n \"\"\"\n Writes the XML data to the specified file.\n :param file_name: string, the name of the file to write the XML data.\n :return: bool, True if the write operation is successful, False otherwise.\n >>> xml_processor = XMLProcessor('test.xml')\n >>> root = xml_processor.read_xml()\n >>> success = xml_processor.write_xml('output.xml')\n >>> print(success)\n True\n \"\"\"\n\n\n def process_xml_data(self, file_name):\n \"\"\"\n Modifies the data in XML elements and writes the updated XML data to a new file.\n :param file_name: string, the name of the file to write the modified XML data.\n :return: bool, True if the write operation is successful, False otherwise.\n >>> xml_processor = XMLProcessor('test.xml')\n >>> root = xml_processor.read_xml()\n >>> success = xml_processor.process_xml_data('processed.xml')\n >>> print(success)\n True\n \"\"\"\n\n\n def find_element(self, element_name):\n \"\"\"\n Finds the XML elements with the specified name.\n :param element_name: string, the name of the elements to find.\n :return: list, a list of found elements with the specified name.\n >>> xml_processor = XMLProcessor('test.xml')\n >>> root = xml_processor.read_xml()\n >>> items = xml_processor.find_element('item')\n >>> for item in items:\n >>> print(item.text)\n apple\n banana\n orange\n \"\"\"", "test": "import unittest\nimport os\n\n\nclass XMLProcessorTestReadXml(unittest.TestCase):\n def test_read_xml_1(self):\n with open('test.xml', 'w') as f:\n f.write('\\n apple\\n banana\\n orange\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n root = self.processor.read_xml()\n self.assertIsNotNone(root)\n lst = root.findall('item')\n self.assertEqual(lst[0].text, 'apple')\n self.assertEqual(lst[1].text, 'banana')\n self.assertEqual(lst[2].text, 'orange')\n\n os.remove('test.xml')\n\n def test_read_xml_2(self):\n with open('test.xml', 'w') as f:\n f.write('\\n aaa\\n bbb\\n ccc\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n root = self.processor.read_xml()\n self.assertIsNotNone(root)\n lst = root.findall('item')\n self.assertEqual(lst[0].text, 'aaa')\n self.assertEqual(lst[1].text, 'bbb')\n self.assertEqual(lst[2].text, 'ccc')\n\n os.remove('test.xml')\n\n def test_read_xml_3(self):\n with open('test.xml', 'w') as f:\n f.write('\\n apple\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n root = self.processor.read_xml()\n self.assertIsNotNone(root)\n lst = root.findall('item')\n self.assertEqual(lst[0].text, 'apple')\n\n os.remove('test.xml')\n\n def test_read_xml_4(self):\n with open('test.xml', 'w') as f:\n f.write('\\n apple\\n banana\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n root = self.processor.read_xml()\n self.assertIsNotNone(root)\n lst = root.findall('item')\n self.assertEqual(lst[0].text, 'apple')\n self.assertEqual(lst[1].text, 'banana')\n\n os.remove('test.xml')\n\n def test_read_xml_5(self):\n with open('test.xml', 'w') as f:\n f.write('\\n apple\\n orange\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n root = self.processor.read_xml()\n self.assertIsNotNone(root)\n lst = root.findall('item')\n self.assertEqual(lst[0].text, 'apple')\n self.assertEqual(lst[1].text, 'orange')\n\n os.remove('test.xml')\n\n def test_read_xml_6(self):\n self.xml_file = ''\n self.processor = XMLProcessor(self.xml_file)\n\n root = self.processor.read_xml()\n self.assertIsNone(root)\n\n\nclass XMLProcessorTestWriteXml(unittest.TestCase):\n def test_write_xml_1(self):\n with open('test.xml', 'w') as f:\n f.write('\\n apple\\n banana\\n orange\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n file_name = 'output.xml'\n result = self.processor.write_xml(file_name)\n self.assertTrue(result)\n\n processor1 = XMLProcessor(file_name)\n tree1 = ET.parse(processor1.file_name)\n processor1.root = tree1.getroot()\n\n self.assertIsNotNone(processor1.root)\n lst = processor1.root.findall('item')\n self.assertEqual(lst[0].text, 'apple')\n self.assertEqual(lst[1].text, 'banana')\n self.assertEqual(lst[2].text, 'orange')\n\n os.remove('output.xml')\n os.remove('test.xml')\n\n def test_write_xml_2(self):\n with open('test.xml', 'w') as f:\n f.write('\\n apple\\n banana\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n file_name = 'output.xml'\n result = self.processor.write_xml(file_name)\n self.assertTrue(result)\n\n processor1 = XMLProcessor(file_name)\n tree1 = ET.parse(processor1.file_name)\n processor1.root = tree1.getroot()\n\n self.assertIsNotNone(processor1.root)\n lst = processor1.root.findall('item')\n self.assertEqual(lst[0].text, 'apple')\n self.assertEqual(lst[1].text, 'banana')\n\n os.remove('output.xml')\n os.remove('test.xml')\n\n def test_write_xml_3(self):\n with open('test.xml', 'w') as f:\n f.write('\\n apple\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n file_name = 'output.xml'\n result = self.processor.write_xml(file_name)\n self.assertTrue(result)\n\n processor1 = XMLProcessor(file_name)\n tree1 = ET.parse(processor1.file_name)\n processor1.root = tree1.getroot()\n\n self.assertIsNotNone(processor1.root)\n lst = processor1.root.findall('item')\n self.assertEqual(lst[0].text, 'apple')\n\n os.remove('output.xml')\n os.remove('test.xml')\n\n def test_write_xml_4(self):\n with open('test.xml', 'w') as f:\n f.write('\\n aaa\\n bbb\\n ccc\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n file_name = 'output.xml'\n result = self.processor.write_xml(file_name)\n self.assertTrue(result)\n\n processor1 = XMLProcessor(file_name)\n tree1 = ET.parse(processor1.file_name)\n processor1.root = tree1.getroot()\n\n self.assertIsNotNone(processor1.root)\n lst = processor1.root.findall('item')\n self.assertEqual(lst[0].text, 'aaa')\n self.assertEqual(lst[1].text, 'bbb')\n self.assertEqual(lst[2].text, 'ccc')\n\n os.remove('output.xml')\n os.remove('test.xml')\n\n def test_write_xml_5(self):\n with open('test.xml', 'w') as f:\n f.write('\\n apple\\n orange\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n file_name = 'output.xml'\n result = self.processor.write_xml(file_name)\n self.assertTrue(result)\n\n processor1 = XMLProcessor(file_name)\n tree1 = ET.parse(processor1.file_name)\n processor1.root = tree1.getroot()\n\n self.assertIsNotNone(processor1.root)\n lst = processor1.root.findall('item')\n self.assertEqual(lst[0].text, 'apple')\n self.assertEqual(lst[1].text, 'orange')\n\n os.remove('output.xml')\n os.remove('test.xml')\n\n def test_write_xml_6(self):\n self.xml_file = ''\n self.processor = XMLProcessor(self.xml_file)\n\n result = self.processor.write_xml(\"\")\n self.assertFalse(result)\n\n\nclass XMLProcessorTestProcessXmlData(unittest.TestCase):\n def test_process_xml_data_1(self):\n with open('test.xml', 'w') as f:\n f.write('\\n apple\\n banana\\n orange\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n file_name = 'processed.xml'\n result = self.processor.process_xml_data(file_name)\n self.assertTrue(result)\n\n processor1 = XMLProcessor(file_name)\n tree1 = ET.parse(processor1.file_name)\n processor1.root = tree1.getroot()\n\n self.assertIsNotNone(processor1.root)\n lst = processor1.root.findall('item')\n self.assertEqual(lst[0].text, 'APPLE')\n self.assertEqual(lst[1].text, 'BANANA')\n self.assertEqual(lst[2].text, 'ORANGE')\n\n os.remove('processed.xml')\n os.remove('test.xml')\n\n def test_process_xml_data_2(self):\n with open('test.xml', 'w') as f:\n f.write('\\n apple\\n banana\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n file_name = 'processed.xml'\n result = self.processor.process_xml_data(file_name)\n self.assertTrue(result)\n\n processor1 = XMLProcessor(file_name)\n tree1 = ET.parse(processor1.file_name)\n processor1.root = tree1.getroot()\n\n self.assertIsNotNone(processor1.root)\n lst = processor1.root.findall('item')\n self.assertEqual(lst[0].text, 'APPLE')\n self.assertEqual(lst[1].text, 'BANANA')\n\n os.remove('processed.xml')\n os.remove('test.xml')\n\n def test_process_xml_data_3(self):\n with open('test.xml', 'w') as f:\n f.write('\\n apple\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n file_name = 'processed.xml'\n result = self.processor.process_xml_data(file_name)\n self.assertTrue(result)\n\n processor1 = XMLProcessor(file_name)\n tree1 = ET.parse(processor1.file_name)\n processor1.root = tree1.getroot()\n\n self.assertIsNotNone(processor1.root)\n lst = processor1.root.findall('item')\n self.assertEqual(lst[0].text, 'APPLE')\n\n os.remove('processed.xml')\n os.remove('test.xml')\n\n def test_process_xml_data_4(self):\n with open('test.xml', 'w') as f:\n f.write('\\n apple\\n orange\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n file_name = 'processed.xml'\n result = self.processor.process_xml_data(file_name)\n self.assertTrue(result)\n\n processor1 = XMLProcessor(file_name)\n tree1 = ET.parse(processor1.file_name)\n processor1.root = tree1.getroot()\n\n self.assertIsNotNone(processor1.root)\n lst = processor1.root.findall('item')\n self.assertEqual(lst[0].text, 'APPLE')\n self.assertEqual(lst[1].text, 'ORANGE')\n\n os.remove('processed.xml')\n os.remove('test.xml')\n\n def test_process_xml_data_5(self):\n with open('test.xml', 'w') as f:\n f.write('\\n aaa\\n bbb\\n ccc\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n file_name = 'processed.xml'\n result = self.processor.process_xml_data(file_name)\n self.assertTrue(result)\n\n processor1 = XMLProcessor(file_name)\n tree1 = ET.parse(processor1.file_name)\n processor1.root = tree1.getroot()\n\n self.assertIsNotNone(processor1.root)\n lst = processor1.root.findall('item')\n self.assertEqual(lst[0].text, 'AAA')\n self.assertEqual(lst[1].text, 'BBB')\n self.assertEqual(lst[2].text, 'CCC')\n\n os.remove('processed.xml')\n os.remove('test.xml')\n\n\nclass XMLProcessorTestFindElement(unittest.TestCase):\n def test_find_element_1(self):\n with open('test.xml', 'w') as f:\n f.write('\\n apple\\n banana\\n orange\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n element_name = 'item'\n root = self.processor.read_xml()\n elements = self.processor.find_element(element_name)\n self.assertEqual(len(elements), 3)\n self.assertEqual(elements[0].text, 'apple')\n self.assertEqual(elements[1].text, 'banana')\n self.assertEqual(elements[2].text, 'orange')\n\n os.remove('test.xml')\n\n def test_find_element_2(self):\n with open('test.xml', 'w') as f:\n f.write('\\n apple\\n banana\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n element_name = 'item'\n root = self.processor.read_xml()\n elements = self.processor.find_element(element_name)\n self.assertEqual(len(elements), 2)\n self.assertEqual(elements[0].text, 'apple')\n self.assertEqual(elements[1].text, 'banana')\n\n os.remove('test.xml')\n\n def test_find_element_3(self):\n with open('test.xml', 'w') as f:\n f.write('\\n apple\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n element_name = 'item'\n root = self.processor.read_xml()\n elements = self.processor.find_element(element_name)\n self.assertEqual(len(elements), 1)\n self.assertEqual(elements[0].text, 'apple')\n\n os.remove('test.xml')\n\n def test_find_element_4(self):\n with open('test.xml', 'w') as f:\n f.write('\\n apple\\n orange\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n element_name = 'item'\n root = self.processor.read_xml()\n elements = self.processor.find_element(element_name)\n self.assertEqual(len(elements), 2)\n self.assertEqual(elements[0].text, 'apple')\n self.assertEqual(elements[1].text, 'orange')\n\n os.remove('test.xml')\n\n def test_find_element_5(self):\n with open('test.xml', 'w') as f:\n f.write('\\n aaa\\n bbb\\n ccc\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n element_name = 'item'\n root = self.processor.read_xml()\n elements = self.processor.find_element(element_name)\n self.assertEqual(len(elements), 3)\n self.assertEqual(elements[0].text, 'aaa')\n self.assertEqual(elements[1].text, 'bbb')\n self.assertEqual(elements[2].text, 'ccc')\n\n os.remove('test.xml')\n\n\nclass XMLProcessorTest(unittest.TestCase):\n def test_XMLProcessor(self):\n with open('test.xml', 'w') as f:\n f.write('\\n apple\\n banana\\n orange\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n root = self.processor.read_xml()\n self.assertIsNotNone(root)\n lst = root.findall('item')\n self.assertEqual(lst[0].text, 'apple')\n self.assertEqual(lst[1].text, 'banana')\n self.assertEqual(lst[2].text, 'orange')\n\n file_name = 'output.xml'\n result = self.processor.write_xml(file_name)\n self.assertTrue(result)\n\n processor1 = XMLProcessor(file_name)\n tree1 = ET.parse(processor1.file_name)\n processor1.root = tree1.getroot()\n\n self.assertIsNotNone(processor1.root)\n lst = processor1.root.findall('item')\n self.assertEqual(lst[0].text, 'apple')\n self.assertEqual(lst[1].text, 'banana')\n self.assertEqual(lst[2].text, 'orange')\n\n os.remove('output.xml')\n\n file_name = 'processed.xml'\n result = self.processor.process_xml_data(file_name)\n self.assertTrue(result)\n\n processor1 = XMLProcessor(file_name)\n tree1 = ET.parse(processor1.file_name)\n processor1.root = tree1.getroot()\n\n self.assertIsNotNone(processor1.root)\n lst = processor1.root.findall('item')\n self.assertEqual(lst[0].text, 'APPLE')\n self.assertEqual(lst[1].text, 'BANANA')\n self.assertEqual(lst[2].text, 'ORANGE')\n\n os.remove('processed.xml')\n\n element_name = 'item'\n root = self.processor.read_xml()\n elements = self.processor.find_element(element_name)\n self.assertEqual(len(elements), 3)\n self.assertEqual(elements[0].text, 'apple')\n self.assertEqual(elements[1].text, 'banana')\n self.assertEqual(elements[2].text, 'orange')\n\n os.remove('test.xml')", "solution_code": "import xml.etree.ElementTree as ET\n\n\nclass XMLProcessor:\n def __init__(self, file_name):\n self.file_name = file_name\n self.root = None\n\n def read_xml(self):\n try:\n tree = ET.parse(self.file_name)\n self.root = tree.getroot()\n return self.root\n except:\n return None\n\n def write_xml(self, file_name):\n try:\n tree = ET.ElementTree(self.root)\n tree.write(file_name)\n return True\n except:\n return False\n\n def process_xml_data(self, file_name):\n for element in self.root.iter('item'):\n text = element.text\n element.text = text.upper()\n return self.write_xml(file_name)\n\n def find_element(self, element_name):\n elements = self.root.findall(element_name)\n return elements", "import_statement": [ "import xml.etree.ElementTree as ET" ], "class_description": " \"\"\"\n This is a class as XML files handler, including reading, writing, processing as well as finding elements in a XML file.\n \"\"\"\n", "class_name": "XMLProcessor", "test_classes": [ "XMLProcessorTestReadXml", "XMLProcessorTestWriteXml", "XMLProcessorTestProcessXmlData", "XMLProcessorTestFindElement", "XMLProcessorTest" ], "class_constructor": "class XMLProcessor: \n def __init__(self, file_name):\n \"\"\"\n Initialize the XMLProcessor object with the given file name.\n :param file_name:string, the name of the XML file to be processed.\n \"\"\"\n self.file_name = file_name\n self.root = None\n\n", "fields": [ "self.file_name", "self.root" ], "methods_info": [ { "method_name": "read_xml", "method_description": "def read_xml(self):\n \"\"\"\n Reads the XML file and returns the root element.\n :return: Element, the root element of the XML file.\n >>> xml_processor = XMLProcessor('test.xml')\n >>> root_element = xml_processor.read_xml()\n >>> print(root_element)\n \n \"\"\"", "test_class": "XMLProcessorTestReadXml", "test_code": "class XMLProcessorTestReadXml(unittest.TestCase):\n def test_read_xml_1(self):\n with open('test.xml', 'w') as f:\n f.write('\\n apple\\n banana\\n orange\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n root = self.processor.read_xml()\n self.assertIsNotNone(root)\n lst = root.findall('item')\n self.assertEqual(lst[0].text, 'apple')\n self.assertEqual(lst[1].text, 'banana')\n self.assertEqual(lst[2].text, 'orange')\n\n os.remove('test.xml')\n\n def test_read_xml_2(self):\n with open('test.xml', 'w') as f:\n f.write('\\n aaa\\n bbb\\n ccc\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n root = self.processor.read_xml()\n self.assertIsNotNone(root)\n lst = root.findall('item')\n self.assertEqual(lst[0].text, 'aaa')\n self.assertEqual(lst[1].text, 'bbb')\n self.assertEqual(lst[2].text, 'ccc')\n\n os.remove('test.xml')\n\n def test_read_xml_3(self):\n with open('test.xml', 'w') as f:\n f.write('\\n apple\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n root = self.processor.read_xml()\n self.assertIsNotNone(root)\n lst = root.findall('item')\n self.assertEqual(lst[0].text, 'apple')\n\n os.remove('test.xml')\n\n def test_read_xml_4(self):\n with open('test.xml', 'w') as f:\n f.write('\\n apple\\n banana\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n root = self.processor.read_xml()\n self.assertIsNotNone(root)\n lst = root.findall('item')\n self.assertEqual(lst[0].text, 'apple')\n self.assertEqual(lst[1].text, 'banana')\n\n os.remove('test.xml')\n\n def test_read_xml_5(self):\n with open('test.xml', 'w') as f:\n f.write('\\n apple\\n orange\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n root = self.processor.read_xml()\n self.assertIsNotNone(root)\n lst = root.findall('item')\n self.assertEqual(lst[0].text, 'apple')\n self.assertEqual(lst[1].text, 'orange')\n\n os.remove('test.xml')\n\n def test_read_xml_6(self):\n self.xml_file = ''\n self.processor = XMLProcessor(self.xml_file)\n\n root = self.processor.read_xml()\n self.assertIsNone(root)", "solution_code": "def read_xml(self):\n try:\n tree = ET.parse(self.file_name)\n self.root = tree.getroot()\n return self.root\n except:\n return None", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.file_name", "self.root" ], "method_dependencies": [] } }, { "method_name": "write_xml", "method_description": "def write_xml(self, file_name):\n \"\"\"\n Writes the XML data to the specified file.\n :param file_name: string, the name of the file to write the XML data.\n :return: bool, True if the write operation is successful, False otherwise.\n >>> xml_processor = XMLProcessor('test.xml')\n >>> root = xml_processor.read_xml()\n >>> success = xml_processor.write_xml('output.xml')\n >>> print(success)\n True\n \"\"\"", "test_class": "XMLProcessorTestWriteXml", "test_code": "class XMLProcessorTestWriteXml(unittest.TestCase):\n def test_write_xml_1(self):\n with open('test.xml', 'w') as f:\n f.write('\\n apple\\n banana\\n orange\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n file_name = 'output.xml'\n result = self.processor.write_xml(file_name)\n self.assertTrue(result)\n\n processor1 = XMLProcessor(file_name)\n tree1 = ET.parse(processor1.file_name)\n processor1.root = tree1.getroot()\n\n self.assertIsNotNone(processor1.root)\n lst = processor1.root.findall('item')\n self.assertEqual(lst[0].text, 'apple')\n self.assertEqual(lst[1].text, 'banana')\n self.assertEqual(lst[2].text, 'orange')\n\n os.remove('output.xml')\n os.remove('test.xml')\n\n def test_write_xml_2(self):\n with open('test.xml', 'w') as f:\n f.write('\\n apple\\n banana\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n file_name = 'output.xml'\n result = self.processor.write_xml(file_name)\n self.assertTrue(result)\n\n processor1 = XMLProcessor(file_name)\n tree1 = ET.parse(processor1.file_name)\n processor1.root = tree1.getroot()\n\n self.assertIsNotNone(processor1.root)\n lst = processor1.root.findall('item')\n self.assertEqual(lst[0].text, 'apple')\n self.assertEqual(lst[1].text, 'banana')\n\n os.remove('output.xml')\n os.remove('test.xml')\n\n def test_write_xml_3(self):\n with open('test.xml', 'w') as f:\n f.write('\\n apple\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n file_name = 'output.xml'\n result = self.processor.write_xml(file_name)\n self.assertTrue(result)\n\n processor1 = XMLProcessor(file_name)\n tree1 = ET.parse(processor1.file_name)\n processor1.root = tree1.getroot()\n\n self.assertIsNotNone(processor1.root)\n lst = processor1.root.findall('item')\n self.assertEqual(lst[0].text, 'apple')\n\n os.remove('output.xml')\n os.remove('test.xml')\n\n def test_write_xml_4(self):\n with open('test.xml', 'w') as f:\n f.write('\\n aaa\\n bbb\\n ccc\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n file_name = 'output.xml'\n result = self.processor.write_xml(file_name)\n self.assertTrue(result)\n\n processor1 = XMLProcessor(file_name)\n tree1 = ET.parse(processor1.file_name)\n processor1.root = tree1.getroot()\n\n self.assertIsNotNone(processor1.root)\n lst = processor1.root.findall('item')\n self.assertEqual(lst[0].text, 'aaa')\n self.assertEqual(lst[1].text, 'bbb')\n self.assertEqual(lst[2].text, 'ccc')\n\n os.remove('output.xml')\n os.remove('test.xml')\n\n def test_write_xml_5(self):\n with open('test.xml', 'w') as f:\n f.write('\\n apple\\n orange\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n file_name = 'output.xml'\n result = self.processor.write_xml(file_name)\n self.assertTrue(result)\n\n processor1 = XMLProcessor(file_name)\n tree1 = ET.parse(processor1.file_name)\n processor1.root = tree1.getroot()\n\n self.assertIsNotNone(processor1.root)\n lst = processor1.root.findall('item')\n self.assertEqual(lst[0].text, 'apple')\n self.assertEqual(lst[1].text, 'orange')\n\n os.remove('output.xml')\n os.remove('test.xml')\n\n def test_write_xml_6(self):\n self.xml_file = ''\n self.processor = XMLProcessor(self.xml_file)\n\n result = self.processor.write_xml(\"\")\n self.assertFalse(result)", "solution_code": "def write_xml(self, file_name):\n try:\n tree = ET.ElementTree(self.root)\n tree.write(file_name)\n return True\n except:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.root" ], "method_dependencies": [] } }, { "method_name": "process_xml_data", "method_description": "def process_xml_data(self, file_name):\n \"\"\"\n Modifies the data in XML elements and writes the updated XML data to a new file.\n :param file_name: string, the name of the file to write the modified XML data.\n :return: bool, True if the write operation is successful, False otherwise.\n >>> xml_processor = XMLProcessor('test.xml')\n >>> root = xml_processor.read_xml()\n >>> success = xml_processor.process_xml_data('processed.xml')\n >>> print(success)\n True\n \"\"\"", "test_class": "XMLProcessorTestProcessXmlData", "test_code": "class XMLProcessorTestProcessXmlData(unittest.TestCase):\n def test_process_xml_data_1(self):\n with open('test.xml', 'w') as f:\n f.write('\\n apple\\n banana\\n orange\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n file_name = 'processed.xml'\n result = self.processor.process_xml_data(file_name)\n self.assertTrue(result)\n\n processor1 = XMLProcessor(file_name)\n tree1 = ET.parse(processor1.file_name)\n processor1.root = tree1.getroot()\n\n self.assertIsNotNone(processor1.root)\n lst = processor1.root.findall('item')\n self.assertEqual(lst[0].text, 'APPLE')\n self.assertEqual(lst[1].text, 'BANANA')\n self.assertEqual(lst[2].text, 'ORANGE')\n\n os.remove('processed.xml')\n os.remove('test.xml')\n\n def test_process_xml_data_2(self):\n with open('test.xml', 'w') as f:\n f.write('\\n apple\\n banana\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n file_name = 'processed.xml'\n result = self.processor.process_xml_data(file_name)\n self.assertTrue(result)\n\n processor1 = XMLProcessor(file_name)\n tree1 = ET.parse(processor1.file_name)\n processor1.root = tree1.getroot()\n\n self.assertIsNotNone(processor1.root)\n lst = processor1.root.findall('item')\n self.assertEqual(lst[0].text, 'APPLE')\n self.assertEqual(lst[1].text, 'BANANA')\n\n os.remove('processed.xml')\n os.remove('test.xml')\n\n def test_process_xml_data_3(self):\n with open('test.xml', 'w') as f:\n f.write('\\n apple\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n file_name = 'processed.xml'\n result = self.processor.process_xml_data(file_name)\n self.assertTrue(result)\n\n processor1 = XMLProcessor(file_name)\n tree1 = ET.parse(processor1.file_name)\n processor1.root = tree1.getroot()\n\n self.assertIsNotNone(processor1.root)\n lst = processor1.root.findall('item')\n self.assertEqual(lst[0].text, 'APPLE')\n\n os.remove('processed.xml')\n os.remove('test.xml')\n\n def test_process_xml_data_4(self):\n with open('test.xml', 'w') as f:\n f.write('\\n apple\\n orange\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n file_name = 'processed.xml'\n result = self.processor.process_xml_data(file_name)\n self.assertTrue(result)\n\n processor1 = XMLProcessor(file_name)\n tree1 = ET.parse(processor1.file_name)\n processor1.root = tree1.getroot()\n\n self.assertIsNotNone(processor1.root)\n lst = processor1.root.findall('item')\n self.assertEqual(lst[0].text, 'APPLE')\n self.assertEqual(lst[1].text, 'ORANGE')\n\n os.remove('processed.xml')\n os.remove('test.xml')\n\n def test_process_xml_data_5(self):\n with open('test.xml', 'w') as f:\n f.write('\\n aaa\\n bbb\\n ccc\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n file_name = 'processed.xml'\n result = self.processor.process_xml_data(file_name)\n self.assertTrue(result)\n\n processor1 = XMLProcessor(file_name)\n tree1 = ET.parse(processor1.file_name)\n processor1.root = tree1.getroot()\n\n self.assertIsNotNone(processor1.root)\n lst = processor1.root.findall('item')\n self.assertEqual(lst[0].text, 'AAA')\n self.assertEqual(lst[1].text, 'BBB')\n self.assertEqual(lst[2].text, 'CCC')\n\n os.remove('processed.xml')\n os.remove('test.xml')", "solution_code": "def process_xml_data(self, file_name):\n for element in self.root.iter('item'):\n text = element.text\n element.text = text.upper()\n return self.write_xml(file_name)", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.root" ], "method_dependencies": [ "write_xml" ] } }, { "method_name": "find_element", "method_description": "def find_element(self, element_name):\n \"\"\"\n Finds the XML elements with the specified name.\n :param element_name: string, the name of the elements to find.\n :return: list, a list of found elements with the specified name.\n >>> xml_processor = XMLProcessor('test.xml')\n >>> root = xml_processor.read_xml()\n >>> items = xml_processor.find_element('item')\n >>> for item in items:\n >>> print(item.text)\n apple\n banana\n orange\n \"\"\"", "test_class": "XMLProcessorTestFindElement", "test_code": "class XMLProcessorTestFindElement(unittest.TestCase):\n def test_find_element_1(self):\n with open('test.xml', 'w') as f:\n f.write('\\n apple\\n banana\\n orange\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n element_name = 'item'\n root = self.processor.read_xml()\n elements = self.processor.find_element(element_name)\n self.assertEqual(len(elements), 3)\n self.assertEqual(elements[0].text, 'apple')\n self.assertEqual(elements[1].text, 'banana')\n self.assertEqual(elements[2].text, 'orange')\n\n os.remove('test.xml')\n\n def test_find_element_2(self):\n with open('test.xml', 'w') as f:\n f.write('\\n apple\\n banana\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n element_name = 'item'\n root = self.processor.read_xml()\n elements = self.processor.find_element(element_name)\n self.assertEqual(len(elements), 2)\n self.assertEqual(elements[0].text, 'apple')\n self.assertEqual(elements[1].text, 'banana')\n\n os.remove('test.xml')\n\n def test_find_element_3(self):\n with open('test.xml', 'w') as f:\n f.write('\\n apple\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n element_name = 'item'\n root = self.processor.read_xml()\n elements = self.processor.find_element(element_name)\n self.assertEqual(len(elements), 1)\n self.assertEqual(elements[0].text, 'apple')\n\n os.remove('test.xml')\n\n def test_find_element_4(self):\n with open('test.xml', 'w') as f:\n f.write('\\n apple\\n orange\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n element_name = 'item'\n root = self.processor.read_xml()\n elements = self.processor.find_element(element_name)\n self.assertEqual(len(elements), 2)\n self.assertEqual(elements[0].text, 'apple')\n self.assertEqual(elements[1].text, 'orange')\n\n os.remove('test.xml')\n\n def test_find_element_5(self):\n with open('test.xml', 'w') as f:\n f.write('\\n aaa\\n bbb\\n ccc\\n')\n self.xml_file = 'test.xml'\n self.processor = XMLProcessor(self.xml_file)\n tree = ET.parse(self.processor.file_name)\n self.processor.root = tree.getroot()\n\n element_name = 'item'\n root = self.processor.read_xml()\n elements = self.processor.find_element(element_name)\n self.assertEqual(len(elements), 3)\n self.assertEqual(elements[0].text, 'aaa')\n self.assertEqual(elements[1].text, 'bbb')\n self.assertEqual(elements[2].text, 'ccc')\n\n os.remove('test.xml')", "solution_code": "def find_element(self, element_name):\n elements = self.root.findall(element_name)\n return elements", "dependencies": { "Standalone": false, "lib_dependencies": [], "field_dependencies": [ "self.root" ], "method_dependencies": [] } } ] }, { "task_id": "ClassEval_99", "skeleton": "\nimport zipfile\n\n\nclass ZipFileProcessor:\n \"\"\"\n This is a compressed file processing class that provides the ability to read and decompress compressed files\n \"\"\"\n\n def __init__(self, file_name):\n \"\"\"\n Initialize file name\n :param file_name:string\n \"\"\"\n self.file_name = file_name\n\n def read_zip_file(self):\n \"\"\"\n Get open file object\n :return:If successful, returns the open file object; otherwise, returns None\n >>> zfp = ZipFileProcessor(\"aaa.zip\")\n >>> file = zfp.read_zip_file()\n \"\"\"\n\n def extract_all(self, output_path):\n \"\"\"\n Extract all zip files and place them in the specified path\n :param output_path: string, The location of the extracted file\n :return: True or False, representing whether the extraction operation was successful\n >>> zfp = ZipFileProcessor(\"aaa.zip\")\n >>> zfp.extract_all(\"result/aaa\")\n \"\"\"\n\n def extract_file(self, file_name, output_path):\n \"\"\"\n Extract the file with the specified name from the zip file and place it in the specified path\n :param file_name:string, The name of the file to be uncompressed\n :param output_path:string, The location of the extracted file\n :return: True or False, representing whether the extraction operation was successful\n >>> zfp = ZipFileProcessor(\"aaa.zip\")\n >>> zfp.extract_file(\"bbb.txt\", \"result/aaa\")\n \"\"\"\n\n def create_zip_file(self, files, output_file_name):\n \"\"\"\n Compress the specified file list into a zip file and place it in the specified path\n :param files:list of string, List of files to compress\n :param output_file_name: string, Specified output path\n :return:True or False, representing whether the compression operation was successful\n >>> zfp = ZipFileProcessor(\"aaa.zip\")\n >>> zfp.create_zip_file([\"bbb.txt\", \"ccc,txt\", \"ddd.txt\"], \"output/bcd\")\n \"\"\"", "test": "import unittest\nimport os\n\n\nclass ZipFileProcessorTestReadZipFile(unittest.TestCase):\n def test_read_zip_file_1(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example1.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n\n zip_file = processor.read_zip_file()\n self.assertEqual(zip_file.filename, 'example1.zip')\n self.assertEqual(zip_file.mode, 'r')\n zip_file.close()\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_read_zip_file_2(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example2.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n\n zip_file = processor.read_zip_file()\n self.assertEqual(zip_file.filename, 'example2.zip')\n self.assertEqual(zip_file.mode, 'r')\n zip_file.close()\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_read_zip_file_3(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example3.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n\n zip_file = processor.read_zip_file()\n self.assertEqual(zip_file.filename, 'example3.zip')\n self.assertEqual(zip_file.mode, 'r')\n zip_file.close()\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_read_zip_file_4(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example4.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n\n zip_file = processor.read_zip_file()\n self.assertEqual(zip_file.filename, 'example4.zip')\n self.assertEqual(zip_file.mode, 'r')\n zip_file.close()\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_read_zip_file_5(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example5.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n zip_file = processor.read_zip_file()\n self.assertEqual(zip_file.filename, 'example5.zip')\n self.assertEqual(zip_file.mode, 'r')\n zip_file.close()\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_read_zip_file_6(self):\n processor = ZipFileProcessor(\"\")\n\n zip_file = processor.read_zip_file()\n self.assertIsNone(zip_file)\n\n\nclass ZipFileProcessorTestExtractAll(unittest.TestCase):\n def test_extract_all_1(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example1.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n success = processor.extract_all(output_directory)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(os.path.join(output_directory, 'example1.txt')))\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_extract_all_2(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example2.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n success = processor.extract_all(output_directory)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(os.path.join(output_directory, 'example2.txt')))\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_extract_all_3(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example3.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n success = processor.extract_all(output_directory)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(os.path.join(output_directory, 'example3.txt')))\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_extract_all_4(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example4.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n success = processor.extract_all(output_directory)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(os.path.join(output_directory, 'example4.txt')))\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_extract_all_5(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example5.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n success = processor.extract_all(output_directory)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(os.path.join(output_directory, 'example5.txt')))\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_extract_all_6(self):\n processor = ZipFileProcessor(\"\")\n\n success = processor.extract_all(\"\")\n self.assertFalse(success)\n\n\nclass ZipFileProcessorTestExtractFile(unittest.TestCase):\n def test_extract_file_1(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example1.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n success = processor.extract_file('example1.txt', output_directory)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(os.path.join(output_directory, 'example1.txt')))\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_extract_file_2(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example2.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n success = processor.extract_file('example2.txt', output_directory)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(os.path.join(output_directory, 'example2.txt')))\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_extract_file_3(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example3.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n success = processor.extract_file('example3.txt', output_directory)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(os.path.join(output_directory, 'example3.txt')))\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_extract_file_4(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example4.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n success = processor.extract_file('example4.txt', output_directory)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(os.path.join(output_directory, 'example4.txt')))\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_extract_file_5(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example5.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n\n success = processor.extract_file('example5.txt', output_directory)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(os.path.join(output_directory, 'example5.txt')))\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_extract_file_6(self):\n processor = ZipFileProcessor(\"\")\n\n success = processor.extract_file(\"\", \"\")\n self.assertFalse(success)\n\n\nclass ZipFileProcessorTestCreateZipFile(unittest.TestCase):\n def test_create_zip_file_1(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example1.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n files_to_zip = [example_file_path]\n success = processor.create_zip_file(files_to_zip, new_zip_file)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(new_zip_file))\n\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_create_zip_file_2(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example2.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n files_to_zip = [example_file_path]\n success = processor.create_zip_file(files_to_zip, new_zip_file)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(new_zip_file))\n\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_create_zip_file_3(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example3.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n files_to_zip = [example_file_path]\n success = processor.create_zip_file(files_to_zip, new_zip_file)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(new_zip_file))\n\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_create_zip_file_4(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example4.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n files_to_zip = [example_file_path]\n success = processor.create_zip_file(files_to_zip, new_zip_file)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(new_zip_file))\n\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_create_zip_file_5(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example5.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n new_zip_file = 'new_zip_file.zip'\n\n files_to_zip = [example_file_path]\n success = processor.create_zip_file(files_to_zip, new_zip_file)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(new_zip_file))\n\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_create_zip_file_6(self):\n processor = ZipFileProcessor(\"\")\n\n success = processor.create_zip_file(\"\", \"\")\n self.assertFalse(success)\n\n\nclass ZipFileProcessorTest(unittest.TestCase):\n def test_ZipFileProcessor(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example1.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n zip_file = processor.read_zip_file()\n self.assertEqual(zip_file.filename, 'example.zip')\n self.assertEqual(zip_file.mode, 'r')\n zip_file.close()\n\n success = processor.extract_all(output_directory)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(os.path.join(output_directory, 'example1.txt')))\n\n files_to_zip = [example_file_path]\n success = processor.create_zip_file(files_to_zip, new_zip_file)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(new_zip_file))\n\n success = processor.extract_file('example1.txt', output_directory)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(os.path.join(output_directory, 'example1.txt')))\n\n files_to_zip = [example_file_path]\n success = processor.create_zip_file(files_to_zip, new_zip_file)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(new_zip_file))\n\n os.remove(example_file_path)\n os.rmdir(test_folder)", "solution_code": "import zipfile\n\n\nclass ZipFileProcessor:\n def __init__(self, file_name):\n self.file_name = file_name\n\n def read_zip_file(self):\n try:\n zip_file = zipfile.ZipFile(self.file_name, 'r')\n return zip_file\n except:\n return None\n\n def extract_all(self, output_path):\n try:\n with zipfile.ZipFile(self.file_name, 'r') as zip_file:\n zip_file.extractall(output_path)\n return True\n except:\n return False\n\n def extract_file(self, file_name, output_path):\n try:\n with zipfile.ZipFile(self.file_name, 'r') as zip_file:\n zip_file.extract(file_name, output_path)\n return True\n except:\n return False\n\n def create_zip_file(self, files, output_file_name):\n try:\n with zipfile.ZipFile(output_file_name, 'w') as zip_file:\n for file in files:\n zip_file.write(file)\n return True\n except:\n return False", "import_statement": [ "import zipfile" ], "class_description": " \"\"\"\n This is a compressed file processing class that provides the ability to read and decompress compressed files\n \"\"\"\n", "class_name": "ZipFileProcessor", "test_classes": [ "ZipFileProcessorTestReadZipFile", "ZipFileProcessorTestExtractAll", "ZipFileProcessorTestExtractFile", "ZipFileProcessorTestCreateZipFile", "ZipFileProcessorTest" ], "class_constructor": "class ZipFileProcessor: \n def __init__(self, file_name):\n \"\"\"\n Initialize file name\n :param file_name:string\n \"\"\"\n self.file_name = file_name\n\n", "fields": [ "self.file_name" ], "methods_info": [ { "method_name": "read_zip_file", "method_description": "def read_zip_file(self):\n \"\"\"\n Get open file object\n :return:If successful, returns the open file object; otherwise, returns None\n >>> zfp = ZipFileProcessor(\"aaa.zip\")\n >>> file = zfp.read_zip_file()\n \"\"\"", "test_class": "ZipFileProcessorTestReadZipFile", "test_code": "class ZipFileProcessorTestReadZipFile(unittest.TestCase):\n def test_read_zip_file_1(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example1.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n\n zip_file = processor.read_zip_file()\n self.assertEqual(zip_file.filename, 'example1.zip')\n self.assertEqual(zip_file.mode, 'r')\n zip_file.close()\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_read_zip_file_2(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example2.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n\n zip_file = processor.read_zip_file()\n self.assertEqual(zip_file.filename, 'example2.zip')\n self.assertEqual(zip_file.mode, 'r')\n zip_file.close()\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_read_zip_file_3(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example3.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n\n zip_file = processor.read_zip_file()\n self.assertEqual(zip_file.filename, 'example3.zip')\n self.assertEqual(zip_file.mode, 'r')\n zip_file.close()\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_read_zip_file_4(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example4.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n\n zip_file = processor.read_zip_file()\n self.assertEqual(zip_file.filename, 'example4.zip')\n self.assertEqual(zip_file.mode, 'r')\n zip_file.close()\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_read_zip_file_5(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example5.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n zip_file = processor.read_zip_file()\n self.assertEqual(zip_file.filename, 'example5.zip')\n self.assertEqual(zip_file.mode, 'r')\n zip_file.close()\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_read_zip_file_6(self):\n processor = ZipFileProcessor(\"\")\n\n zip_file = processor.read_zip_file()\n self.assertIsNone(zip_file)", "solution_code": "def read_zip_file(self):\n try:\n zip_file = zipfile.ZipFile(self.file_name, 'r')\n return zip_file\n except:\n return None", "dependencies": { "Standalone": false, "lib_dependencies": [ "zipfile" ], "field_dependencies": [ "self.file_name" ], "method_dependencies": [] } }, { "method_name": "extract_all", "method_description": "def extract_all(self, output_path):\n \"\"\"\n Extract all zip files and place them in the specified path\n :param output_path: string, The location of the extracted file\n :return: True or False, representing whether the extraction operation was successful\n >>> zfp = ZipFileProcessor(\"aaa.zip\")\n >>> zfp.extract_all(\"result/aaa\")\n \"\"\"", "test_class": "ZipFileProcessorTestExtractAll", "test_code": "class ZipFileProcessorTestExtractAll(unittest.TestCase):\n def test_extract_all_1(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example1.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n success = processor.extract_all(output_directory)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(os.path.join(output_directory, 'example1.txt')))\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_extract_all_2(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example2.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n success = processor.extract_all(output_directory)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(os.path.join(output_directory, 'example2.txt')))\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_extract_all_3(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example3.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n success = processor.extract_all(output_directory)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(os.path.join(output_directory, 'example3.txt')))\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_extract_all_4(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example4.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n success = processor.extract_all(output_directory)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(os.path.join(output_directory, 'example4.txt')))\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_extract_all_5(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example5.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n success = processor.extract_all(output_directory)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(os.path.join(output_directory, 'example5.txt')))\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_extract_all_6(self):\n processor = ZipFileProcessor(\"\")\n\n success = processor.extract_all(\"\")\n self.assertFalse(success)", "solution_code": "def extract_all(self, output_path):\n try:\n with zipfile.ZipFile(self.file_name, 'r') as zip_file:\n zip_file.extractall(output_path)\n return True\n except:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [ "zipfile" ], "field_dependencies": [ "self.file_name" ], "method_dependencies": [] } }, { "method_name": "extract_file", "method_description": "def extract_file(self, file_name, output_path):\n \"\"\"\n Extract the file with the specified name from the zip file and place it in the specified path\n :param file_name:string, The name of the file to be uncompressed\n :param output_path:string, The location of the extracted file\n :return: True or False, representing whether the extraction operation was successful\n >>> zfp = ZipFileProcessor(\"aaa.zip\")\n >>> zfp.extract_file(\"bbb.txt\", \"result/aaa\")\n \"\"\"", "test_class": "ZipFileProcessorTestExtractFile", "test_code": "class ZipFileProcessorTestExtractFile(unittest.TestCase):\n def test_extract_file_1(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example1.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n success = processor.extract_file('example1.txt', output_directory)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(os.path.join(output_directory, 'example1.txt')))\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_extract_file_2(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example2.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n success = processor.extract_file('example2.txt', output_directory)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(os.path.join(output_directory, 'example2.txt')))\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_extract_file_3(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example3.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n success = processor.extract_file('example3.txt', output_directory)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(os.path.join(output_directory, 'example3.txt')))\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_extract_file_4(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example4.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n success = processor.extract_file('example4.txt', output_directory)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(os.path.join(output_directory, 'example4.txt')))\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_extract_file_5(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example5.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n\n success = processor.extract_file('example5.txt', output_directory)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(os.path.join(output_directory, 'example5.txt')))\n\n os.remove(zip_file_name)\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_extract_file_6(self):\n processor = ZipFileProcessor(\"\")\n\n success = processor.extract_file(\"\", \"\")\n self.assertFalse(success)", "solution_code": "def extract_file(self, file_name, output_path):\n try:\n with zipfile.ZipFile(self.file_name, 'r') as zip_file:\n zip_file.extract(file_name, output_path)\n return True\n except:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [ "zipfile" ], "field_dependencies": [ "self.file_name" ], "method_dependencies": [] } }, { "method_name": "create_zip_file", "method_description": "def create_zip_file(self, files, output_file_name):\n \"\"\"\n Compress the specified file list into a zip file and place it in the specified path\n :param files:list of string, List of files to compress\n :param output_file_name: string, Specified output path\n :return:True or False, representing whether the compression operation was successful\n >>> zfp = ZipFileProcessor(\"aaa.zip\")\n >>> zfp.create_zip_file([\"bbb.txt\", \"ccc,txt\", \"ddd.txt\"], \"output/bcd\")\n \"\"\"", "test_class": "ZipFileProcessorTestCreateZipFile", "test_code": "class ZipFileProcessorTestCreateZipFile(unittest.TestCase):\n def test_create_zip_file_1(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example1.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n files_to_zip = [example_file_path]\n success = processor.create_zip_file(files_to_zip, new_zip_file)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(new_zip_file))\n\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_create_zip_file_2(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example2.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n files_to_zip = [example_file_path]\n success = processor.create_zip_file(files_to_zip, new_zip_file)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(new_zip_file))\n\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_create_zip_file_3(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example3.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n files_to_zip = [example_file_path]\n success = processor.create_zip_file(files_to_zip, new_zip_file)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(new_zip_file))\n\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_create_zip_file_4(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example4.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n output_directory = 'output_directory'\n new_zip_file = 'new_zip_file.zip'\n\n files_to_zip = [example_file_path]\n success = processor.create_zip_file(files_to_zip, new_zip_file)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(new_zip_file))\n\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_create_zip_file_5(self):\n test_folder = 'test_folder'\n os.makedirs(test_folder, exist_ok=True)\n example_file_path = os.path.join(test_folder, 'example5.txt')\n with open(example_file_path, 'w') as file:\n file.write('This is an example file.')\n\n zip_file_name = 'example.zip'\n with zipfile.ZipFile(zip_file_name, 'w') as zip_file:\n zip_file.write(example_file_path, os.path.basename(example_file_path))\n\n processor = ZipFileProcessor(zip_file_name)\n new_zip_file = 'new_zip_file.zip'\n\n files_to_zip = [example_file_path]\n success = processor.create_zip_file(files_to_zip, new_zip_file)\n self.assertTrue(success)\n self.assertTrue(os.path.exists(new_zip_file))\n\n os.remove(example_file_path)\n os.rmdir(test_folder)\n\n def test_create_zip_file_6(self):\n processor = ZipFileProcessor(\"\")\n\n success = processor.create_zip_file(\"\", \"\")\n self.assertFalse(success)", "solution_code": "def create_zip_file(self, files, output_file_name):\n try:\n with zipfile.ZipFile(output_file_name, 'w') as zip_file:\n for file in files:\n zip_file.write(file)\n return True\n except:\n return False", "dependencies": { "Standalone": false, "lib_dependencies": [ "zipfile" ], "field_dependencies": [], "method_dependencies": [] } } ] } ]