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_0_sum | import logging
import datetime
class AccessGatewayFilter:
"""
This class is a filter used for accessing gateway filtering, primarily for authentication and access log recording.
"""
def __init__(self):
pass
def is_start_with(self, request_uri):
"""
Check if the request UR... | import logging
import datetime
class AccessGatewayFilter:
"""
This class is a filter used for accessing gateway filtering, primarily for authentication and access log recording.
"""
def __init__(self):
pass
def is_start_with(self, request_uri):
"""
Check if the reque... | def filter(self, request):
request_uri = request['path']
method = request['method']
if self.is_start_with(request_uri):
return True
try:
token = self.get_jwt_user(request)
user = token['user']
if user['level'] > 2:
self.se... | Filter the incoming request based on certain rules and conditions. |
ClassEval_0_sum | import logging
import datetime
class AccessGatewayFilter:
"""
This class is a filter used for accessing gateway filtering, primarily for authentication and access log recording.
"""
def __init__(self):
pass
def filter(self, request):
"""
Filter the incoming request based ... | import logging
import datetime
class AccessGatewayFilter:
"""
This class is a filter used for accessing gateway filtering, primarily for authentication and access log recording.
"""
def __init__(self):
pass
def filter(self, request):
"""
Filter the incoming request based o... | def is_start_with(self, request_uri):
start_with = ["/api", '/login']
for s in start_with:
if request_uri.startswith(s):
return True
return False | Check if the request URI starts with certain prefixes. |
ClassEval_0_sum | import logging
import datetime
class AccessGatewayFilter:
"""
This class is a filter used for accessing gateway filtering, primarily for authentication and access log recording.
"""
def __init__(self):
pass
def filter(self, request):
"""
Filter the incoming request based ... | import logging
import datetime
class AccessGatewayFilter:
"""
This class is a filter used for accessing gateway filtering, primarily for authentication and access log recording.
"""
def __init__(self):
pass
def filter(self, request):
"""
Filter the incoming request based o... | def get_jwt_user(self, request):
token = request['headers']['Authorization']
user = token['user']
if token['jwt'].startswith(user['name']):
jwt_str_date = token['jwt'].split(user['name'])[1]
jwt_date = datetime.datetime.strptime(jwt_str_date, "%Y-%m-%d")
if da... | Get the user information from the JWT token in the request. |
ClassEval_0_sum | import logging
import datetime
class AccessGatewayFilter:
"""
This class is a filter used for accessing gateway filtering, primarily for authentication and access log recording.
"""
def __init__(self):
pass
def filter(self, request):
"""
Filter the incoming request based ... | import logging
import datetime
class AccessGatewayFilter:
"""
This class is a filter used for accessing gateway filtering, primarily for authentication and access log recording.
"""
def __init__(self):
pass
def filter(self, request):
"""
Filter the incoming request based o... | def set_current_user_info_and_log(self, user):
host = user['address']
logging.log(msg=user['name'] + host + str(datetime.datetime.now()), level=1) | Set the current user information and log the access. |
ClassEval_1_sum | import math
class AreaCalculator:
"""
This is a class for calculating the area of different shapes, including circle, sphere, cylinder, sector and annulus.
"""
def __init__(self, radius):
self.radius = radius
def calculate_sphere_area(self):
"""
calculate the area of sphe... | import math
class AreaCalculator:
"""
This is a class for calculating the area of different shapes, including circle, sphere, cylinder, sector and annulus.
"""
def __init__(self, radius):
"""
Initialize the radius for shapes.
:param radius: float
"""
self.radius... | def calculate_circle_area(self):
return math.pi * self.radius ** 2 | calculate the area of circle based on self.radius |
ClassEval_1_sum | import math
class AreaCalculator:
"""
This is a class for calculating the area of different shapes, including circle, sphere, cylinder, sector and annulus.
"""
def __init__(self, radius):
self.radius = radius
def calculate_circle_area(self):
"""
calculate the area of circ... | import math
class AreaCalculator:
"""
This is a class for calculating the area of different shapes, including circle, sphere, cylinder, sector and annulus.
"""
def __init__(self, radius):
"""
Initialize the radius for shapes.
:param radius: float
"""
self.radius... | def calculate_sphere_area(self):
return 4 * math.pi * self.radius ** 2 | calculate the area of sphere based on self.radius |
ClassEval_1_sum | import math
class AreaCalculator:
"""
This is a class for calculating the area of different shapes, including circle, sphere, cylinder, sector and annulus.
"""
def __init__(self, radius):
self.radius = radius
def calculate_circle_area(self):
"""
calculate the area of circ... | import math
class AreaCalculator:
"""
This is a class for calculating the area of different shapes, including circle, sphere, cylinder, sector and annulus.
"""
def __init__(self, radius):
"""
Initialize the radius for shapes.
:param radius: float
"""
self.radius... | def calculate_cylinder_area(self, height):
return 2 * math.pi * self.radius * (self.radius + height) | calculate the area of cylinder based on self.radius and height |
ClassEval_1_sum | import math
class AreaCalculator:
"""
This is a class for calculating the area of different shapes, including circle, sphere, cylinder, sector and annulus.
"""
def __init__(self, radius):
self.radius = radius
def calculate_circle_area(self):
"""
calculate the area of circ... | import math
class AreaCalculator:
"""
This is a class for calculating the area of different shapes, including circle, sphere, cylinder, sector and annulus.
"""
def __init__(self, radius):
"""
Initialize the radius for shapes.
:param radius: float
"""
self.radius... | def calculate_sector_area(self, angle):
return self.radius ** 2 * angle / 2 | calculate the area of sector based on self.radius and angle |
ClassEval_1_sum | import math
class AreaCalculator:
"""
This is a class for calculating the area of different shapes, including circle, sphere, cylinder, sector and annulus.
"""
def __init__(self, radius):
self.radius = radius
def calculate_circle_area(self):
"""
calculate the area of circ... | import math
class AreaCalculator:
"""
This is a class for calculating the area of different shapes, including circle, sphere, cylinder, sector and annulus.
"""
def __init__(self, radius):
"""
Initialize the radius for shapes.
:param radius: float
"""
self.radius... | def calculate_annulus_area(self, inner_radius, outer_radius):
return math.pi * (outer_radius ** 2 - inner_radius ** 2) | calculate the area of annulus based on inner_radius and out_radius |
ClassEval_2_sum | class ArgumentParser:
"""
This is a class for parsing command line arguments to a dictionary.
"""
def __init__(self):
self.arguments = {}
self.required = set()
self.types = {}
def get_argument(self, key):
"""
Retrieves the value of the specified argument from... | class ArgumentParser:
"""
This is a class for parsing command line arguments to a dictionary.
"""
def __init__(self):
"""
Initialize the fields.
self.arguments is a dict that stores the args in a command line
self.requried is a set that stores the required arguments
... | def parse_arguments(self, command_string):
args = command_string.split()[1:]
for i in range(len(args)):
arg = args[i]
if arg.startswith('--'):
key_value = arg[2:].split('=')
if len(key_value) == 2:
self.arguments[key_value[0]] =... | Parses the given command line argument string and invoke _convert_type to stores the parsed result in specific type in the arguments dictionary. Checks for missing required arguments, if any, and returns False with the missing argument names, otherwise returns True. |
ClassEval_2_sum | class ArgumentParser:
"""
This is a class for parsing command line arguments to a dictionary.
"""
def __init__(self):
self.arguments = {}
self.required = set()
self.types = {}
def parse_arguments(self, command_string):
"""
Parses the given command line argume... | class ArgumentParser:
"""
This is a class for parsing command line arguments to a dictionary.
"""
def __init__(self):
"""
Initialize the fields.
self.arguments is a dict that stores the args in a command line
self.requried is a set that stores the required arguments
... | def get_argument(self, key):
return self.arguments.get(key) | Retrieves the value of the specified argument from the arguments dictionary and returns it. |
ClassEval_2_sum | class ArgumentParser:
"""
This is a class for parsing command line arguments to a dictionary.
"""
def __init__(self):
self.arguments = {}
self.required = set()
self.types = {}
def parse_arguments(self, command_string):
"""
Parses the given command line argume... | class ArgumentParser:
"""
This is a class for parsing command line arguments to a dictionary.
"""
def __init__(self):
"""
Initialize the fields.
self.arguments is a dict that stores the args in a command line
self.requried is a set that stores the required arguments
... | def add_argument(self, arg, required=False, arg_type=str):
if required:
self.required.add(arg)
self.types[arg] = arg_type | Adds an argument to self.types and self.required. Check if it is a required argument and store the argument type. If the argument is set as required, it wull be added to the required set. The argument type and name are stored in the types dictionary as key-value pairs. |
ClassEval_2_sum | class ArgumentParser:
"""
This is a class for parsing command line arguments to a dictionary.
"""
def __init__(self):
self.arguments = {}
self.required = set()
self.types = {}
def parse_arguments(self, command_string):
"""
Parses the given command line argume... | class ArgumentParser:
"""
This is a class for parsing command line arguments to a dictionary.
"""
def __init__(self):
"""
Initialize the fields.
self.arguments is a dict that stores the args in a command line
self.requried is a set that stores the required arguments
... | def _convert_type(self, arg, value):
try:
return self.types[arg](value)
except (ValueError, KeyError):
return value | Try to convert the type of input value by searching in self.types. |
ClassEval_3_sum | import itertools
class ArrangementCalculator:
"""
The Arrangement class provides permutation calculations and selection operations for a given set of data elements.
"""
def __init__(self, datas):
self.datas = datas
@staticmethod
@staticmethod
def count_all(n):
"""
... | import itertools
class ArrangementCalculator:
"""
The Arrangement class provides permutation calculations and selection operations for a given set of data elements.
"""
def __init__(self, datas):
"""
Initializes the ArrangementCalculator object with a list of datas.
:param data... | def count(n, m=None):
if m is None or n == m:
return ArrangementCalculator.factorial(n)
else:
return ArrangementCalculator.factorial(n) // ArrangementCalculator.factorial(n - m) | Counts the number of arrangements by choosing m items from n items (permutations). If m is not provided or n equals m, returns factorial(n). |
ClassEval_3_sum | import itertools
class ArrangementCalculator:
"""
The Arrangement class provides permutation calculations and selection operations for a given set of data elements.
"""
def __init__(self, datas):
self.datas = datas
@staticmethod
def count(n, m=None):
"""
Counts the num... | import itertools
class ArrangementCalculator:
"""
The Arrangement class provides permutation calculations and selection operations for a given set of data elements.
"""
def __init__(self, datas):
"""
Initializes the ArrangementCalculator object with a list of datas.
:param data... | @staticmethod
def count_all(n):
total = 0
for i in range(1, n + 1):
total += ArrangementCalculator.count(n, i)
return total | Counts the total number of all possible arrangements by choosing at least 1 item and at most n items from n items. |
ClassEval_3_sum | import itertools
class ArrangementCalculator:
"""
The Arrangement class provides permutation calculations and selection operations for a given set of data elements.
"""
def __init__(self, datas):
self.datas = datas
@staticmethod
def count(n, m=None):
"""
Counts the num... | import itertools
class ArrangementCalculator:
"""
The Arrangement class provides permutation calculations and selection operations for a given set of data elements.
"""
def __init__(self, datas):
"""
Initializes the ArrangementCalculator object with a list of datas.
:param data... | def select(self, m=None):
if m is None:
m = len(self.datas)
result = []
for permutation in itertools.permutations(self.datas, m):
result.append(list(permutation))
return result | Generates a list of arrangements by selecting m items from the internal datas. If m is not provided, selects all items. |
ClassEval_3_sum | import itertools
class ArrangementCalculator:
"""
The Arrangement class provides permutation calculations and selection operations for a given set of data elements.
"""
def __init__(self, datas):
self.datas = datas
@staticmethod
def count(n, m=None):
"""
Counts the num... | import itertools
class ArrangementCalculator:
"""
The Arrangement class provides permutation calculations and selection operations for a given set of data elements.
"""
def __init__(self, datas):
"""
Initializes the ArrangementCalculator object with a list of datas.
:param data... | def select_all(self):
result = []
for i in range(1, len(self.datas) + 1):
result.extend(self.select(i))
return result | Generates a list of all arrangements by selecting at least 1 item and at most the number of internal datas. |
ClassEval_3_sum | import itertools
class ArrangementCalculator:
"""
The Arrangement class provides permutation calculations and selection operations for a given set of data elements.
"""
def __init__(self, datas):
self.datas = datas
@staticmethod
def count(n, m=None):
"""
Counts the num... | import itertools
class ArrangementCalculator:
"""
The Arrangement class provides permutation calculations and selection operations for a given set of data elements.
"""
def __init__(self, datas):
"""
Initializes the ArrangementCalculator object with a list of datas.
:param data... | @staticmethod
def factorial(n):
result = 1
for i in range(2, n + 1):
result *= i
return result | Calculates the factorial of a given number. |
ClassEval_4_sum | class AssessmentSystem:
"""
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.
"""
def __init__(self):
self.students = {}
def add_course_score(self, name, course, score):
"""
... | class AssessmentSystem:
"""
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.
"""
def __init__(self):
"""
Initialize the students dict in assessment system.
"""
self... | def add_student(self, name, grade, major):
self.students[name] = {'name': name, 'grade': grade, 'major': major, 'courses': {}} | Add a new student into self.students dict |
ClassEval_4_sum | class AssessmentSystem:
"""
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.
"""
def __init__(self):
self.students = {}
def add_student(self, name, grade, major):
"""
A... | class AssessmentSystem:
"""
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.
"""
def __init__(self):
"""
Initialize the students dict in assessment system.
"""
self... | def add_course_score(self, name, course, score):
if name in self.students:
self.students[name]['courses'][course] = score | Add score of specific course for student in self.students |
ClassEval_4_sum | class AssessmentSystem:
"""
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.
"""
def __init__(self):
self.students = {}
def add_student(self, name, grade, major):
"""
A... | class AssessmentSystem:
"""
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.
"""
def __init__(self):
"""
Initialize the students dict in assessment system.
"""
self... | def get_gpa(self, name):
if name in self.students and self.students[name]['courses']:
return sum(self.students[name]['courses'].values()) / len(self.students[name]['courses'])
else:
return None | Get average grade of one student. |
ClassEval_4_sum | class AssessmentSystem:
"""
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.
"""
def __init__(self):
self.students = {}
def add_student(self, name, grade, major):
"""
A... | class AssessmentSystem:
"""
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.
"""
def __init__(self):
"""
Initialize the students dict in assessment system.
"""
self... | def get_all_students_with_fail_course(self):
students = []
for name, student in self.students.items():
for course, score in student['courses'].items():
if score < 60:
students.append(name)
break
return students | Get all students who have any score blow 60 |
ClassEval_4_sum | class AssessmentSystem:
"""
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.
"""
def __init__(self):
self.students = {}
def add_student(self, name, grade, major):
"""
A... | class AssessmentSystem:
"""
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.
"""
def __init__(self):
"""
Initialize the students dict in assessment system.
"""
self... | def get_course_average(self, course):
total = 0
count = 0
for student in self.students.values():
if course in student['courses']:
score = student['courses'][course]
if score is not None:
total += score
count += 1... | Get the average score of a specific course. |
ClassEval_4_sum | class AssessmentSystem:
"""
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.
"""
def __init__(self):
self.students = {}
def add_student(self, name, grade, major):
"""
A... | class AssessmentSystem:
"""
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.
"""
def __init__(self):
"""
Initialize the students dict in assessment system.
"""
self... | def get_top_student(self):
top_student = None
top_gpa = 0
for name, student in self.students.items():
gpa = self.get_gpa(name)
if gpa is not None and gpa > top_gpa:
top_gpa = gpa
top_student = name
return top_student | Calculate every student's gpa with get_gpa method, and find the student with highest gpa |
ClassEval_5_sum | class AutomaticGuitarSimulator:
"""
This class is an automatic guitar simulator that can interpret and play based on the input guitar sheet music.
"""
def __init__(self, text) -> None:
self.play_text = text
def display(self, key, value):
"""
Print out chord and play tune wit... | class AutomaticGuitarSimulator:
"""
This class is an automatic guitar simulator that can interpret and play based on the input guitar sheet music.
"""
def __init__(self, text) -> None:
"""
Initialize the score to be played
:param text:str, score to be played
"""
... | def interpret(self, display=False):
if len(self.play_text) == 0:
return
else:
play_list = []
play_segs = self.play_text.split(" ")
for play_seg in play_segs:
pos = 0
for ele in play_seg:
if ele.isalpha():... | Interpret the music score to be played |
ClassEval_5_sum | class AutomaticGuitarSimulator:
"""
This class is an automatic guitar simulator that can interpret and play based on the input guitar sheet music.
"""
def __init__(self, text) -> None:
self.play_text = text
def interpret(self, display=False):
"""
Interpret the music score to... | class AutomaticGuitarSimulator:
"""
This class is an automatic guitar simulator that can interpret and play based on the input guitar sheet music.
"""
def __init__(self, text) -> None:
"""
Initialize the score to be played
:param text:str, score to be played
"""
... | def display(self, key, value):
return "Normal Guitar Playing -- Chord: %s, Play Tune: %s" % (key, value) | Print out chord and play tune with following format: Normal Guitar Playing -- Chord: %s, Play Tune: %s |
ClassEval_6_sum | class AvgPartition:
"""
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.
"""
def __init__(self, lst, limit):
self.lst = lst
self.limit = limit
def get(self, in... | class AvgPartition:
"""
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.
"""
def __init__(self, lst, limit):
"""
Initialize the class with the given list and the number of ... | def setNum(self):
size = len(self.lst) // self.limit
remainder = len(self.lst) % self.limit
return size, remainder | Calculate the size of each block and the remainder of the division. |
ClassEval_6_sum | class AvgPartition:
"""
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.
"""
def __init__(self, lst, limit):
self.lst = lst
self.limit = limit
def setNum(self):
... | class AvgPartition:
"""
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.
"""
def __init__(self, lst, limit):
"""
Initialize the class with the given list and the number of ... | def get(self, index):
size, remainder = self.setNum()
start = index * size + min(index, remainder)
end = start + size
if index + 1 <= remainder:
end += 1
return self.lst[start:end] | 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. |
ClassEval_7_sum | class BalancedBrackets:
"""
This is a class that checks for bracket matching
"""
def __init__(self, expr):
self.stack = []
self.left_brackets = ["(", "{", "["]
self.right_brackets = [")", "}", "]"]
self.expr = expr
def check_balanced_brackets(self):
"""
... | class BalancedBrackets:
"""
This is a class that checks for bracket matching
"""
def __init__(self, expr):
"""
Initializes the class with an expression.
:param expr: The expression to check for balanced brackets,str.
"""
self.stack = []
self.left_brackets... | def clear_expr(self):
self.expr = ''.join(c for c in self.expr if (c in self.left_brackets or c in self.right_brackets)) | Clears the expression of all characters that are not brackets. |
ClassEval_7_sum | class BalancedBrackets:
"""
This is a class that checks for bracket matching
"""
def __init__(self, expr):
self.stack = []
self.left_brackets = ["(", "{", "["]
self.right_brackets = [")", "}", "]"]
self.expr = expr
def clear_expr(self):
"""
Clears the... | class BalancedBrackets:
"""
This is a class that checks for bracket matching
"""
def __init__(self, expr):
"""
Initializes the class with an expression.
:param expr: The expression to check for balanced brackets,str.
"""
self.stack = []
self.left_brackets... | def check_balanced_brackets(self):
self.clear_expr()
for Brkt in self.expr:
if Brkt in self.left_brackets:
self.stack.append(Brkt)
else:
Current_Brkt = self.stack.pop()
if Current_Brkt == "(":
if Brkt != ")":
... | Checks if the expression has balanced brackets. |
ClassEval_8_sum | class BankAccount:
"""
This is a class as a bank account system, which supports deposit money, withdraw money, view balance, and transfer money.
"""
def __init__(self, balance=0):
self.balance = balance
def withdraw(self, amount):
"""
Withdraws a certain amount from the acco... | class BankAccount:
"""
This is a class as a bank account system, which supports deposit money, withdraw money, view balance, and transfer money.
"""
def __init__(self, balance=0):
"""
Initializes a bank account object with an attribute balance, default value is 0.
"""
se... | def deposit(self, amount):
if amount < 0:
raise ValueError("Invalid amount")
self.balance += amount
return self.balance | Deposits a certain amount into the account, increasing the account balance, return the current account balance. If amount is negative, raise a ValueError("Invalid amount"). |
ClassEval_8_sum | class BankAccount:
"""
This is a class as a bank account system, which supports deposit money, withdraw money, view balance, and transfer money.
"""
def __init__(self, balance=0):
self.balance = balance
def deposit(self, amount):
"""
Deposits a certain amount into the accoun... | class BankAccount:
"""
This is a class as a bank account system, which supports deposit money, withdraw money, view balance, and transfer money.
"""
def __init__(self, balance=0):
"""
Initializes a bank account object with an attribute balance, default value is 0.
"""
se... | def withdraw(self, amount):
if amount < 0:
raise ValueError("Invalid amount")
if amount > self.balance:
raise ValueError("Insufficient balance.")
self.balance -= amount
return self.balance | Withdraws a certain amount from the account, decreasing the account balance, return the current account balance. If amount is negative, raise a ValueError("Invalid amount"). If the withdrawal amount is greater than the account balance, raise a ValueError("Insufficient balance."). |
ClassEval_8_sum | class BankAccount:
"""
This is a class as a bank account system, which supports deposit money, withdraw money, view balance, and transfer money.
"""
def __init__(self, balance=0):
self.balance = balance
def deposit(self, amount):
"""
Deposits a certain amount into the accoun... | class BankAccount:
"""
This is a class as a bank account system, which supports deposit money, withdraw money, view balance, and transfer money.
"""
def __init__(self, balance=0):
"""
Initializes a bank account object with an attribute balance, default value is 0.
"""
se... | def view_balance(self):
return self.balance | Return the account balance. |
ClassEval_8_sum | class BankAccount:
"""
This is a class as a bank account system, which supports deposit money, withdraw money, view balance, and transfer money.
"""
def __init__(self, balance=0):
self.balance = balance
def deposit(self, amount):
"""
Deposits a certain amount into the accoun... | class BankAccount:
"""
This is a class as a bank account system, which supports deposit money, withdraw money, view balance, and transfer money.
"""
def __init__(self, balance=0):
"""
Initializes a bank account object with an attribute balance, default value is 0.
"""
se... | def transfer(self, other_account, amount):
self.withdraw(amount)
other_account.deposit(amount) | Transfers a certain amount from the current account to another account. |
ClassEval_9_sum | class BigNumCalculator:
"""
This is a class that implements big number calculations, including adding, subtracting and multiplying.
"""
@staticmethod
@staticmethod
def subtract(num1, num2):
"""
Subtracts two big numbers.
:param num1: The first number to subtract,str.
... | class BigNumCalculator:
"""
This is a class that implements big number calculations, including adding, subtracting and multiplying.
"""
@staticmethod
@staticmethod
def subtract(num1, num2):
"""
Subtracts two big numbers.
:param num1: The first number to subtract,str... | def add(num1, num2):
max_length = max(len(num1), len(num2))
num1 = num1.zfill(max_length)
num2 = num2.zfill(max_length)
carry = 0
result = []
for i in range(max_length - 1, -1, -1):
digit_sum = int(num1[i]) + int(num2[i]) + carry
carry = digit_sum... | Adds two big numbers. |
ClassEval_9_sum | class BigNumCalculator:
"""
This is a class that implements big number calculations, including adding, subtracting and multiplying.
"""
@staticmethod
def add(num1, num2):
"""
Adds two big numbers.
:param num1: The first number to add,str.
:param num2: The second numbe... | class BigNumCalculator:
"""
This is a class that implements big number calculations, including adding, subtracting and multiplying.
"""
@staticmethod
def add(num1, num2):
"""
Adds two big numbers.
:param num1: The first number to add,str.
:param num2: The second numb... | @staticmethod
def subtract(num1, num2):
if len(num1) < len(num2):
num1, num2 = num2, num1
negative = True
elif len(num1) > len(num2):
negative = False
else:
if num1 < num2:
num1, num2 = num2, num1
negative = Tru... | Subtracts two big numbers. |
ClassEval_9_sum | class BigNumCalculator:
"""
This is a class that implements big number calculations, including adding, subtracting and multiplying.
"""
@staticmethod
def add(num1, num2):
"""
Adds two big numbers.
:param num1: The first number to add,str.
:param num2: The second numbe... | class BigNumCalculator:
"""
This is a class that implements big number calculations, including adding, subtracting and multiplying.
"""
@staticmethod
def add(num1, num2):
"""
Adds two big numbers.
:param num1: The first number to add,str.
:param num2: The second numb... | @staticmethod
def multiply(num1, num2):
len1, len2 = len(num1), len(num2)
result = [0] * (len1 + len2)
for i in range(len1 - 1, -1, -1):
for j in range(len2 - 1, -1, -1):
mul = int(num1[i]) * int(num2[j])
p1, p2 = i + j, i + j + 1
... | Multiplies two big numbers. |
ClassEval_10_sum | class BinaryDataProcessor:
"""
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.
"""
def __init__(self, binary_string):
sel... | class BinaryDataProcessor:
"""
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.
"""
def __init__(self, binary_string):
""... | def clean_non_binary_chars(self):
self.binary_string = ''.join(filter(lambda x: x in '01', self.binary_string)) | Clean the binary string by removing all non 0 or 1 characters. |
ClassEval_10_sum | class BinaryDataProcessor:
"""
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.
"""
def __init__(self, binary_string):
sel... | class BinaryDataProcessor:
"""
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.
"""
def __init__(self, binary_string):
""... | def calculate_binary_info(self):
zeroes_count = self.binary_string.count('0')
ones_count = self.binary_string.count('1')
total_length = len(self.binary_string)
zeroes_percentage = (zeroes_count / total_length)
ones_percentage = (ones_count / total_length)
return {
... | Calculate the binary string information, including the percentage of 0 and 1, and the total length of the binary string. |
ClassEval_10_sum | class BinaryDataProcessor:
"""
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.
"""
def __init__(self, binary_string):
sel... | class BinaryDataProcessor:
"""
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.
"""
def __init__(self, binary_string):
""... | def convert_to_ascii(self):
byte_array = bytearray()
for i in range(0, len(self.binary_string), 8):
byte = self.binary_string[i:i+8]
decimal = int(byte, 2)
byte_array.append(decimal)
return byte_array.decode('ascii') | Convert the binary string to ascii string. |
ClassEval_10_sum | class BinaryDataProcessor:
"""
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.
"""
def __init__(self, binary_string):
sel... | class BinaryDataProcessor:
"""
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.
"""
def __init__(self, binary_string):
""... | def convert_to_utf8(self):
byte_array = bytearray()
for i in range(0, len(self.binary_string), 8):
byte = self.binary_string[i:i+8]
decimal = int(byte, 2)
byte_array.append(decimal)
return byte_array.decode('utf-8') | Convert the binary string to utf-8 string. |
ClassEval_11_sum | class BitStatusUtil:
"""
This is a utility class that provides methods for manipulating and checking status using bitwise operations.
"""
@staticmethod
@staticmethod
def has(states, stat):
"""
Check if the current status contains the specified status,and check the parameters whea... | class BitStatusUtil:
"""
This is a utility class that provides methods for manipulating and checking status using bitwise operations.
"""
@staticmethod
@staticmethod
def has(states, stat):
"""
Check if the current status contains the specified status,and check the parameter... | def add(states, stat):
BitStatusUtil.check([states, stat])
return states | stat | Add a status to the current status,and check the parameters wheather they are legal. |
ClassEval_11_sum | class BitStatusUtil:
"""
This is a utility class that provides methods for manipulating and checking status using bitwise operations.
"""
@staticmethod
def add(states, stat):
"""
Add a status to the current status,and check the parameters wheather they are legal.
:param state... | class BitStatusUtil:
"""
This is a utility class that provides methods for manipulating and checking status using bitwise operations.
"""
@staticmethod
def add(states, stat):
"""
Add a status to the current status,and check the parameters wheather they are legal.
:param stat... | @staticmethod
def has(states, stat):
BitStatusUtil.check([states, stat])
return (states & stat) == stat | Check if the current status contains the specified status,and check the parameters wheather they are legal. |
ClassEval_11_sum | class BitStatusUtil:
"""
This is a utility class that provides methods for manipulating and checking status using bitwise operations.
"""
@staticmethod
def add(states, stat):
"""
Add a status to the current status,and check the parameters wheather they are legal.
:param state... | class BitStatusUtil:
"""
This is a utility class that provides methods for manipulating and checking status using bitwise operations.
"""
@staticmethod
def add(states, stat):
"""
Add a status to the current status,and check the parameters wheather they are legal.
:param stat... | @staticmethod
def remove(states, stat):
BitStatusUtil.check([states, stat])
if BitStatusUtil.has(states, stat):
return states ^ stat
return states | Remove the specified status from the current status,and check the parameters wheather they are legal. |
ClassEval_11_sum | class BitStatusUtil:
"""
This is a utility class that provides methods for manipulating and checking status using bitwise operations.
"""
@staticmethod
def add(states, stat):
"""
Add a status to the current status,and check the parameters wheather they are legal.
:param state... | class BitStatusUtil:
"""
This is a utility class that provides methods for manipulating and checking status using bitwise operations.
"""
@staticmethod
def add(states, stat):
"""
Add a status to the current status,and check the parameters wheather they are legal.
:param stat... | @staticmethod
def check(args):
for arg in args:
if arg < 0:
raise ValueError(f"{arg} must be greater than or equal to 0")
if arg % 2 != 0:
raise ValueError(f"{arg} not even") | Check if the parameters are legal, args must be greater than or equal to 0 and must be even,if not,raise ValueError. |
ClassEval_12_sum | import random
class BlackjackGame:
"""
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.
"""
def __init__(self):
self.deck = self.create_deck()
s... | import random
class BlackjackGame:
"""
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.
"""
def __init__(self):
"""
Initialize the Blackjack Game... | def create_deck(self):
deck = []
suits = ['S', 'C', 'D', 'H']
ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
for suit in suits:
for rank in ranks:
deck.append(rank + suit)
random.shuffle(deck)
return deck | Create a deck of 52 cards, which stores 52 rondom order poker with the Jokers removed. |
ClassEval_12_sum | import random
class BlackjackGame:
"""
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.
"""
def __init__(self):
self.deck = self.create_deck()
s... | import random
class BlackjackGame:
"""
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.
"""
def __init__(self):
"""
Initialize the Blackjack Game... | def calculate_hand_value(self, hand):
value = 0
num_aces = 0
for card in hand:
rank = card[:-1]
if rank.isdigit():
value += int(rank)
elif rank in ['J', 'Q', 'K']:
value += 10
elif rank == 'A':
value ... | Calculate the value of the poker cards stored in hand list according to the rules of the Blackjack Game. If the card is a digit, its value is added to the total hand value. Value of J, Q, or K is 10, while Aces are worth 11. If the total hand value exceeds 21 and there are Aces present, one Ace is treated as having a v... |
ClassEval_12_sum | import random
class BlackjackGame:
"""
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.
"""
def __init__(self):
self.deck = self.create_deck()
s... | import random
class BlackjackGame:
"""
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.
"""
def __init__(self):
"""
Initialize the Blackjack Game... | def check_winner(self, player_hand, dealer_hand):
player_value = self.calculate_hand_value(player_hand)
dealer_value = self.calculate_hand_value(dealer_hand)
if player_value > 21 and dealer_value > 21:
if player_value <= dealer_value:
return 'Player wins'
... | Determines the winner of a game by comparing the hand values of the player and dealer. rule: 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. Otherwise, the winner is the one with the lower hand value. |
ClassEval_13_sum | class BookManagement:
"""
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.
"""
def __init__(self):
self.inventory = {}
def remove_book(self, title, quantity):
"""
... | class BookManagement:
"""
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.
"""
def __init__(self):
"""
Initialize the inventory of Book Manager.
"""
se... | def add_book(self, title, quantity=1):
if title in self.inventory:
self.inventory[title] += quantity
else:
self.inventory[title] = quantity | Add one or several books to inventory which is sorted by book title. |
ClassEval_13_sum | class BookManagement:
"""
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.
"""
def __init__(self):
self.inventory = {}
def add_book(self, title, quantity=1):
"""
... | class BookManagement:
"""
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.
"""
def __init__(self):
"""
Initialize the inventory of Book Manager.
"""
se... | def remove_book(self, title, quantity):
if title not in self.inventory or self.inventory[title] < quantity:
raise False
self.inventory[title] -= quantity
if self.inventory[title] == 0:
del (self.inventory[title]) | Remove one or several books from inventory which is sorted by book title. Raise false while get invalid input. |
ClassEval_13_sum | class BookManagement:
"""
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.
"""
def __init__(self):
self.inventory = {}
def add_book(self, title, quantity=1):
"""
... | class BookManagement:
"""
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.
"""
def __init__(self):
"""
Initialize the inventory of Book Manager.
"""
se... | def view_inventory(self):
return self.inventory | Get the inventory of the Book Management. |
ClassEval_13_sum | class BookManagement:
"""
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.
"""
def __init__(self):
self.inventory = {}
def add_book(self, title, quantity=1):
"""
... | class BookManagement:
"""
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.
"""
def __init__(self):
"""
Initialize the inventory of Book Manager.
"""
se... | def view_book_quantity(self, title):
if title not in self.inventory:
return 0
return self.inventory[title] | Get the quantity of a book. |
ClassEval_14_sum | import sqlite3
class BookManagementDB:
"""
This is a database class as a book management system, used to handle the operations of adding, removing, updating, and searching books.
"""
def __init__(self, db_name):
self.connection = sqlite3.connect(db_name)
self.cursor = self.connection.cu... | import sqlite3
class BookManagementDB:
"""
This is a database class as a book management system, used to handle the operations of adding, removing, updating, and searching books.
"""
def __init__(self, db_name):
"""
Initializes the class by creating a database connection and cursor,
... | def create_table(self):
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS books (
id INTEGER PRIMARY KEY,
title TEXT,
author TEXT,
available INTEGER
)
''')
self.connection.commit() | Creates the book table in the database if it does not already exist. |
ClassEval_14_sum | import sqlite3
class BookManagementDB:
"""
This is a database class as a book management system, used to handle the operations of adding, removing, updating, and searching books.
"""
def __init__(self, db_name):
self.connection = sqlite3.connect(db_name)
self.cursor = self.connection.cu... | import sqlite3
class BookManagementDB:
"""
This is a database class as a book management system, used to handle the operations of adding, removing, updating, and searching books.
"""
def __init__(self, db_name):
"""
Initializes the class by creating a database connection and cursor,
... | def add_book(self, title, author):
self.cursor.execute('''
INSERT INTO books (title, author, available)
VALUES (?, ?, 1)
''', (title, author))
self.connection.commit() | Adds a book to the database with the specified title and author, setting its availability to 1 as free to borrow. |
ClassEval_14_sum | import sqlite3
class BookManagementDB:
"""
This is a database class as a book management system, used to handle the operations of adding, removing, updating, and searching books.
"""
def __init__(self, db_name):
self.connection = sqlite3.connect(db_name)
self.cursor = self.connection.cu... | import sqlite3
class BookManagementDB:
"""
This is a database class as a book management system, used to handle the operations of adding, removing, updating, and searching books.
"""
def __init__(self, db_name):
"""
Initializes the class by creating a database connection and cursor,
... | def remove_book(self, book_id):
self.cursor.execute('''
DELETE FROM books WHERE id = ?
''', (book_id,))
self.connection.commit() | Removes a book from the database based on the given book ID. |
ClassEval_14_sum | import sqlite3
class BookManagementDB:
"""
This is a database class as a book management system, used to handle the operations of adding, removing, updating, and searching books.
"""
def __init__(self, db_name):
self.connection = sqlite3.connect(db_name)
self.cursor = self.connection.cu... | import sqlite3
class BookManagementDB:
"""
This is a database class as a book management system, used to handle the operations of adding, removing, updating, and searching books.
"""
def __init__(self, db_name):
"""
Initializes the class by creating a database connection and cursor,
... | def borrow_book(self, book_id):
self.cursor.execute('''
UPDATE books SET available = 0 WHERE id = ?
''', (book_id,))
self.connection.commit() | Marks a book as borrowed in the database based on the given book ID. |
ClassEval_14_sum | import sqlite3
class BookManagementDB:
"""
This is a database class as a book management system, used to handle the operations of adding, removing, updating, and searching books.
"""
def __init__(self, db_name):
self.connection = sqlite3.connect(db_name)
self.cursor = self.connection.cu... | import sqlite3
class BookManagementDB:
"""
This is a database class as a book management system, used to handle the operations of adding, removing, updating, and searching books.
"""
def __init__(self, db_name):
"""
Initializes the class by creating a database connection and cursor,
... | def return_book(self, book_id):
self.cursor.execute('''
UPDATE books SET available = 1 WHERE id = ?
''', (book_id,))
self.connection.commit() | Marks a book as returned in the database based on the given book ID. |
ClassEval_14_sum | import sqlite3
class BookManagementDB:
"""
This is a database class as a book management system, used to handle the operations of adding, removing, updating, and searching books.
"""
def __init__(self, db_name):
self.connection = sqlite3.connect(db_name)
self.cursor = self.connection.cu... | import sqlite3
class BookManagementDB:
"""
This is a database class as a book management system, used to handle the operations of adding, removing, updating, and searching books.
"""
def __init__(self, db_name):
"""
Initializes the class by creating a database connection and cursor,
... | def search_books(self):
self.cursor.execute('''
SELECT * FROM books
''')
books = self.cursor.fetchall()
return books | Retrieves all books from the database and returns their information. |
ClassEval_15_sum | class BoyerMooreSearch:
"""
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.
"""
def __init__(self, text, pattern):
self.text, self.pattern = text, pattern
self.textLen, self.patLen = len(te... | class BoyerMooreSearch:
"""
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.
"""
def __init__(self, text, pattern):
"""
Initializes the BoyerMooreSearch class with the given text and patter... | def match_in_pattern(self, char):
for i in range(self.patLen - 1, -1, -1):
if char == self.pattern[i]:
return i
return -1 | Finds the rightmost occurrence of a character in the pattern. |
ClassEval_15_sum | class BoyerMooreSearch:
"""
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.
"""
def __init__(self, text, pattern):
self.text, self.pattern = text, pattern
self.textLen, self.patLen = len(te... | class BoyerMooreSearch:
"""
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.
"""
def __init__(self, text, pattern):
"""
Initializes the BoyerMooreSearch class with the given text and patter... | def mismatch_in_text(self, currentPos):
for i in range(self.patLen - 1, -1, -1):
if self.pattern[i] != self.text[currentPos + i]:
return currentPos + i
return -1 | Determines the position of the first dismatch between the pattern and the text. |
ClassEval_15_sum | class BoyerMooreSearch:
"""
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.
"""
def __init__(self, text, pattern):
self.text, self.pattern = text, pattern
self.textLen, self.patLen = len(te... | class BoyerMooreSearch:
"""
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.
"""
def __init__(self, text, pattern):
"""
Initializes the BoyerMooreSearch class with the given text and patter... | def bad_character_heuristic(self):
positions = []
for i in range(self.textLen - self.patLen + 1):
mismatch_index = self.mismatch_in_text(i)
if mismatch_index == -1:
positions.append(i)
else:
match_index = self.match_in_pattern(self.text... | Finds all occurrences of the pattern in the text. |
ClassEval_16_sum | class Calculator:
"""
This is a class for a calculator, capable of performing basic arithmetic calculations on numerical expressions using the operators +, -, *, /, and ^ (exponentiation).
"""
def __init__(self):
self.operators = {
'+': lambda x, y: x + y,
'-': lambda x, ... | class Calculator:
"""
This is a class for a calculator, capable of performing basic arithmetic calculations on numerical expressions using the operators +, -, *, /, and ^ (exponentiation).
"""
def __init__(self):
"""
Initialize the operations performed by the five operators'+','-','*','... | def calculate(self, expression):
operand_stack = []
operator_stack = []
num_buffer = ''
for char in expression:
if char.isdigit() or char == '.':
num_buffer += char
else:
if num_buffer:
operand_stack.append(floa... | Calculate the value of a given expression |
ClassEval_16_sum | class Calculator:
"""
This is a class for a calculator, capable of performing basic arithmetic calculations on numerical expressions using the operators +, -, *, /, and ^ (exponentiation).
"""
def __init__(self):
self.operators = {
'+': lambda x, y: x + y,
'-': lambda x, ... | class Calculator:
"""
This is a class for a calculator, capable of performing basic arithmetic calculations on numerical expressions using the operators +, -, *, /, and ^ (exponentiation).
"""
def __init__(self):
"""
Initialize the operations performed by the five operators'+','-','*','... | def precedence(self, operator):
precedences = {
'+': 1,
'-': 1,
'*': 2,
'/': 2,
'^': 3
}
return precedences.get(operator, 0) | 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 '-' |
ClassEval_16_sum | class Calculator:
"""
This is a class for a calculator, capable of performing basic arithmetic calculations on numerical expressions using the operators +, -, *, /, and ^ (exponentiation).
"""
def __init__(self):
self.operators = {
'+': lambda x, y: x + y,
'-': lambda x, ... | class Calculator:
"""
This is a class for a calculator, capable of performing basic arithmetic calculations on numerical expressions using the operators +, -, *, /, and ^ (exponentiation).
"""
def __init__(self):
"""
Initialize the operations performed by the five operators'+','-','*','... | def apply_operator(self, operand_stack, operator_stack):
operator = operator_stack.pop()
if operator == '^':
operand2 = operand_stack.pop()
operand1 = operand_stack.pop()
result = self.operators[operator](operand1, operand2)
operand_stack.append(result)
... | 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 |
ClassEval_17_sum | from datetime import datetime, timedelta
class CalendarUtil:
"""
This is a class as CalendarUtil that provides functionalities to manage calendar events, schedule appointments, and perform conflict checks.
"""
def __init__(self):
self.events = []
def remove_event(self, event):
"""
... | from datetime import datetime, timedelta
class CalendarUtil:
"""
This is a class as CalendarUtil that provides functionalities to manage calendar events, schedule appointments, and perform conflict checks.
"""
def __init__(self):
"""
Initialize the calendar with an empty list of events... | def add_event(self, event):
self.events.append(event) | Add an event to the calendar. |
ClassEval_17_sum | from datetime import datetime, timedelta
class CalendarUtil:
"""
This is a class as CalendarUtil that provides functionalities to manage calendar events, schedule appointments, and perform conflict checks.
"""
def __init__(self):
self.events = []
def add_event(self, event):
"""
... | from datetime import datetime, timedelta
class CalendarUtil:
"""
This is a class as CalendarUtil that provides functionalities to manage calendar events, schedule appointments, and perform conflict checks.
"""
def __init__(self):
"""
Initialize the calendar with an empty list of events... | def remove_event(self, event):
if event in self.events:
self.events.remove(event) | Remove an event from the calendar. |
ClassEval_17_sum | from datetime import datetime, timedelta
class CalendarUtil:
"""
This is a class as CalendarUtil that provides functionalities to manage calendar events, schedule appointments, and perform conflict checks.
"""
def __init__(self):
self.events = []
def add_event(self, event):
"""
... | from datetime import datetime, timedelta
class CalendarUtil:
"""
This is a class as CalendarUtil that provides functionalities to manage calendar events, schedule appointments, and perform conflict checks.
"""
def __init__(self):
"""
Initialize the calendar with an empty list of events... | def get_events(self, date):
events_on_date = []
for event in self.events:
if event['date'].date() == date.date():
events_on_date.append(event)
return events_on_date | Get all events on a given date. |
ClassEval_17_sum | from datetime import datetime, timedelta
class CalendarUtil:
"""
This is a class as CalendarUtil that provides functionalities to manage calendar events, schedule appointments, and perform conflict checks.
"""
def __init__(self):
self.events = []
def add_event(self, event):
"""
... | from datetime import datetime, timedelta
class CalendarUtil:
"""
This is a class as CalendarUtil that provides functionalities to manage calendar events, schedule appointments, and perform conflict checks.
"""
def __init__(self):
"""
Initialize the calendar with an empty list of events... | def is_available(self, start_time, end_time):
for event in self.events:
if start_time < event['end_time'] and end_time > event['start_time']:
return False
return True | Check if the calendar is available for a given time slot. |
ClassEval_17_sum | from datetime import datetime, timedelta
class CalendarUtil:
"""
This is a class as CalendarUtil that provides functionalities to manage calendar events, schedule appointments, and perform conflict checks.
"""
def __init__(self):
self.events = []
def add_event(self, event):
"""
... | from datetime import datetime, timedelta
class CalendarUtil:
"""
This is a class as CalendarUtil that provides functionalities to manage calendar events, schedule appointments, and perform conflict checks.
"""
def __init__(self):
"""
Initialize the calendar with an empty list of events... | def get_available_slots(self, date):
available_slots = []
start_time = datetime(date.year, date.month, date.day, 0, 0)
end_time = datetime(date.year, date.month, date.day, 23, 59)
while start_time < end_time:
slot_end_time = start_time + timedelta(minutes=60)
if ... | Get all available time slots on a given date. |
ClassEval_17_sum | from datetime import datetime, timedelta
class CalendarUtil:
"""
This is a class as CalendarUtil that provides functionalities to manage calendar events, schedule appointments, and perform conflict checks.
"""
def __init__(self):
self.events = []
def add_event(self, event):
"""
... | from datetime import datetime, timedelta
class CalendarUtil:
"""
This is a class as CalendarUtil that provides functionalities to manage calendar events, schedule appointments, and perform conflict checks.
"""
def __init__(self):
"""
Initialize the calendar with an empty list of events... | def get_upcoming_events(self, num_events):
now = datetime.now()
upcoming_events = []
for event in self.events:
if event['start_time'] >= now:
upcoming_events.append(event)
if len(upcoming_events) == num_events:
break
return upcoming... | Get the next n upcoming events from a given date. |
ClassEval_18_sum | class CamelCaseMap:
"""
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.
"""
def __init__(self):
self._data = {}
def __setitem__(self, key, value):
"""
Set the value corr... | class CamelCaseMap:
"""
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.
"""
def __init__(self):
"""
Initialize data to an empty dictionary
"""
self._data = {}
... | def __getitem__(self, key):
return self._data[self._convert_key(key)] | Return the value corresponding to the key |
ClassEval_18_sum | class CamelCaseMap:
"""
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.
"""
def __init__(self):
self._data = {}
def __getitem__(self, key):
"""
Return the value correspo... | class CamelCaseMap:
"""
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.
"""
def __init__(self):
"""
Initialize data to an empty dictionary
"""
self._data = {}
d... | def __setitem__(self, key, value):
self._data[self._convert_key(key)] = value | Set the value corresponding to the key to the specified value |
ClassEval_18_sum | class CamelCaseMap:
"""
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.
"""
def __init__(self):
self._data = {}
def __getitem__(self, key):
"""
Return the value correspo... | class CamelCaseMap:
"""
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.
"""
def __init__(self):
"""
Initialize data to an empty dictionary
"""
self._data = {}
d... | def __delitem__(self, key):
del self._data[self._convert_key(key)] | Delete the value corresponding to the key |
ClassEval_18_sum | class CamelCaseMap:
"""
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.
"""
def __init__(self):
self._data = {}
def __getitem__(self, key):
"""
Return the value correspo... | class CamelCaseMap:
"""
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.
"""
def __init__(self):
"""
Initialize data to an empty dictionary
"""
self._data = {}
d... | def __iter__(self):
return iter(self._data) | Returning Iterateable Objects with Own Data |
ClassEval_18_sum | class CamelCaseMap:
"""
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.
"""
def __init__(self):
self._data = {}
def __getitem__(self, key):
"""
Return the value correspo... | class CamelCaseMap:
"""
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.
"""
def __init__(self):
"""
Initialize data to an empty dictionary
"""
self._data = {}
d... | def __len__(self):
return len(self._data) | Returns the length of the own data |
ClassEval_18_sum | class CamelCaseMap:
"""
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.
"""
def __init__(self):
self._data = {}
def __getitem__(self, key):
"""
Return the value correspo... | class CamelCaseMap:
"""
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.
"""
def __init__(self):
"""
Initialize data to an empty dictionary
"""
self._data = {}
d... | def _convert_key(self, key):
if isinstance(key, str):
return self._to_camel_case(key)
return key | convert key string into camel case |
ClassEval_18_sum | class CamelCaseMap:
"""
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.
"""
def __init__(self):
self._data = {}
def __getitem__(self, key):
"""
Return the value correspo... | class CamelCaseMap:
"""
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.
"""
def __init__(self):
"""
Initialize data to an empty dictionary
"""
self._data = {}
d... | @staticmethod
def _to_camel_case(key):
parts = key.split('_')
return parts[0] + ''.join(part.title() for part in parts[1:]) | convert key string into camel case |
ClassEval_19_sum | class ChandrasekharSieve:
"""
This is a class that uses the Chandrasekhar's Sieve method to find all prime numbers within the range
"""
def __init__(self, n):
self.n = n
self.primes = self.generate_primes()
def get_primes(self):
"""
Get the list of generated prime nu... | class ChandrasekharSieve:
"""
This is a class that uses the Chandrasekhar's Sieve method to find all prime numbers within the range
"""
def __init__(self, n):
"""
Initialize the ChandrasekharSieve class with the given limit.
:param n: int, the upper limit for generating prime nu... | def generate_primes(self):
if self.n < 2:
return []
sieve = [True] * (self.n + 1)
sieve[0] = sieve[1] = False
p = 2
while p * p <= self.n:
if sieve[p]:
for i in range(p * p, self.n + 1, p):
sieve[i] = False
... | Generate prime numbers up to the specified limit using the Chandrasekhar sieve algorithm. |
ClassEval_19_sum | class ChandrasekharSieve:
"""
This is a class that uses the Chandrasekhar's Sieve method to find all prime numbers within the range
"""
def __init__(self, n):
self.n = n
self.primes = self.generate_primes()
def generate_primes(self):
"""
Generate prime numbers up to ... | class ChandrasekharSieve:
"""
This is a class that uses the Chandrasekhar's Sieve method to find all prime numbers within the range
"""
def __init__(self, n):
"""
Initialize the ChandrasekharSieve class with the given limit.
:param n: int, the upper limit for generating prime nu... | def get_primes(self):
return self.primes | Get the list of generated prime numbers. |
ClassEval_20_sum | from datetime import datetime
class Chat:
"""
This is a chat class with the functions of adding users, removing users, sending messages, and obtaining messages.
"""
def __init__(self):
self.users = {}
def remove_user(self, username):
"""
Remove a user from the Chat.
... | from datetime import datetime
class Chat:
"""
This is a chat class with the functions of adding users, removing users, sending messages, and obtaining messages.
"""
def __init__(self):
"""
Initialize the Chat with an attribute users, which is an empty dictionary.
"""
se... | def add_user(self, username):
if username in self.users:
return False
else:
self.users[username] = []
return True | Add a new user to the Chat. |
ClassEval_20_sum | from datetime import datetime
class Chat:
"""
This is a chat class with the functions of adding users, removing users, sending messages, and obtaining messages.
"""
def __init__(self):
self.users = {}
def add_user(self, username):
"""
Add a new user to the Chat.
:pa... | from datetime import datetime
class Chat:
"""
This is a chat class with the functions of adding users, removing users, sending messages, and obtaining messages.
"""
def __init__(self):
"""
Initialize the Chat with an attribute users, which is an empty dictionary.
"""
se... | def remove_user(self, username):
if username in self.users:
del self.users[username]
return True
else:
return False | Remove a user from the Chat. |
ClassEval_20_sum | from datetime import datetime
class Chat:
"""
This is a chat class with the functions of adding users, removing users, sending messages, and obtaining messages.
"""
def __init__(self):
self.users = {}
def add_user(self, username):
"""
Add a new user to the Chat.
:pa... | from datetime import datetime
class Chat:
"""
This is a chat class with the functions of adding users, removing users, sending messages, and obtaining messages.
"""
def __init__(self):
"""
Initialize the Chat with an attribute users, which is an empty dictionary.
"""
se... | def send_message(self, sender, receiver, message):
if sender not in self.users or receiver not in self.users:
return False
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
message_info = {
'sender': sender,
'receiver': receiver,
'message':... | Send a message from a user to another user. |
ClassEval_20_sum | from datetime import datetime
class Chat:
"""
This is a chat class with the functions of adding users, removing users, sending messages, and obtaining messages.
"""
def __init__(self):
self.users = {}
def add_user(self, username):
"""
Add a new user to the Chat.
:pa... | from datetime import datetime
class Chat:
"""
This is a chat class with the functions of adding users, removing users, sending messages, and obtaining messages.
"""
def __init__(self):
"""
Initialize the Chat with an attribute users, which is an empty dictionary.
"""
se... | def get_messages(self, username):
if username not in self.users:
return []
return self.users[username] | Get all the messages of a user from the Chat. |
ClassEval_21_sum | from datetime import datetime
class Classroom:
"""
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.
"""
def __init__(self, id):
self.id = id
self.courses = []
... | from datetime import datetime
class Classroom:
"""
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.
"""
def __init__(self, id):
"""
Initialize the classroom mana... | def add_course(self, course):
if course not in self.courses:
self.courses.append(course) | Add course to self.courses list if the course wasn't in it. |
ClassEval_21_sum | from datetime import datetime
class Classroom:
"""
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.
"""
def __init__(self, id):
self.id = id
self.courses = []
... | from datetime import datetime
class Classroom:
"""
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.
"""
def __init__(self, id):
"""
Initialize the classroom mana... | def remove_course(self, course):
if course in self.courses:
self.courses.remove(course) | Remove course from self.courses list if the course was in it. |
ClassEval_21_sum | from datetime import datetime
class Classroom:
"""
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.
"""
def __init__(self, id):
self.id = id
self.courses = []
... | from datetime import datetime
class Classroom:
"""
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.
"""
def __init__(self, id):
"""
Initialize the classroom mana... | def is_free_at(self, check_time):
check_time = datetime.strptime(check_time, '%H:%M')
for course in self.courses:
if datetime.strptime(course['start_time'], '%H:%M') <= check_time <= datetime.strptime(course['end_time'],
... | change the time format as '%H:%M' and check the time is free or not in the classroom. |
ClassEval_21_sum | from datetime import datetime
class Classroom:
"""
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.
"""
def __init__(self, id):
self.id = id
self.courses = []
... | from datetime import datetime
class Classroom:
"""
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.
"""
def __init__(self, id):
"""
Initialize the classroom mana... | def check_course_conflict(self, new_course):
new_start_time = datetime.strptime(new_course['start_time'], '%H:%M')
new_end_time = datetime.strptime(new_course['end_time'], '%H:%M')
flag = True
for course in self.courses:
start_time = datetime.strptime(course['start_time'], '... | Before adding a new course, check if the new course time conflicts with any other course. |
ClassEval_22_sum | class ClassRegistrationSystem:
"""
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.
"""
def __init__(self):
self.students ... | class ClassRegistrationSystem:
"""
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.
"""
def __init__(self):
"""
I... | def register_student(self, student):
if student in self.students:
return 0
else:
self.students.append(student)
return 1 | register a student to the system, add the student to the students list, if the student is already registered, return 0, else return 1 |
ClassEval_22_sum | class ClassRegistrationSystem:
"""
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.
"""
def __init__(self):
self.students ... | class ClassRegistrationSystem:
"""
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.
"""
def __init__(self):
"""
I... | def register_class(self, student_name, class_name):
if student_name in self.students_registration_classes:
self.students_registration_classes[student_name].append(class_name)
else:
self.students_registration_classes[student_name] = [class_name]
return self.students_regist... | register a class to the student. |
ClassEval_22_sum | class ClassRegistrationSystem:
"""
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.
"""
def __init__(self):
self.students ... | class ClassRegistrationSystem:
"""
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.
"""
def __init__(self):
"""
I... | def get_students_by_major(self, major):
student_list = []
for student in self.students:
if student["major"] == major:
student_list.append(student["name"])
return student_list | get all students in the major |
ClassEval_22_sum | class ClassRegistrationSystem:
"""
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.
"""
def __init__(self):
self.students ... | class ClassRegistrationSystem:
"""
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.
"""
def __init__(self):
"""
I... | def get_all_major(self):
major_list = []
for student in self.students:
if student["major"] not in major_list:
major_list.append(student["major"])
return major_list | get all majors in the system |
ClassEval_22_sum | class ClassRegistrationSystem:
"""
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.
"""
def __init__(self):
self.students ... | class ClassRegistrationSystem:
"""
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.
"""
def __init__(self):
"""
I... | def get_most_popular_class_in_major(self, major):
class_list = []
for student in self.students:
if student["major"] == major:
class_list += self.students_registration_classes[student["name"]]
most_popular_class = max(set(class_list), key=class_list.count)
retu... | get the class with the highest enrollment in the major. |
ClassEval_23_sum | import math
from typing import List
class CombinationCalculator:
"""
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.
"""
def __init__(self, datas: List... | import math
from typing import List
class CombinationCalculator:
"""
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.
"""
def __init__(self, datas: Lis... | def count(n: int, m: int) -> int:
if m == 0 or n == m:
return 1
return math.factorial(n) // (math.factorial(n - m) * math.factorial(m)) | Calculate the number of combinations for a specific count. |
ClassEval_23_sum | import math
from typing import List
class CombinationCalculator:
"""
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.
"""
def __init__(self, datas: List... | import math
from typing import List
class CombinationCalculator:
"""
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.
"""
def __init__(self, datas: Lis... | @staticmethod
def count_all(n: int) -> int:
if n < 0 or n > 63:
return False
return (1 << n) - 1 if n != 63 else float("inf") | Calculate the number of all possible combinations. |
ClassEval_23_sum | import math
from typing import List
class CombinationCalculator:
"""
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.
"""
def __init__(self, datas: List... | import math
from typing import List
class CombinationCalculator:
"""
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.
"""
def __init__(self, datas: Lis... | def select(self, m: int) -> List[List[str]]:
result = []
self._select(0, [None] * m, 0, result)
return result | Generate combinations with a specified number of elements. |
ClassEval_23_sum | import math
from typing import List
class CombinationCalculator:
"""
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.
"""
def __init__(self, datas: List... | import math
from typing import List
class CombinationCalculator:
"""
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.
"""
def __init__(self, datas: Lis... | def select_all(self) -> List[List[str]]:
result = []
for i in range(1, len(self.datas) + 1):
result.extend(self.select(i))
return result | Generate all possible combinations of selecting elements from the given data list,and it uses the select method. |
ClassEval_23_sum | import math
from typing import List
class CombinationCalculator:
"""
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.
"""
def __init__(self, datas: List... | import math
from typing import List
class CombinationCalculator:
"""
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.
"""
def __init__(self, datas: Lis... | def _select(self, dataIndex: int, resultList: List[str], resultIndex: int, result: List[List[str]]):
resultLen = len(resultList)
resultCount = resultIndex + 1
if resultCount > resultLen:
result.append(resultList.copy())
return
for i in range(dataIndex, len(self.d... | Generate combinations with a specified number of elements by recursion. |
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):
real = c1.real + c2.real
imaginary = c1.imag + c2.imag
ans... | class ComplexCalculator:
"""
This is a class that implements addition, subtraction, multiplication, and division operations for complex numbers.
"""
def __init__(self):
pass
@staticmethod
@staticmethod
def subtract(c1, c2):
"""
Subtracts two complex numbers.
... | def add(c1, c2):
real = c1.real + c2.real
imaginary = c1.imag + c2.imag
answer = complex(real, imaginary)
return answer | Adds two complex numbers. |
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 subtract(c1, c2):
real = c1.real - c2.real
imaginary = c1.imag - c2.imag
return complex(real, imaginary) | Subtracts two complex numbers. |
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 multiply(c1, c2):
real = c1.real * c2.real - c1.imag * c2.imag
imaginary = c1.real * c2.imag + c1.imag * c2.real
return complex(real, imaginary) | Multiplies two complex numbers. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.