Appearance
question:Objective Design and implement an asynchronous network echo server using asyncio's event loop that handles multiple simultaneous client connections. Description You are required to implement an echo server that listens on a specified host and port, handles multiple concurrent client connections, and echoes back any data it receives from a client. The server should use asyncio's event loop for handling connections and data in a non-blocking manner. Requirements 1. Implement a function `start_echo_server(host, port)` that: - Listens on the specified host and port. - Accepts multiple simultaneous client connections. - Reads data from each connected client and echoes it back to the sender. - Handles connections and data asynchronously using asyncio's event loop. 2. Implement appropriate error handling and cleanup: - Ensure connections are properly closed when done. - Handle any exceptions that occur during data handling without crashing the server. 3. The server should keep running indefinitely, accepting and handling new client connections. 4. You should implement the logic using asyncio's low-level event loop API rather than the higher-level `asyncio.run()` function. Example Usage ```python import asyncio async def handle_client(reader, writer): data = await reader.read(100) message = data.decode() writer.write(data) await writer.drain() writer.close() async def start_echo_server(host, port): srv = await asyncio.start_server(handle_client, host, port) async with srv: await srv.serve_forever() if __name__ == '__main__': host = 'localhost' port = 8888 loop = asyncio.get_event_loop() loop.run_until_complete(start_echo_server(host, port)) loop.run_forever() ``` Constraints - Do not use `asyncio.run()` to run your event loop. - Ensure that the server can handle multiple clients concurrently. - Implement proper logging to record any errors or exceptions. Additional Notes - You can test the server using various network tools (e.g., `telnet`, `nc`) or by writing client code to connect to the server and send messages. - Focus on handling data asynchronously and ensuring robust error handling. Submission Submit your implementation of the `start_echo_server` function along with a brief explanation of how your implementation works and any considerations taken into account for error handling and resource cleanup.
answer:import asyncio async def handle_client(reader, writer): try: while True: data = await reader.read(100) if not data: break writer.write(data) await writer.drain() except Exception as e: print(f'Error: {e}') finally: writer.close() await writer.wait_closed() async def start_echo_server(host, port): server = await asyncio.start_server(handle_client, host, port) async with server: await server.serve_forever() if __name__ == '__main__': host = 'localhost' port = 8888 loop = asyncio.get_event_loop() loop.run_until_complete(start_echo_server(host, port)) loop.run_forever()
question:# Advanced ASCII Character Manipulation Problem Statement: You have been provided with a text input where you need to perform a series of operations on ASCII characters. 1. Validate if all characters in the string belong to the ASCII set. 2. Identify and separate the control characters from the printable characters. 3. Convert all control characters to their caret notation using the `unctrl` function. 4. For printable characters not being alphanumeric, replace them with their corresponding ASCII values in hexadecimal notation. You are required to implement the following function: ```python def process_ascii_text(text: str) -> str: Process the given text according to the specified rules: 1. Validate if all characters in the string belong to the ASCII set; raise a ValueError if not. 2. Identify and separate control characters from printable characters. 3. Convert all control characters to their caret notation using the `unctrl` function. 4. For printable characters that are not alphanumeric, replace them with their corresponding ASCII values in hexadecimal notation. Args: text (str): The input text to be processed. Returns: str: The processed text as per the above rules. Control characters (with caret notation) will be followed by printable characters (alphanumeric and non-alphanumeric characters represented in hexadecimal). pass ``` Constraints: - Raise a `ValueError` if any character in the string is non-ASCII. - The input string `text` will always contain at least one character. Example: ```python text = "HellonWorld!" # 'Hello' -> remains as 'Hello' # 'n' -> careted to "^J" # '!' -> replaced with its hexadecimal value "x21" result = process_ascii_text(text) print(result) # Output should be "Hello^JWorldx21" ``` Notes: - You can use the `curses.ascii` module in your implementation. - Consider using the `ord()` and `hex()` built-in Python functions where needed. - Ensure your implementation handles both single-character strings and the entire text correctly.
answer:import curses.ascii def process_ascii_text(text: str) -> str: Process the given text according to the specified rules: 1. Validate if all characters in the string belong to the ASCII set; raise a ValueError if not. 2. Identify and separate control characters from printable characters. 3. Convert all control characters to their caret notation using the `unctrl` function. 4. For printable characters that are not alphanumeric, replace them with their corresponding ASCII values in hexadecimal notation. Args: text (str): The input text to be processed. Returns: str: The processed text as per the above rules. result = [] for char in text: # Check for ASCII if not curses.ascii.isascii(char): raise ValueError("All characters must be ASCII.") if curses.ascii.iscntrl(char): result.append(curses.ascii.unctrl(char)) elif not char.isalnum(): result.append(f"x{ord(char):02x}") else: result.append(char) return ''.join(result)
question:# Coding Assessment: Advanced Seaborn Bar Plots **Objective:** Write a function that generates a complex seaborn bar plot based on a given dataset and set of parameters. Your function should demonstrate an understanding of seaborn's `barplot` capabilities, including handling different data formats, error bar configurations, and customization options. **Function Signature:** ```python import seaborn as sns import pandas as pd def advanced_bar_plot(data: pd.DataFrame, x: str, y: str, hue: str = None, orient: str = 'v', errorbar: str = 'ci', estimator: str = 'mean') -> sns.axisgrid.FacetGrid: Generates a customized seaborn bar plot. Parameters: - data (pd.DataFrame): The input dataset. - x (str): Column name to be plotted on the x-axis. - y (str): Column name to be plotted on the y-axis. - hue (str, optional): Column name for color encoding. Defaults to None. - orient (str, optional): 'v' for vertical bars, 'h' for horizontal bars. Defaults to 'v'. - errorbar (str, optional): Error bar configuration. 'ci' for confidence interval, 'sd' for standard deviation, or None. Defaults to 'ci'. - estimator (str, optional): Statistical function for aggregation. Defaults to 'mean'. Returns: - sns.axisgrid.FacetGrid: The generated seaborn FacetGrid object with the bar plot. ``` **Expected Input and Output Formats:** - *Input:* - `data`: A pandas DataFrame containing the dataset. - `x`: A string representing the column name to be plotted on the x-axis. - `y`: A string representing the column name to be plotted on the y-axis. - `hue`: (Optional) A string representing the column name for color encoding. - `orient`: (Optional) A string, either 'v' for vertical bars or 'h' for horizontal bars. - `errorbar`: (Optional) A string, either 'ci' for confidence interval, 'sd' for standard deviation, or None for no error bars. - `estimator`: (Optional) A string representing the statistical function for aggregation (e.g., 'mean', 'sum'). - *Output:* - A seaborn `FacetGrid` object containing the generated bar plot. **Constraints:** - Ensure the function handles missing data gracefully and doesn't crash if columns specified are not found in the dataset. - The function should include relevant error handling for incorrect parameter types and values. - Consider performance optimization for large datasets. **Example:** ```python import seaborn as sns import pandas as pd # Sample Data data = sns.load_dataset("penguins") # Generate the plot plot = advanced_bar_plot(data, x="island", y="body_mass_g", hue="sex", orient='v', errorbar='sd', estimator='mean') # Display the plot plot.fig.show() ``` **Notes:** - Utilize `sns.barplot`, `sns.catplot`, and other relevant seaborn functions as needed. - Customize the appearance using matplotlib keyword arguments if necessary. - Ensure the plot contains appropriate labels, titles, and legends. Test similar datasets, such as the `flights` dataset, to validate your function.
answer:import seaborn as sns import pandas as pd def advanced_bar_plot(data: pd.DataFrame, x: str, y: str, hue: str = None, orient: str = 'v', errorbar: str = 'ci', estimator: str = 'mean'): Generates a customized seaborn bar plot. Parameters: - data (pd.DataFrame): The input dataset. - x (str): Column name to be plotted on the x-axis. - y (str): Column name to be plotted on the y-axis. - hue (str, optional): Column name for color encoding. Defaults to None. - orient (str, optional): 'v' for vertical bars, 'h' for horizontal bars. Defaults to 'v'. - errorbar (str, optional): Error bar configuration. 'ci' for confidence interval, 'sd' for standard deviation, or None. Defaults to 'ci'. - estimator (str, optional): Statistical function for aggregation. Defaults to 'mean'. Returns: - sns.axisgrid.FacetGrid: The generated seaborn FacetGrid object with the bar plot. # Check if provided columns x and y exist in the DataFrame if x not in data.columns or y not in data.columns: raise ValueError(f"Column '{x}' or '{y}' not found in the dataset.") if hue is not None and hue not in data.columns: raise ValueError(f"Column '{hue}' not found in the dataset.") # Set estimator function estimator_func = None if estimator == 'mean': estimator_func = 'mean' elif estimator == 'sum': estimator_func = 'sum' else: raise ValueError("Estimator not recognized. Use 'mean' or 'sum'.") # Generate the plot plot = sns.catplot( data=data, kind="bar", x=x if orient == 'v' else y, y=y if orient == 'v' else x, hue=hue, ci=None if errorbar is None else errorbar, estimator=estimator_func, orient=orient ) # Customize the plot plot.set_axis_labels(x, y) if hue: plot.add_legend(title=hue) return plot
question:Advanced Coding Assessment: Unittest Framework # Objective Design a testing module using Python’s unittest framework that demonstrates various capabilities such as setting up class-level fixtures, individual test cases, handling exceptions, and using different assertion methods. # Problem Statement You are tasked with writing a test script for a library management system. The system includes a `Library` class with methods to add and remove books, check for the presence of a book, and list all books. Your task is to create unit tests for this `Library` class using the `unittest` framework. # Implementation 1. Implement a `Library` class as outlined below. 2. Write a `TestLibrary` class that tests the `Library` class using the `unittest` framework. 3. Use setup and teardown methods appropriately to manage resources. # `Library` Class Implement the following methods in the `Library` class: 1. `add_book(title)`: Adds a book to the library. 2. `remove_book(title)`: Removes a book from the library. 3. `has_book(title)`: Returns `True` if the book is in the library, `False` otherwise. 4. `list_books()`: Returns a list of all book titles in the library. # Constraints - The books should be stored in a set to ensure each book title is unique. - Removing a book that doesn’t exist in the library should raise a `ValueError`. # Example ```python class Library: def __init__(self): self.books = set() def add_book(self, title): self.books.add(title) def remove_book(self, title): if title not in self.books: raise ValueError("The book is not available in the library.") self.books.remove(title) def has_book(self, title): return title in self.books def list_books(self): return list(self.books) ``` # Testing Requirements Using the `unittest` framework: 1. Write a `TestLibrary` class that inherits from `unittest.TestCase`. 2. Use the `setUpClass` and `tearDownClass` class methods to prepare resources before all tests and clean up after all tests. 3. Use the `setUp` and `tearDown` methods for setup and cleanup required for each test. 4. Implement the following test cases: - `test_add_book`: Verify that books are added correctly. - `test_remove_book`: Verify that books are removed correctly and handle exceptions for non-existing books. - `test_has_book`: Check the existence of books in the library. - `test_list_books`: Verify the listing of all books. # Example Usage ```python import unittest class TestLibrary(unittest.TestCase): @classmethod def setUpClass(cls): print("Setting up the Library test environment") @classmethod def tearDownClass(cls): print("Cleaning up the Library test environment") def setUp(self): self.library = Library() def tearDown(self): pass # No specific tearDown needed for each test in this case def test_add_book(self): self.library.add_book("1984") self.assertTrue(self.library.has_book("1984")) def test_remove_book(self): self.library.add_book("1984") self.library.remove_book("1984") self.assertFalse(self.library.has_book("1984")) def test_remove_book_non_existing(self): with self.assertRaises(ValueError): self.library.remove_book("Non-existing Book") def test_has_book(self): self.library.add_book("1984") self.assertTrue(self.library.has_book("1984")) self.assertFalse(self.library.has_book("Brave New World")) def test_list_books(self): self.library.add_book("1984") self.library.add_book("Brave New World") books = self.library.list_books() self.assertIn("1984", books) self.assertIn("Brave New World", books) if __name__ == '__main__': unittest.main() ``` - Ensure your implementation includes the `Library` class and the `TestLibrary` class. - Your solution will be assessed based on correctness, completeness, and the use of unittest framework functionalities. # Submission - Provide your implementation in a single `.py` file.
answer:class Library: def __init__(self): self.books = set() def add_book(self, title): self.books.add(title) def remove_book(self, title): if title not in self.books: raise ValueError("The book is not available in the library.") self.books.remove(title) def has_book(self, title): return title in self.books def list_books(self): return list(self.books)