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_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 add_user(self, username): """ Add a user to the sign-in syst...
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 add_user(sel...
def sign_in(self, username): if username not in self.users: return False else: self.users[username] = True return True
Sign in a user if the user was in the self.users and change the state to True.
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 add_user(self, username): """ Add a user to the sign-in syst...
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 add_user(sel...
def check_sign_in(self, username): if username not in self.users: return False else: if self.users[username]: return True else: return False
Check if a user is signed in.
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 add_user(self, username): """ Add a user to the sign-in syst...
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 add_user(sel...
def all_signed_in(self): if all(self.users.values()): return True else: return False
Check if all users are signed in.
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 add_user(self, username): """ Add a user to the sign-in syst...
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 add_user(sel...
def all_not_signed_in(self): not_signed_in_users = [] for username, signed_in in self.users.items(): if not signed_in: not_signed_in_users.append(username) return not_signed_in_users
Get a list of usernames that are not signed in.
ClassEval_77_sum
import random class Snake: """ The class is a snake game, with allows snake to move and eat food, and also enables to reset, and generat a random food position. """ def __init__(self, SCREEN_WIDTH, SCREEN_HEIGHT, BLOCK_SIZE, food_position): self.length = 1 self.SCREEN_WIDTH = SCREEN_WI...
import random class Snake: """ The class is a snake game, with allows snake to move and eat food, and also enables to reset, and generat a random food position. """ def __init__(self, SCREEN_WIDTH, SCREEN_HEIGHT, BLOCK_SIZE, food_position): """ Initialize the length of the snake, scree...
def move(self, direction): cur = self.positions[0] x, y = direction new = ( ((cur[0] + (x * self.BLOCK_SIZE)) % self.SCREEN_WIDTH), (cur[1] + (y * self.BLOCK_SIZE)) % self.SCREEN_HEIGHT, ) if new == self.food_position: self.eat_food() ...
Move the snake in the specified direction. If the new position of the snake's head is equal to the position of the food, then eat the food; If the position of the snake's head is equal to the position of its body, then start over, otherwise its own length plus one.
ClassEval_77_sum
import random class Snake: """ The class is a snake game, with allows snake to move and eat food, and also enables to reset, and generat a random food position. """ def __init__(self, SCREEN_WIDTH, SCREEN_HEIGHT, BLOCK_SIZE, food_position): self.length = 1 self.SCREEN_WIDTH = SCREEN_WI...
import random class Snake: """ The class is a snake game, with allows snake to move and eat food, and also enables to reset, and generat a random food position. """ def __init__(self, SCREEN_WIDTH, SCREEN_HEIGHT, BLOCK_SIZE, food_position): """ Initialize the length of the snake, scree...
def random_food_position(self): while self.food_position in self.positions: self.food_position = (random.randint(0, self.SCREEN_WIDTH // self.BLOCK_SIZE - 1) * self.BLOCK_SIZE, random.randint(0, self.SCREEN_HEIGHT // self.BLOCK_SIZE - 1) * self.BLOCK_SIZE)
Randomly generate a new food position, but don't place it on the snake.
ClassEval_77_sum
import random class Snake: """ The class is a snake game, with allows snake to move and eat food, and also enables to reset, and generat a random food position. """ def __init__(self, SCREEN_WIDTH, SCREEN_HEIGHT, BLOCK_SIZE, food_position): self.length = 1 self.SCREEN_WIDTH = SCREEN_WI...
import random class Snake: """ The class is a snake game, with allows snake to move and eat food, and also enables to reset, and generat a random food position. """ def __init__(self, SCREEN_WIDTH, SCREEN_HEIGHT, BLOCK_SIZE, food_position): """ Initialize the length of the snake, scree...
def reset(self): self.length = 1 self.positions = [((self.SCREEN_WIDTH / 2), (self.SCREEN_HEIGHT / 2))] self.score = 0 self.random_food_position()
Reset the snake to its initial state. Set the length to 1, the snake head position to ((SCREEN_WIDTH/2), (SCREEN_HEIGHT/2)), the score to 0, and randomly generate new food position.
ClassEval_77_sum
import random class Snake: """ The class is a snake game, with allows snake to move and eat food, and also enables to reset, and generat a random food position. """ def __init__(self, SCREEN_WIDTH, SCREEN_HEIGHT, BLOCK_SIZE, food_position): self.length = 1 self.SCREEN_WIDTH = SCREEN_WI...
import random class Snake: """ The class is a snake game, with allows snake to move and eat food, and also enables to reset, and generat a random food position. """ def __init__(self, SCREEN_WIDTH, SCREEN_HEIGHT, BLOCK_SIZE, food_position): """ Initialize the length of the snake, scree...
def eat_food(self): self.length += 1 self.score += 100 self.random_food_position()
Increase the length of the snake by 1 and increase the score by 100. Randomly generate a new food position, but don't place it on the snake.
ClassEval_78_sum
import re class SplitSentence: """ The class allows to split sentences, count words in a sentence, and process a text file to find the maximum word count. """ def count_words(self, sentence): """ Count the number of words in a sentence. Note that words are separated by spaces and that...
import re class SplitSentence: """ The class allows to split sentences, count words in a sentence, and process a text file to find the maximum word count. """ def count_words(self, sentence): """ Count the number of words in a sentence. Note that words are separated by spaces and...
def split_sentences(self, sentences_string): sentences = re.split(r'(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?)\s', sentences_string) return sentences
Split a string into a list of sentences. Sentences end with . or ? and with a space after that. Please note that Mr. also end with . but are not sentences.
ClassEval_78_sum
import re class SplitSentence: """ The class allows to split sentences, count words in a sentence, and process a text file to find the maximum word count. """ def split_sentences(self, sentences_string): """ Split a string into a list of sentences. Sentences end with . or ? and with a...
import re class SplitSentence: """ The class allows to split sentences, count words in a sentence, and process a text file to find the maximum word count. """ def split_sentences(self, sentences_string): """ Split a string into a list of sentences. Sentences end with . or ? and with a...
def count_words(self, sentence): sentence = re.sub(r'[^a-zA-Z\s]', '', sentence) words = sentence.split() return len(words)
Count the number of words in a sentence. Note that words are separated by spaces and that punctuation marks and numbers are not counted as words.
ClassEval_78_sum
import re class SplitSentence: """ The class allows to split sentences, count words in a sentence, and process a text file to find the maximum word count. """ def split_sentences(self, sentences_string): """ Split a string into a list of sentences. Sentences end with . or ? and with a...
import re class SplitSentence: """ The class allows to split sentences, count words in a sentence, and process a text file to find the maximum word count. """ def split_sentences(self, sentences_string): """ Split a string into a list of sentences. Sentences end with . or ? and with a...
def process_text_file(self, sentences_string): sentences = self.split_sentences(sentences_string) max_count = 0 for sentence in sentences: count = self.count_words(sentence) if count > max_count: max_count = count return max_count
Given a text, return the number of words in the longest sentence
ClassEval_79_sum
class SQLGenerator: """ This class generates SQL statements for common operations on a table, such as SELECT, INSERT, UPDATE, and DELETE. """ def __init__(self, table_name): self.table_name = table_name def insert(self, data): """ Generates an INSERT SQL statement based on t...
class SQLGenerator: """ This class generates SQL statements for common operations on a table, such as SELECT, INSERT, UPDATE, and DELETE. """ def __init__(self, table_name): """ Initialize the table name. :param table_name: str """ self.table_name = table_name ...
def select(self, fields=None, condition=None): if fields is None: fields = "*" else: fields = ", ".join(fields) sql = f"SELECT {fields} FROM {self.table_name}" if condition is not None: sql += f" WHERE {condition}" return sql + ";"
Generates a SELECT SQL statement based on the specified fields and conditions.
ClassEval_79_sum
class SQLGenerator: """ This class generates SQL statements for common operations on a table, such as SELECT, INSERT, UPDATE, and DELETE. """ def __init__(self, table_name): self.table_name = table_name def select(self, fields=None, condition=None): """ Generates a SELECT SQ...
class SQLGenerator: """ This class generates SQL statements for common operations on a table, such as SELECT, INSERT, UPDATE, and DELETE. """ def __init__(self, table_name): """ Initialize the table name. :param table_name: str """ self.table_name = table_name ...
def insert(self, data): fields = ", ".join(data.keys()) values = ", ".join([f"'{value}'" for value in data.values()]) sql = f"INSERT INTO {self.table_name} ({fields}) VALUES ({values})" return sql + ";"
Generates an INSERT SQL statement based on the given data.
ClassEval_79_sum
class SQLGenerator: """ This class generates SQL statements for common operations on a table, such as SELECT, INSERT, UPDATE, and DELETE. """ def __init__(self, table_name): self.table_name = table_name def select(self, fields=None, condition=None): """ Generates a SELECT SQ...
class SQLGenerator: """ This class generates SQL statements for common operations on a table, such as SELECT, INSERT, UPDATE, and DELETE. """ def __init__(self, table_name): """ Initialize the table name. :param table_name: str """ self.table_name = table_name ...
def update(self, data, condition): set_clause = ", ".join([f"{field} = '{value}'" for field, value in data.items()]) sql = f"UPDATE {self.table_name} SET {set_clause} WHERE {condition}" return sql + ";"
Generates an UPDATE SQL statement based on the given data and condition.
ClassEval_79_sum
class SQLGenerator: """ This class generates SQL statements for common operations on a table, such as SELECT, INSERT, UPDATE, and DELETE. """ def __init__(self, table_name): self.table_name = table_name def select(self, fields=None, condition=None): """ Generates a SELECT SQ...
class SQLGenerator: """ This class generates SQL statements for common operations on a table, such as SELECT, INSERT, UPDATE, and DELETE. """ def __init__(self, table_name): """ Initialize the table name. :param table_name: str """ self.table_name = table_name ...
def delete(self, condition): sql = f"DELETE FROM {self.table_name} WHERE {condition}" return sql + ";"
Generates a DELETE SQL statement based on the given condition.
ClassEval_79_sum
class SQLGenerator: """ This class generates SQL statements for common operations on a table, such as SELECT, INSERT, UPDATE, and DELETE. """ def __init__(self, table_name): self.table_name = table_name def select(self, fields=None, condition=None): """ Generates a SELECT SQ...
class SQLGenerator: """ This class generates SQL statements for common operations on a table, such as SELECT, INSERT, UPDATE, and DELETE. """ def __init__(self, table_name): """ Initialize the table name. :param table_name: str """ self.table_name = table_name ...
def select_female_under_age(self, age): condition = f"age < {age} AND gender = 'female'" return self.select(condition=condition)
Generates a SQL statement to select females under a specified age.
ClassEval_79_sum
class SQLGenerator: """ This class generates SQL statements for common operations on a table, such as SELECT, INSERT, UPDATE, and DELETE. """ def __init__(self, table_name): self.table_name = table_name def select(self, fields=None, condition=None): """ Generates a SELECT SQ...
class SQLGenerator: """ This class generates SQL statements for common operations on a table, such as SELECT, INSERT, UPDATE, and DELETE. """ def __init__(self, table_name): """ Initialize the table name. :param table_name: str """ self.table_name = table_name ...
def select_by_age_range(self, min_age, max_age): condition = f"age BETWEEN {min_age} AND {max_age}" return self.select(condition=condition)
Generates a SQL statement to select records within a specified age range.
ClassEval_80_sum
class SQLQueryBuilder: """ This class provides to build SQL queries, including SELECT, INSERT, UPDATE, and DELETE statements. """ @staticmethod @staticmethod def insert(table, data): """ Generate the INSERT SQL statement from the given parameters. :param table: str, the...
class SQLQueryBuilder: """ This class provides to build SQL queries, including SELECT, INSERT, UPDATE, and DELETE statements. """ @staticmethod @staticmethod def insert(table, data): """ Generate the INSERT SQL statement from the given parameters. :param table: st...
def select(table, columns='*', where=None): if columns != '*': columns = ', '.join(columns) query = f"SELECT {columns} FROM {table}" if where: query += " WHERE " + ' AND '.join(f"{k}='{v}'" for k, v in where.items()) return query
Generate the SELECT SQL statement from the given parameters.
ClassEval_80_sum
class SQLQueryBuilder: """ This class provides to build SQL queries, including SELECT, INSERT, UPDATE, and DELETE statements. """ @staticmethod def select(table, columns='*', where=None): """ Generate the SELECT SQL statement from the given parameters. :param table: str, th...
class SQLQueryBuilder: """ This class provides to build SQL queries, including SELECT, INSERT, UPDATE, and DELETE statements. """ @staticmethod def select(table, columns='*', where=None): """ Generate the SELECT SQL statement from the given parameters. :param table: str, t...
@staticmethod def insert(table, data): keys = ', '.join(data.keys()) values = ', '.join(f"'{v}'" for v in data.values()) return f"INSERT INTO {table} ({keys}) VALUES ({values})"
Generate the INSERT SQL statement from the given parameters.
ClassEval_80_sum
class SQLQueryBuilder: """ This class provides to build SQL queries, including SELECT, INSERT, UPDATE, and DELETE statements. """ @staticmethod def select(table, columns='*', where=None): """ Generate the SELECT SQL statement from the given parameters. :param table: str, th...
class SQLQueryBuilder: """ This class provides to build SQL queries, including SELECT, INSERT, UPDATE, and DELETE statements. """ @staticmethod def select(table, columns='*', where=None): """ Generate the SELECT SQL statement from the given parameters. :param table: str, t...
@staticmethod def delete(table, where=None): query = f"DELETE FROM {table}" if where: query += " WHERE " + ' AND '.join(f"{k}='{v}'" for k, v in where.items()) return query
Generate the DELETE SQL statement from the given parameters.
ClassEval_80_sum
class SQLQueryBuilder: """ This class provides to build SQL queries, including SELECT, INSERT, UPDATE, and DELETE statements. """ @staticmethod def select(table, columns='*', where=None): """ Generate the SELECT SQL statement from the given parameters. :param table: str, th...
class SQLQueryBuilder: """ This class provides to build SQL queries, including SELECT, INSERT, UPDATE, and DELETE statements. """ @staticmethod def select(table, columns='*', where=None): """ Generate the SELECT SQL statement from the given parameters. :param table: str, t...
@staticmethod def update(table, data, where=None): update_str = ', '.join(f"{k}='{v}'" for k, v in data.items()) query = f"UPDATE {table} SET {update_str}" if where: query += " WHERE " + ' AND '.join(f"{k}='{v}'" for k, v in where.items()) return query
Generate the UPDATE SQL statement from the given parameters.
ClassEval_81_sum
import math class Statistics3: """ This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics. """ @staticmethod @staticmethod def mode(data): """ calculates the mode of the given list. :param dat...
import math class Statistics3: """ This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics. """ @staticmethod @staticmethod def mode(data): """ calculates the mode of the given list. :pa...
def median(data): sorted_data = sorted(data) n = len(sorted_data) if n % 2 == 1: return sorted_data[n // 2] else: return (sorted_data[n // 2 - 1] + sorted_data[n // 2]) / 2
calculates the median of the given list.
ClassEval_81_sum
import math class Statistics3: """ This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics. """ @staticmethod def median(data): """ calculates the median of the given list. :param data: the given l...
import math class Statistics3: """ This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics. """ @staticmethod def median(data): """ calculates the median of the given list. :param data: the given...
@staticmethod def mode(data): counts = {} for value in data: counts[value] = counts.get(value, 0) + 1 max_count = max(counts.values()) mode_values = [value for value, count in counts.items() if count == max_count] return mode_values
calculates the mode of the given list.
ClassEval_81_sum
import math class Statistics3: """ This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics. """ @staticmethod def median(data): """ calculates the median of the given list. :param data: the given l...
import math class Statistics3: """ This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics. """ @staticmethod def median(data): """ calculates the median of the given list. :param data: the given...
@staticmethod def correlation(x, y): n = len(x) mean_x = sum(x) / n mean_y = sum(y) / n numerator = sum((xi - mean_x) * (yi - mean_y) for xi, yi in zip(x, y)) denominator = math.sqrt(sum((xi - mean_x) ** 2 for xi in x) * sum((yi - mean_y) ** 2 for yi in y)) if denomin...
calculates the correlation of the given list.
ClassEval_81_sum
import math class Statistics3: """ This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics. """ @staticmethod def median(data): """ calculates the median of the given list. :param data: the given l...
import math class Statistics3: """ This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics. """ @staticmethod def median(data): """ calculates the median of the given list. :param data: the given...
@staticmethod def mean(data): if len(data) == 0: return None return sum(data) / len(data)
calculates the mean of the given list.
ClassEval_81_sum
import math class Statistics3: """ This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics. """ @staticmethod def median(data): """ calculates the median of the given list. :param data: the given l...
import math class Statistics3: """ This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics. """ @staticmethod def median(data): """ calculates the median of the given list. :param data: the given...
@staticmethod def correlation_matrix(data): matrix = [] for i in range(len(data[0])): row = [] for j in range(len(data[0])): column1 = [row[i] for row in data] column2 = [row[j] for row in data] correlation = Statistics3.correla...
calculates the correlation matrix of the given list.
ClassEval_81_sum
import math class Statistics3: """ This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics. """ @staticmethod def median(data): """ calculates the median of the given list. :param data: the given l...
import math class Statistics3: """ This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics. """ @staticmethod def median(data): """ calculates the median of the given list. :param data: the given...
@staticmethod def standard_deviation(data): n = len(data) if n < 2: return None mean_value = Statistics3.mean(data) variance = sum((x - mean_value) ** 2 for x in data) / (n - 1) return math.sqrt(variance)
calculates the standard deviation of the given list.
ClassEval_81_sum
import math class Statistics3: """ This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics. """ @staticmethod def median(data): """ calculates the median of the given list. :param data: the given l...
import math class Statistics3: """ This is a class that implements methods for calculating indicators such as median, mode, correlation matrix, and Z-score in statistics. """ @staticmethod def median(data): """ calculates the median of the given list. :param data: the given...
@staticmethod def z_score(data): mean = Statistics3.mean(data) std_deviation = Statistics3.standard_deviation(data) if std_deviation is None or std_deviation == 0: return None return [(x - mean) / std_deviation for x in data]
calculates the z-score of the given list.
ClassEval_82_sum
class StockPortfolioTracker: """ This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio. """ def __init__(self, cash_balance): self.portfolio = [] self.c...
class StockPortfolioTracker: """ This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio. """ def __init__(self, cash_balance): """ Initialize the StockP...
def add_stock(self, stock): for pf in self.portfolio: if pf['name'] == stock['name']: pf['quantity'] += stock['quantity'] return self.portfolio.append(stock)
Add a stock to the portfolio.
ClassEval_82_sum
class StockPortfolioTracker: """ This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio. """ def __init__(self, cash_balance): self.portfolio = [] self.c...
class StockPortfolioTracker: """ This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio. """ def __init__(self, cash_balance): """ Initialize the StockP...
def remove_stock(self, stock): for pf in self.portfolio: if pf['name'] == stock['name'] and pf['quantity'] >= stock['quantity']: pf['quantity'] -= stock['quantity'] if pf['quantity'] == 0: self.portfolio.remove(pf) return True ...
Remove a stock from the portfolio.
ClassEval_82_sum
class StockPortfolioTracker: """ This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio. """ def __init__(self, cash_balance): self.portfolio = [] self.c...
class StockPortfolioTracker: """ This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio. """ def __init__(self, cash_balance): """ Initialize the StockP...
def buy_stock(self, stock): if stock['price'] * stock['quantity'] > self.cash_balance: return False else: self.add_stock(stock) self.cash_balance -= stock['price'] * stock['quantity'] return True
Buy a stock and add it to the portfolio.
ClassEval_82_sum
class StockPortfolioTracker: """ This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio. """ def __init__(self, cash_balance): self.portfolio = [] self.c...
class StockPortfolioTracker: """ This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio. """ def __init__(self, cash_balance): """ Initialize the StockP...
def sell_stock(self, stock): if self.remove_stock(stock) == False: return False self.cash_balance += stock['price'] * stock['quantity'] return True
Sell a stock and remove it from the portfolio and add the cash to the cash balance.
ClassEval_82_sum
class StockPortfolioTracker: """ This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio. """ def __init__(self, cash_balance): self.portfolio = [] self.c...
class StockPortfolioTracker: """ This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio. """ def __init__(self, cash_balance): """ Initialize the StockP...
def calculate_portfolio_value(self): total_value = self.cash_balance for stock in self.portfolio: total_value += stock['price'] * stock['quantity'] return total_value
Calculate the total value of the portfolio.
ClassEval_82_sum
class StockPortfolioTracker: """ This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio. """ def __init__(self, cash_balance): self.portfolio = [] self.c...
class StockPortfolioTracker: """ This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio. """ def __init__(self, cash_balance): """ Initialize the StockP...
def get_portfolio_summary(self): summary = [] for stock in self.portfolio: value = self.get_stock_value(stock) summary.append({"name": stock["name"], "value": value}) portfolio_value = self.calculate_portfolio_value() return portfolio_value, summary
Get a summary of the portfolio.
ClassEval_82_sum
class StockPortfolioTracker: """ This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio. """ def __init__(self, cash_balance): self.portfolio = [] self.c...
class StockPortfolioTracker: """ This is a class as StockPortfolioTracker that allows to add stocks, remove stocks, buy stocks, sell stocks, calculate the total value of the portfolio, and obtain a summary of the portfolio. """ def __init__(self, cash_balance): """ Initialize the StockP...
def get_stock_value(self, stock): return stock['price'] * stock['quantity']
Get the value of a stock.
ClassEval_83_sum
import sqlite3 class StudentDatabaseProcessor: """ This is a class with database operation, including inserting student information, searching for student information by name, and deleting student information by name. """ def __init__(self, database_name): self.database_name = database_name ...
import sqlite3 class StudentDatabaseProcessor: """ This is a class with database operation, including inserting student information, searching for student information by name, and deleting student information by name. """ def __init__(self, database_name): """ Initializes the StudentDa...
def create_student_table(self): conn = sqlite3.connect(self.database_name) cursor = conn.cursor() create_table_query = """ CREATE TABLE IF NOT EXISTS students ( id INTEGER PRIMARY KEY, name TEXT, age INTEGER, gender TEXT, grade...
Creates a "students" table in the database if it does not exist already.Fields include ID of type int, name of type str, age of type int, gender of type str, and grade of type int
ClassEval_83_sum
import sqlite3 class StudentDatabaseProcessor: """ This is a class with database operation, including inserting student information, searching for student information by name, and deleting student information by name. """ def __init__(self, database_name): self.database_name = database_name ...
import sqlite3 class StudentDatabaseProcessor: """ This is a class with database operation, including inserting student information, searching for student information by name, and deleting student information by name. """ def __init__(self, database_name): """ Initializes the StudentDa...
def insert_student(self, student_data): conn = sqlite3.connect(self.database_name) cursor = conn.cursor() insert_query = """ INSERT INTO students (name, age, gender, grade) VALUES (?, ?, ?, ?) """ cursor.execute(insert_query, (student_data[...
Inserts a new student into the "students" table.
ClassEval_83_sum
import sqlite3 class StudentDatabaseProcessor: """ This is a class with database operation, including inserting student information, searching for student information by name, and deleting student information by name. """ def __init__(self, database_name): self.database_name = database_name ...
import sqlite3 class StudentDatabaseProcessor: """ This is a class with database operation, including inserting student information, searching for student information by name, and deleting student information by name. """ def __init__(self, database_name): """ Initializes the StudentDa...
def search_student_by_name(self, name): conn = sqlite3.connect(self.database_name) cursor = conn.cursor() select_query = "SELECT * FROM students WHERE name = ?" cursor.execute(select_query, (name,)) result = cursor.fetchall() conn.close() return result
Searches for a student in the "students" table by their name.
ClassEval_83_sum
import sqlite3 class StudentDatabaseProcessor: """ This is a class with database operation, including inserting student information, searching for student information by name, and deleting student information by name. """ def __init__(self, database_name): self.database_name = database_name ...
import sqlite3 class StudentDatabaseProcessor: """ This is a class with database operation, including inserting student information, searching for student information by name, and deleting student information by name. """ def __init__(self, database_name): """ Initializes the StudentDa...
def delete_student_by_name(self, name): conn = sqlite3.connect(self.database_name) cursor = conn.cursor() delete_query = "DELETE FROM students WHERE name = ?" cursor.execute(delete_query, (name,)) conn.commit() conn.close()
Deletes a student from the "students" table by their name.
ClassEval_84_sum
import json class TextFileProcessor: """ The class handles reading, writing, and processing text files. It can read the file as JSON, read the raw text, write content to the file, and process the file by removing non-alphabetic characters. """ def __init__(self, file_path): self.file_path = fi...
import json class TextFileProcessor: """ The class handles reading, writing, and processing text files. It can read the file as JSON, read the raw text, write content to the file, and process the file by removing non-alphabetic characters. """ def __init__(self, file_path): """ Initial...
def read_file_as_json(self): with open(self.file_path, 'r') as file: data = json.load(file) return data
Read the self.file_path file as json format. if the file content doesn't obey json format, the code will raise error.
ClassEval_84_sum
import json class TextFileProcessor: """ The class handles reading, writing, and processing text files. It can read the file as JSON, read the raw text, write content to the file, and process the file by removing non-alphabetic characters. """ def __init__(self, file_path): self.file_path = fi...
import json class TextFileProcessor: """ The class handles reading, writing, and processing text files. It can read the file as JSON, read the raw text, write content to the file, and process the file by removing non-alphabetic characters. """ def __init__(self, file_path): """ Initial...
def read_file(self): with open(self.file_path, 'r') as file: return file.read()
Read the return the content of self.file_path file.
ClassEval_84_sum
import json class TextFileProcessor: """ The class handles reading, writing, and processing text files. It can read the file as JSON, read the raw text, write content to the file, and process the file by removing non-alphabetic characters. """ def __init__(self, file_path): self.file_path = fi...
import json class TextFileProcessor: """ The class handles reading, writing, and processing text files. It can read the file as JSON, read the raw text, write content to the file, and process the file by removing non-alphabetic characters. """ def __init__(self, file_path): """ Initial...
def write_file(self, content): with open(self.file_path, 'w') as file: file.write(content)
Write content into the self.file_path file, and overwrite if the file has already existed.
ClassEval_84_sum
import json class TextFileProcessor: """ The class handles reading, writing, and processing text files. It can read the file as JSON, read the raw text, write content to the file, and process the file by removing non-alphabetic characters. """ def __init__(self, file_path): self.file_path = fi...
import json class TextFileProcessor: """ The class handles reading, writing, and processing text files. It can read the file as JSON, read the raw text, write content to the file, and process the file by removing non-alphabetic characters. """ def __init__(self, file_path): """ Initial...
def process_file(self): content = self.read_file() content = ''.join([char for char in content if char.isalpha()]) self.write_file(content) return content
Read the self.file_path file and filter out non-alphabetic characters from the content string. Overwrite the after-processed data into the same self.file_path file.
ClassEval_85_sum
import time class Thermostat: """ The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation. """ def __init__(self, current_temperature, target_temperature, mode): self.current_temperature = current_t...
import time class Thermostat: """ The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation. """ def __init__(self, current_temperature, target_temperature, mode): """ initialize instances of...
def get_target_temperature(self): return self.target_temperature
Get the target temperature of an instance of the Thermostat class.
ClassEval_85_sum
import time class Thermostat: """ The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation. """ def __init__(self, current_temperature, target_temperature, mode): self.current_temperature = current_t...
import time class Thermostat: """ The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation. """ def __init__(self, current_temperature, target_temperature, mode): """ initialize instances of...
def set_target_temperature(self, temperature): self.target_temperature = temperature
Set the target temperature
ClassEval_85_sum
import time class Thermostat: """ The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation. """ def __init__(self, current_temperature, target_temperature, mode): self.current_temperature = current_t...
import time class Thermostat: """ The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation. """ def __init__(self, current_temperature, target_temperature, mode): """ initialize instances of...
def get_mode(self): return self.mode
Get the current work mode
ClassEval_85_sum
import time class Thermostat: """ The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation. """ def __init__(self, current_temperature, target_temperature, mode): self.current_temperature = current_t...
import time class Thermostat: """ The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation. """ def __init__(self, current_temperature, target_temperature, mode): """ initialize instances of...
def set_mode(self, mode): if mode in ['heat', 'cool']: self.mode = mode else: return False
Get the current work mode
ClassEval_85_sum
import time class Thermostat: """ The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation. """ def __init__(self, current_temperature, target_temperature, mode): self.current_temperature = current_t...
import time class Thermostat: """ The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation. """ def __init__(self, current_temperature, target_temperature, mode): """ initialize instances of...
def auto_set_mode(self): if self.current_temperature < self.target_temperature: self.mode = 'heat' else: self.mode = 'cool'
Automatically set the operating mode by comparing with the current temperature and target temperature. If the current temperature is lower than the target temperature, the operating mode is set to 'heat', otherwise it is set to 'cool'.
ClassEval_85_sum
import time class Thermostat: """ The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation. """ def __init__(self, current_temperature, target_temperature, mode): self.current_temperature = current_t...
import time class Thermostat: """ The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation. """ def __init__(self, current_temperature, target_temperature, mode): """ initialize instances of...
def auto_check_conflict(self): if self.current_temperature > self.target_temperature: if self.mode == 'cool': return True else: self.auto_set_mode() return False else: if self.mode == 'heat': return True ...
Check if there is a conflict between the operating mode and the relationship between the current temperature and the target temperature. If there is a conflict, the operating mode will be adjusted automatically.
ClassEval_85_sum
import time class Thermostat: """ The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation. """ def __init__(self, current_temperature, target_temperature, mode): self.current_temperature = current_t...
import time class Thermostat: """ The class manages temperature control, including setting and retrieving the target temperature, adjusting the mode, and simulating temperature operation. """ def __init__(self, current_temperature, target_temperature, mode): """ initialize instances of...
def simulate_operation(self): self.auto_set_mode() use_time = 0 if self.mode == 'heat': while(self.current_temperature < self.target_temperature): self.current_temperature += 1 use_time += 1 else: while(self.current_temperature > se...
simulate the operation of Thermostat. It will automatically start the auto_set_mode method to set the operating mode, and then automatically adjust the current temperature according to the operating mode until the target temperature is reached.
ClassEval_86_sum
class TicTacToe: """ The class represents a game of Tic-Tac-Toe and its functions include making a move on the board, checking for a winner, and determining if the board is full. """ def __init__(self, N=3): self.board = [[' ' for _ in range(N)] for _ in range(3)] self.current_player = '...
class TicTacToe: """ The class represents a game of Tic-Tac-Toe and its functions include making a move on the board, checking for a winner, and determining if the board is full. """ def __init__(self, N=3): """ Initialize a 3x3 game board with all empty spaces and current symble player...
def make_move(self, row, col): if self.board[row][col] == ' ': self.board[row][col] = self.current_player self.current_player = 'O' if self.current_player == 'X' else 'X' return True else: return False
Place the current player's mark at the specified position on the board and switch the mark.
ClassEval_86_sum
class TicTacToe: """ The class represents a game of Tic-Tac-Toe and its functions include making a move on the board, checking for a winner, and determining if the board is full. """ def __init__(self, N=3): self.board = [[' ' for _ in range(N)] for _ in range(3)] self.current_player = '...
class TicTacToe: """ The class represents a game of Tic-Tac-Toe and its functions include making a move on the board, checking for a winner, and determining if the board is full. """ def __init__(self, N=3): """ Initialize a 3x3 game board with all empty spaces and current symble player...
def check_winner(self): for row in self.board: if row[0] == row[1] == row[2] != ' ': return row[0] for col in range(3): if self.board[0][col] == self.board[1][col] == self.board[2][col] != ' ': return self.board[0][col] if self.board[0][0] ...
Check if there is a winner on the board in rows, columns and diagonals three directions
ClassEval_86_sum
class TicTacToe: """ The class represents a game of Tic-Tac-Toe and its functions include making a move on the board, checking for a winner, and determining if the board is full. """ def __init__(self, N=3): self.board = [[' ' for _ in range(N)] for _ in range(3)] self.current_player = '...
class TicTacToe: """ The class represents a game of Tic-Tac-Toe and its functions include making a move on the board, checking for a winner, and determining if the board is full. """ def __init__(self, N=3): """ Initialize a 3x3 game board with all empty spaces and current symble player...
def is_board_full(self): for row in self.board: if ' ' in row: return False return True
Check if the game board is completely filled.
ClassEval_87_sum
import datetime import time class TimeUtils: """ This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object. """ def __init__(self): ...
import datetime import time class TimeUtils: """ This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object. """ def __init__(self):...
def get_current_time(self): format = "%H:%M:%S" return self.datetime.strftime(format)
Return the current time in the format of '%H:%M:%S'
ClassEval_87_sum
import datetime import time class TimeUtils: """ This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object. """ def __init__(self): ...
import datetime import time class TimeUtils: """ This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object. """ def __init__(self):...
def get_current_date(self): format = "%Y-%m-%d" return self.datetime.strftime(format)
Return the current date in the format of "%Y-%m-%d"
ClassEval_87_sum
import datetime import time class TimeUtils: """ This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object. """ def __init__(self): ...
import datetime import time class TimeUtils: """ This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object. """ def __init__(self):...
def add_seconds(self, seconds): new_datetime = self.datetime + datetime.timedelta(seconds=seconds) format = "%H:%M:%S" return new_datetime.strftime(format)
Add the specified number of seconds to the current time
ClassEval_87_sum
import datetime import time class TimeUtils: """ This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object. """ def __init__(self): ...
import datetime import time class TimeUtils: """ This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object. """ def __init__(self):...
def string_to_datetime(self, string): return datetime.datetime.strptime(string, "%Y-%m-%d %H:%M:%S")
Convert the time string to a datetime instance
ClassEval_87_sum
import datetime import time class TimeUtils: """ This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object. """ def __init__(self): ...
import datetime import time class TimeUtils: """ This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object. """ def __init__(self):...
def datetime_to_string(self, datetime): return datetime.strftime("%Y-%m-%d %H:%M:%S")
Convert a datetime instance to a string
ClassEval_87_sum
import datetime import time class TimeUtils: """ This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object. """ def __init__(self): ...
import datetime import time class TimeUtils: """ This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object. """ def __init__(self):...
def get_minutes(self, string_time1, string_time2): time1 = self.string_to_datetime(string_time1) time2 = self.string_to_datetime(string_time2) return round((time2 - time1).seconds / 60)
Calculate how many minutes have passed between two times, and round the results to the nearest
ClassEval_87_sum
import datetime import time class TimeUtils: """ This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object. """ def __init__(self): ...
import datetime import time class TimeUtils: """ This is a time util class, including getting the current time and date, adding seconds to a datetime, converting between strings and datetime objects, calculating the time difference in minutes, and formatting a datetime object. """ def __init__(self):...
def get_format_time(self, year, month, day, hour, minute, second): format = "%Y-%m-%d %H:%M:%S" time_item = datetime.datetime(year, month, day, hour, minute, second) return time_item.strftime(format)
get format time
ClassEval_88_sum
from math import pi, fabs class TriCalculator: """ The class allows to calculate trigonometric values, including cosine, sine, and tangent, using Taylor series approximations. """ def __init__(self): pass def factorial(self, a): """ Calculate the factorial of a :p...
from math import pi, fabs class TriCalculator: """ The class allows to calculate trigonometric values, including cosine, sine, and tangent, using Taylor series approximations. """ def __init__(self): pass def factorial(self, a): """ Calculate the factorial of a ...
def cos(self, x): return round(self.taylor(x, 50), 10)
Calculate the cos value of the x-degree angle
ClassEval_88_sum
from math import pi, fabs class TriCalculator: """ The class allows to calculate trigonometric values, including cosine, sine, and tangent, using Taylor series approximations. """ def __init__(self): pass def cos(self, x): """ Calculate the cos value of the x-degree angle...
from math import pi, fabs class TriCalculator: """ The class allows to calculate trigonometric values, including cosine, sine, and tangent, using Taylor series approximations. """ def __init__(self): pass def cos(self, x): """ Calculate the cos value of the x-degree angle...
def factorial(self, a): b = 1 while a != 1: b *= a a -= 1 return b
Calculate the factorial of a
ClassEval_88_sum
from math import pi, fabs class TriCalculator: """ The class allows to calculate trigonometric values, including cosine, sine, and tangent, using Taylor series approximations. """ def __init__(self): pass def cos(self, x): """ Calculate the cos value of the x-degree angle...
from math import pi, fabs class TriCalculator: """ The class allows to calculate trigonometric values, including cosine, sine, and tangent, using Taylor series approximations. """ def __init__(self): pass def cos(self, x): """ Calculate the cos value of the x-degree angle...
def taylor(self, x, n): a = 1 x = x / 180 * pi count = 1 for k in range(1, n): if count % 2 != 0: a -= (x ** (2 * k)) / self.factorial(2 * k) else: a += (x ** (2 * k)) / self.factorial(2 * k) count += 1 return a
Finding the n-order Taylor expansion value of cos (x/180 * pi)
ClassEval_88_sum
from math import pi, fabs class TriCalculator: """ The class allows to calculate trigonometric values, including cosine, sine, and tangent, using Taylor series approximations. """ def __init__(self): pass def cos(self, x): """ Calculate the cos value of the x-degree angle...
from math import pi, fabs class TriCalculator: """ The class allows to calculate trigonometric values, including cosine, sine, and tangent, using Taylor series approximations. """ def __init__(self): pass def cos(self, x): """ Calculate the cos value of the x-degree angle...
def sin(self, x): x = x / 180 * pi g = 0 t = x n = 1 while fabs(t) >= 1e-15: g += t n += 1 t = -t * x * x / (2 * n - 1) / (2 * n - 2) return round(g, 10)
Calculate the sin value of the x-degree angle
ClassEval_88_sum
from math import pi, fabs class TriCalculator: """ The class allows to calculate trigonometric values, including cosine, sine, and tangent, using Taylor series approximations. """ def __init__(self): pass def cos(self, x): """ Calculate the cos value of the x-degree angle...
from math import pi, fabs class TriCalculator: """ The class allows to calculate trigonometric values, including cosine, sine, and tangent, using Taylor series approximations. """ def __init__(self): pass def cos(self, x): """ Calculate the cos value of the x-degree angle...
def tan(self, x): if self.cos(x) != 0: result = self.sin(x) / self.cos(x) return round(result, 10) else: return False
Calculate the tan value of the x-degree angle
ClassEval_89_sum
import random class TwentyFourPointGame: """ This ia a game of twenty-four points, which provides to generate four numbers and check whether player's expression is equal to 24. """ def __init__(self) -> None: self.nums = [] def get_my_cards(self): """ Get a list of four ra...
import random class TwentyFourPointGame: """ This ia a game of twenty-four points, which provides to generate four numbers and check whether player's expression is equal to 24. """ def __init__(self) -> None: self.nums = [] def get_my_cards(self): """ Get a list of ...
def _generate_cards(self): for i in range(4): self.nums.append(random.randint(1, 9)) assert len(self.nums) == 4
Generate random numbers between 1 and 9 for the cards.
ClassEval_89_sum
import random class TwentyFourPointGame: """ This ia a game of twenty-four points, which provides to generate four numbers and check whether player's expression is equal to 24. """ def __init__(self) -> None: self.nums = [] def _generate_cards(self): """ Generate random nu...
import random class TwentyFourPointGame: """ This ia a game of twenty-four points, which provides to generate four numbers and check whether player's expression is equal to 24. """ def __init__(self) -> None: self.nums = [] def _generate_cards(self): """ Generate random n...
def get_my_cards(self): self.nums = [] self._generate_cards() return self.nums
Get a list of four random numbers between 1 and 9 representing the player's cards.
ClassEval_89_sum
import random class TwentyFourPointGame: """ This ia a game of twenty-four points, which provides to generate four numbers and check whether player's expression is equal to 24. """ def __init__(self) -> None: self.nums = [] def _generate_cards(self): """ Generate random nu...
import random class TwentyFourPointGame: """ This ia a game of twenty-four points, which provides to generate four numbers and check whether player's expression is equal to 24. """ def __init__(self) -> None: self.nums = [] def _generate_cards(self): """ Generate random n...
def answer(self, expression): if expression == 'pass': return self.get_my_cards() statistic = {} for c in expression: if c.isdigit() and int(c) in self.nums: statistic[c] = statistic.get(c, 0) + 1 nums_used = statistic.copy() for num in s...
Check if a given mathematical expression using the cards can evaluate to 24.
ClassEval_89_sum
import random class TwentyFourPointGame: """ This ia a game of twenty-four points, which provides to generate four numbers and check whether player's expression is equal to 24. """ def __init__(self) -> None: self.nums = [] def _generate_cards(self): """ Generate random nu...
import random class TwentyFourPointGame: """ This ia a game of twenty-four points, which provides to generate four numbers and check whether player's expression is equal to 24. """ def __init__(self) -> None: self.nums = [] def _generate_cards(self): """ Generate random n...
def evaluate_expression(self, expression): try: if eval(expression) == 24: return True else: return False except Exception as e: return False
Evaluate a mathematical expression and check if the result is 24.
ClassEval_90_sum
class URLHandler: """ The class supports to handle URLs, including extracting the scheme, host, path, query parameters, and fragment. """ def __init__(self, url): self.url = url def get_host(self): """ Get the second part of the URL, which is the host domain name :re...
class URLHandler: """ The class supports to handle URLs, including extracting the scheme, host, path, query parameters, and fragment. """ def __init__(self, url): """ Initialize URLHandler's URL """ self.url = url def get_host(self): """ Get th...
def get_scheme(self): scheme_end = self.url.find("://") if scheme_end != -1: return self.url[:scheme_end] return None
get the scheme of the URL
ClassEval_90_sum
class URLHandler: """ The class supports to handle URLs, including extracting the scheme, host, path, query parameters, and fragment. """ def __init__(self, url): self.url = url def get_scheme(self): """ get the scheme of the URL :return: string, If successful, retur...
class URLHandler: """ The class supports to handle URLs, including extracting the scheme, host, path, query parameters, and fragment. """ def __init__(self, url): """ Initialize URLHandler's URL """ self.url = url def get_scheme(self): """ get the sc...
def get_host(self): scheme_end = self.url.find("://") if scheme_end != -1: url_without_scheme = self.url[scheme_end + 3:] host_end = url_without_scheme.find("/") if host_end != -1: return url_without_scheme[:host_end] return url_without_sch...
Get the second part of the URL, which is the host domain name
ClassEval_90_sum
class URLHandler: """ The class supports to handle URLs, including extracting the scheme, host, path, query parameters, and fragment. """ def __init__(self, url): self.url = url def get_scheme(self): """ get the scheme of the URL :return: string, If successful, retur...
class URLHandler: """ The class supports to handle URLs, including extracting the scheme, host, path, query parameters, and fragment. """ def __init__(self, url): """ Initialize URLHandler's URL """ self.url = url def get_scheme(self): """ get the sc...
def get_path(self): scheme_end = self.url.find("://") if scheme_end != -1: url_without_scheme = self.url[scheme_end + 3:] host_end = url_without_scheme.find("/") if host_end != -1: return url_without_scheme[host_end:] return None
Get the third part of the URL, which is the address of the resource
ClassEval_90_sum
class URLHandler: """ The class supports to handle URLs, including extracting the scheme, host, path, query parameters, and fragment. """ def __init__(self, url): self.url = url def get_scheme(self): """ get the scheme of the URL :return: string, If successful, retur...
class URLHandler: """ The class supports to handle URLs, including extracting the scheme, host, path, query parameters, and fragment. """ def __init__(self, url): """ Initialize URLHandler's URL """ self.url = url def get_scheme(self): """ get the sc...
def get_query_params(self): query_start = self.url.find("?") fragment_start = self.url.find("#") if query_start != -1: query_string = self.url[query_start + 1:fragment_start] params = {} if len(query_string) > 0: param_pairs = query_string.spli...
Get the request parameters for the URL
ClassEval_90_sum
class URLHandler: """ The class supports to handle URLs, including extracting the scheme, host, path, query parameters, and fragment. """ def __init__(self, url): self.url = url def get_scheme(self): """ get the scheme of the URL :return: string, If successful, retur...
class URLHandler: """ The class supports to handle URLs, including extracting the scheme, host, path, query parameters, and fragment. """ def __init__(self, url): """ Initialize URLHandler's URL """ self.url = url def get_scheme(self): """ get the sc...
def get_fragment(self): fragment_start = self.url.find("#") if fragment_start != -1: return self.url[fragment_start + 1:] return None
Get the fragment after '#' in the URL
ClassEval_91_sum
import urllib.parse class UrlPath: """ The class is a utility for encapsulating and manipulating the path component of a URL, including adding nodes, parsing path strings, and building path strings with optional encoding. """ def __init__(self): self.segments = [] self.with_end_tag = ...
import urllib.parse class UrlPath: """ The class is a utility for encapsulating and manipulating the path component of a URL, including adding nodes, parsing path strings, and building path strings with optional encoding. """ def __init__(self): """ Initializes the UrlPath object with...
def add(self, segment): self.segments.append(self.fix_path(segment))
Adds a segment to the list of segments in the UrlPath.
ClassEval_91_sum
import urllib.parse class UrlPath: """ The class is a utility for encapsulating and manipulating the path component of a URL, including adding nodes, parsing path strings, and building path strings with optional encoding. """ def __init__(self): self.segments = [] self.with_end_tag = ...
import urllib.parse class UrlPath: """ The class is a utility for encapsulating and manipulating the path component of a URL, including adding nodes, parsing path strings, and building path strings with optional encoding. """ def __init__(self): """ Initializes the UrlPath object with...
def parse(self, path, charset): if path: if path.endswith('/'): self.with_end_tag = True path = self.fix_path(path) if path: split = path.split('/') for seg in split: decoded_seg = urllib.parse.unquote(seg, ...
Parses a given path string and populates the list of segments in the UrlPath.
ClassEval_91_sum
import urllib.parse class UrlPath: """ The class is a utility for encapsulating and manipulating the path component of a URL, including adding nodes, parsing path strings, and building path strings with optional encoding. """ def __init__(self): self.segments = [] self.with_end_tag = ...
import urllib.parse class UrlPath: """ The class is a utility for encapsulating and manipulating the path component of a URL, including adding nodes, parsing path strings, and building path strings with optional encoding. """ def __init__(self): """ Initializes the UrlPath object with...
@staticmethod def fix_path(path): if not path: return '' segment_str = path.strip('/') return segment_str
Fixes the given path string by removing leading and trailing slashes.
ClassEval_92_sum
import sqlite3 class UserLoginDB: """ This is a database management class for user login verification, providing functions for inserting user information, searching user information, deleting user information, and validating user login. """ def __init__(self, db_name): self.connection = sqlite...
class UserLoginDB: """ This is a database management class for user login verification, providing functions for inserting user information, searching user information, deleting user information, and validating user login. """ def __init__(self, db_name): """ Initializes the UserLoginDB ...
def insert_user(self, username, password): self.cursor.execute(''' INSERT INTO users (username, password) VALUES (?, ?) ''', (username, password)) self.connection.commit()
Inserts a new user into the "users" table.
ClassEval_92_sum
import sqlite3 class UserLoginDB: """ This is a database management class for user login verification, providing functions for inserting user information, searching user information, deleting user information, and validating user login. """ def __init__(self, db_name): self.connection = sqlite...
class UserLoginDB: """ This is a database management class for user login verification, providing functions for inserting user information, searching user information, deleting user information, and validating user login. """ def __init__(self, db_name): """ Initializes the UserLoginDB ...
def search_user_by_username(self, username): self.cursor.execute(''' SELECT * FROM users WHERE username = ? ''', (username,)) user = self.cursor.fetchone() return user
Searches for users in the "users" table by username.
ClassEval_92_sum
import sqlite3 class UserLoginDB: """ This is a database management class for user login verification, providing functions for inserting user information, searching user information, deleting user information, and validating user login. """ def __init__(self, db_name): self.connection = sqlite...
class UserLoginDB: """ This is a database management class for user login verification, providing functions for inserting user information, searching user information, deleting user information, and validating user login. """ def __init__(self, db_name): """ Initializes the UserLoginDB ...
def delete_user_by_username(self, username): self.cursor.execute(''' DELETE FROM users WHERE username = ? ''', (username,)) self.connection.commit()
Deletes a user from the "users" table by username.
ClassEval_92_sum
import sqlite3 class UserLoginDB: """ This is a database management class for user login verification, providing functions for inserting user information, searching user information, deleting user information, and validating user login. """ def __init__(self, db_name): self.connection = sqlite...
class UserLoginDB: """ This is a database management class for user login verification, providing functions for inserting user information, searching user information, deleting user information, and validating user login. """ def __init__(self, db_name): """ Initializes the UserLoginDB ...
def validate_user_login(self, username, password): user = self.search_user_by_username(username) if user is not None and user[1] == password: return True return False
Determine whether the user can log in, that is, the user is in the database and the password is correct
ClassEval_93_sum
import numpy as np from gensim import matutils from numpy import dot, array class VectorUtil: """ The class provides vector operations, including calculating similarity, cosine similarities, average similarity, and IDF weights. """ @staticmethod @staticmethod def cosine_similarities(vector_1, ...
import numpy as np from gensim import matutils from numpy import dot, array class VectorUtil: """ The class provides vector operations, including calculating similarity, cosine similarities, average similarity, and IDF weights. """ @staticmethod @staticmethod def cosine_similarities(vect...
def similarity(vector_1, vector_2): return dot(matutils.unitvec(vector_1), matutils.unitvec(vector_2))
Compute the cosine similarity between one vector and another vector.
ClassEval_93_sum
import numpy as np from gensim import matutils from numpy import dot, array class VectorUtil: """ The class provides vector operations, including calculating similarity, cosine similarities, average similarity, and IDF weights. """ @staticmethod def similarity(vector_1, vector_2): """ ...
import numpy as np from gensim import matutils from numpy import dot, array class VectorUtil: """ The class provides vector operations, including calculating similarity, cosine similarities, average similarity, and IDF weights. """ @staticmethod def similarity(vector_1, vector_2): """ ...
@staticmethod def cosine_similarities(vector_1, vectors_all): norm = np.linalg.norm(vector_1) all_norms = np.linalg.norm(vectors_all, axis=1) dot_products = dot(vectors_all, vector_1) similarities = dot_products / (norm * all_norms) return similarities
Compute cosine similarities between one vector and a set of other vectors.
ClassEval_93_sum
import numpy as np from gensim import matutils from numpy import dot, array class VectorUtil: """ The class provides vector operations, including calculating similarity, cosine similarities, average similarity, and IDF weights. """ @staticmethod def similarity(vector_1, vector_2): """ ...
import numpy as np from gensim import matutils from numpy import dot, array class VectorUtil: """ The class provides vector operations, including calculating similarity, cosine similarities, average similarity, and IDF weights. """ @staticmethod def similarity(vector_1, vector_2): """ ...
@staticmethod def n_similarity(vector_list_1, vector_list_2): if not (len(vector_list_1) and len(vector_list_2)): raise ZeroDivisionError('At least one of the passed list is empty.') return dot(matutils.unitvec(array(vector_list_1).mean(axis=0)), matutils.unitvec(arra...
Compute cosine similarity between two sets of vectors.
ClassEval_93_sum
import numpy as np from gensim import matutils from numpy import dot, array class VectorUtil: """ The class provides vector operations, including calculating similarity, cosine similarities, average similarity, and IDF weights. """ @staticmethod def similarity(vector_1, vector_2): """ ...
import numpy as np from gensim import matutils from numpy import dot, array class VectorUtil: """ The class provides vector operations, including calculating similarity, cosine similarities, average similarity, and IDF weights. """ @staticmethod def similarity(vector_1, vector_2): """ ...
@staticmethod def compute_idf_weight_dict(total_num, number_dict): index_2_key_map = {} index = 0 count_list = [] for key, count in number_dict.items(): index_2_key_map[index] = key count_list.append(count) index = index + 1 a = np.array...
Calculate log(total_num+1/count+1) for each count in number_dict
ClassEval_94_sum
class VendingMachine: """ This is a class to simulate a vending machine, including adding products, inserting coins, purchasing products, viewing balance, replenishing product inventory, and displaying product information. """ def __init__(self): self.inventory = {} self.balance = 0 ...
class VendingMachine: """ This is a class to simulate a vending machine, including adding products, inserting coins, purchasing products, viewing balance, replenishing product inventory, and displaying product information. """ def __init__(self): """ Initializes the vending machine's in...
def add_item(self, item_name, price, quantity): if not self.restock_item(item_name, quantity): self.inventory[item_name] = {'price': price, 'quantity': quantity}
Adds a product to the vending machine's inventory.
ClassEval_94_sum
class VendingMachine: """ This is a class to simulate a vending machine, including adding products, inserting coins, purchasing products, viewing balance, replenishing product inventory, and displaying product information. """ def __init__(self): self.inventory = {} self.balance = 0 ...
class VendingMachine: """ This is a class to simulate a vending machine, including adding products, inserting coins, purchasing products, viewing balance, replenishing product inventory, and displaying product information. """ def __init__(self): """ Initializes the vending machine's in...
def insert_coin(self, amount): self.balance += amount return self.balance
Inserts coins into the vending machine.
ClassEval_94_sum
class VendingMachine: """ This is a class to simulate a vending machine, including adding products, inserting coins, purchasing products, viewing balance, replenishing product inventory, and displaying product information. """ def __init__(self): self.inventory = {} self.balance = 0 ...
class VendingMachine: """ This is a class to simulate a vending machine, including adding products, inserting coins, purchasing products, viewing balance, replenishing product inventory, and displaying product information. """ def __init__(self): """ Initializes the vending machine's in...
def purchase_item(self, item_name): if item_name in self.inventory: item = self.inventory[item_name] if item['quantity'] > 0 and self.balance >= item['price']: self.balance -= item['price'] item['quantity'] -= 1 return self.balance ...
Purchases a product from the vending machine and returns the balance after the purchase and display purchase unsuccessful if the product is out of stock.
ClassEval_94_sum
class VendingMachine: """ This is a class to simulate a vending machine, including adding products, inserting coins, purchasing products, viewing balance, replenishing product inventory, and displaying product information. """ def __init__(self): self.inventory = {} self.balance = 0 ...
class VendingMachine: """ This is a class to simulate a vending machine, including adding products, inserting coins, purchasing products, viewing balance, replenishing product inventory, and displaying product information. """ def __init__(self): """ Initializes the vending machine's in...
def restock_item(self, item_name, quantity): if item_name in self.inventory: self.inventory[item_name]['quantity'] += quantity return True else: return False
Replenishes the inventory of a product already in the vending machine.
ClassEval_94_sum
class VendingMachine: """ This is a class to simulate a vending machine, including adding products, inserting coins, purchasing products, viewing balance, replenishing product inventory, and displaying product information. """ def __init__(self): self.inventory = {} self.balance = 0 ...
class VendingMachine: """ This is a class to simulate a vending machine, including adding products, inserting coins, purchasing products, viewing balance, replenishing product inventory, and displaying product information. """ def __init__(self): """ Initializes the vending machine's in...
def display_items(self): if not self.inventory: return False else: items = [] for item_name, item_info in self.inventory.items(): items.append(f"{item_name} - ${item_info['price']} [{item_info['quantity']}]") return "\n".join(items)
Displays the products in the vending machine.
ClassEval_95_sum
class Warehouse: """ The class manages inventory and orders, including adding products, updating product quantities, retrieving product quantities, creating orders, changing order statuses, and tracking orders. """ def __init__(self): self.inventory = {} # Product ID: Product self.order...
class Warehouse: """ The class manages inventory and orders, including adding products, updating product quantities, retrieving product quantities, creating orders, changing order statuses, and tracking orders. """ def __init__(self): """ Initialize two fields. self.inventory is...
def add_product(self, product_id, name, quantity): if product_id not in self.inventory: self.inventory[product_id] = {'name': name, 'quantity': quantity} else: self.inventory[product_id]['quantity'] += quantity
Add product to inventory and plus the quantity if it has existed in inventory. Or just add new product to dict otherwise.
ClassEval_95_sum
class Warehouse: """ The class manages inventory and orders, including adding products, updating product quantities, retrieving product quantities, creating orders, changing order statuses, and tracking orders. """ def __init__(self): self.inventory = {} # Product ID: Product self.order...
class Warehouse: """ The class manages inventory and orders, including adding products, updating product quantities, retrieving product quantities, creating orders, changing order statuses, and tracking orders. """ def __init__(self): """ Initialize two fields. self.inventory is...
def update_product_quantity(self, product_id, quantity): if product_id in self.inventory: self.inventory[product_id]['quantity'] += quantity
According to product_id, add the quantity to the corresponding product in inventory.
ClassEval_95_sum
class Warehouse: """ The class manages inventory and orders, including adding products, updating product quantities, retrieving product quantities, creating orders, changing order statuses, and tracking orders. """ def __init__(self): self.inventory = {} # Product ID: Product self.order...
class Warehouse: """ The class manages inventory and orders, including adding products, updating product quantities, retrieving product quantities, creating orders, changing order statuses, and tracking orders. """ def __init__(self): """ Initialize two fields. self.inventory is...
def get_product_quantity(self, product_id): if product_id in self.inventory: return self.inventory[product_id]['quantity'] else: return False
Get the quantity of specific product by product_id.
ClassEval_95_sum
class Warehouse: """ The class manages inventory and orders, including adding products, updating product quantities, retrieving product quantities, creating orders, changing order statuses, and tracking orders. """ def __init__(self): self.inventory = {} # Product ID: Product self.order...
class Warehouse: """ The class manages inventory and orders, including adding products, updating product quantities, retrieving product quantities, creating orders, changing order statuses, and tracking orders. """ def __init__(self): """ Initialize two fields. self.inventory is...
def create_order(self, order_id, product_id, quantity): if self.get_product_quantity(product_id) >= quantity: self.update_product_quantity(product_id, -quantity) self.orders[order_id] = {'product_id': product_id, 'quantity': quantity, 'status': 'Shipped'} else: return...
Create a order which includes the infomation of product, like id and quantity. And put the new order into self.orders. The default value of status is 'Shipped'.
ClassEval_95_sum
class Warehouse: """ The class manages inventory and orders, including adding products, updating product quantities, retrieving product quantities, creating orders, changing order statuses, and tracking orders. """ def __init__(self): self.inventory = {} # Product ID: Product self.order...
class Warehouse: """ The class manages inventory and orders, including adding products, updating product quantities, retrieving product quantities, creating orders, changing order statuses, and tracking orders. """ def __init__(self): """ Initialize two fields. self.inventory is...
def change_order_status(self, order_id, status): if order_id in self.orders: self.orders[order_id]['status'] = status else: return False
Change the status of order if the input order_id is in self.orders.
ClassEval_95_sum
class Warehouse: """ The class manages inventory and orders, including adding products, updating product quantities, retrieving product quantities, creating orders, changing order statuses, and tracking orders. """ def __init__(self): self.inventory = {} # Product ID: Product self.order...
class Warehouse: """ The class manages inventory and orders, including adding products, updating product quantities, retrieving product quantities, creating orders, changing order statuses, and tracking orders. """ def __init__(self): """ Initialize two fields. self.inventory is...
def track_order(self, order_id): if order_id in self.orders: return self.orders[order_id]['status'] else: return False
Get the status of specific order.
ClassEval_96_sum
class WeatherSystem: """ This is a class representing a weather system that provides functionality to query weather information for a specific city and convert temperature units between Celsius and Fahrenheit. """ def __init__(self, city) -> None: self.temperature = None self.weather = N...
class WeatherSystem: """ This is a class representing a weather system that provides functionality to query weather information for a specific city and convert temperature units between Celsius and Fahrenheit. """ def __init__(self, city) -> None: """ Initialize the weather system with ...
def query(self, weather_list, tmp_units = 'celsius'): self.weather_list = weather_list if self.city not in weather_list: return False else: self.temperature = self.weather_list[self.city]['temperature'] self.weather = self.weather_list[self.city]['weather'] ...
Query the weather system for the weather and temperature of the city,and convert the temperature units based on the input parameter.
ClassEval_96_sum
class WeatherSystem: """ This is a class representing a weather system that provides functionality to query weather information for a specific city and convert temperature units between Celsius and Fahrenheit. """ def __init__(self, city) -> None: self.temperature = None self.weather = N...
class WeatherSystem: """ This is a class representing a weather system that provides functionality to query weather information for a specific city and convert temperature units between Celsius and Fahrenheit. """ def __init__(self, city) -> None: """ Initialize the weather system with ...
def set_city(self, city): self.city = city
Set the city of the weather system.
ClassEval_96_sum
class WeatherSystem: """ This is a class representing a weather system that provides functionality to query weather information for a specific city and convert temperature units between Celsius and Fahrenheit. """ def __init__(self, city) -> None: self.temperature = None self.weather = N...
class WeatherSystem: """ This is a class representing a weather system that provides functionality to query weather information for a specific city and convert temperature units between Celsius and Fahrenheit. """ def __init__(self, city) -> None: """ Initialize the weather system with ...
def celsius_to_fahrenheit(self): return (self.temperature * 9/5) + 32
Convert the temperature from Celsius to Fahrenheit.
ClassEval_96_sum
class WeatherSystem: """ This is a class representing a weather system that provides functionality to query weather information for a specific city and convert temperature units between Celsius and Fahrenheit. """ def __init__(self, city) -> None: self.temperature = None self.weather = N...
class WeatherSystem: """ This is a class representing a weather system that provides functionality to query weather information for a specific city and convert temperature units between Celsius and Fahrenheit. """ def __init__(self, city) -> None: """ Initialize the weather system with ...
def fahrenheit_to_celsius(self): return (self.temperature - 32) * 5/9
Convert the temperature from Fahrenheit to Celsius.