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_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 read_json(self, file_path): """ Read a JSON file and return the data....
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 read_json(self, file_path): """ Read a JSON file and return the data....
def write_json(self, data, file_path): try: with open(file_path, 'w') as file: json.dump(data, file) return 1 except: return -1
Write data to a JSON file and save it to the given path.
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 read_json(self, file_path): """ Read a JSON file and return the data....
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 read_json(self, file_path): """ Read a JSON file and return the data....
def process_json(self, file_path, remove_key): data = self.read_json(file_path) if data == 0 or data == -1: return 0 if remove_key in data: del data[remove_key] self.write_json(data, file_path) return 1 else: return 0
read a JSON file and process the data by removing a specified key and rewrite the modified data back to the file.
ClassEval_51_sum
import numpy as np class KappaCalculator: """ This is a class as KappaCalculator, supporting to calculate Cohen's and Fleiss' kappa coefficient. """ @staticmethod @staticmethod def fleiss_kappa(testData, N, k, n): """ Calculate the fliss kappa value of an N * k matrix ...
import numpy as np class KappaCalculator: """ This is a class as KappaCalculator, supporting to calculate Cohen's and Fleiss' kappa coefficient. """ @staticmethod @staticmethod def fleiss_kappa(testData, N, k, n): """ Calculate the fliss kappa value of an N * k matrix ...
def kappa(testData, k): dataMat = np.mat(testData) P0 = 0.0 for i in range(k): P0 += dataMat[i, i] * 1.0 xsum = np.sum(dataMat, axis=1) ysum = np.sum(dataMat, axis=0) sum = np.sum(dataMat) Pe = float(ysum * xsum) / sum / sum P0 = float(P0 / sum...
Calculate the cohens kappa value of a k-dimensional matrix
ClassEval_51_sum
import numpy as np class KappaCalculator: """ This is a class as KappaCalculator, supporting to calculate Cohen's and Fleiss' kappa coefficient. """ @staticmethod def kappa(testData, k): """ Calculate the cohens kappa value of a k-dimensional matrix :param testData: The k-...
import numpy as np class KappaCalculator: """ This is a class as KappaCalculator, supporting to calculate Cohen's and Fleiss' kappa coefficient. """ @staticmethod def kappa(testData, k): """ Calculate the cohens kappa value of a k-dimensional matrix :param testData: The k-...
@staticmethod def fleiss_kappa(testData, N, k, n): dataMat = np.mat(testData, float) oneMat = np.ones((k, 1)) sum = 0.0 P0 = 0.0 for i in range(N): temp = 0.0 for j in range(k): sum += dataMat[i, j] temp += 1.0 * dataMat...
Calculate the fliss kappa value of an N * k matrix
ClassEval_52_sum
import nltk from nltk.stem import WordNetLemmatizer from nltk import pos_tag, word_tokenize import string nltk.download('averaged_perceptron_tagger') nltk.download('punkt') nltk.download('wordnet') class Lemmatization: """ This is a class about Lemmatization, which utilizes the nltk library to perform lemmat...
import nltk from nltk.stem import WordNetLemmatizer from nltk import pos_tag, word_tokenize import string nltk.download('averaged_perceptron_tagger') nltk.download('punkt') nltk.download('wordnet') class Lemmatization: """ This is a class about Lemmatization, which utilizes the nltk library to perform lemmat...
def lemmatize_sentence(self, sentence): lemmatized_words = [] sentence = self.remove_punctuation(sentence) words = word_tokenize(sentence) tagged_words = pos_tag(words) for word, tag in tagged_words: if tag.startswith('V'): lemmatized_word = self.lemma...
Remove punctuations of the sentence and tokenizes the input sentence, mark the part of speech tag of each word, lemmatizes the words with different parameters based on their parts of speech, and stores in a list.
ClassEval_52_sum
import nltk from nltk.stem import WordNetLemmatizer from nltk import pos_tag, word_tokenize import string nltk.download('averaged_perceptron_tagger') nltk.download('punkt') nltk.download('wordnet') class Lemmatization: """ This is a class about Lemmatization, which utilizes the nltk library to perform lemmat...
import nltk from nltk.stem import WordNetLemmatizer from nltk import pos_tag, word_tokenize import string nltk.download('averaged_perceptron_tagger') nltk.download('punkt') nltk.download('wordnet') class Lemmatization: """ This is a class about Lemmatization, which utilizes the nltk library to perform lemmat...
def get_pos_tag(self, sentence): pos_tags = [] sentence = self.remove_punctuation(sentence) words = word_tokenize(sentence) tagged_words = pos_tag(words) for tagged_word in tagged_words: pos_tags.append(tagged_word[1]) return pos_tags
Remove punctuations of the sentence and tokenizes the input sentence, mark the part of speech tag of each word.
ClassEval_52_sum
import nltk from nltk.stem import WordNetLemmatizer from nltk import pos_tag, word_tokenize import string nltk.download('averaged_perceptron_tagger') nltk.download('punkt') nltk.download('wordnet') class Lemmatization: """ This is a class about Lemmatization, which utilizes the nltk library to perform lemmat...
import nltk from nltk.stem import WordNetLemmatizer from nltk import pos_tag, word_tokenize import string nltk.download('averaged_perceptron_tagger') nltk.download('punkt') nltk.download('wordnet') class Lemmatization: """ This is a class about Lemmatization, which utilizes the nltk library to perform lemmat...
def remove_punctuation(self, sentence): return sentence.translate(str.maketrans('', '', string.punctuation))
Removes punctuation from the input text.
ClassEval_53_sum
import re import string class LongestWord: """ This is a class allows to add words to a list and find the longest word in a given sentence by comparing the words with the ones in the word list. """ def __init__(self): self.word_list = [] def find_longest_word(self, sentence): """...
import re import string class LongestWord: """ This is a class allows to add words to a list and find the longest word in a given sentence by comparing the words with the ones in the word list. """ def __init__(self): """ Initialize a list of word. """ self.word_list = ...
def add_word(self, word): self.word_list.append(word)
append the input word into self.word_list
ClassEval_53_sum
import re import string class LongestWord: """ This is a class allows to add words to a list and find the longest word in a given sentence by comparing the words with the ones in the word list. """ def __init__(self): self.word_list = [] def add_word(self, word): """ appe...
import re import string class LongestWord: """ This is a class allows to add words to a list and find the longest word in a given sentence by comparing the words with the ones in the word list. """ def __init__(self): """ Initialize a list of word. """ self.word_list = ...
def find_longest_word(self, sentence): longest_word = "" sentence = sentence.lower() sentence = re.sub('[%s]' % re.escape(string.punctuation), '', sentence) sentence = re.split(' ', sentence) for word in sentence: if word in self.word_list and len(word) > len(longest_...
Remove punctuation marks and split a sentence into a list of word. Find the longest splited word that is in the self.word_list. Words are strictly case sensitive.
ClassEval_54_sum
import random class MahjongConnect: """ MahjongConnect is a class representing a game board for Mahjong Connect with features like creating the board, checking valid moves, finding paths, removing icons, and checking if the game is over. """ def __init__(self, BOARD_SIZE, ICONS): self.BOARD_SI...
import random class MahjongConnect: """ MahjongConnect is a class representing a game board for Mahjong Connect with features like creating the board, checking valid moves, finding paths, removing icons, and checking if the game is over. """ def __init__(self, BOARD_SIZE, ICONS): """ i...
def create_board(self): board = [[random.choice(self.ICONS) for _ in range(self.BOARD_SIZE[1])] for _ in range(self.BOARD_SIZE[0])] return board
create the game board with the given board size and icons
ClassEval_54_sum
import random class MahjongConnect: """ MahjongConnect is a class representing a game board for Mahjong Connect with features like creating the board, checking valid moves, finding paths, removing icons, and checking if the game is over. """ def __init__(self, BOARD_SIZE, ICONS): self.BOARD_SI...
import random class MahjongConnect: """ MahjongConnect is a class representing a game board for Mahjong Connect with features like creating the board, checking valid moves, finding paths, removing icons, and checking if the game is over. """ def __init__(self, BOARD_SIZE, ICONS): """ i...
def is_valid_move(self, pos1, pos2): x1, y1 = pos1 x2, y2 = pos2 # Check if positions are within the game board range if not (0 <= x1 < self.BOARD_SIZE[0] and 0 <= y1 < self.BOARD_SIZE[1] and 0 <= x2 < self.BOARD_SIZE[ 0] and 0 <= y2 < self.BOARD_SIZE[1]): ...
check if the move of two icons is valid (i.e. positions are within the game board range, the two positions are not the same, the two positions have the same icon, and there is a valid path between the two positions)
ClassEval_54_sum
import random class MahjongConnect: """ MahjongConnect is a class representing a game board for Mahjong Connect with features like creating the board, checking valid moves, finding paths, removing icons, and checking if the game is over. """ def __init__(self, BOARD_SIZE, ICONS): self.BOARD_SI...
import random class MahjongConnect: """ MahjongConnect is a class representing a game board for Mahjong Connect with features like creating the board, checking valid moves, finding paths, removing icons, and checking if the game is over. """ def __init__(self, BOARD_SIZE, ICONS): """ i...
def has_path(self, pos1, pos2): visited = set() stack = [pos1] while stack: current_pos = stack.pop() if current_pos == pos2: return True if current_pos in visited: continue visited.add(current_pos) x,...
check if there is a path between two icons
ClassEval_54_sum
import random class MahjongConnect: """ MahjongConnect is a class representing a game board for Mahjong Connect with features like creating the board, checking valid moves, finding paths, removing icons, and checking if the game is over. """ def __init__(self, BOARD_SIZE, ICONS): self.BOARD_SI...
import random class MahjongConnect: """ MahjongConnect is a class representing a game board for Mahjong Connect with features like creating the board, checking valid moves, finding paths, removing icons, and checking if the game is over. """ def __init__(self, BOARD_SIZE, ICONS): """ i...
def remove_icons(self, pos1, pos2): x1, y1 = pos1 x2, y2 = pos2 self.board[x1][y1] = ' ' self.board[x2][y2] = ' '
remove the connected icons on the game board
ClassEval_54_sum
import random class MahjongConnect: """ MahjongConnect is a class representing a game board for Mahjong Connect with features like creating the board, checking valid moves, finding paths, removing icons, and checking if the game is over. """ def __init__(self, BOARD_SIZE, ICONS): self.BOARD_SI...
import random class MahjongConnect: """ MahjongConnect is a class representing a game board for Mahjong Connect with features like creating the board, checking valid moves, finding paths, removing icons, and checking if the game is over. """ def __init__(self, BOARD_SIZE, ICONS): """ i...
def is_game_over(self): for row in self.board: if any(icon != ' ' for icon in row): return False return True
Check if the game is over (i.e., if there are no more icons on the game board)
ClassEval_55_sum
class Manacher: """ his is a class that implements a manacher algorithm to find the Longest palindromic substring in a given string. """ def __init__(self, input_string) -> None: self.input_string = input_string def palindromic_string(self): """ Finds the longest palindromi...
class Manacher: """ his is a class that implements a manacher algorithm to find the Longest palindromic substring in a given string. """ def __init__(self, input_string) -> None: """ Initializes the Manacher class with the given input_string. :param input_string: The input_strin...
def palindromic_length(self, center, diff, string): if (center - diff == -1 or center + diff == len(string) or string[center - diff] != string[center + diff]): return 0 return 1 + self.palindromic_length(center, diff + 1, string)
Recursively calculates the length of the palindromic substring based on a given center, difference value, and input string.
ClassEval_55_sum
class Manacher: """ his is a class that implements a manacher algorithm to find the Longest palindromic substring in a given string. """ def __init__(self, input_string) -> None: self.input_string = input_string def palindromic_length(self, center, diff, string): """ Recursi...
class Manacher: """ his is a class that implements a manacher algorithm to find the Longest palindromic substring in a given string. """ def __init__(self, input_string) -> None: """ Initializes the Manacher class with the given input_string. :param input_string: The input_strin...
def palindromic_string(self): max_length = 0 new_input_string = "" output_string = "" for i in self.input_string[:len(self.input_string) - 1]: new_input_string += i + "|" new_input_string += self.input_string[-1] for i in range(len(new_input_string)): ...
Finds the longest palindromic substring in the given string.
ClassEval_56_sum
class MetricsCalculator: """ The class calculates precision, recall, F1 score, and accuracy based on predicted and true labels. """ def __init__(self): self.true_positives = 0 self.false_positives = 0 self.false_negatives = 0 self.true_negatives = 0 def precision(sel...
class MetricsCalculator: """ The class calculates precision, recall, F1 score, and accuracy based on predicted and true labels. """ def __init__(self): """ Initialize the number of all four samples to 0 """ self.true_positives = 0 self.false_positives = 0 ...
def update(self, predicted_labels, true_labels): for predicted, true in zip(predicted_labels, true_labels): if predicted == 1 and true == 1: self.true_positives += 1 elif predicted == 1 and true == 0: self.false_positives += 1 elif predicted ==...
Update the number of all four samples(true_positives, false_positives, false_negatives, true_negatives)
ClassEval_56_sum
class MetricsCalculator: """ The class calculates precision, recall, F1 score, and accuracy based on predicted and true labels. """ def __init__(self): self.true_positives = 0 self.false_positives = 0 self.false_negatives = 0 self.true_negatives = 0 def update(self, ...
class MetricsCalculator: """ The class calculates precision, recall, F1 score, and accuracy based on predicted and true labels. """ def __init__(self): """ Initialize the number of all four samples to 0 """ self.true_positives = 0 self.false_positives = 0 ...
def precision(self, predicted_labels, true_labels): self.update(predicted_labels, true_labels) if self.true_positives + self.false_positives == 0: return 0.0 return self.true_positives / (self.true_positives + self.false_positives)
Calculate precision
ClassEval_56_sum
class MetricsCalculator: """ The class calculates precision, recall, F1 score, and accuracy based on predicted and true labels. """ def __init__(self): self.true_positives = 0 self.false_positives = 0 self.false_negatives = 0 self.true_negatives = 0 def update(self, ...
class MetricsCalculator: """ The class calculates precision, recall, F1 score, and accuracy based on predicted and true labels. """ def __init__(self): """ Initialize the number of all four samples to 0 """ self.true_positives = 0 self.false_positives = 0 ...
def recall(self, predicted_labels, true_labels): self.update(predicted_labels, true_labels) if self.true_positives + self.false_negatives == 0: return 0.0 return self.true_positives / (self.true_positives + self.false_negatives)
Calculate recall
ClassEval_56_sum
class MetricsCalculator: """ The class calculates precision, recall, F1 score, and accuracy based on predicted and true labels. """ def __init__(self): self.true_positives = 0 self.false_positives = 0 self.false_negatives = 0 self.true_negatives = 0 def update(self, ...
class MetricsCalculator: """ The class calculates precision, recall, F1 score, and accuracy based on predicted and true labels. """ def __init__(self): """ Initialize the number of all four samples to 0 """ self.true_positives = 0 self.false_positives = 0 ...
def f1_score(self, predicted_labels, true_labels): self.update(predicted_labels, true_labels) precision = self.precision(predicted_labels, true_labels) recall = self.recall(predicted_labels, true_labels) if precision + recall == 0.0: return 0.0 return (2 * precision *...
Calculate f1 score, which is the harmonic mean of precision and recall
ClassEval_56_sum
class MetricsCalculator: """ The class calculates precision, recall, F1 score, and accuracy based on predicted and true labels. """ def __init__(self): self.true_positives = 0 self.false_positives = 0 self.false_negatives = 0 self.true_negatives = 0 def update(self, ...
class MetricsCalculator: """ The class calculates precision, recall, F1 score, and accuracy based on predicted and true labels. """ def __init__(self): """ Initialize the number of all four samples to 0 """ self.true_positives = 0 self.false_positives = 0 ...
def accuracy(self, predicted_labels, true_labels): self.update(predicted_labels, true_labels) total = self.true_positives + self.true_negatives + self.false_positives + self.false_negatives if total == 0: return 0.0 return (self.true_positives + self.true_negatives) / total
Calculate accuracy
ClassEval_57_sum
import numpy as np class MetricsCalculator2: """ The class provides to calculate Mean Reciprocal Rank (MRR) and Mean Average Precision (MAP) based on input data, where MRR measures the ranking quality and MAP measures the average precision. """ def __init__(self): pass @staticmethod @...
import numpy as np class MetricsCalculator2: """ The class provides to calculate Mean Reciprocal Rank (MRR) and Mean Average Precision (MAP) based on input data, where MRR measures the ranking quality and MAP measures the average precision. """ def __init__(self): pass @staticmethod ...
def mrr(data): if type(data) != list and type(data) != tuple: raise Exception("the input must be a tuple([0,...,1,...],int) or a iteration of list of tuple") if len(data) == 0: return 0.0, [0.0] if type(data) == tuple: (sub_list, total_num) = data ...
compute the MRR of the input data. MRR is a widely used evaluation index. It is the mean of reciprocal rank.
ClassEval_57_sum
import numpy as np class MetricsCalculator2: """ The class provides to calculate Mean Reciprocal Rank (MRR) and Mean Average Precision (MAP) based on input data, where MRR measures the ranking quality and MAP measures the average precision. """ def __init__(self): pass @staticmethod d...
import numpy as np class MetricsCalculator2: """ The class provides to calculate Mean Reciprocal Rank (MRR) and Mean Average Precision (MAP) based on input data, where MRR measures the ranking quality and MAP measures the average precision. """ def __init__(self): pass @staticmethod ...
@staticmethod def map(data): if type(data) != list and type(data) != tuple: raise Exception("the input must be a tuple([0,...,1,...],int) or a iteration of list of tuple") if len(data) == 0: return 0.0, [0.0] if type(data) == tuple: (sub_list, total_num) ...
compute the MAP of the input data. MAP is a widely used evaluation index. It is the mean of AP (average precision).
ClassEval_58_sum
import random class MinesweeperGame: """ This is a class that implements mine sweeping games including minesweeping and winning judgment. """ def __init__(self, n, k) -> None: self.n = n self.k = k self.minesweeper_map = self.generate_mine_sweeper_map() self.player_map =...
import random class MinesweeperGame: """ This is a class that implements mine sweeping games including minesweeping and winning judgment. """ def __init__(self, n, k) -> None: """ Initializes the MinesweeperGame class with the size of the board and the number of mines. :param n...
def generate_mine_sweeper_map(self): arr = [[0 for row in range(self.n)] for column in range(self.n)] for num in range(self.k): x = random.randint(0, self.n-1) y = random.randint(0, self.n-1) arr[y][x] = 'X' if (x >=0 and x <= self.n-2) and (y >= 0 and y <...
Generates a minesweeper map with the given size of the board and the number of mines,the given parameter n is the size of the board,the size of the board is n*n,the parameter k is the number of mines,'X' represents the mine,other numbers represent the number of mines around the position.
ClassEval_58_sum
import random class MinesweeperGame: """ This is a class that implements mine sweeping games including minesweeping and winning judgment. """ def __init__(self, n, k) -> None: self.n = n self.k = k self.minesweeper_map = self.generate_mine_sweeper_map() self.player_map =...
import random class MinesweeperGame: """ This is a class that implements mine sweeping games including minesweeping and winning judgment. """ def __init__(self, n, k) -> None: """ Initializes the MinesweeperGame class with the size of the board and the number of mines. :param n...
def generate_playerMap(self): arr = [['-' for row in range(self.n)] for column in range(self.n)] return arr
Generates a player map with the given size of the board, the given parameter n is the size of the board,the size of the board is n*n,the parameter k is the number of mines,'-' represents the unknown position.
ClassEval_58_sum
import random class MinesweeperGame: """ This is a class that implements mine sweeping games including minesweeping and winning judgment. """ def __init__(self, n, k) -> None: self.n = n self.k = k self.minesweeper_map = self.generate_mine_sweeper_map() self.player_map =...
import random class MinesweeperGame: """ This is a class that implements mine sweeping games including minesweeping and winning judgment. """ def __init__(self, n, k) -> None: """ Initializes the MinesweeperGame class with the size of the board and the number of mines. :param n...
def check_won(self, map): for i in range(self.n): for j in range(self.n): if map[i][j] == '-' and self.minesweeper_map[i][j] != 'X': return False return True
Checks whether the player has won the game,if there are just mines in the player map,return True,otherwise return False.
ClassEval_58_sum
import random class MinesweeperGame: """ This is a class that implements mine sweeping games including minesweeping and winning judgment. """ def __init__(self, n, k) -> None: self.n = n self.k = k self.minesweeper_map = self.generate_mine_sweeper_map() self.player_map =...
import random class MinesweeperGame: """ This is a class that implements mine sweeping games including minesweeping and winning judgment. """ def __init__(self, n, k) -> None: """ Initializes the MinesweeperGame class with the size of the board and the number of mines. :param n...
def sweep(self, x, y): if (self.minesweeper_map[x][y] == 'X'): return False else: self.player_map[x][y] = self.minesweeper_map[x][y] self.score += 1 if self.check_won(self.player_map) == True: return True return self.player_map
Sweeps the given position.
ClassEval_59_sum
from datetime import datetime import numpy as np class MovieBookingSystem: """ this is a class as movie booking system, which allows to add movies, book tickets and check the available movies within a given time range. """ def __init__(self): self.movies = [] def book_ticket(self, name, s...
from datetime import datetime import numpy as np class MovieBookingSystem: """ this is a class as movie booking system, which allows to add movies, book tickets and check the available movies within a given time range. """ def __init__(self): """ Initialize movies contains the informa...
def add_movie(self, name, price, start_time, end_time, n): movie = { 'name': name, 'price': price, 'start_time': datetime.strptime(start_time, '%H:%M'), 'end_time': datetime.strptime(end_time, '%H:%M'), 'seats': np.zeros((n, n)) } self....
Add a new movie into self.movies
ClassEval_59_sum
from datetime import datetime import numpy as np class MovieBookingSystem: """ this is a class as movie booking system, which allows to add movies, book tickets and check the available movies within a given time range. """ def __init__(self): self.movies = [] def add_movie(self, name, pri...
from datetime import datetime import numpy as np class MovieBookingSystem: """ this is a class as movie booking system, which allows to add movies, book tickets and check the available movies within a given time range. """ def __init__(self): """ Initialize movies contains the informa...
def book_ticket(self, name, seats_to_book): for movie in self.movies: if movie['name'] == name: for seat in seats_to_book: if movie['seats'][seat[0]][seat[1]] == 0: movie['seats'][seat[0]][seat[1]] = 1 else: ...
Book tickets for a movie. Change the seats value in self.movies if book successfully.
ClassEval_59_sum
from datetime import datetime import numpy as np class MovieBookingSystem: """ this is a class as movie booking system, which allows to add movies, book tickets and check the available movies within a given time range. """ def __init__(self): self.movies = [] def add_movie(self, name, pri...
from datetime import datetime import numpy as np class MovieBookingSystem: """ this is a class as movie booking system, which allows to add movies, book tickets and check the available movies within a given time range. """ def __init__(self): """ Initialize movies contains the informa...
def available_movies(self, start_time, end_time): start_time = datetime.strptime(start_time, '%H:%M') end_time = datetime.strptime(end_time, '%H:%M') available_movies = [] for movie in self.movies: if start_time <= movie['start_time'] and movie['end_time'] <= end_time: ...
Get a list of available movies within the specified time range
ClassEval_60_sum
import sqlite3 class MovieTicketDB: """ This is a class for movie database operations, which allows for inserting movie information, searching for movie information by name, and deleting movie information by name. """ def __init__(self, db_name): self.connection = sqlite3.connect(db_name) ...
import sqlite3 class MovieTicketDB: """ This is a class for movie database operations, which allows for inserting movie information, searching for movie information by name, and deleting movie information by name. """ def __init__(self, db_name): """ Initializes the MovieTicketDB objec...
def create_table(self): self.cursor.execute(''' CREATE TABLE IF NOT EXISTS tickets ( id INTEGER PRIMARY KEY, movie_name TEXT, theater_name TEXT, seat_number TEXT, customer_name TEXT ) ''') sel...
Creates a "tickets" table in the database if it does not exist already.Fields include ID of type int, movie name of type str, theater name of type str, seat number of type str, and customer name of type str
ClassEval_60_sum
import sqlite3 class MovieTicketDB: """ This is a class for movie database operations, which allows for inserting movie information, searching for movie information by name, and deleting movie information by name. """ def __init__(self, db_name): self.connection = sqlite3.connect(db_name) ...
import sqlite3 class MovieTicketDB: """ This is a class for movie database operations, which allows for inserting movie information, searching for movie information by name, and deleting movie information by name. """ def __init__(self, db_name): """ Initializes the MovieTicketDB objec...
def insert_ticket(self, movie_name, theater_name, seat_number, customer_name): self.cursor.execute(''' INSERT INTO tickets (movie_name, theater_name, seat_number, customer_name) VALUES (?, ?, ?, ?) ''', (movie_name, theater_name, seat_number, customer_name)) self.connecti...
Inserts a new ticket into the "tickets" table.
ClassEval_60_sum
import sqlite3 class MovieTicketDB: """ This is a class for movie database operations, which allows for inserting movie information, searching for movie information by name, and deleting movie information by name. """ def __init__(self, db_name): self.connection = sqlite3.connect(db_name) ...
import sqlite3 class MovieTicketDB: """ This is a class for movie database operations, which allows for inserting movie information, searching for movie information by name, and deleting movie information by name. """ def __init__(self, db_name): """ Initializes the MovieTicketDB objec...
def search_tickets_by_customer(self, customer_name): self.cursor.execute(''' SELECT * FROM tickets WHERE customer_name = ? ''', (customer_name,)) tickets = self.cursor.fetchall() return tickets
Searches for tickets in the "tickets" table by customer name.
ClassEval_60_sum
import sqlite3 class MovieTicketDB: """ This is a class for movie database operations, which allows for inserting movie information, searching for movie information by name, and deleting movie information by name. """ def __init__(self, db_name): self.connection = sqlite3.connect(db_name) ...
import sqlite3 class MovieTicketDB: """ This is a class for movie database operations, which allows for inserting movie information, searching for movie information by name, and deleting movie information by name. """ def __init__(self, db_name): """ Initializes the MovieTicketDB objec...
def delete_ticket(self, ticket_id): self.cursor.execute(''' DELETE FROM tickets WHERE id = ? ''', (ticket_id,)) self.connection.commit()
Deletes a ticket from the "tickets" table by ticket ID.
ClassEval_61_sum
class MusicPlayer: """ This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song. """ def __init__(self): self.playlist = [] self.current_song = None self.volume = 50 def remove_song(s...
class MusicPlayer: """ This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song. """ def __init__(self): """ Initializes the music player with an empty playlist, no current song, and a default vo...
def add_song(self, song): self.playlist.append(song)
Adds a song to the playlist.
ClassEval_61_sum
class MusicPlayer: """ This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song. """ def __init__(self): self.playlist = [] self.current_song = None self.volume = 50 def add_song(self...
class MusicPlayer: """ This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song. """ def __init__(self): """ Initializes the music player with an empty playlist, no current song, and a default vo...
def remove_song(self, song): if song in self.playlist: self.playlist.remove(song) if self.current_song == song: self.stop()
Removes a song from the playlist.
ClassEval_61_sum
class MusicPlayer: """ This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song. """ def __init__(self): self.playlist = [] self.current_song = None self.volume = 50 def add_song(self...
class MusicPlayer: """ This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song. """ def __init__(self): """ Initializes the music player with an empty playlist, no current song, and a default vo...
def play(self): if self.playlist and self.current_song: return self.playlist[0] elif len(self.playlist): return False
Plays the current song in the playlist.
ClassEval_61_sum
class MusicPlayer: """ This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song. """ def __init__(self): self.playlist = [] self.current_song = None self.volume = 50 def add_song(self...
class MusicPlayer: """ This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song. """ def __init__(self): """ Initializes the music player with an empty playlist, no current song, and a default vo...
def stop(self): if self.current_song: self.current_song = None return True else: return False
Stops the current song in the playlist.
ClassEval_61_sum
class MusicPlayer: """ This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song. """ def __init__(self): self.playlist = [] self.current_song = None self.volume = 50 def add_song(self...
class MusicPlayer: """ This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song. """ def __init__(self): """ Initializes the music player with an empty playlist, no current song, and a default vo...
def switch_song(self): if self.current_song: current_index = self.playlist.index(self.current_song) if current_index < len(self.playlist) - 1: self.current_song = self.playlist[current_index + 1] return True else: return False ...
Switches to the next song in the playlist.
ClassEval_61_sum
class MusicPlayer: """ This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song. """ def __init__(self): self.playlist = [] self.current_song = None self.volume = 50 def add_song(self...
class MusicPlayer: """ This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song. """ def __init__(self): """ Initializes the music player with an empty playlist, no current song, and a default vo...
def previous_song(self): if self.current_song: current_index = self.playlist.index(self.current_song) if current_index > 0: self.current_song = self.playlist[current_index - 1] return True else: return False else: ...
Switches to the previous song in the playlist.
ClassEval_61_sum
class MusicPlayer: """ This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song. """ def __init__(self): self.playlist = [] self.current_song = None self.volume = 50 def add_song(self...
class MusicPlayer: """ This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song. """ def __init__(self): """ Initializes the music player with an empty playlist, no current song, and a default vo...
def set_volume(self, volume): if 0 <= volume <= 100: self.volume = volume else: return False
Sets the volume of the music player,ifthe volume is between 0 and 100 is valid.
ClassEval_61_sum
class MusicPlayer: """ This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song. """ def __init__(self): self.playlist = [] self.current_song = None self.volume = 50 def add_song(self...
class MusicPlayer: """ This is a class as a music player that provides to play, stop, add songs, remove songs, set volume, shuffle, and switch to the next or previous song. """ def __init__(self): """ Initializes the music player with an empty playlist, no current song, and a default vo...
def shuffle(self): if self.playlist: import random random.shuffle(self.playlist) return True else: return False
Shuffles the playlist.
ClassEval_62_sum
class NLPDataProcessor: """ The class processes NLP data by removing stop words from a list of strings using a pre-defined stop word list. """ def remove_stop_words(self, string_list, stop_word_list): """ Remove all the stop words from the list of strings. :param string_list: a ...
class NLPDataProcessor: """ The class processes NLP data by removing stop words from a list of strings using a pre-defined stop word list. """ def remove_stop_words(self, string_list, stop_word_list): """ Remove all the stop words from the list of strings. :param string_lis...
def construct_stop_word_list(self): stop_word_list = ['a', 'an', 'the'] return stop_word_list
Construct a stop word list including 'a', 'an', 'the'.
ClassEval_62_sum
class NLPDataProcessor: """ The class processes NLP data by removing stop words from a list of strings using a pre-defined stop word list. """ def construct_stop_word_list(self): """ Construct a stop word list including 'a', 'an', 'the'. :return: a list of stop words >>>...
class NLPDataProcessor: """ The class processes NLP data by removing stop words from a list of strings using a pre-defined stop word list. """ def construct_stop_word_list(self): """ Construct a stop word list including 'a', 'an', 'the'. :return: a list of stop words >>...
def remove_stop_words(self, string_list, stop_word_list): answer = [] for string in string_list: string_split = string.split() for word in string_split: if word in stop_word_list: string_split.remove(word) answer.append(string_split...
Remove all the stop words from the list of strings.
ClassEval_62_sum
class NLPDataProcessor: """ The class processes NLP data by removing stop words from a list of strings using a pre-defined stop word list. """ def construct_stop_word_list(self): """ Construct a stop word list including 'a', 'an', 'the'. :return: a list of stop words >>>...
class NLPDataProcessor: """ The class processes NLP data by removing stop words from a list of strings using a pre-defined stop word list. """ def construct_stop_word_list(self): """ Construct a stop word list including 'a', 'an', 'the'. :return: a list of stop words >>...
def process(self, string_list): stop_word_list = self.construct_stop_word_list() words_list = self.remove_stop_words(string_list, stop_word_list) return words_list
Construct a stop word list including 'a', 'an', 'the', and remove all the stop words from the list of strings.
ClassEval_63_sum
from collections import Counter import re class NLPDataProcessor2: """ The class processes NLP data by extracting words from a list of strings, calculating the frequency of each word, and returning the top 5 most frequent words. """ def calculate_word_frequency(self, words_list): """ C...
import re from collections import Counter class NLPDataProcessor2: """ The class processes NLP data by extracting words from a list of strings, calculating the frequency of each word, and returning the top 5 most frequent words. """ def calculate_word_frequency(self, words_list): """ ...
def process_data(self, string_list): words_list = [] for string in string_list: # Remove non-English letters and convert to lowercase processed_string = re.sub(r'[^a-zA-Z\s]', '', string.lower()) # Split the string into words words = processed_string.split...
keep only English letters and spaces in the string, then convert the string to lower case, and then split the string into a list of words.
ClassEval_63_sum
from collections import Counter import re class NLPDataProcessor2: """ The class processes NLP data by extracting words from a list of strings, calculating the frequency of each word, and returning the top 5 most frequent words. """ def process_data(self, string_list): """ keep only En...
import re from collections import Counter class NLPDataProcessor2: """ The class processes NLP data by extracting words from a list of strings, calculating the frequency of each word, and returning the top 5 most frequent words. """ def process_data(self, string_list): """ keep only E...
def calculate_word_frequency(self, words_list): word_frequency = Counter() for words in words_list: word_frequency.update(words) sorted_word_frequency = dict(sorted(word_frequency.items(), key=lambda x: x[1], reverse=True)) top_5_word_frequency = dict(list(sorted_word_frequen...
Calculate the word frequency of each word in the list of words list, and sort the word frequency dictionary by value in descending order.
ClassEval_63_sum
from collections import Counter import re class NLPDataProcessor2: """ The class processes NLP data by extracting words from a list of strings, calculating the frequency of each word, and returning the top 5 most frequent words. """ def process_data(self, string_list): """ keep only En...
import re from collections import Counter class NLPDataProcessor2: """ The class processes NLP data by extracting words from a list of strings, calculating the frequency of each word, and returning the top 5 most frequent words. """ def process_data(self, string_list): """ keep only E...
def process(self, string_list): words_list = self.process_data(string_list) word_frequency_dict = self.calculate_word_frequency(words_list) return word_frequency_dict
keep only English letters and spaces in the string, then convert the string to lower case, and then split the string into a list of words. Calculate the word frequency of each word in the list of words list, and sort the word frequency dictionary by value in descending order.
ClassEval_64_sum
class NumberConverter: """ The class allows to convert decimal to binary, octal and hexadecimal repectively and contrarily """ @staticmethod @staticmethod def binary_to_decimal(binary_num): """ Convert a number from binary format to decimal format. :param binary_num: str...
class NumberConverter: """ The class allows to convert decimal to binary, octal and hexadecimal repectively and contrarily """ @staticmethod @staticmethod def binary_to_decimal(binary_num): """ Convert a number from binary format to decimal format. :param binary_nu...
def decimal_to_binary(decimal_num): binary_num = bin(decimal_num)[2:] return binary_num
Convert a number from decimal format to binary format.
ClassEval_64_sum
class NumberConverter: """ The class allows to convert decimal to binary, octal and hexadecimal repectively and contrarily """ @staticmethod def decimal_to_binary(decimal_num): """ Convert a number from decimal format to binary format. :param decimal_num: int, decimal number...
class NumberConverter: """ The class allows to convert decimal to binary, octal and hexadecimal repectively and contrarily """ @staticmethod def decimal_to_binary(decimal_num): """ Convert a number from decimal format to binary format. :param decimal_num: int, decimal numbe...
@staticmethod def binary_to_decimal(binary_num): decimal_num = int(binary_num, 2) return decimal_num
Convert a number from binary format to decimal format.
ClassEval_64_sum
class NumberConverter: """ The class allows to convert decimal to binary, octal and hexadecimal repectively and contrarily """ @staticmethod def decimal_to_binary(decimal_num): """ Convert a number from decimal format to binary format. :param decimal_num: int, decimal number...
class NumberConverter: """ The class allows to convert decimal to binary, octal and hexadecimal repectively and contrarily """ @staticmethod def decimal_to_binary(decimal_num): """ Convert a number from decimal format to binary format. :param decimal_num: int, decimal numbe...
@staticmethod def decimal_to_octal(decimal_num): octal_num = oct(decimal_num)[2:] return octal_num
Convert a number from decimal format to octal format.
ClassEval_64_sum
class NumberConverter: """ The class allows to convert decimal to binary, octal and hexadecimal repectively and contrarily """ @staticmethod def decimal_to_binary(decimal_num): """ Convert a number from decimal format to binary format. :param decimal_num: int, decimal number...
class NumberConverter: """ The class allows to convert decimal to binary, octal and hexadecimal repectively and contrarily """ @staticmethod def decimal_to_binary(decimal_num): """ Convert a number from decimal format to binary format. :param decimal_num: int, decimal numbe...
@staticmethod def octal_to_decimal(octal_num): decimal_num = int(octal_num, 8) return decimal_num
Convert a number from octal format to decimal format.
ClassEval_64_sum
class NumberConverter: """ The class allows to convert decimal to binary, octal and hexadecimal repectively and contrarily """ @staticmethod def decimal_to_binary(decimal_num): """ Convert a number from decimal format to binary format. :param decimal_num: int, decimal number...
class NumberConverter: """ The class allows to convert decimal to binary, octal and hexadecimal repectively and contrarily """ @staticmethod def decimal_to_binary(decimal_num): """ Convert a number from decimal format to binary format. :param decimal_num: int, decimal numbe...
@staticmethod def decimal_to_hex(decimal_num): hex_num = hex(decimal_num)[2:] return hex_num
Convert a number from decimal format to hex format.
ClassEval_64_sum
class NumberConverter: """ The class allows to convert decimal to binary, octal and hexadecimal repectively and contrarily """ @staticmethod def decimal_to_binary(decimal_num): """ Convert a number from decimal format to binary format. :param decimal_num: int, decimal number...
class NumberConverter: """ The class allows to convert decimal to binary, octal and hexadecimal repectively and contrarily """ @staticmethod def decimal_to_binary(decimal_num): """ Convert a number from decimal format to binary format. :param decimal_num: int, decimal numbe...
@staticmethod def hex_to_decimal(hex_num): decimal_num = int(hex_num, 16) return decimal_num
Convert a number from hex format to decimal format.
ClassEval_65_sum
class NumberWordFormatter: """ This is a class that provides to convert numbers into their corresponding English word representation, including handling the conversion of both the integer and decimal parts, and incorporating appropriate connectors and units. """ def __init__(self): self.NUMBER =...
class NumberWordFormatter: """ This is a class that provides to convert numbers into their corresponding English word representation, including handling the conversion of both the integer and decimal parts, and incorporating appropriate connectors and units. """ def __init__(self): """ ...
def format(self, x): if x is not None: return self.format_string(str(x)) else: return ""
Converts a number into words format
ClassEval_65_sum
class NumberWordFormatter: """ This is a class that provides to convert numbers into their corresponding English word representation, including handling the conversion of both the integer and decimal parts, and incorporating appropriate connectors and units. """ def __init__(self): self.NUMBER =...
class NumberWordFormatter: """ This is a class that provides to convert numbers into their corresponding English word representation, including handling the conversion of both the integer and decimal parts, and incorporating appropriate connectors and units. """ def __init__(self): """ ...
def format_string(self, x): lstr, rstr = (x.split('.') + [''])[:2] lstrrev = lstr[::-1] a = [''] * 5 if len(lstrrev) % 3 == 1: lstrrev += "00" elif len(lstrrev) % 3 == 2: lstrrev += "0" lm = "" for i in range(len(lstrrev) // 3): ...
Converts a string representation of a number into words format
ClassEval_65_sum
class NumberWordFormatter: """ This is a class that provides to convert numbers into their corresponding English word representation, including handling the conversion of both the integer and decimal parts, and incorporating appropriate connectors and units. """ def __init__(self): self.NUMBER =...
class NumberWordFormatter: """ This is a class that provides to convert numbers into their corresponding English word representation, including handling the conversion of both the integer and decimal parts, and incorporating appropriate connectors and units. """ def __init__(self): """ ...
def trans_two(self, s): s = s.zfill(2) if s[0] == "0": return self.NUMBER[int(s[-1])] elif s[0] == "1": return self.NUMBER_TEEN[int(s) - 10] elif s[1] == "0": return self.NUMBER_TEN[int(s[0]) - 1] else: return self.NUMBER_TEN[int(s[...
Converts a two-digit number into words format
ClassEval_65_sum
class NumberWordFormatter: """ This is a class that provides to convert numbers into their corresponding English word representation, including handling the conversion of both the integer and decimal parts, and incorporating appropriate connectors and units. """ def __init__(self): self.NUMBER =...
class NumberWordFormatter: """ This is a class that provides to convert numbers into their corresponding English word representation, including handling the conversion of both the integer and decimal parts, and incorporating appropriate connectors and units. """ def __init__(self): """ ...
def trans_three(self, s): if s[0] == "0": return self.trans_two(s[1:]) elif s[1:] == "00": return f"{self.NUMBER[int(s[0])]} HUNDRED" else: return f"{self.NUMBER[int(s[0])]} HUNDRED AND {self.trans_two(s[1:])}"
Converts a three-digit number into words format
ClassEval_65_sum
class NumberWordFormatter: """ This is a class that provides to convert numbers into their corresponding English word representation, including handling the conversion of both the integer and decimal parts, and incorporating appropriate connectors and units. """ def __init__(self): self.NUMBER =...
class NumberWordFormatter: """ This is a class that provides to convert numbers into their corresponding English word representation, including handling the conversion of both the integer and decimal parts, and incorporating appropriate connectors and units. """ def __init__(self): """ ...
def parse_more(self, i): return self.NUMBER_MORE[i]
Parses the thousand/million/billion suffix based on the index
ClassEval_66_sum
class NumericEntityUnescaper: """ This is a class that provides functionality to replace numeric entities with their corresponding characters in a given string. """ def __init__(self): pass @staticmethod def is_hex_char(char): """ Determines whether a given character is ...
class NumericEntityUnescaper: """ This is a class that provides functionality to replace numeric entities with their corresponding characters in a given string. """ def __init__(self): pass @staticmethod def is_hex_char(char): """ Determines whether a given charac...
def replace(self, string): out = [] pos = 0 length = len(string) while pos < length - 2: if string[pos] == '&' and string[pos + 1] == '#': start = pos + 2 is_hex = False first_char = string[start] if first_char...
Replaces numeric character references (HTML entities) in the input string with their corresponding Unicode characters.
ClassEval_66_sum
class NumericEntityUnescaper: """ This is a class that provides functionality to replace numeric entities with their corresponding characters in a given string. """ def __init__(self): pass def replace(self, string): """ Replaces numeric character references (HTML entities) ...
class NumericEntityUnescaper: """ This is a class that provides functionality to replace numeric entities with their corresponding characters in a given string. """ def __init__(self): pass def replace(self, string): """ Replaces numeric character references (HTML entities)...
@staticmethod def is_hex_char(char): return char.isdigit() or ('a' <= char.lower() <= 'f')
Determines whether a given character is a hexadecimal digit.
ClassEval_67_sum
class Order: """ The class manages restaurant orders by allowing the addition of dishes, calculation of the total cost, and checkout. """ def __init__(self): self.menu = [] # menu = [{"dish": dish name, "price": price, "count": count}, ...] self.selected_dishes = [] # se...
class Order: """ The class manages restaurant orders by allowing the addition of dishes, calculation of the total cost, and checkout. """ def __init__(self): """ Initialize the order management system self.menu stores the dishes of resturant inventory menu = [{"dish": d...
def add_dish(self, dish): for menu_dish in self.menu: if dish["dish"] == menu_dish["dish"]: if menu_dish["count"] < dish["count"]: return False else: menu_dish["count"] -= dish["count"] break self.sel...
Check the self.menu and add into self.selected_dish if the dish count is valid. And if the dish has successfully been added, change the count in self.menu.
ClassEval_67_sum
class Order: """ The class manages restaurant orders by allowing the addition of dishes, calculation of the total cost, and checkout. """ def __init__(self): self.menu = [] # menu = [{"dish": dish name, "price": price, "count": count}, ...] self.selected_dishes = [] # se...
class Order: """ The class manages restaurant orders by allowing the addition of dishes, calculation of the total cost, and checkout. """ def __init__(self): """ Initialize the order management system self.menu stores the dishes of resturant inventory menu = [{"dish": d...
def calculate_total(self): total = 0 for dish in self.selected_dishes: total += dish["price"] * dish["count"] * self.sales[dish["dish"]] return total
Calculate the total price of dishes that have been ordered. Multiply the count, price and sales.
ClassEval_67_sum
class Order: """ The class manages restaurant orders by allowing the addition of dishes, calculation of the total cost, and checkout. """ def __init__(self): self.menu = [] # menu = [{"dish": dish name, "price": price, "count": count}, ...] self.selected_dishes = [] # se...
class Order: """ The class manages restaurant orders by allowing the addition of dishes, calculation of the total cost, and checkout. """ def __init__(self): """ Initialize the order management system self.menu stores the dishes of resturant inventory menu = [{"dish": d...
def checkout(self): if len(self.selected_dishes) == 0: return False total = self.calculate_total() self.selected_dishes = [] return total
Check out the dished ordered. IF the self.selected_dishes is not empty, invoke the calculate_total method to check out.
ClassEval_68_sum
class PageUtil: """ PageUtil class is a versatile utility for handling pagination and search functionalities in an efficient and convenient manner. """ def __init__(self, data, page_size): self.data = data self.page_size = page_size self.total_items = len(data) self.total...
class PageUtil: """ PageUtil class is a versatile utility for handling pagination and search functionalities in an efficient and convenient manner. """ def __init__(self, data, page_size): """ Initialize the PageUtil object with the given data and page size. :param data: list, t...
def get_page(self, page_number): if page_number < 1 or page_number > self.total_pages: return [] start_index = (page_number - 1) * self.page_size end_index = start_index + self.page_size return self.data[start_index:end_index]
Retrieve a specific page of data.
ClassEval_68_sum
class PageUtil: """ PageUtil class is a versatile utility for handling pagination and search functionalities in an efficient and convenient manner. """ def __init__(self, data, page_size): self.data = data self.page_size = page_size self.total_items = len(data) self.total...
class PageUtil: """ PageUtil class is a versatile utility for handling pagination and search functionalities in an efficient and convenient manner. """ def __init__(self, data, page_size): """ Initialize the PageUtil object with the given data and page size. :param data: list, t...
def get_page_info(self, page_number): if page_number < 1 or page_number > self.total_pages: return {} start_index = (page_number - 1) * self.page_size end_index = min(start_index + self.page_size, self.total_items) page_data = self.data[start_index:end_index] page_i...
Retrieve information about a specific page.
ClassEval_68_sum
class PageUtil: """ PageUtil class is a versatile utility for handling pagination and search functionalities in an efficient and convenient manner. """ def __init__(self, data, page_size): self.data = data self.page_size = page_size self.total_items = len(data) self.total...
class PageUtil: """ PageUtil class is a versatile utility for handling pagination and search functionalities in an efficient and convenient manner. """ def __init__(self, data, page_size): """ Initialize the PageUtil object with the given data and page size. :param data: list, t...
def search(self, keyword): results = [item for item in self.data if keyword in str(item)] num_results = len(results) num_pages = (num_results + self.page_size - 1) // self.page_size search_info = { "keyword": keyword, "total_results": num_results, "to...
Search for items in the data that contain the given keyword.
ClassEval_69_sum
import PyPDF2 class PDFHandler: """ The class allows merging multiple PDF files into one and extracting text from PDFs using PyPDF2 library. """ def __init__(self, filepaths): self.filepaths = filepaths # PdfFileReader is deprecated and was removed in PyPDF2 3.0.0. Use PdfReader instea...
import PyPDF2 class PDFHandler: """ The class allows merging multiple PDF files into one and extracting text from PDFs using PyPDF2 library. """ def __init__(self, filepaths): """ takes a list of file paths filepaths as a parameter. It creates a list named readers using PyPDF2,...
def merge_pdfs(self, output_filepath): pdf_writer = PyPDF2.PdfWriter() for reader in self.readers: # reader.getNumPages is deprecated and was removed in PyPDF2 3.0.0. Use len(reader.pages) instead. for page_num in range(len(reader.pages)): # reader.getPage(pageNu...
Read files in self.readers which stores handles to multiple PDF files. Merge them to one pdf and update the page number, then save in disk.
ClassEval_69_sum
import PyPDF2 class PDFHandler: """ The class allows merging multiple PDF files into one and extracting text from PDFs using PyPDF2 library. """ def __init__(self, filepaths): self.filepaths = filepaths # PdfFileReader is deprecated and was removed in PyPDF2 3.0.0. Use PdfReader instea...
import PyPDF2 class PDFHandler: """ The class allows merging multiple PDF files into one and extracting text from PDFs using PyPDF2 library. """ def __init__(self, filepaths): """ takes a list of file paths filepaths as a parameter. It creates a list named readers using PyPDF2,...
def extract_text_from_pdfs(self): pdf_texts = [] for reader in self.readers: for page_num in range(len(reader.pages)): page = reader.pages[page_num] pdf_texts.append(page.extract_text()) return pdf_texts
Extract text from pdf files in self.readers
ClassEval_70_sum
class PersonRequest: """ This class validates input personal information data and sets invalid fields to None based to specific rules. """ def __init__(self, name: str, sex: str, phoneNumber: str): self.name = self._validate_name(name) self.sex = self._validate_sex(sex) self.phon...
class PersonRequest: """ This class validates input personal information data and sets invalid fields to None based to specific rules. """ def __init__(self, name: str, sex: str, phoneNumber: str): """ Initialize PersonRequest object with the provided information. :param name: s...
def _validate_name(self, name: str) -> str: if not name: return None if len(name) > 33: return None return name
Validate the name and return it. If name is empty or exceeds 33 characters in length, set to None.
ClassEval_70_sum
class PersonRequest: """ This class validates input personal information data and sets invalid fields to None based to specific rules. """ def __init__(self, name: str, sex: str, phoneNumber: str): self.name = self._validate_name(name) self.sex = self._validate_sex(sex) self.phon...
class PersonRequest: """ This class validates input personal information data and sets invalid fields to None based to specific rules. """ def __init__(self, name: str, sex: str, phoneNumber: str): """ Initialize PersonRequest object with the provided information. :param name: s...
def _validate_sex(self, sex: str) -> str: if sex not in ["Man", "Woman", "UGM"]: return None return sex
Validate the sex and return it. If sex is not Man, Woman, or UGM, set to None.
ClassEval_70_sum
class PersonRequest: """ This class validates input personal information data and sets invalid fields to None based to specific rules. """ def __init__(self, name: str, sex: str, phoneNumber: str): self.name = self._validate_name(name) self.sex = self._validate_sex(sex) self.phon...
class PersonRequest: """ This class validates input personal information data and sets invalid fields to None based to specific rules. """ def __init__(self, name: str, sex: str, phoneNumber: str): """ Initialize PersonRequest object with the provided information. :param name: s...
def _validate_phoneNumber(self, phoneNumber: str) -> str: if not phoneNumber: return None if len(phoneNumber) != 11 or not phoneNumber.isdigit(): return None return phoneNumber
Validate the phone number and return it. If phoneNumber is empty or not an 11 digit number, set to None.
ClassEval_71_sum
class PushBoxGame: """ This class implements a functionality of a sokoban game, where the player needs to move boxes to designated targets in order to win. """ def __init__(self, map): self.map = map self.player_row = 0 self.player_col = 0 self.targets = [] self.b...
class PushBoxGame: """ This class implements a functionality of a sokoban game, where the player needs to move boxes to designated targets in order to win. """ def __init__(self, map): """ Initialize the push box game with the map and various attributes. :param map: list[str], t...
def init_game(self): for row in range(len(self.map)): for col in range(len(self.map[row])): if self.map[row][col] == "O": self.player_row = row self.player_col = col elif self.map[row][col] == "G": self.targe...
Initialize the game by setting the positions of the player, targets, and boxes based on the map.
ClassEval_71_sum
class PushBoxGame: """ This class implements a functionality of a sokoban game, where the player needs to move boxes to designated targets in order to win. """ def __init__(self, map): self.map = map self.player_row = 0 self.player_col = 0 self.targets = [] self.b...
class PushBoxGame: """ This class implements a functionality of a sokoban game, where the player needs to move boxes to designated targets in order to win. """ def __init__(self, map): """ Initialize the push box game with the map and various attributes. :param map: list[str], t...
def check_win(self): box_on_target_count = 0 for box in self.boxes: if box in self.targets: box_on_target_count += 1 if box_on_target_count == self.target_count: self.is_game_over = True return self.is_game_over
Check if the game is won. The game is won when all the boxes are placed on target positions. And update the value of self.is_game_over.
ClassEval_71_sum
class PushBoxGame: """ This class implements a functionality of a sokoban game, where the player needs to move boxes to designated targets in order to win. """ def __init__(self, map): self.map = map self.player_row = 0 self.player_col = 0 self.targets = [] self.b...
class PushBoxGame: """ This class implements a functionality of a sokoban game, where the player needs to move boxes to designated targets in order to win. """ def __init__(self, map): """ Initialize the push box game with the map and various attributes. :param map: list[str], t...
def move(self, direction): new_player_row = self.player_row new_player_col = self.player_col if direction == "w": new_player_row -= 1 elif direction == "s": new_player_row += 1 elif direction == "a": new_player_col -= 1 elif direction ...
Move the player based on the specified direction and check if the game is won.
ClassEval_72_sum
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def findall(self, pattern, text): """ Find all ma...
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def findall(self, pattern, text): """ Find a...
def match(self, pattern, text): ans = re.match(pattern, text) if ans: return True else: return False
Check if the text matches the regular expression
ClassEval_72_sum
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the ...
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the ...
def findall(self, pattern, text): return re.findall(pattern, text)
Find all matching substrings and return a list of all matching substrings
ClassEval_72_sum
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the ...
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the ...
def split(self, pattern, text): return re.split(pattern, text)
Split text based on regular expression patterns and return a list of substrings
ClassEval_72_sum
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the ...
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the ...
def sub(self, pattern, replacement, text): return re.sub(pattern, replacement, text)
Replace the substring matched by a regular expression with the specified string
ClassEval_72_sum
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the ...
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the ...
def generate_email_pattern(self): pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' return pattern
Generate regular expression patterns that match email addresses
ClassEval_72_sum
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the ...
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the ...
def generate_phone_number_pattern(self): pattern = r'\b\d{3}-\d{3}-\d{4}\b' return pattern
Generate regular expression patterns that match phone numbers
ClassEval_72_sum
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the ...
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the ...
def generate_split_sentences_pattern(self): pattern = r'[.!?][\s]{1,2}(?=[A-Z])' return pattern
Generate regular expression patterns that match the middle characters of two sentences
ClassEval_72_sum
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the ...
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the ...
def split_sentences(self, text): pattern = self.generate_split_sentences_pattern() return self.split(pattern, text)
Split the text into a list of sentences without Punctuation except the last sentence
ClassEval_72_sum
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the ...
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the ...
def validate_phone_number(self, phone_number): pattern = self.generate_phone_number_pattern() return self.match(pattern, phone_number)
Verify if the phone number is valid
ClassEval_72_sum
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the ...
import re class RegexUtils: """ The class provides to match, find all occurrences, split, and substitute text using regular expressions. It also includes predefined patterns, validating phone numbers and extracting email addresses. """ def match(self, pattern, text): """ Check if the ...
def extract_email(self, text): pattern = self.generate_email_pattern() return self.findall(pattern, text)
Extract all email addresses from the text
ClassEval_73_sum
class RPGCharacter: """ The class represents a role-playing game character, which allows to attack other characters, heal, gain experience, level up, and check if the character is alive. """ def __init__(self, name, hp, attack_power, defense, level=1): self.name = name self.hp = hp ...
class RPGCharacter: """ The class represents a role-playing game character, which allows to attack other characters, heal, gain experience, level up, and check if the character is alive. """ def __init__(self, name, hp, attack_power, defense, level=1): """ Initialize an RPG character ob...
def attack(self, other_character): damage = max(self.attack_power - other_character.defense, 1) other_character.hp -= damage
Attack another character. The damage caused needs to offset the defense value.
ClassEval_73_sum
class RPGCharacter: """ The class represents a role-playing game character, which allows to attack other characters, heal, gain experience, level up, and check if the character is alive. """ def __init__(self, name, hp, attack_power, defense, level=1): self.name = name self.hp = hp ...
class RPGCharacter: """ The class represents a role-playing game character, which allows to attack other characters, heal, gain experience, level up, and check if the character is alive. """ def __init__(self, name, hp, attack_power, defense, level=1): """ Initialize an RPG character ob...
def heal(self): self.hp += 10 if self.hp > 100: self.hp = 100 return self.hp
Heal the character with 10 hp and the max hp is 100.
ClassEval_73_sum
class RPGCharacter: """ The class represents a role-playing game character, which allows to attack other characters, heal, gain experience, level up, and check if the character is alive. """ def __init__(self, name, hp, attack_power, defense, level=1): self.name = name self.hp = hp ...
class RPGCharacter: """ The class represents a role-playing game character, which allows to attack other characters, heal, gain experience, level up, and check if the character is alive. """ def __init__(self, name, hp, attack_power, defense, level=1): """ Initialize an RPG character ob...
def gain_exp(self, amount): while amount != 0: if self.exp + amount >= self.level * 100: amount -= (self.level * 100 - self.exp) self.level_up() else: self.exp += amount amount = 0
Gain experience points for the character and level_up when the exp has reached the values that is 100 times the current level The experience that overflows should be used to calculate the next leve up untill exhausts
ClassEval_73_sum
class RPGCharacter: """ The class represents a role-playing game character, which allows to attack other characters, heal, gain experience, level up, and check if the character is alive. """ def __init__(self, name, hp, attack_power, defense, level=1): self.name = name self.hp = hp ...
class RPGCharacter: """ The class represents a role-playing game character, which allows to attack other characters, heal, gain experience, level up, and check if the character is alive. """ def __init__(self, name, hp, attack_power, defense, level=1): """ Initialize an RPG character ob...
def level_up(self): if self.level < 100: self.level += 1 self.exp = 0 self.hp += 20 self.attack_power += 5 self.defense += 5 return self.level, self.hp, self.attack_power, self.defense
Level up the character and return to zero experience points, increase hp by 20 points, attack power and defense points by 5 points. max level is 100
ClassEval_73_sum
class RPGCharacter: """ The class represents a role-playing game character, which allows to attack other characters, heal, gain experience, level up, and check if the character is alive. """ def __init__(self, name, hp, attack_power, defense, level=1): self.name = name self.hp = hp ...
class RPGCharacter: """ The class represents a role-playing game character, which allows to attack other characters, heal, gain experience, level up, and check if the character is alive. """ def __init__(self, name, hp, attack_power, defense, level=1): """ Initialize an RPG character ob...
def is_alive(self): return self.hp > 0
Check if player is alive.
ClassEval_74_sum
class Server: """ This is a class as a server, which handles a white list, message sending and receiving, and information display. """ def __init__(self): self.white_list = [] self.send_struct = {} self.receive_struct = {} def del_white_list(self, addr): """ ...
class Server: """ This is a class as a server, which handles a white list, message sending and receiving, and information display. """ def __init__(self): """ Initialize the whitelist as an empty list, and initialize the sending and receiving information as an empty dictionary ...
def add_white_list(self, addr): if addr in self.white_list: return False else: self.white_list.append(addr) return self.white_list
Add an address to the whitelist and do nothing if it already exists
ClassEval_74_sum
class Server: """ This is a class as a server, which handles a white list, message sending and receiving, and information display. """ def __init__(self): self.white_list = [] self.send_struct = {} self.receive_struct = {} def add_white_list(self, addr): """ ...
class Server: """ This is a class as a server, which handles a white list, message sending and receiving, and information display. """ def __init__(self): """ Initialize the whitelist as an empty list, and initialize the sending and receiving information as an empty dictionary ...
def del_white_list(self, addr): if addr not in self.white_list: return False else: self.white_list.remove(addr) return self.white_list
Remove an address from the whitelist and do nothing if it does not exist
ClassEval_74_sum
class Server: """ This is a class as a server, which handles a white list, message sending and receiving, and information display. """ def __init__(self): self.white_list = [] self.send_struct = {} self.receive_struct = {} def add_white_list(self, addr): """ ...
class Server: """ This is a class as a server, which handles a white list, message sending and receiving, and information display. """ def __init__(self): """ Initialize the whitelist as an empty list, and initialize the sending and receiving information as an empty dictionary ...
def recv(self, info): if not isinstance(info, dict) or "addr" not in info or "content" not in info: return -1 addr = info["addr"] content = info["content"] if addr not in self.white_list: return False else: self.receive_struct = {"addr": addr, ...
Receive information containing address and content. If the address is on the whitelist, receive the content; otherwise, do not receive it
ClassEval_74_sum
class Server: """ This is a class as a server, which handles a white list, message sending and receiving, and information display. """ def __init__(self): self.white_list = [] self.send_struct = {} self.receive_struct = {} def add_white_list(self, addr): """ ...
class Server: """ This is a class as a server, which handles a white list, message sending and receiving, and information display. """ def __init__(self): """ Initialize the whitelist as an empty list, and initialize the sending and receiving information as an empty dictionary ...
def send(self, info): if not isinstance(info, dict) or "addr" not in info or "content" not in info: return "info structure is not correct" self.send_struct = {"addr": info["addr"], "content": info["content"]}
Send information containing address and content
ClassEval_74_sum
class Server: """ This is a class as a server, which handles a white list, message sending and receiving, and information display. """ def __init__(self): self.white_list = [] self.send_struct = {} self.receive_struct = {} def add_white_list(self, addr): """ ...
class Server: """ This is a class as a server, which handles a white list, message sending and receiving, and information display. """ def __init__(self): """ Initialize the whitelist as an empty list, and initialize the sending and receiving information as an empty dictionary ...
def show(self, type): if type == "send": return self.send_struct elif type == "receive": return self.receive_struct else: return False
Returns struct of the specified type
ClassEval_75_sum
class ShoppingCart: """ The class manages items, their prices, quantities, and allows to for add, removie, view items, and calculate the total price. """ def __init__(self): self.items = {} def remove_item(self, item, quantity=1): """ Subtract the specified quantity of item ...
class ShoppingCart: """ The class manages items, their prices, quantities, and allows to for add, removie, view items, and calculate the total price. """ def __init__(self): """ Initialize the items representing the shopping list as an empty dictionary """ self.items = {...
def add_item(self, item, price, quantity=1): if item in self.items: self.items[item] = {'price': price, 'quantity': quantity} else: self.items[item] = {'price': price, 'quantity': quantity}
Add item information to the shopping list items, including price and quantity. The default quantity is 1
ClassEval_75_sum
class ShoppingCart: """ The class manages items, their prices, quantities, and allows to for add, removie, view items, and calculate the total price. """ def __init__(self): self.items = {} def add_item(self, item, price, quantity=1): """ Add item information to the shopping...
class ShoppingCart: """ The class manages items, their prices, quantities, and allows to for add, removie, view items, and calculate the total price. """ def __init__(self): """ Initialize the items representing the shopping list as an empty dictionary """ self.items = {...
def remove_item(self, item, quantity=1): if item in self.items: self.items[item]['quantity'] -= quantity else: pass
Subtract the specified quantity of item from the shopping list items
ClassEval_75_sum
class ShoppingCart: """ The class manages items, their prices, quantities, and allows to for add, removie, view items, and calculate the total price. """ def __init__(self): self.items = {} def add_item(self, item, price, quantity=1): """ Add item information to the shopping...
class ShoppingCart: """ The class manages items, their prices, quantities, and allows to for add, removie, view items, and calculate the total price. """ def __init__(self): """ Initialize the items representing the shopping list as an empty dictionary """ self.items = {...
def view_items(self) -> dict: return self.items
Return the current shopping list items
ClassEval_75_sum
class ShoppingCart: """ The class manages items, their prices, quantities, and allows to for add, removie, view items, and calculate the total price. """ def __init__(self): self.items = {} def add_item(self, item, price, quantity=1): """ Add item information to the shopping...
class ShoppingCart: """ The class manages items, their prices, quantities, and allows to for add, removie, view items, and calculate the total price. """ def __init__(self): """ Initialize the items representing the shopping list as an empty dictionary """ self.items = {...
def total_price(self) -> float: return sum([item['quantity'] * item['price'] for item in self.items.values()])
Calculate the total price of all items in the shopping list, which is the quantity of each item multiplied by the price
ClassEval_76_sum
class SignInSystem: """ This is a class as sigin in system, including adding users, signing in/out, checking sign-in status, and retrieving signed-in/not signed-in users. """ def __init__(self): self.users = {} def sign_in(self, username): """ Sign in a user if the user was ...
class SignInSystem: """ This is a class as sigin in system, including adding users, signing in/out, checking sign-in status, and retrieving signed-in/not signed-in users. """ def __init__(self): """ Initialize the sign-in system. """ self.users = {} def sign_in...
def add_user(self, username): if username in self.users: return False else: self.users[username] = False return True
Add a user to the sign-in system if the user wasn't in the self.users. And the initial state is False.