Appearance
question:Objective You are required to implement a function that fetches data from multiple URLs. The function should handle HTTP GET and POST requests, manage headers, and handle potential errors gracefully. Problem Statement Implement a function `fetch_multiple_urls(urls, data=None, headers=None)` that takes a list of URLs and makes HTTP requests to fetch data from those URLs. 1. **URLs (list of str)**: List of URLs to fetch data from. 2. **data (dict, optional)**: Dictionary containing data to be sent via a POST request. If `None`, a GET request should be made. 3. **headers (dict, optional)**: Dictionary containing additional headers to be included in the request. If `None`, no extra headers are added. Function Signature ```python import urllib.request import urllib.parse def fetch_multiple_urls(urls, data=None, headers=None): # your code here ``` Expected Behavior 1. The function should iterate over the list of URLs and fetch their content. 2. If `data` is provided, it should be sent as a POST request. The dictionary should be encoded using `urllib.parse.urlencode` and `data.encode('ascii')`. 3. If `headers` are provided, they should be included in the request. 4. The function should handle exceptions such as `URLError` and `HTTPError` and return appropriate error messages. 5. The function should return a dictionary where keys are URLs and values are either the content retrieved or the error message in case of failure. Example ```python urls = [ 'http://www.example.com', 'http://www.nonexistentwebsite.xyz' ] data = { 'name': 'John Doe', 'location': 'Earth' } headers = { 'User-Agent': 'Mozilla/5.0' } result = fetch_multiple_urls(urls, data, headers) ``` **Expected Output:** ```python { 'http://www.example.com': '<response content>', 'http://www.nonexistentwebsite.xyz': 'Error: <appropriate error message>' } ``` Constraints 1. The function should handle the case where some URLs might not be reachable or return errors. 2. The response content can be large, ensure to handle large responses efficiently. Tips - Use the `urllib.request.Request` class for building the requests. - Utilize `urlopen` to make the requests and handle exceptions using `try-except` blocks. - Use the `response.read()` method to get the content of the response. - Remember to close the response object after reading from it. Additional Note For advanced students, include handling of different HTTP status codes in the error handling.
answer:import urllib.request import urllib.parse import socket def fetch_multiple_urls(urls, data=None, headers=None): results = {} for url in urls: try: if data: data_encoded = urllib.parse.urlencode(data).encode('ascii') request = urllib.request.Request(url, data=data_encoded) else: request = urllib.request.Request(url) if headers: for key, value in headers.items(): request.add_header(key, value) with urllib.request.urlopen(request, timeout=10) as response: content = response.read().decode('utf-8') results[url] = content except urllib.error.HTTPError as e: results[url] = f'Error: HTTPError {e.code} {e.reason}' except urllib.error.URLError as e: results[url] = f'Error: URLError {e.reason}' except socket.timeout as e: results[url] = 'Error: Timeout' except Exception as e: results[url] = f'Error: {str(e)}' return results
question:# PyTorch IR Programming Challenge PyTorch 2.0 introduces two sets of intermediate representations (IRs) called Core Aten IR and Prims IR. These IRs are used for composing operations that can interface with backend compilers. The Core Aten IR includes a subset of functional operators, while the Prims IR includes primitive operators with explicit type promotion and broadcasting. In this coding challenge, you will implement a custom operation that consists of a composition of both Core Aten IR and Prims IR operators. Your task is to create a function that computes the element-wise power of a tensor and then scales the result by a scalar factor using these IRs. Function Signature ```python import torch def custom_operation(tensor: torch.Tensor, exponent: float, scale_factor: float) -> torch.Tensor: pass ``` Requirements 1. **Input:** - `tensor`: A `torch.Tensor` of any shape. - `exponent`: A `float` representing the power to which each element of the tensor should be raised. - `scale_factor`: A `float` representing the factor by which the result should be scaled. 2. **Output:** - A `torch.Tensor` of the same shape as the input tensor with each element raised to the specified exponent and then scaled by the scale factor. 3. **Constraints:** - You must utilize both Core Aten IR and Prims IR in your implementation. - The function should handle tensors of any shape and value ranges. Example ```python tensor = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) exponent = 2.0 scale_factor = 0.5 result = custom_operation(tensor, exponent, scale_factor) print(result) # Expected output: tensor([[0.5, 2.0], [4.5, 8.0]]) ``` Guidelines 1. Use `Core Aten IR` for performing the exponentiation. 2. Use `Prims IR` for applying the type promotion and scaling the tensor. 3. Please ensure the function is efficient and handles edge cases gracefully. Tips - Review the `Core Aten IR` and `Prims IR` operations available in the provided CSV files to identify the necessary operators. - Ensure proper type promotion and broadcasting where applicable. Good luck, and happy coding!
answer:import torch def custom_operation(tensor: torch.Tensor, exponent: float, scale_factor: float) -> torch.Tensor: Performs an element-wise power on the input tensor and then scales the result by the given factor. Parameters: tensor (torch.Tensor): Input tensor. exponent (float): The exponent to which each element is raised. scale_factor (float): The scale factor by which the result is multiplied. Returns: torch.Tensor: The resultant tensor after the operations. # Core Aten IR for exponentiation tensor_exp = torch.pow(tensor, exponent) # Prims IR for scaling # Unfortunately, we need to use standard multiplication as the specific Prims IR function is not directly accessible # in standard PyTorch distributions as of the current PyTorch IRs. In a real environment, you should replace this # with the corresponding primitive operation. result = tensor_exp * scale_factor return result
question:# Secure File Integrity Verification You are tasked with designing a mechanism to ensure the integrity and security of files transferred over a network. For this, you will use the Python cryptographic services. Specifically, you need to: 1. Compute secure hashes of files using the `hashlib` module. 2. Implement a keyed-hashing mechanism using the `hmac` module to ensure the integrity and authenticity of the file. 3. Generate a secure token using the `secrets` module to unique identify each file during the transmission. Requirements 1. **Function 1**: `compute_file_hash(filepath: str) -> str` - Compute and return the SHA-256 hash of the file located at `filepath`. - **Input**: `filepath` (str) — Path to the file. - **Output**: (str) — The SHA-256 hash of the file in hexadecimal format. 2. **Function 2**: `compute_hmac(filepath: str, key: bytes) -> str` - Compute and return the HMAC (using SHA-256) of the file located at `filepath` with the given `key`. - **Input**: 1. `filepath` (str) — Path to the file. 2. `key` (bytes) — The key to use for the HMAC computation. - **Output**: (str) — The computed HMAC in hexadecimal format. 3. **Function 3**: `generate_secure_token() -> str` - Generate and return a secure random token using the `secrets` module. - **Input**: None - **Output**: (str) — A hexadecimal token of at least 16 bytes. Constraints 1. Assume that the file size will not exceed 100MB. 2. You must handle file read/write exceptions and other potential errors gracefully. 3. Ensure that your functions are efficient and utilize appropriate cryptographic standards. Example ```python # Let's assume you have a file named 'example.txt' # Function 1: Compute file hash hash_value = compute_file_hash('example.txt') print(hash_value) # Outputs the SHA-256 hash of the file # Function 2: Compute HMAC key = b'secret_key' hmac_value = compute_hmac('example.txt', key) print(hmac_value) # Outputs the HMAC of the file # Function 3: Generate Secure Token token = generate_secure_token() print(token) # Outputs a random secure token ``` Please implement these three functions to meet the described requirements. Ensure you follow best practices and proper error handling.
answer:import hashlib import hmac import secrets def compute_file_hash(filepath: str) -> str: Compute and return the SHA-256 hash of the file located at filepath. try: sha256_hash = hashlib.sha256() with open(filepath, "rb") as f: for byte_block in iter(lambda: f.read(4096), b""): sha256_hash.update(byte_block) return sha256_hash.hexdigest() except Exception as e: raise RuntimeError(f"Error computing file hash: {e}") def compute_hmac(filepath: str, key: bytes) -> str: Compute and return the HMAC (using SHA-256) of the file located at filepath with the given key. try: hmac_hash = hmac.new(key, digestmod=hashlib.sha256) with open(filepath, "rb") as f: for byte_block in iter(lambda: f.read(4096), b""): hmac_hash.update(byte_block) return hmac_hash.hexdigest() except Exception as e: raise RuntimeError(f"Error computing HMAC: {e}") def generate_secure_token() -> str: Generate and return a secure random token. return secrets.token_hex(16)
question:**Problem Statement:** You have been provided with a dataset containing information about passengers from the Titanic. Your task is to create a comprehensive visual analysis using seaborn to gain insights into the passengers' demographics and survival rates. **Dataset:** Use the Titanic dataset provided by seaborn: ```python df = sns.load_dataset("titanic") ``` **Requirements:** 1. **Strip Plot:** - Create a strip plot of passengers' ages for each class, colored by their sex. Ensure that the jitter effect is enabled for better visualization. 2. **Box Plot:** - Generate a box plot that compares the age distribution across different classes. Separate the data by the 'sex' variable. 3. **Violin Plot:** - Create a violin plot to compare the distribution of ages across different classes. Adjust the bandwidth and trim the violin plot tails. Ensure that the violins are split by the 'sex' variable. 4. **Bar Plot with Subplots:** - Construct bar plots to visualize the survival rate for each class. Create subplots for 'sex' to show separate bar plots for male and female passengers. Adjust the subplot size and aspect ratio. 5. **Combined Plot:** - Generate a combined plot where a violin plot shows the age distribution (with a light color and without inner marks), and overlay a swarmplot on top to show individual age data points colored by class. Ensure the swarmplot points are small enough to be distinct. 6. **Customization:** - Fine-tune one of the plots (e.g., the bar plot with subplots) by customizing the axes labels, tick labels, titles, setting the y-axis limit between 0 and 1, and removing the spine on the left side. **Constraints:** - Use seaborn and matplotlib.pyplot for your visualizations. - Ensure your plots are easy to read and interpret. - Reuse the dataset for all visualizations. **Expected Output:** - Multiple visualizations as described in the requirements. - Each plot should be displayed and labeled appropriately. **Performance Requirements:** - The code should execute without errors and generate the required visualizations efficiently. **Note:** Include comments in your code to describe each step and part of the visualizations. Ensure that your code is well-structured and adheres to best practices in data visualization.
answer:import seaborn as sns import matplotlib.pyplot as plt def analyze_titanic_data(): Perform a comprehensive visual analysis on the Titanic dataset. # Load the Titanic dataset df = sns.load_dataset("titanic") # Strip plot of passengers' ages for each class, colored by sex plt.figure(figsize=(10, 6)) sns.stripplot(x="class", y="age", hue="sex", data=df, jitter=True, palette="Set1") plt.title("Strip Plot of Ages for Each Class by Sex") plt.show() # Box plot comparing the age distribution across different classes, separated by sex plt.figure(figsize=(10, 6)) sns.boxplot(x="class", y="age", hue="sex", data=df, palette="Set2") plt.title("Box Plot of Age Distribution Across Classes by Sex") plt.show() # Violin plot comparing the distribution of ages across different classes plt.figure(figsize=(10, 6)) sns.violinplot(x="class", y="age", hue="sex", data=df, palette="Set3", split=True, bw=0.2, cut=0) plt.title("Violin Plot of Age Distribution Across Classes by Sex") plt.show() # Bar Plot with Subplots: Survival rate for each class by sex g = sns.catplot(x="class", hue="survived", col="sex", data=df, kind="count", height=5, aspect=1.2, palette="Set1") g.set_axis_labels("Class", "Survival Count") g.fig.suptitle("Survival Rate by Class and Sex", y=1.05) plt.show() # Fine-tuning the subplot grid for ax in g.axes.flat: ax.set_ylim(0, 150) ax.set_yticks(range(0, 150, 30)) ax.spines['left'].set_visible(False) # Combined plot: Violin plot and swarmplot for age distribution and individual data points by class plt.figure(figsize=(10, 6)) sns.violinplot(x="class", y="age", data=df, color="lightgrey", cut=0) sns.swarmplot(x="class", y="age", hue="class", data=df, palette="Set1", size=3, dodge=True) plt.title("Combined Plot of Age Distribution by Class") plt.show()