class_id stringlengths 15 16 | class_code stringlengths 519 6.03k | skeleton stringlengths 561 4.56k | method_code stringlengths 44 1.82k | method_summary stringlengths 15 540 |
|---|---|---|---|---|
ClassEval_24_sum | class ComplexCalculator:
"""
This is a class that implements addition, subtraction, multiplication, and division operations for complex numbers.
"""
def __init__(self):
pass
@staticmethod
def add(c1, c2):
"""
Adds two complex numbers.
:param c1: The first complex... | class ComplexCalculator:
"""
This is a class that implements addition, subtraction, multiplication, and division operations for complex numbers.
"""
def __init__(self):
pass
@staticmethod
def add(c1, c2):
"""
Adds two complex numbers.
:param c1: The first compl... | @staticmethod
def divide(c1, c2):
denominator = c2.real**2 + c2.imag**2
real = (c1.real * c2.real + c1.imag * c2.imag) / denominator
imaginary = (c1.imag * c2.real - c1.real * c2.imag) / denominator
return complex(real, imaginary) | Divides two complex numbers. |
ClassEval_25_sum | import json
class CookiesUtil:
"""
This is a class as utility for managing and manipulating Cookies, including methods for retrieving, saving, and setting Cookies data.
"""
def __init__(self, cookies_file):
self.cookies_file = cookies_file
self.cookies = None
def load_cookies(self)... | import json
class CookiesUtil:
"""
This is a class as utility for managing and manipulating Cookies, including methods for retrieving, saving, and setting Cookies data.
"""
def __init__(self, cookies_file):
"""
Initializes the CookiesUtil with the specified cookies file.
:param... | def get_cookies(self, reponse):
self.cookies = reponse['cookies']
self._save_cookies() | Gets the cookies from the specified response,and save it to cookies_file. |
ClassEval_25_sum | import json
class CookiesUtil:
"""
This is a class as utility for managing and manipulating Cookies, including methods for retrieving, saving, and setting Cookies data.
"""
def __init__(self, cookies_file):
self.cookies_file = cookies_file
self.cookies = None
def get_cookies(self, ... | import json
class CookiesUtil:
"""
This is a class as utility for managing and manipulating Cookies, including methods for retrieving, saving, and setting Cookies data.
"""
def __init__(self, cookies_file):
"""
Initializes the CookiesUtil with the specified cookies file.
:param... | def load_cookies(self):
try:
with open(self.cookies_file, 'r') as file:
cookies_data = json.load(file)
return cookies_data
except FileNotFoundError:
return {} | Loads the cookies from the cookies_file to the cookies data. |
ClassEval_25_sum | import json
class CookiesUtil:
"""
This is a class as utility for managing and manipulating Cookies, including methods for retrieving, saving, and setting Cookies data.
"""
def __init__(self, cookies_file):
self.cookies_file = cookies_file
self.cookies = None
def get_cookies(self, ... | import json
class CookiesUtil:
"""
This is a class as utility for managing and manipulating Cookies, including methods for retrieving, saving, and setting Cookies data.
"""
def __init__(self, cookies_file):
"""
Initializes the CookiesUtil with the specified cookies file.
:param... | def _save_cookies(self):
try:
with open(self.cookies_file, 'w') as file:
json.dump(self.cookies, file)
return True
except:
return False | Saves the cookies to the cookies_file, and returns True if successful, False otherwise. |
ClassEval_26_sum | import csv
class CSVProcessor:
"""
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.
"""
def __init__(self):
pass
def write_csv(self, data, file_name):
"""
Write data ... | import csv
class CSVProcessor:
"""
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.
"""
def __init__(self):
pass
def write_csv(self, data, file_name):
"""
Write ... | def read_csv(self, file_name):
data = []
with open(file_name, 'r') as file:
reader = csv.reader(file)
title = next(reader)
for row in reader:
data.append(row)
return title, data | Read the csv file by file_name, get the title and data from it |
ClassEval_26_sum | import csv
class CSVProcessor:
"""
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.
"""
def __init__(self):
pass
def read_csv(self, file_name):
"""
Read the csv file ... | import csv
class CSVProcessor:
"""
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.
"""
def __init__(self):
pass
def read_csv(self, file_name):
"""
Read the csv file ... | def write_csv(self, data, file_name):
try:
with open(file_name, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
return 1
except:
return 0 | Write data into a csv file. |
ClassEval_26_sum | import csv
class CSVProcessor:
"""
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.
"""
def __init__(self):
pass
def read_csv(self, file_name):
"""
Read the csv file ... | import csv
class CSVProcessor:
"""
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.
"""
def __init__(self):
pass
def read_csv(self, file_name):
"""
Read the csv file ... | def process_csv_data(self, N, save_file_name):
title, data = self.read_csv(save_file_name)
column_data = [row[N] for row in data]
column_data = [row.upper() for row in column_data]
new_data = [title, column_data]
return self.write_csv(new_data, save_file_name.split('.')[0] + '_pr... | Read a csv file into variable title and data. Only remain the N th (from 0) column data and Capitalize them, store the title and new data into a new csv file. Add '_process' suffix after old file name, as a new file name. |
ClassEval_27_sum | class CurrencyConverter:
"""
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.
"""
def __init__(self):
self.rates = {
'USD': 1.0,
... | class CurrencyConverter:
"""
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.
"""
def __init__(self):
"""
Initialize the exchange rate of th... | def convert(self, amount, from_currency, to_currency):
if from_currency == to_currency:
return amount
if from_currency not in self.rates or to_currency not in self.rates:
return False
from_rate = self.rates[from_currency]
to_rate = self.rates[to_currency]
... | Convert the value of a given currency to another currency type |
ClassEval_27_sum | class CurrencyConverter:
"""
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.
"""
def __init__(self):
self.rates = {
'USD': 1.0,
... | class CurrencyConverter:
"""
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.
"""
def __init__(self):
"""
Initialize the exchange rate of th... | def get_supported_currencies(self):
return list(self.rates.keys()) | Returns a list of supported currency types |
ClassEval_27_sum | class CurrencyConverter:
"""
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.
"""
def __init__(self):
self.rates = {
'USD': 1.0,
... | class CurrencyConverter:
"""
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.
"""
def __init__(self):
"""
Initialize the exchange rate of th... | def add_currency_rate(self, currency, rate):
if currency in self.rates:
return False
self.rates[currency] = rate | Add a new supported currency type, return False if the currency type is already in the support list |
ClassEval_27_sum | class CurrencyConverter:
"""
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.
"""
def __init__(self):
self.rates = {
'USD': 1.0,
... | class CurrencyConverter:
"""
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.
"""
def __init__(self):
"""
Initialize the exchange rate of th... | def update_currency_rate(self, currency, new_rate):
if currency not in self.rates:
return False
self.rates[currency] = new_rate | Update the exchange rate for a certain currency |
ClassEval_28_sum | import sqlite3
import pandas as pd
class DatabaseProcessor:
"""
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.
"""
def __init__(self, database_name):
self.database_name = ... | import sqlite3
import pandas as pd
class DatabaseProcessor:
"""
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.
"""
def __init__(self, database_name):
"""
Initializ... | def create_table(self, table_name, key1, key2):
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
create_table_query = f"CREATE TABLE IF NOT EXISTS {table_name} (id INTEGER PRIMARY KEY, {key1} TEXT, {key2} INTEGER)"
cursor.execute(create_table_query)
conn.commit... | Create a new table in the database if it doesn't exist. And make id (INTEGER) as PRIMARY KEY, make key1 as TEXT, key2 as INTEGER |
ClassEval_28_sum | import sqlite3
import pandas as pd
class DatabaseProcessor:
"""
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.
"""
def __init__(self, database_name):
self.database_name = ... | import sqlite3
import pandas as pd
class DatabaseProcessor:
"""
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.
"""
def __init__(self, database_name):
"""
Initializ... | def insert_into_database(self, table_name, data):
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
for item in data:
insert_query = f"INSERT INTO {table_name} (name, age) VALUES (?, ?)"
cursor.execute(insert_query, (item['name'], item['age']))
c... | Insert data into the specified table in the database. |
ClassEval_28_sum | import sqlite3
import pandas as pd
class DatabaseProcessor:
"""
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.
"""
def __init__(self, database_name):
self.database_name = ... | import sqlite3
import pandas as pd
class DatabaseProcessor:
"""
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.
"""
def __init__(self, database_name):
"""
Initializ... | def search_database(self, table_name, name):
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
select_query = f"SELECT * FROM {table_name} WHERE name = ?"
cursor.execute(select_query, (name,))
result = cursor.fetchall()
if result:
return res... | Search the specified table in the database for rows with a matching name. |
ClassEval_28_sum | import sqlite3
import pandas as pd
class DatabaseProcessor:
"""
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.
"""
def __init__(self, database_name):
self.database_name = ... | import sqlite3
import pandas as pd
class DatabaseProcessor:
"""
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.
"""
def __init__(self, database_name):
"""
Initializ... | def delete_from_database(self, table_name, name):
conn = sqlite3.connect(self.database_name)
cursor = conn.cursor()
delete_query = f"DELETE FROM {table_name} WHERE name = ?"
cursor.execute(delete_query, (name,))
conn.commit()
conn.close() | Delete rows from the specified table in the database with a matching name. |
ClassEval_29_sum | from collections import Counter
class DataStatistics:
"""
This is a class for performing data statistics, supporting to calculate the mean, median, and mode of a given data set.
"""
def median(self, data):
"""
Calculate the median of a group of data, accurate to two digits after the De... | from collections import Counter
class DataStatistics:
"""
This is a class for performing data statistics, supporting to calculate the mean, median, and mode of a given data set.
"""
def median(self, data):
"""
Calculate the median of a group of data, accurate to two digits after t... | def mean(self, data):
return round(sum(data) / len(data), 2) | Calculate the average value of a group of data, accurate to two digits after the Decimal separator |
ClassEval_29_sum | from collections import Counter
class DataStatistics:
"""
This is a class for performing data statistics, supporting to calculate the mean, median, and mode of a given data set.
"""
def mean(self, data):
"""
Calculate the average value of a group of data, accurate to two digits after t... | from collections import Counter
class DataStatistics:
"""
This is a class for performing data statistics, supporting to calculate the mean, median, and mode of a given data set.
"""
def mean(self, data):
"""
Calculate the average value of a group of data, accurate to two digits after t... | def median(self, data):
sorted_data = sorted(data)
n = len(sorted_data)
if n % 2 == 0:
middle = n // 2
return round((sorted_data[middle - 1] + sorted_data[middle]) / 2, 2)
else:
middle = n // 2
return sorted_data[middle] | Calculate the median of a group of data, accurate to two digits after the Decimal separator |
ClassEval_29_sum | from collections import Counter
class DataStatistics:
"""
This is a class for performing data statistics, supporting to calculate the mean, median, and mode of a given data set.
"""
def mean(self, data):
"""
Calculate the average value of a group of data, accurate to two digits after t... | from collections import Counter
class DataStatistics:
"""
This is a class for performing data statistics, supporting to calculate the mean, median, and mode of a given data set.
"""
def mean(self, data):
"""
Calculate the average value of a group of data, accurate to two digits after t... | def mode(self, data):
counter = Counter(data)
mode_count = max(counter.values())
mode = [x for x, count in counter.items() if count == mode_count]
return mode | Calculate the mode of a set of data |
ClassEval_30_sum | import numpy as np
class DataStatistics2:
"""
This is a class for performing data statistics, supporting to get the sum, minimum, maximum, variance, standard deviation, and correlation of a given dataset.
"""
def __init__(self, data):
self.data = np.array(data)
def get_min(self):
... | import numpy as np
class DataStatistics2:
"""
This is a class for performing data statistics, supporting to get the sum, minimum, maximum, variance, standard deviation, and correlation of a given dataset.
"""
def __init__(self, data):
"""
Initialize Data List
:param data:list
... | def get_sum(self):
return np.sum(self.data) | Calculate the sum of data |
ClassEval_30_sum | import numpy as np
class DataStatistics2:
"""
This is a class for performing data statistics, supporting to get the sum, minimum, maximum, variance, standard deviation, and correlation of a given dataset.
"""
def __init__(self, data):
self.data = np.array(data)
def get_sum(self):
... | import numpy as np
class DataStatistics2:
"""
This is a class for performing data statistics, supporting to get the sum, minimum, maximum, variance, standard deviation, and correlation of a given dataset.
"""
def __init__(self, data):
"""
Initialize Data List
:param data:list
... | def get_min(self):
return np.min(self.data) | Calculate the minimum value in the data |
ClassEval_30_sum | import numpy as np
class DataStatistics2:
"""
This is a class for performing data statistics, supporting to get the sum, minimum, maximum, variance, standard deviation, and correlation of a given dataset.
"""
def __init__(self, data):
self.data = np.array(data)
def get_sum(self):
... | import numpy as np
class DataStatistics2:
"""
This is a class for performing data statistics, supporting to get the sum, minimum, maximum, variance, standard deviation, and correlation of a given dataset.
"""
def __init__(self, data):
"""
Initialize Data List
:param data:list
... | def get_max(self):
return np.max(self.data) | Calculate the maximum value in the data |
ClassEval_30_sum | import numpy as np
class DataStatistics2:
"""
This is a class for performing data statistics, supporting to get the sum, minimum, maximum, variance, standard deviation, and correlation of a given dataset.
"""
def __init__(self, data):
self.data = np.array(data)
def get_sum(self):
... | import numpy as np
class DataStatistics2:
"""
This is a class for performing data statistics, supporting to get the sum, minimum, maximum, variance, standard deviation, and correlation of a given dataset.
"""
def __init__(self, data):
"""
Initialize Data List
:param data:list
... | def get_variance(self):
return round(np.var(self.data), 2) | Calculate variance, accurate to two digits after the Decimal separator |
ClassEval_30_sum | import numpy as np
class DataStatistics2:
"""
This is a class for performing data statistics, supporting to get the sum, minimum, maximum, variance, standard deviation, and correlation of a given dataset.
"""
def __init__(self, data):
self.data = np.array(data)
def get_sum(self):
... | import numpy as np
class DataStatistics2:
"""
This is a class for performing data statistics, supporting to get the sum, minimum, maximum, variance, standard deviation, and correlation of a given dataset.
"""
def __init__(self, data):
"""
Initialize Data List
:param data:list
... | def get_std_deviation(self):
return round(np.std(self.data), 2) | Calculate standard deviation, accurate to two digits after the Decimal separator |
ClassEval_30_sum | import numpy as np
class DataStatistics2:
"""
This is a class for performing data statistics, supporting to get the sum, minimum, maximum, variance, standard deviation, and correlation of a given dataset.
"""
def __init__(self, data):
self.data = np.array(data)
def get_sum(self):
... | import numpy as np
class DataStatistics2:
"""
This is a class for performing data statistics, supporting to get the sum, minimum, maximum, variance, standard deviation, and correlation of a given dataset.
"""
def __init__(self, data):
"""
Initialize Data List
:param data:list
... | def get_correlation(self):
return np.corrcoef(self.data, rowvar=False) | Calculate correlation |
ClassEval_31_sum | import math
class DataStatistics4:
"""
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.
"""
@staticmethod
def correlation_coefficient(data1, data... | import math
class DataStatistics4:
"""
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.
"""
@staticmethod
@staticmethod
def skewness(da... | def correlation_coefficient(data1, data2):
n = len(data1)
mean1 = sum(data1) / n
mean2 = sum(data2) / n
numerator = sum((data1[i] - mean1) * (data2[i] - mean2) for i in range(n))
denominator = math.sqrt(sum((data1[i] - mean1) ** 2 for i in range(n))) * math.sqrt(sum((data2[i] - ... | Calculate the correlation coefficient of two sets of data. |
ClassEval_31_sum | import math
class DataStatistics4:
"""
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.
"""
@staticmethod
def correlation_coefficient(data1, data... | import math
class DataStatistics4:
"""
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.
"""
@staticmethod
def correlation_coefficient(data1, dat... | @staticmethod
def skewness(data):
n = len(data)
mean = sum(data) / n
variance = sum((x - mean) ** 2 for x in data) / n
std_deviation = math.sqrt(variance)
skewness = sum((x - mean) ** 3 for x in data) * n / ((n - 1) * (n - 2) * std_deviation ** 3) if std_deviation != 0 else ... | Calculate the skewness of a set of data. |
ClassEval_31_sum | import math
class DataStatistics4:
"""
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.
"""
@staticmethod
def correlation_coefficient(data1, data... | import math
class DataStatistics4:
"""
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.
"""
@staticmethod
def correlation_coefficient(data1, dat... | @staticmethod
def kurtosis(data):
n = len(data)
mean = sum(data) / n
std_dev = math.sqrt(sum((x - mean) ** 2 for x in data) / n)
if std_dev == 0:
return math.nan
centered_data = [(x - mean) for x in data]
fourth_moment = sum(x ** 4 for x in centered_dat... | Calculate the kurtosis of a set of data. |
ClassEval_31_sum | import math
class DataStatistics4:
"""
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.
"""
@staticmethod
def correlation_coefficient(data1, data... | import math
class DataStatistics4:
"""
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.
"""
@staticmethod
def correlation_coefficient(data1, dat... | @staticmethod
def pdf(data, mu, sigma):
pdf_values = [1 / (sigma * math.sqrt(2 * math.pi)) * math.exp(-0.5 * ((x - mu) / sigma) ** 2) for x in data]
return pdf_values | Calculate the probability density function (PDF) of a set of data under a normal distribution. |
ClassEval_32_sum | class DecryptionUtils:
"""
This is a class that provides methods for decryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.
"""
def __init__(self, key):
self.key = key
def caesar_decipher(self, ciphertext, shift):
plaintext = ""
for char in ciph... | class DecryptionUtils:
"""
This is a class that provides methods for decryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.
"""
def __init__(self, key):
"""
Initializes the decryption utility with a key.
:param key: The key to use for decryption,str.
... | def caesar_decipher(self, ciphertext, shift):
plaintext = ""
for char in ciphertext:
if char.isalpha():
if char.isupper():
ascii_offset = 65
else:
ascii_offset = 97
shifted_char = chr((ord(char) - ascii_o... | Deciphers the given ciphertext using the Caesar cipher |
ClassEval_32_sum | class DecryptionUtils:
"""
This is a class that provides methods for decryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.
"""
def __init__(self, key):
self.key = key
def caesar_decipher(self, ciphertext, shift):
"""
Deciphers the given ciphert... | class DecryptionUtils:
"""
This is a class that provides methods for decryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.
"""
def __init__(self, key):
"""
Initializes the decryption utility with a key.
:param key: The key to use for decryption,str.
... | def vigenere_decipher(self, ciphertext):
decrypted_text = ""
key_index = 0
for char in ciphertext:
if char.isalpha():
shift = ord(self.key[key_index % len(self.key)].lower()) - ord('a')
decrypted_char = chr((ord(char.lower()) - ord('a') - shift) % 26 +... | Deciphers the given ciphertext using the Vigenere cipher |
ClassEval_32_sum | class DecryptionUtils:
"""
This is a class that provides methods for decryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.
"""
def __init__(self, key):
self.key = key
def caesar_decipher(self, ciphertext, shift):
"""
Deciphers the given ciphert... | class DecryptionUtils:
"""
This is a class that provides methods for decryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.
"""
def __init__(self, key):
"""
Initializes the decryption utility with a key.
:param key: The key to use for decryption,str.
... | def rail_fence_decipher(self, encrypted_text, rails):
fence = [['\n' for _ in range(len(encrypted_text))] for _ in range(rails)]
direction = -1
row, col = 0, 0
for _ in range(len(encrypted_text)):
if row == 0 or row == rails - 1:
direction = -direction
... | Deciphers the given ciphertext using the Rail Fence cipher |
ClassEval_33_sum | class DiscountStrategy:
"""
This is a class that allows to use different discount strategy based on shopping credit or shopping cart in supermarket.
"""
def __init__(self, customer, cart, promotion=None):
self.customer = customer
self.cart = cart
self.promotion = promotion
... | class DiscountStrategy:
"""
This is a class that allows to use different discount strategy based on shopping credit or shopping cart in supermarket.
"""
def __init__(self, customer, cart, promotion=None):
"""
Initialize the DiscountStrategy with customer information, a cart of items, an... | def total(self):
self.__total = sum(item['quantity'] * item['price'] for item in self.cart)
return self.__total | Calculate the total cost of items in the cart. |
ClassEval_33_sum | class DiscountStrategy:
"""
This is a class that allows to use different discount strategy based on shopping credit or shopping cart in supermarket.
"""
def __init__(self, customer, cart, promotion=None):
self.customer = customer
self.cart = cart
self.promotion = promotion
... | class DiscountStrategy:
"""
This is a class that allows to use different discount strategy based on shopping credit or shopping cart in supermarket.
"""
def __init__(self, customer, cart, promotion=None):
"""
Initialize the DiscountStrategy with customer information, a cart of items, an... | def due(self):
if self.promotion is None:
discount = 0
else:
discount = self.promotion(self)
return self.__total - discount | Calculate the final amount to be paid after applying the discount. |
ClassEval_33_sum | class DiscountStrategy:
"""
This is a class that allows to use different discount strategy based on shopping credit or shopping cart in supermarket.
"""
def __init__(self, customer, cart, promotion=None):
self.customer = customer
self.cart = cart
self.promotion = promotion
... | class DiscountStrategy:
"""
This is a class that allows to use different discount strategy based on shopping credit or shopping cart in supermarket.
"""
def __init__(self, customer, cart, promotion=None):
"""
Initialize the DiscountStrategy with customer information, a cart of items, an... | @staticmethod
def FidelityPromo(order):
return order.total() * 0.05 if order.customer['fidelity'] >= 1000 else 0 | 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. |
ClassEval_33_sum | class DiscountStrategy:
"""
This is a class that allows to use different discount strategy based on shopping credit or shopping cart in supermarket.
"""
def __init__(self, customer, cart, promotion=None):
self.customer = customer
self.cart = cart
self.promotion = promotion
... | class DiscountStrategy:
"""
This is a class that allows to use different discount strategy based on shopping credit or shopping cart in supermarket.
"""
def __init__(self, customer, cart, promotion=None):
"""
Initialize the DiscountStrategy with customer information, a cart of items, an... | @staticmethod
def BulkItemPromo(order):
discount = 0
for item in order.cart:
if item['quantity'] >= 20:
discount += item['quantity'] * item['price'] * 0.1
return discount | 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. |
ClassEval_33_sum | class DiscountStrategy:
"""
This is a class that allows to use different discount strategy based on shopping credit or shopping cart in supermarket.
"""
def __init__(self, customer, cart, promotion=None):
self.customer = customer
self.cart = cart
self.promotion = promotion
... | class DiscountStrategy:
"""
This is a class that allows to use different discount strategy based on shopping credit or shopping cart in supermarket.
"""
def __init__(self, customer, cart, promotion=None):
"""
Initialize the DiscountStrategy with customer information, a cart of items, an... | @staticmethod
def LargeOrderPromo(order):
return order.total() * 0.07 if len({item['product'] for item in order.cart}) >= 10 else 0 | 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. |
ClassEval_34_sum | from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
class DocFileHandler:
"""
This is a class that handles Word documents and provides functionalities for reading, writing, and modifying the content of Word documents.
"""
def __init__(self, file_path)... | from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
class DocFileHandler:
"""
This is a class that handles Word documents and provides functionalities for reading, writing, and modifying the content of Word documents.
"""
def __init__(self, file_path... | def read_text(self):
doc = Document(self.file_path)
text = []
for paragraph in doc.paragraphs:
text.append(paragraph.text)
return "\n".join(text) | Reads the content of a Word document and returns it as a string. |
ClassEval_34_sum | from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
class DocFileHandler:
"""
This is a class that handles Word documents and provides functionalities for reading, writing, and modifying the content of Word documents.
"""
def __init__(self, file_path)... | from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
class DocFileHandler:
"""
This is a class that handles Word documents and provides functionalities for reading, writing, and modifying the content of Word documents.
"""
def __init__(self, file_path... | def write_text(self, content, font_size=12, alignment='left'):
try:
doc = Document()
paragraph = doc.add_paragraph()
run = paragraph.add_run(content)
font = run.font
font.size = Pt(font_size)
alignment_value = self._get_alignment_value(alig... | Writes the specified content to a Word document. |
ClassEval_34_sum | from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
class DocFileHandler:
"""
This is a class that handles Word documents and provides functionalities for reading, writing, and modifying the content of Word documents.
"""
def __init__(self, file_path)... | from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
class DocFileHandler:
"""
This is a class that handles Word documents and provides functionalities for reading, writing, and modifying the content of Word documents.
"""
def __init__(self, file_path... | def add_heading(self, heading, level=1):
try:
doc = Document(self.file_path)
doc.add_heading(heading, level)
doc.save(self.file_path)
return True
except:
return False | Adds a heading to the Word document. |
ClassEval_34_sum | from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
class DocFileHandler:
"""
This is a class that handles Word documents and provides functionalities for reading, writing, and modifying the content of Word documents.
"""
def __init__(self, file_path)... | from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
class DocFileHandler:
"""
This is a class that handles Word documents and provides functionalities for reading, writing, and modifying the content of Word documents.
"""
def __init__(self, file_path... | def add_table(self, data):
try:
doc = Document(self.file_path)
table = doc.add_table(rows=len(data), cols=len(data[0]))
for i, row in enumerate(data):
for j, cell_value in enumerate(row):
table.cell(i, j).text = str(cell_value)
... | Adds a table to the Word document with the specified data. |
ClassEval_34_sum | from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
class DocFileHandler:
"""
This is a class that handles Word documents and provides functionalities for reading, writing, and modifying the content of Word documents.
"""
def __init__(self, file_path)... | from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
class DocFileHandler:
"""
This is a class that handles Word documents and provides functionalities for reading, writing, and modifying the content of Word documents.
"""
def __init__(self, file_path... | def _get_alignment_value(self, alignment):
alignment_options = {
'left': WD_PARAGRAPH_ALIGNMENT.LEFT,
'center': WD_PARAGRAPH_ALIGNMENT.CENTER,
'right': WD_PARAGRAPH_ALIGNMENT.RIGHT
}
return alignment_options.get(alignment.lower(), WD_PARAGRAPH_ALIGNMENT.LEFT) | Returns the alignment value corresponding to the given alignment string. |
ClassEval_35_sum | class EightPuzzle:
"""
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.
"""
def __init__(self, initial_state):
self.initial_state = init... | class EightPuzzle:
"""
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.
"""
def __init__(self, initial_state):
"""
Initializing... | def find_blank(self, state):
for i in range(3):
for j in range(3):
if state[i][j] == 0:
return i, j | Find the blank position of current state, which is the 0 element. |
ClassEval_35_sum | class EightPuzzle:
"""
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.
"""
def __init__(self, initial_state):
self.initial_state = init... | class EightPuzzle:
"""
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.
"""
def __init__(self, initial_state):
"""
Initializing... | def move(self, state, direction):
i, j = self.find_blank(state)
new_state = [row[:] for row in state]
if direction == 'up':
new_state[i][j], new_state[i - 1][j] = new_state[i - 1][j], new_state[i][j]
elif direction == 'down':
new_state[i][j], new_state[i + 1][j] ... | Find the blank block, then makes the board moves forward the given direction. |
ClassEval_35_sum | class EightPuzzle:
"""
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.
"""
def __init__(self, initial_state):
self.initial_state = init... | class EightPuzzle:
"""
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.
"""
def __init__(self, initial_state):
"""
Initializing... | def get_possible_moves(self, state):
moves = []
i, j = self.find_blank(state)
if i > 0:
moves.append('up')
if i < 2:
moves.append('down')
if j > 0:
moves.append('left')
if j < 2:
moves.append('right')
return moves | According the current state, find all the possible moving directions. Only has 4 direction 'up', 'down', 'left', 'right'. |
ClassEval_35_sum | class EightPuzzle:
"""
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.
"""
def __init__(self, initial_state):
self.initial_state = init... | class EightPuzzle:
"""
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.
"""
def __init__(self, initial_state):
"""
Initializing... | def solve(self):
open_list = [(self.initial_state, [])]
closed_list = []
while open_list:
current_state, path = open_list.pop(0)
closed_list.append(current_state)
if current_state == self.goal_state:
return path
for move in self.... | Use BFS algorithm to find the path solution which makes the initial state to the goal method. Maintain a list as a queue, named as open_list, append the initial state. Always visit and pop the 0 index element, invoke get_possible_moves method find all the possible directions. Traversal the possible_moves list and invok... |
ClassEval_36_sum | from datetime import datetime
class EmailClient:
"""
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
"""
def __init__(self, addr, capacity) -> None:
self.addr = addr
self... | from datetime import datetime
class EmailClient:
"""
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
"""
def __init__(self, addr, capacity) -> None:
"""
Initializes the ... | def send_to(self, recv, content, size):
if not recv.is_full_with_one_more_email(size):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
email = {
"sender": self.addr,
"receiver": recv.addr,
"content": content,
"size"... | Sends an email to the given email address. |
ClassEval_36_sum | from datetime import datetime
class EmailClient:
"""
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
"""
def __init__(self, addr, capacity) -> None:
self.addr = addr
self... | from datetime import datetime
class EmailClient:
"""
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
"""
def __init__(self, addr, capacity) -> None:
"""
Initializes the ... | def fetch(self):
if len(self.inbox) == 0:
return None
for i in range(len(self.inbox)):
if self.inbox[i]['state'] == "unread":
self.inbox[i]['state'] = "read"
return self.inbox[i]
return None | Retrieves the first unread email in the email box and marks it as read. |
ClassEval_36_sum | from datetime import datetime
class EmailClient:
"""
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
"""
def __init__(self, addr, capacity) -> None:
self.addr = addr
self... | from datetime import datetime
class EmailClient:
"""
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
"""
def __init__(self, addr, capacity) -> None:
"""
Initializes the ... | def is_full_with_one_more_email(self, size):
occupied_size = self.get_occupied_size()
return True if occupied_size + size > self.capacity else False | Determines whether the email box is full after adding an email of the given size. |
ClassEval_36_sum | from datetime import datetime
class EmailClient:
"""
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
"""
def __init__(self, addr, capacity) -> None:
self.addr = addr
self... | from datetime import datetime
class EmailClient:
"""
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
"""
def __init__(self, addr, capacity) -> None:
"""
Initializes the ... | def get_occupied_size(self):
occupied_size = 0
for email in self.inbox:
occupied_size += email["size"]
return occupied_size | Gets the total size of the emails in the email box. |
ClassEval_36_sum | from datetime import datetime
class EmailClient:
"""
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
"""
def __init__(self, addr, capacity) -> None:
self.addr = addr
self... | from datetime import datetime
class EmailClient:
"""
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
"""
def __init__(self, addr, capacity) -> None:
"""
Initializes the ... | def clear_inbox(self, size):
if len(self.addr) == 0:
return
freed_space = 0
while freed_space < size and self.inbox:
email = self.inbox[0]
freed_space += email['size']
del self.inbox[0] | Clears the email box by deleting the oldest emails until the email box has enough space to accommodate the given size. |
ClassEval_37_sum | class EncryptionUtils:
"""
This is a class that provides methods for encryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.
"""
def __init__(self, key):
self.key = key
def caesar_cipher(self, plaintext, shift):
ciphertext = ""
for char in plaintext:... | class EncryptionUtils:
"""
This is a class that provides methods for encryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.
"""
def __init__(self, key):
"""
Initializes the class with a key.
:param key: The key to use for encryption, str.
"""
... | def caesar_cipher(self, plaintext, shift):
ciphertext = ""
for char in plaintext:
if char.isalpha():
if char.isupper():
ascii_offset = 65
else:
ascii_offset = 97
shifted_char = chr((ord(char) - ascii_offs... | Encrypts the plaintext using the Caesar cipher. |
ClassEval_37_sum | class EncryptionUtils:
"""
This is a class that provides methods for encryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.
"""
def __init__(self, key):
self.key = key
def caesar_cipher(self, plaintext, shift):
"""
Encrypts the plaintext using the C... | class EncryptionUtils:
"""
This is a class that provides methods for encryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.
"""
def __init__(self, key):
"""
Initializes the class with a key.
:param key: The key to use for encryption, str.
"""
... | def vigenere_cipher(self, plain_text):
encrypted_text = ""
key_index = 0
for char in plain_text:
if char.isalpha():
shift = ord(self.key[key_index % len(self.key)].lower()) - ord('a')
encrypted_char = chr((ord(char.lower()) - ord('a') + shift) % 26 + o... | Encrypts the plaintext using the Vigenere cipher. |
ClassEval_37_sum | class EncryptionUtils:
"""
This is a class that provides methods for encryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.
"""
def __init__(self, key):
self.key = key
def caesar_cipher(self, plaintext, shift):
"""
Encrypts the plaintext using the C... | class EncryptionUtils:
"""
This is a class that provides methods for encryption, including the Caesar cipher, Vigenere cipher, and Rail Fence cipher.
"""
def __init__(self, key):
"""
Initializes the class with a key.
:param key: The key to use for encryption, str.
"""
... | def rail_fence_cipher(self, plain_text, rails):
fence = [['\n' for _ in range(len(plain_text))] for _ in range(rails)]
direction = -1
row, col = 0, 0
for char in plain_text:
if row == 0 or row == rails-1:
direction = -direction
fence[row][col] = ... | Encrypts the plaintext using the Rail Fence cipher. |
ClassEval_38_sum | import openpyxl
class ExcelProcessor:
"""
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.
"""
def __init__(self):
pass
def write_excel(self, data, file_name):
"""
... | import openpyxl
class ExcelProcessor:
"""
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.
"""
def __init__(self):
pass
def write_excel(self, data, file_name):
""... | def read_excel(self, file_name):
data = []
try:
workbook = openpyxl.load_workbook(file_name)
sheet = workbook.active
for row in sheet.iter_rows(values_only=True):
data.append(row)
workbook.close()
return data
except:
... | Reading data from Excel files |
ClassEval_38_sum | import openpyxl
class ExcelProcessor:
"""
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.
"""
def __init__(self):
pass
def read_excel(self, file_name):
"""
Read... | import openpyxl
class ExcelProcessor:
"""
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.
"""
def __init__(self):
pass
def read_excel(self, file_name):
"""
Rea... | def write_excel(self, data, file_name):
try:
workbook = openpyxl.Workbook()
sheet = workbook.active
for row in data:
sheet.append(row)
workbook.save(file_name)
workbook.close()
return 1
except:
return 0 | Write data to the specified Excel file |
ClassEval_38_sum | import openpyxl
class ExcelProcessor:
"""
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.
"""
def __init__(self):
pass
def read_excel(self, file_name):
"""
Read... | import openpyxl
class ExcelProcessor:
"""
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.
"""
def __init__(self):
pass
def read_excel(self, file_name):
"""
Rea... | def process_excel_data(self, N, save_file_name):
data = self.read_excel(save_file_name)
if data is None or N >= len(data[0]):
return 0
new_data = []
for row in data:
new_row = list(row[:])
if not str(row[N]).isdigit():
new_row.append(st... | Change the specified column in the Excel file to uppercase |
ClassEval_39_sum | import re
from collections import deque
from decimal import Decimal
class ExpressionCalculator:
"""
This is a class in Python that can perform calculations with basic arithmetic operations, including addition, subtraction, multiplication, division, and modulo.
"""
def __init__(self):
self.post... | class ExpressionCalculator:
"""
This is a class in Python that can perform calculations with basic arithmetic operations, including addition, subtraction, multiplication, division, and modulo.
"""
def __init__(self):
"""
Initialize the expression calculator
"""
self.post... | def calculate(self, expression):
self.prepare(self.transform(expression))
result_stack = deque()
self.postfix_stack.reverse()
while self.postfix_stack:
current_op = self.postfix_stack.pop()
if not self.is_operator(current_op):
current_op = curren... | Calculate the result of the given postfix expression |
ClassEval_39_sum | import re
from collections import deque
from decimal import Decimal
class ExpressionCalculator:
"""
This is a class in Python that can perform calculations with basic arithmetic operations, including addition, subtraction, multiplication, division, and modulo.
"""
def __init__(self):
self.post... | class ExpressionCalculator:
"""
This is a class in Python that can perform calculations with basic arithmetic operations, including addition, subtraction, multiplication, division, and modulo.
"""
def __init__(self):
"""
Initialize the expression calculator
"""
self.post... | def prepare(self, expression):
op_stack = deque([','])
arr = list(expression)
current_index = 0
count = 0
for i, current_op in enumerate(arr):
if self.is_operator(current_op):
if count > 0:
self.postfix_stack.append("".join(arr[cur... | Prepare the infix expression for conversion to postfix notation |
ClassEval_39_sum | import re
from collections import deque
from decimal import Decimal
class ExpressionCalculator:
"""
This is a class in Python that can perform calculations with basic arithmetic operations, including addition, subtraction, multiplication, division, and modulo.
"""
def __init__(self):
self.post... | class ExpressionCalculator:
"""
This is a class in Python that can perform calculations with basic arithmetic operations, including addition, subtraction, multiplication, division, and modulo.
"""
def __init__(self):
"""
Initialize the expression calculator
"""
self.post... | @staticmethod
def is_operator(c):
return c in {'+', '-', '*', '/', '(', ')', '%'} | Check if a character is an operator in {'+', '-', '*', '/', '(', ')', '%'} |
ClassEval_39_sum | import re
from collections import deque
from decimal import Decimal
class ExpressionCalculator:
"""
This is a class in Python that can perform calculations with basic arithmetic operations, including addition, subtraction, multiplication, division, and modulo.
"""
def __init__(self):
self.post... | class ExpressionCalculator:
"""
This is a class in Python that can perform calculations with basic arithmetic operations, including addition, subtraction, multiplication, division, and modulo.
"""
def __init__(self):
"""
Initialize the expression calculator
"""
self.post... | def compare(self, cur, peek):
if cur == '%':
cur = '/'
if peek == '%':
peek = '/'
return self.operat_priority[ord(peek) - 40] >= self.operat_priority[ord(cur) - 40] | Compare the precedence of two operators |
ClassEval_39_sum | import re
from collections import deque
from decimal import Decimal
class ExpressionCalculator:
"""
This is a class in Python that can perform calculations with basic arithmetic operations, including addition, subtraction, multiplication, division, and modulo.
"""
def __init__(self):
self.post... | class ExpressionCalculator:
"""
This is a class in Python that can perform calculations with basic arithmetic operations, including addition, subtraction, multiplication, division, and modulo.
"""
def __init__(self):
"""
Initialize the expression calculator
"""
self.post... | @staticmethod
def _calculate(first_value, second_value, current_op):
if current_op == '+':
return Decimal(first_value) + Decimal(second_value)
elif current_op == '-':
return Decimal(first_value) - Decimal(second_value)
elif current_op == '*':
return Decima... | Perform the mathematical calculation based on the given operands and operator |
ClassEval_39_sum | import re
from collections import deque
from decimal import Decimal
class ExpressionCalculator:
"""
This is a class in Python that can perform calculations with basic arithmetic operations, including addition, subtraction, multiplication, division, and modulo.
"""
def __init__(self):
self.post... | class ExpressionCalculator:
"""
This is a class in Python that can perform calculations with basic arithmetic operations, including addition, subtraction, multiplication, division, and modulo.
"""
def __init__(self):
"""
Initialize the expression calculator
"""
self.post... | @staticmethod
def transform(expression):
expression = re.sub(r"\s+", "", expression)
expression = re.sub(r"=$", "", expression)
arr = list(expression)
for i, c in enumerate(arr):
if c == '-':
if i == 0:
arr[i] = '~'
els... | Transform the infix expression to a format suitable for conversion |
ClassEval_40_sum | class FitnessTracker:
"""
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.
"""
def __init__(self, height, weight, age, sex) -> None:
self.height = height
self.weight = weight
... | class FitnessTracker:
"""
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.
"""
def __init__(self, height, weight, age, sex) -> None:
"""
Initialize the class with height, weight, ag... | def get_BMI(self):
return self.weight / self.height ** 2 | Calculate the BMI based on the height and weight. |
ClassEval_40_sum | class FitnessTracker:
"""
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.
"""
def __init__(self, height, weight, age, sex) -> None:
self.height = height
self.weight = weight
... | class FitnessTracker:
"""
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.
"""
def __init__(self, height, weight, age, sex) -> None:
"""
Initialize the class with height, weight, ag... | def condition_judge(self):
BMI = self.get_BMI()
if self.sex == "male":
BMI_range = self.BMI_std[0]["male"]
else:
BMI_range = self.BMI_std[1]["female"]
if BMI > BMI_range[1]:
# too fat
return 1
elif BMI < BMI_range[0]:
# ... | Judge the condition of the user based on the BMI standard. |
ClassEval_40_sum | class FitnessTracker:
"""
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.
"""
def __init__(self, height, weight, age, sex) -> None:
self.height = height
self.weight = weight
... | class FitnessTracker:
"""
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.
"""
def __init__(self, height, weight, age, sex) -> None:
"""
Initialize the class with height, weight, ag... | def calculate_calorie_intake(self):
if self.sex == "male":
BMR = 10 * self.weight + 6.25 * self.height - 5 * self.age + 5
else:
BMR = 10 * self.weight + 6.25 * self.height - 5 * self.age - 161
if self.condition_judge() == 1:
calorie_intake = BMR * 1.2 # Seden... | 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 cal... |
ClassEval_41_sum | class GomokuGame:
"""
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.
"""
def __init__(self, board_size):
self.board_size = board_size
self.board = [[' ' for _ in r... | class GomokuGame:
"""
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.
"""
def __init__(self, board_size):
"""
Initializes the game with a given board size.
... | def make_move(self, row, col):
if self.board[row][col] == ' ':
self.board[row][col] = self.current_player
self.current_player = 'O' if self.current_player == 'X' else 'X'
return True
return False | Makes a move at the given row and column. If the move is valid, it places the current player's symbol on the board and changes the current player to the other player (if the current player is 'X', then it becomes 'O' and vice versa). |
ClassEval_41_sum | class GomokuGame:
"""
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.
"""
def __init__(self, board_size):
self.board_size = board_size
self.board = [[' ' for _ in r... | class GomokuGame:
"""
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.
"""
def __init__(self, board_size):
"""
Initializes the game with a given board size.
... | def check_winner(self):
directions = [(0, 1), (1, 0), (1, 1), (1, -1)]
for row in range(self.board_size):
for col in range(self.board_size):
if self.board[row][col] != ' ':
for direction in directions:
if self._check_five_in_a_row(r... | Checks if there is a winner by looking for five in a row in all directions (horizontal, vertical, diagonal). return: the symbol of the winning player (either 'X' or 'O') if there is a winner, or None otherwise. |
ClassEval_41_sum | class GomokuGame:
"""
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.
"""
def __init__(self, board_size):
self.board_size = board_size
self.board = [[' ' for _ in r... | class GomokuGame:
"""
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.
"""
def __init__(self, board_size):
"""
Initializes the game with a given board size.
... | def _check_five_in_a_row(self, row, col, direction):
dx, dy = direction
count = 1
symbol = self.board[row][col]
for i in range(1, 5):
new_row = row + dx * i
new_col = col + dy * i
if not (0 <= new_row < self.board_size and 0 <= new_col < self.board_siz... | 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). Counts the number of consecutive symbols in that direction starting from the given cell, |
ClassEval_42_sum | class Hotel:
"""
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.
"""
def __init__(self, name, rooms):
self.name = name
self.available_rooms = rooms
# available_rooms = {room_typ... | class Hotel:
"""
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.
"""
def __init__(self, name, rooms):
"""
Initialize the three fields in Hotel System.
name is the hotel name.
... | def book_room(self, room_type, room_number, name):
# Check if there are any rooms of the specified type available
if room_type not in self.available_rooms.keys():
return False
if room_number <= self.available_rooms[room_type]:
# Book the room by adding it to the booked_r... | Check if there are any rooms of the specified type available. if rooms are adequate, modify available_rooms and booked_rooms and finish booking, or fail to book otherwise. |
ClassEval_42_sum | class Hotel:
"""
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.
"""
def __init__(self, name, rooms):
self.name = name
self.available_rooms = rooms
# available_rooms = {room_typ... | class Hotel:
"""
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.
"""
def __init__(self, name, rooms):
"""
Initialize the three fields in Hotel System.
name is the hotel name.
... | def check_in(self, room_type, room_number, name):
# Check if the room of the specified type and number is booked
if room_type not in self.booked_rooms.keys():
return False
if name in self.booked_rooms[room_type]:
if room_number > self.booked_rooms[room_type][name]:
... | Check if the room of the specified type and number is booked by the person named name. 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... |
ClassEval_42_sum | class Hotel:
"""
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.
"""
def __init__(self, name, rooms):
self.name = name
self.available_rooms = rooms
# available_rooms = {room_typ... | class Hotel:
"""
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.
"""
def __init__(self, name, rooms):
"""
Initialize the three fields in Hotel System.
name is the hotel name.
... | def check_out(self, room_type, room_number):
if room_type in self.available_rooms:
self.available_rooms[room_type] += room_number
else:
self.available_rooms[room_type] = room_number | Check out rooms, add number for specific type in available_rooms. If room_type is new, add new type in available_rooms. |
ClassEval_42_sum | class Hotel:
"""
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.
"""
def __init__(self, name, rooms):
self.name = name
self.available_rooms = rooms
# available_rooms = {room_typ... | class Hotel:
"""
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.
"""
def __init__(self, name, rooms):
"""
Initialize the three fields in Hotel System.
name is the hotel name.
... | def get_available_rooms(self, room_type):
return self.available_rooms[room_type] | Get the number of specific type of available rooms. |
ClassEval_43_sum | class HRManagementSystem:
"""
This is a class as personnel management system that implements functions such as adding, deleting, querying, and updating employees
"""
def __init__(self):
self.employees = {}
def remove_employee(self, employee_id):
"""
Remove an employee from t... | class HRManagementSystem:
"""
This is a class as personnel management system that implements functions such as adding, deleting, querying, and updating employees
"""
def __init__(self):
"""
Initialize the HRManagementSystem withan attribute employees, which is an empty dictionary.
... | def add_employee(self, employee_id, name, position, department, salary):
if employee_id in self.employees:
return False
else:
self.employees[employee_id] = {
'name': name,
'position': position,
'department': department,
... | Add a new employee to the HRManagementSystem. |
ClassEval_43_sum | class HRManagementSystem:
"""
This is a class as personnel management system that implements functions such as adding, deleting, querying, and updating employees
"""
def __init__(self):
self.employees = {}
def add_employee(self, employee_id, name, position, department, salary):
"""
... | class HRManagementSystem:
"""
This is a class as personnel management system that implements functions such as adding, deleting, querying, and updating employees
"""
def __init__(self):
"""
Initialize the HRManagementSystem withan attribute employees, which is an empty dictionary.
... | def remove_employee(self, employee_id):
if employee_id in self.employees:
del self.employees[employee_id]
return True
else:
return False | Remove an employee from the HRManagementSystem. |
ClassEval_43_sum | class HRManagementSystem:
"""
This is a class as personnel management system that implements functions such as adding, deleting, querying, and updating employees
"""
def __init__(self):
self.employees = {}
def add_employee(self, employee_id, name, position, department, salary):
"""
... | class HRManagementSystem:
"""
This is a class as personnel management system that implements functions such as adding, deleting, querying, and updating employees
"""
def __init__(self):
"""
Initialize the HRManagementSystem withan attribute employees, which is an empty dictionary.
... | def update_employee(self, employee_id: int, employee_info: dict):
employee = self.get_employee(employee_id)
if employee == False:
return False
else:
for key, value in employee_info.items():
if key not in employee:
return False
... | Update an employee's information in the HRManagementSystem. |
ClassEval_43_sum | class HRManagementSystem:
"""
This is a class as personnel management system that implements functions such as adding, deleting, querying, and updating employees
"""
def __init__(self):
self.employees = {}
def add_employee(self, employee_id, name, position, department, salary):
"""
... | class HRManagementSystem:
"""
This is a class as personnel management system that implements functions such as adding, deleting, querying, and updating employees
"""
def __init__(self):
"""
Initialize the HRManagementSystem withan attribute employees, which is an empty dictionary.
... | def get_employee(self, employee_id):
if employee_id in self.employees:
return self.employees[employee_id]
else:
return False | Get an employee's information from the HRManagementSystem. |
ClassEval_43_sum | class HRManagementSystem:
"""
This is a class as personnel management system that implements functions such as adding, deleting, querying, and updating employees
"""
def __init__(self):
self.employees = {}
def add_employee(self, employee_id, name, position, department, salary):
"""
... | class HRManagementSystem:
"""
This is a class as personnel management system that implements functions such as adding, deleting, querying, and updating employees
"""
def __init__(self):
"""
Initialize the HRManagementSystem withan attribute employees, which is an empty dictionary.
... | def list_employees(self):
employee_data = {}
if self.employees:
for employee_id, employee_info in self.employees.items():
employee_details = {}
employee_details["employee_ID"] = employee_id
for key, value in employee_info.items():
... | List all employees' information in the HRManagementSystem. |
ClassEval_44_sum | import re
import string
import gensim
from bs4 import BeautifulSoup
class HtmlUtil:
"""
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.
"""
def __init__(self):
s... | import re
import string
import gensim
from bs4 import BeautifulSoup
class HtmlUtil:
"""
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.
"""
def __init__(self):
""... | def __format_line_feed(text):
return re.sub(re.compile(r'\n+'), '\n', text) | Replace consecutive line breaks with a single line break |
ClassEval_44_sum | import re
import string
import gensim
from bs4 import BeautifulSoup
class HtmlUtil:
"""
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.
"""
def __init__(self):
s... | import re
import string
import gensim
from bs4 import BeautifulSoup
class HtmlUtil:
"""
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.
"""
def __init__(self):
""... | def format_line_html_text(self, html_text):
if html_text is None or len(html_text) == 0:
return ''
soup = BeautifulSoup(html_text, 'lxml')
code_tag = soup.find_all(name=['pre', 'blockquote'])
for tag in code_tag:
tag.string = self.CODE_MARK
ul_ol_group =... | get the html text without the code, and add the code tag -CODE- where the code is |
ClassEval_44_sum | import re
import string
import gensim
from bs4 import BeautifulSoup
class HtmlUtil:
"""
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.
"""
def __init__(self):
s... | import re
import string
import gensim
from bs4 import BeautifulSoup
class HtmlUtil:
"""
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.
"""
def __init__(self):
""... | def extract_code_from_html_text(self, html_text):
text_with_code_tag = self.format_line_html_text(html_text)
if self.CODE_MARK not in text_with_code_tag:
return []
code_index_start = 0
soup = BeautifulSoup(html_text, 'lxml')
code_tag = soup.find_all(name=['pre', 'bl... | extract codes from the html body |
ClassEval_45_sum | from PIL import Image, ImageEnhance, ImageChops
class ImageProcessor:
"""
This is a class to process image, including loading, saving, resizing, rotating, and adjusting the brightness of images.
"""
def __init__(self):
self.image = None
def save_image(self, save_path):
"""
... | from PIL import Image, ImageEnhance
class ImageProcessor:
"""
This is a class to process image, including loading, saving, resizing, rotating, and adjusting the brightness of images.
"""
def __init__(self):
"""
Initialize self.image
"""
self.image = None
def s... | def load_image(self, image_path):
self.image = Image.open(image_path) | Use Image util in PIL to open a image |
ClassEval_45_sum | from PIL import Image, ImageEnhance, ImageChops
class ImageProcessor:
"""
This is a class to process image, including loading, saving, resizing, rotating, and adjusting the brightness of images.
"""
def __init__(self):
self.image = None
def load_image(self, image_path):
"""
... | from PIL import Image, ImageEnhance
class ImageProcessor:
"""
This is a class to process image, including loading, saving, resizing, rotating, and adjusting the brightness of images.
"""
def __init__(self):
"""
Initialize self.image
"""
self.image = None
def load_i... | def save_image(self, save_path):
if self.image:
self.image.save(save_path) | Save image to a path if image has opened |
ClassEval_45_sum | from PIL import Image, ImageEnhance, ImageChops
class ImageProcessor:
"""
This is a class to process image, including loading, saving, resizing, rotating, and adjusting the brightness of images.
"""
def __init__(self):
self.image = None
def load_image(self, image_path):
"""
... | from PIL import Image, ImageEnhance
class ImageProcessor:
"""
This is a class to process image, including loading, saving, resizing, rotating, and adjusting the brightness of images.
"""
def __init__(self):
"""
Initialize self.image
"""
self.image = None
def load_i... | def resize_image(self, width, height):
if self.image:
self.image = self.image.resize((width, height)) | Risize the image if image has opened. |
ClassEval_45_sum | from PIL import Image, ImageEnhance, ImageChops
class ImageProcessor:
"""
This is a class to process image, including loading, saving, resizing, rotating, and adjusting the brightness of images.
"""
def __init__(self):
self.image = None
def load_image(self, image_path):
"""
... | from PIL import Image, ImageEnhance
class ImageProcessor:
"""
This is a class to process image, including loading, saving, resizing, rotating, and adjusting the brightness of images.
"""
def __init__(self):
"""
Initialize self.image
"""
self.image = None
def load_i... | def rotate_image(self, degrees):
if self.image:
self.image = self.image.rotate(degrees) | rotate image if image has opened |
ClassEval_45_sum | from PIL import Image, ImageEnhance, ImageChops
class ImageProcessor:
"""
This is a class to process image, including loading, saving, resizing, rotating, and adjusting the brightness of images.
"""
def __init__(self):
self.image = None
def load_image(self, image_path):
"""
... | from PIL import Image, ImageEnhance
class ImageProcessor:
"""
This is a class to process image, including loading, saving, resizing, rotating, and adjusting the brightness of images.
"""
def __init__(self):
"""
Initialize self.image
"""
self.image = None
def load_i... | def adjust_brightness(self, factor):
if self.image:
enhancer = ImageEnhance.Brightness(self.image)
self.image = enhancer.enhance(factor) | Adjust the brightness of image if image has opened. |
ClassEval_46_sum | class Interpolation:
"""
This is a class that implements the Linear interpolation operation of one-dimensional and two-dimensional data
"""
def __init__(self):
pass
@staticmethod
def interpolate_1d(x, y, x_interp):
y_interp = []
for xi in x_interp:
for i in r... | class Interpolation:
"""
This is a class that implements the Linear interpolation operation of one-dimensional and two-dimensional data
"""
def __init__(self):
pass
@staticmethod
@staticmethod
def interpolate_2d(x, y, z, x_interp, y_interp):
”“”
Linear interpol... | def interpolate_1d(x, y, x_interp):
y_interp = []
for xi in x_interp:
for i in range(len(x) - 1):
if x[i] <= xi <= x[i+1]:
yi = y[i] + (y[i+1] - y[i]) * (xi - x[i]) / (x[i+1] - x[i])
y_interp.append(yi)
break
... | Linear interpolation of one-dimensional data |
ClassEval_46_sum | class Interpolation:
"""
This is a class that implements the Linear interpolation operation of one-dimensional and two-dimensional data
"""
def __init__(self):
pass
@staticmethod
def interpolate_1d(x, y, x_interp):
"""
Linear interpolation of one-dimensional data
... | class Interpolation:
"""
This is a class that implements the Linear interpolation operation of one-dimensional and two-dimensional data
"""
def __init__(self):
pass
@staticmethod
def interpolate_1d(x, y, x_interp):
"""
Linear interpolation of one-dimensional data
... | @staticmethod
def interpolate_2d(x, y, z, x_interp, y_interp):
z_interp = []
for xi, yi in zip(x_interp, y_interp):
for i in range(len(x) - 1):
if x[i] <= xi <= x[i+1]:
for j in range(len(y) - 1):
if y[j] <= yi <= y[j+1]:
... | Linear interpolation of two-dimensional data |
ClassEval_47_sum | class IPAddress:
"""
This is a class to process IP Address, including validating, getting the octets and obtaining the binary representation of a valid IP address.
"""
def __init__(self, ip_address):
self.ip_address = ip_address
def get_octets(self):
"""
If the IP address is... | class IPAddress:
"""
This is a class to process IP Address, including validating, getting the octets and obtaining the binary representation of a valid IP address.
"""
def __init__(self, ip_address):
"""
Initialize the IP address to the specified address
:param ip_address:string... | def is_valid(self):
octets = self.ip_address.split('.')
if len(octets) != 4:
return False
for octet in octets:
if not octet.isdigit() or int(octet) < 0 or int(octet) > 255:
return False
return True | 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 |
ClassEval_47_sum | class IPAddress:
"""
This is a class to process IP Address, including validating, getting the octets and obtaining the binary representation of a valid IP address.
"""
def __init__(self, ip_address):
self.ip_address = ip_address
def is_valid(self):
"""
Judge whether the IP a... | class IPAddress:
"""
This is a class to process IP Address, including validating, getting the octets and obtaining the binary representation of a valid IP address.
"""
def __init__(self, ip_address):
"""
Initialize the IP address to the specified address
:param ip_address:string... | def get_octets(self):
if self.is_valid():
return self.ip_address.split('.')
else:
return [] | 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 |
ClassEval_47_sum | class IPAddress:
"""
This is a class to process IP Address, including validating, getting the octets and obtaining the binary representation of a valid IP address.
"""
def __init__(self, ip_address):
self.ip_address = ip_address
def is_valid(self):
"""
Judge whether the IP a... | class IPAddress:
"""
This is a class to process IP Address, including validating, getting the octets and obtaining the binary representation of a valid IP address.
"""
def __init__(self, ip_address):
"""
Initialize the IP address to the specified address
:param ip_address:string... | def get_binary(self):
if self.is_valid():
binary_octets = []
for octet in self.get_octets():
binary_octets.append(format(int(octet), '08b'))
return '.'.join(binary_octets)
else:
return '' | If the IP address is valid, return the binary form of the IP address; otherwise, return '' |
ClassEval_48_sum | import socket
class IpUtil:
"""
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.
"""
@staticmethod
@staticmethod
def is_valid_ipv6(ip_address):
"""
... | import socket
import netifaces
class IpUtil:
"""
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.
"""
@staticmethod
@staticmethod
def is_valid_ipv6(ip_addres... | def is_valid_ipv4(ip_address):
try:
socket.inet_pton(socket.AF_INET, ip_address)
return True
except socket.error:
return False | Check if the given IP address is a valid IPv4 address. |
ClassEval_48_sum | import socket
class IpUtil:
"""
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.
"""
@staticmethod
def is_valid_ipv4(ip_address):
"""
Check if the give... | import socket
import netifaces
class IpUtil:
"""
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.
"""
@staticmethod
def is_valid_ipv4(ip_address):
"""
... | @staticmethod
def is_valid_ipv6(ip_address):
try:
socket.inet_pton(socket.AF_INET6, ip_address)
return True
except socket.error:
return False | Check if the given IP address is a valid IPv6 address. |
ClassEval_48_sum | import socket
class IpUtil:
"""
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.
"""
@staticmethod
def is_valid_ipv4(ip_address):
"""
Check if the give... | import socket
import netifaces
class IpUtil:
"""
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.
"""
@staticmethod
def is_valid_ipv4(ip_address):
"""
... | @staticmethod
def get_hostname(ip_address):
try:
hostname = socket.gethostbyaddr(ip_address)[0]
return hostname
except socket.herror:
return None | Get the hostname associated with the given IP address. |
ClassEval_49_sum | class JobMarketplace:
"""
This is a class that provides functionalities to publish positions, remove positions, submit resumes, withdraw resumes, search for positions, and obtain candidate information.
"""
def __init__(self):
self.job_listings = []
self.resumes = []
def remove_job(s... | class JobMarketplace:
"""
This is a class that provides functionalities to publish positions, remove positions, submit resumes, withdraw resumes, search for positions, and obtain candidate information.
"""
def __init__(self):
self.job_listings = []
self.resumes = []
def remove... | def post_job(self, job_title, company, requirements):
# requirements = ['requirement1', 'requirement2']
job = {"job_title": job_title, "company": company, "requirements": requirements}
self.job_listings.append(job) | This function is used to publish positions,and add the position information to the job_listings list. |
ClassEval_49_sum | class JobMarketplace:
"""
This is a class that provides functionalities to publish positions, remove positions, submit resumes, withdraw resumes, search for positions, and obtain candidate information.
"""
def __init__(self):
self.job_listings = []
self.resumes = []
def post_job(sel... | class JobMarketplace:
"""
This is a class that provides functionalities to publish positions, remove positions, submit resumes, withdraw resumes, search for positions, and obtain candidate information.
"""
def __init__(self):
self.job_listings = []
self.resumes = []
def post_job(se... | def remove_job(self, job):
self.job_listings.remove(job) | This function is used to remove positions,and remove the position information from the job_listings list. |
ClassEval_49_sum | class JobMarketplace:
"""
This is a class that provides functionalities to publish positions, remove positions, submit resumes, withdraw resumes, search for positions, and obtain candidate information.
"""
def __init__(self):
self.job_listings = []
self.resumes = []
def post_job(sel... | class JobMarketplace:
"""
This is a class that provides functionalities to publish positions, remove positions, submit resumes, withdraw resumes, search for positions, and obtain candidate information.
"""
def __init__(self):
self.job_listings = []
self.resumes = []
def post_job(se... | def submit_resume(self, name, skills, experience):
resume = {"name": name, "skills": skills, "experience": experience}
self.resumes.append(resume) | This function is used to submit resumes,and add the resume information to the resumes list. |
ClassEval_49_sum | class JobMarketplace:
"""
This is a class that provides functionalities to publish positions, remove positions, submit resumes, withdraw resumes, search for positions, and obtain candidate information.
"""
def __init__(self):
self.job_listings = []
self.resumes = []
def post_job(sel... | class JobMarketplace:
"""
This is a class that provides functionalities to publish positions, remove positions, submit resumes, withdraw resumes, search for positions, and obtain candidate information.
"""
def __init__(self):
self.job_listings = []
self.resumes = []
def post_job(se... | def withdraw_resume(self, resume):
self.resumes.remove(resume) | This function is used to withdraw resumes,and remove the resume information from the resumes list. |
ClassEval_49_sum | class JobMarketplace:
"""
This is a class that provides functionalities to publish positions, remove positions, submit resumes, withdraw resumes, search for positions, and obtain candidate information.
"""
def __init__(self):
self.job_listings = []
self.resumes = []
def post_job(sel... | class JobMarketplace:
"""
This is a class that provides functionalities to publish positions, remove positions, submit resumes, withdraw resumes, search for positions, and obtain candidate information.
"""
def __init__(self):
self.job_listings = []
self.resumes = []
def post_job(se... | def search_jobs(self, criteria):
matching_jobs = []
for job_listing in self.job_listings:
if criteria.lower() in job_listing["job_title"].lower() or criteria.lower() in [r.lower() for r in job_listing["requirements"]]:
matching_jobs.append(job_listing)
return matching... | This function is used to search for positions,and return the position information that meets the requirements. |
ClassEval_49_sum | class JobMarketplace:
"""
This is a class that provides functionalities to publish positions, remove positions, submit resumes, withdraw resumes, search for positions, and obtain candidate information.
"""
def __init__(self):
self.job_listings = []
self.resumes = []
def post_job(sel... | class JobMarketplace:
"""
This is a class that provides functionalities to publish positions, remove positions, submit resumes, withdraw resumes, search for positions, and obtain candidate information.
"""
def __init__(self):
self.job_listings = []
self.resumes = []
def post_job(se... | def get_job_applicants(self, job):
applicants = []
for resume in self.resumes:
if self.matches_requirements(resume, job["requirements"]):
applicants.append(resume)
return applicants | This function is used to obtain candidate information,and return the candidate information that meets the requirements by calling the matches_requirements function. |
ClassEval_50_sum | import json
import os
class JSONProcessor:
"""
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.
"""
def write_json(self, data, file_path):
"""
Write data to a JSON file and ... | import json
import os
class JSONProcessor:
"""
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.
"""
def write_json(self, data, file_path):
"""
Write data to a JSON file... | def read_json(self, file_path):
if not os.path.exists(file_path):
return 0
try:
with open(file_path, 'r') as file:
data = json.load(file)
return data
except:
return -1 | Read a JSON file and return the data. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.