response_seed
stringlengths
53
5.17k
instruction_seed
stringlengths
29
4.02k
response
stringlengths
16
8.81k
__original_row_idx
int64
0
50k
To implement this function, we can use the `batch.reshape(-1)` function to reshape the input batch into a 1-dimensional tensor, which makes it easier to calculate the L2 norm of the entire tensor. We then divide each element of the input batch by the L2 norm and subtract the L2 norm from each element. However, if the i...
Write a Python function `normalize_and_subtract_mean_from_batch` that takes a PyTorch tensor `batch` as input, normalizes it by dividing each element by the L2 norm of the entire tensor, and then subtracts the L2 norm of the entire tensor from each element. However, if the input batch is a scalar, the function should r...
Certainly! Below is a Python function named `normalize_and_subtract_mean_from_batch` that implements the described functionality using PyTorch. This function checks if the input `batch` is a scalar and if so, it returns it directly. If it's a tensor, it computes the L2 norm, normalizes the tensor, and then subtracts t...
16,000
```python def build_tag(tag_name, class_attr=None): tag = f"<{tag_name}" if class_attr: tag += f' class="{class_attr}"' tag += ">" return tag ``` This implementation uses string concatenation to build the HTML tag string. The `class` attribute is added within the tag if it is provided as a func...
Write a Python function to build a string to represent an HTML tag with an optional `class` attribute. The function should accept the tag name as the first parameter, and an optional `class` attribute as the second parameter. If the `class` attribute is provided, it should be set as the value of a `class` attribute on ...
You can create a Python function to build an HTML tag with an optional `class` attribute quite easily. Below is an example of how such a function can be implemented: ```python def build_html_tag(tag_name, class_name=None): """ Build a string representation of an HTML tag. Parameters: - tag_name: T...
16,001
To write a Python function to configure a font family based on a user's preferences, you can follow these steps: 1. Identify the parameters that should be configurable, such as font family, font size, and font color. 2. Define a default value for each of these parameters. 3. Create a function that accepts a dictionary...
Write a Python function to configure a font family based on a user's preferences. The function should accept a dictionary of parameters, which can contain the following keys: - "font_family": The font family to use. Default: "Arial" - "font_size": The font size in pixels. Default: 16 - "font_color": The color of the f...
You can create a Python function that configures the font family based on the user's preferences. Here's a sample implementation of the function based on the specifications you provided: ```python def configure_font(params=None): # Default values default_settings = { "font_family": "Arial", "fo...
16,002
Here is a Python function that implements this approach: ```python def create_filter(filter_fn): """ Creates a function that accepts a list of strings and returns a filtered list based on a passed in filter function. """ return lambda strings: [s for s in strings if filter_fn(s)] ```
Write a Python function `create_filter` that creates a function that accepts a list of strings and returns a filtered list based on a passed in filter function. The `create_filter` function should take in a filter function as an argument and return a new function that takes in a list of strings and uses the passed in f...
To create the `create_filter` function as described, you can define it to take a filter function as an argument and then return another function. This returned function will take a list of integers and apply the filter function to produce a filtered result. Below is the implementation of this logic: ```python def crea...
16,003
To implement `replace_nested_dict_value(dict_obj, key, old_value, new_value)`, you need to use a recursive approach to traverse the nested dictionary and identify the key-value pair with the specified `old_value`. Once found, you can change the value to the `new_value` and return the updated dictionary. Here is an exa...
Implement a Python function `replace_nested_dict_value(dict_obj, key, old_value, new_value)` that searches for a nested dictionary within a given dictionary object and replaces a specific value at a given key. The function should recursively traverse the dictionary to find the key and replace the matching value with th...
Certainly! Below is a Python function called `replace_nested_dict_value` which takes a dictionary object, a key, an old value, and a new value. It will recursively search through the nested dictionary structure, replacing all occurrences of the specified old value associated with the given key. ```python def replace_n...
16,004
The goal is to develop a Python function `format_pi_string(x)` that takes a float-valued number as input and returns a string with `"π"` and the value of `x` with four decimal places. The function should handle the cases where `x` is positive or negative, and handle the cases where `x` is an integer or a floating-poin...
Develop a Python function named `format_pi_string` that takes a float-valued number `x` as input. The function should return a string representation of `x` in the format `'{PI}{value}'`, where `PI` is the Greek letter pi and `value` is the value of `x` with four decimal places. You may assume that `x` is a float. If `...
You can create the `format_pi_string` function in Python following the specifications you provided. The function will format the input float `x` into a string that represents the value along with the Greek letter pi. Here's how you can implement this: ```python def format_pi_string(x): # Format the value with four...
16,005
```python def count_resources(template, resource_type): resources = template.get('resources', {}) return len({key: value for key, value in resources.items() if value.get('type') == resource_type}) ``` This implementation uses a dictionary comprehension to filter the resources dictionary based on the desired re...
Write a Python function that reads an OpenStack Heat template (HOT) and returns the number of resources of a certain type. The function should take two arguments: the template file contents (a dictionary) and the resource type (a string). The function should return the number of resources of the given type.
You can create a Python function to count the number of resources of a specified type in an OpenStack Heat Template (HOT) by using the `template` dictionary. The function will iterate through the resources defined in the template and count how many of them match the specified resource type. Here’s an example implement...
16,006
Here is the implementation: ```python import re import keyword def is_valid_placeholder_argument_name(name): pattern = r"^\$[a-zA-Z_][a-zA-Z0-9_]*$" if re.match(pattern, name): if not keyword.iskeyword(name[1:]): return True return False ```
Write a Python function that checks whether the input is a valid placeholder argument name. The function should accept a string and return a boolean value. Here are the rules for valid placeholder argument names: - The argument name must start with a dollar sign `$` and contain at least one character after it. - The a...
To implement the function `is_valid_placeholder_argument_name`, we need to follow the rules you provided for a valid placeholder argument name while also accommodating error handling for invalid input types. I'll first define a list of common Python reserved words that the function should check against. Here's the imp...
16,007
The function can be implemented using a regular expression to extract the pattern from each string. First, you define a helper function to extract the pattern from a given string using the provided regular expression. Then, you can iterate over the list of strings, extract the pattern using the helper function, and sto...
Design a function named `extract_pattern` that takes a list of strings and an optional pattern. The function should extract the first occurrence of the pattern in each string, and return a dictionary with the extracted pattern as the key and the corresponding string as the value. The function should work for any valid...
To implement the function `extract_pattern`, you can follow these steps: 1. Import the `re` module for regular expressions. 2. Define a helper function that will be responsible for extracting the first occurrence of the pattern from a given string. 3. In the main function, iterate through each string in the input list...
16,008
You can create a Python function that takes a `text` string and a `words` list as arguments. The function should remove all occurrences of the words from the text. Here's how you could implement it: ```python def remove_words(text, words): words_set = set(words) filtered_text = ' '.join(word for word in text....
Write a Python function that takes two arguments: a string `text` and a list of strings `words`. The function should remove all occurrences of the `words` from `text`. Your code should pass the following test case: ```python text = "The quick brown fox jumps over the lazy dog" words = ["quick", "brown", "jumps"] filte...
You can achieve this by defining a function that iterates through the list of words and removes each word from the given text. Here’s a function that implements this: ```python def remove_words(text, words): for word in words: text = text.replace(word, "") # Remove any extra whitespace left after remov...
16,009
Here's how you can implement the function using a single-line conditional expression: ```python def some_function(dicts_list, key): return [dict.get(key, None) for dict in dicts_list] ``` This function uses a list comprehension to iterate through the list of dictionaries and extract the value for the given key us...
Write a Python function `some_function` that takes in a list of dictionaries. The function should iterate through the list and return a list of values corresponding to a specific key. If the key does not exist in a dictionary, the value should be set to `None` instead of an error being raised. Use a single-line conditi...
You can achieve this by defining a function named `some_function` which takes a list of dictionaries and a specific key as parameters. The function will iterate through each dictionary in the list and retrieve the value for the given key, defaulting to `None` if the key does not exist. The function will return a list o...
16,010
Here's the implementation of the function: ```python from datetime import date def is_date_within_range(date_to_check: date, start_date: date, end_date: date) -> bool: return start_date <= date_to_check <= end_date ```
Write a Python function to determine whether a date is within a specified interval range. The function should take three parameters: the date to check, the start date of the interval, and the end date of the interval. The function should return a boolean value indicating if the date is within the interval or not. For e...
You can achieve this by using the `datetime` module in Python, which provides a convenient way to work with dates. Here’s a function that checks if a given date is within a specified interval: ```python from datetime import datetime def is_date_within_interval(date_to_check, start_date, end_date): # Convert the i...
16,011
To parse a string as an integer, you need to check if it can be converted to an integer and handle the cases where it's not. You can do this by using a try-except block and handling the ValueError exception. Here's how you could implement a Python function `parse_integer`: ```python def parse_integer(s, default=None)...
Write a Python function `parse_integer` that takes two arguments: `s`, a string representing an integer, and `default`, a default value to return if the string cannot be parsed as an integer. The function should parse the string `s` and return the integer value. If the string cannot be parsed as an integer, the functio...
You can create a function called `parse_integer` that attempts to convert a given string into an integer. If the conversion fails due to an error (such as a `ValueError`), it will return the specified default value. Here's how to implement this function in Python: ```python def parse_integer(s, default): try: ...
16,012
Here is a Python function that implements this algorithm: ```python def is_repetition_match(a: str, b: str) -> bool: """ Checks if `b` is a repetition of `a`. Here, a repetition means that `b` contains at least one substring that is repeated multiple times, and the repetition can be non-continuous. """...
Write a Python function called `is_repetition_match` that takes two strings `a` and `b` and checks if `b` is a repetition of `a`. Here, a repetition means that `b` contains at least one substring that is repeated multiple times, and the repetition can be non-continuous. For example, `is_repetition_match("abcabc", "abc...
To create the function `is_repetition_match`, we need to check if string `b` can be constructed by taking substrings from string `a` and repeating them, regardless of whether the repetitions are continuous or not. The function will return `True` if such a repetition exists and `False` otherwise. Here's a possible impl...
16,013
Here's how you could do it: ```python def shuffle_with_value_checking(array): values_count = dict() for value in array: if value not in values_count: values_count[value] = 1 else: values_count[value] += 1 for value, count in values_count.items(): if count >...
Implement a Python function `shuffle_with_value_checking(array)` that shuffles the elements of an array in a random order while ensuring that no value is lost. Your function should check for duplicate values and return an error message if they exist. Your code should pass the following test case: ```python array = [1,...
To implement the `shuffle_with_value_checking(array)` function, we need to take the following steps: 1. Check for duplicate values in the input array. 2. If duplicates are found, the function should return an error message indicating the duplicate value. 3. If there are no duplicates, we can proceed to shuffle the arr...
16,014
Here is a Python function that implements this approach: ```python import re def natural_sort(strings): """ Sorts a list of strings in natural (human-readable) order. """ def key_func(string): return [int(s) if s.isdigit() else s.lower() for s in re.split(r'(\d+)', string)] return sorted(s...
Create a Python function that takes a list of strings and returns the list sorted in natural (human-readable) order. The list may contain numbers, letters, or a mixture of both. Here are some examples: ```python natural_sort(["1", "2", "10"]) -> ["1", "2", "10"] natural_sort(["abc1", "abc2", "abc10"]) -> ["abc1", "ab...
You can achieve natural sorting in Python by using the `natsort` library, which is specifically designed for this purpose. However, if you want to implement a solution using only built-in Python functionality, you can create a custom sorting function using the `re` module to split strings into components of digits and ...
16,015
To count the occurrences of a sublist in a list, we can use a sliding window approach. This approach allows us to process items in `lst` in order, and returns as soon as possible if `sublst` is not found in `lst`. It also prevents unnecessary comparisons when `sublst` is not found in `lst`. Here's how we can implement...
Write a Python function `count_sublist_occurrences(lst, sublst)` that counts the number of times a sublist `sublst` appears in a list `lst`. The function should return 0 if `sublst` is not found in `lst` or if `lst` or `sublst` is empty. Your function should satisfy the following conditions: - It should process items...
Certainly! Below is the implementation of the `count_sublist_occurrences` function that meets the specified requirements: ```python def count_sublist_occurrences(lst, sublst): # Check for empty lst or sublst if not lst or not sublst: return 0 count = 0 sub_length = len(sublst) # I...
16,016
Here's one possible implementation in Python: ```python import re def get_bucket_path(key): match = re.search(r's3://([^/]+)/(.*)', key) if match: bucket_name = match.group(1) object_path = match.group(2) return bucket_name, object_path else: raise ValueError('Invalid S3 ke...
Implement the function `get_bucket_path` in Python to parse the input `key` and return the bucket and object path. The function should take the input `key` and return a tuple of two values: the first value should be the bucket name, and the second value should be the full path to the object inside the bucket. You can...
To implement the `get_bucket_path` function, you can follow these steps: 1. Check if the input `key` starts with the `s3://` prefix. If it does not, handle it appropriately (in this example, we will assume valid input). 2. Remove the `s3://` prefix from the key. 3. Split the remaining string into the bucket name and t...
16,017
The covariance matrix of a matrix is a symmetric matrix whose elements represent the covariance between pairs of variables in the matrix. To compute the covariance matrix, we can use the `np.cov` function provided by the numpy library. Here is the implementation: ```python import numpy as np def covariance_matrix(ma...
Write a Python function to compute the covariance matrix of a matrix. The input is a 2-dimensional numpy array, and the output is a 2-dimensional numpy array representing the covariance matrix.
You can compute the covariance matrix of a 2-dimensional numpy array using the `numpy` library. Below is a Python function that takes a 2D numpy array as input and returns the covariance matrix: ```python import numpy as np def compute_covariance_matrix(data): """ Computes the covariance matrix of a given 2D ...
16,018
Here's an example of a mocking-based unit test for the function: ```python import unittest from unittest.mock import patch def is_balanced(s): stack = [] for c in s: if c == '(': stack.append(c) elif c == ')': if len(stack) == 0: return False ...
I want to write a Python function that takes a string input and returns true if and only if the input is a valid string of parentheses that is balanced. For example, "()" and "()()" would be valid inputs, but "(]" and "(()" would not. I have written the main logic of the function, but I need to write the unit tests fo...
Certainly! Below, I'll provide you with a sample implementation of your function to check if a string of parentheses is balanced. Then, I'll demonstrate how to write unit tests for it using the `unittest` framework, specifically using mocking where applicable. ### Implementation of the Function Here's a simple implem...
16,019
To build a function that parses a JSON string and returns a dictionary that maps the keys of each inner dictionary to its full path, we can use the `json` module to parse the JSON string into a Python dictionary. We can then use recursion to traverse the dictionary and build the full path for each key. Here is how you...
Build a Python function that accepts a JSON string as input and returns a dictionary that maps the keys of each inner dictionary to its full path. For example, given the JSON string: `{"a": {"b": {"c": 1, "d": 2}}, "e": {"f": 3}}` The function should return a dictionary: `{"a.b.c": 1, "a.b.d": 2, "e.f": 3}`
You can achieve this by defining a recursive function that traverses the nested dictionaries and constructs the full paths of the keys. Here’s a Python function that accomplishes this: ```python import json def map_keys_to_paths(json_string): # Parse the JSON string into a Python dictionary data = json.loads(...
16,020
The function `interpolate_string` aims to replace placeholders within a given string with their corresponding values from a given dictionary. It supports nested placeholders, i.e., placeholders within placeholders. The function makes use of regular expressions to find and replace placeholders in the provided string. H...
Write a Python function called `interpolate_string` that takes a string and a dictionary of placeholders as inputs. The function should return a new string with the placeholders replaced by the corresponding values from the dictionary. The function should support nested placeholders, i.e., placeholders within placehold...
To create the `interpolate_string` function that replaces placeholders in a string with values from a dictionary, we'll need to handle both simple and nested placeholders. We'll utilize a loop to repeatedly search for placeholders in the string and replace them with the corresponding values from the dictionary until no...
16,021
You can implement the padding as follows: ```python import torch def pad_tensor(input_tensor, height, width): batch_size, num_channels, input_height, input_width = input_tensor.shape output_tensor = torch.zeros(batch_size, num_channels+1, height, width) output_tensor[:, :-1, 1:1+input_height, 1:1+input_wi...
Write a Python function to pad an input tensor of shape `(batch_size, num_channels, height, width)` to an output tensor of shape `(batch_size, num_channels, padded_height, padded_width)` by padding each sample with a single zero channel on the top, bottom, left, and right (respectively). Ensure the padding is applied o...
You can create a Python function that uses the `torch` library (from PyTorch) to pad a tensor with zeros in the specified manner. The padding should be applied only to the `height` and `width` dimensions, effectively adding one zero channel on each side (top, bottom, left, and right) of the input tensor. Here's how you...
16,022
Here's how you can implement a recursive function to solve this problem: ```python def sum_mpo(mpo): if isinstance(mpo, list): return sum(sum_mpo(item) for item in mpo) elif isinstance(mpo, dict): return sum(sum_mpo(mpo[key]) for key in mpo) elif isinstance(mpo, int): return mpo ...
Create a Python function `sum_mpo(mpo)` that takes a multi-part object `mpo` and returns the sum of all the numbers in the objects. The function should traverse the object and sum the numbers, including the numbers in lists, dictionaries, and nested objects.
You can achieve this by writing a recursive function that traverses different data structures such as lists, dictionaries, and other objects. The function will check each element, and when it encounters a number, it will add it to the sum. Below is a Python implementation of the `sum_mpo` function: ```python def sum_m...
16,023
Here is an example implementation of the function: ```python def format_obj(obj): obj_id = obj.id obj_name = obj.name result = str(obj_id) + ":" + obj_name return result ```
In Python, given an object that stores two attributes: `id` and `name`, create a function that takes such an object and returns a formatted string. The string should be a concatenation of the object's `id` and `name` attributes, separated by a colon. For example, given an object with `id` of 5 and `name` of "Alice", th...
You can create a function that accepts an object with `id` and `name` attributes and returns a formatted string as described. Here's how you can do that in Python: ```python def format_object(obj): return f"{obj.id}:{obj.name}" # Example usage: class MyObject: def __init__(self, id, name): self.id = i...
16,024
Here is a Python function that takes a nested data structure as input and returns a flattened dictionary: ```python def flatten_data(data): flat_data = {} def _flatten(data, parent_keys=[]): for key, value in data.items(): if isinstance(value, dict): _flatten(value, parent_...
Given a JSON data structure with nested lists and dictionaries, write a Python function to flatten it into a single-level dictionary. The keys should be a combination of the parent and child keys. For example, given the data `{'a': 1, 'b': {'c': 2, 'd': 3}}`, the output should be `{'a': 1, 'b.c': 2, 'b.d': 3}`.
You can flatten a nested dictionary in Python by recursively traversing through all keys and values. Below is a function that accomplishes this task, combining parent keys and child keys into a single-level structure: ```python def flatten_dict(data, parent_key='', sep='.'): flat_dict = {} for k, v in dat...
16,025
To create a Python function to convert a GPU tensor to a JSON-serializable format, you'll need to leverage the PyTorch library and its functions for GPU tensors. The function should take in a GPU tensor and the dimension along which the values are to be extracted. It should then convert the tensor to a numpy array, ext...
Create a Python function to convert a GPU tensor to a JSON-serializable format, where the JSON object is a dictionary with two keys. The first key is "dtype" and represents the data type of the tensor as a string. The second key is "data" and represents the values of the tensor as a list of lists. The values of the inn...
To convert a GPU tensor to a JSON-serializable format, you can create a function that extracts the values along a specified dimension and returns them in a dictionary with the required structure. Here's a PyTorch-based implementation for a tensor on a GPU: ```python import json import torch def gpu_tensor_to_json(ten...
16,026
Here is an implementation of the `add_indices()` function: ```python def add_indices(d): """ Adds the index of each key in a dictionary to the value of each key. The resulting dictionary has the same keys, but each value is a tuple containing the value of the input dictionary and the index of the key. ...
Define a Python function `add_indices(d)` that takes a dictionary as input and returns another dictionary with the same keys, but each value is a tuple containing the value of the input dictionary and the index of the key. For example, `add_indices({'a': 1, 'b': 2})` should return `{'a': (1, 0), 'b': (2, 1)}`. If a ke...
To create the `add_indices` function as specified, we will implement it to handle dictionaries by checking the input type, iterating through the items of the dictionary to build the new dictionary with index values included, and handling nested dictionaries recursively. In the case where the original keys are sparse or...
16,027
Here's a solution that fulfills the requirements: ```python def count_words_in_file(file_path): try: with open(file_path, 'r') as file: words = file.read().split() return len(words) except Exception: return -1 ``` In the code: - `with open(file_path, 'r') as file:` open...
Create a Python function that takes a file path as input and returns the number of words in the file. The function should do the following: - Open the file in read mode. - Read the entire file and split it into individual words using the `split()` method. - Return the number of words in the file. The function should...
Certainly! Below is a Python function that accomplishes the task you've described. The function `count_words_in_file` takes a file path as input, reads the file, splits its contents into words, and returns the total number of words. If an exception occurs during file reading, it will return `-1`. ```python def count_w...
16,028
Here's how you could write the Python function and the test function: ```python def byte_to_string_format(byte): string_format = '' for bit in byte: string_format += f'{bit} ' # Formatting as a string with each character separated by a space return string_format.rstrip() # Remove the trailing spa...
Write a Python function `byte_to_string_format(byte)` that converts a byte of data (which is represented as a sequence of 8 bits) into a space-separated string. The string should be formatted using a format string, where each character representing a bit is separated by a space. Additionally, write a test function to v...
Sure! Let's create a Python function `byte_to_string_format(byte)` that takes a byte (as an integer from 0 to 255) and converts it into a space-separated string. Additionally, I'll provide a test function called `test_byte_to_string_format` to validate the functionality using example data. Here's the complete implemen...
16,029
Here is a Python function that implements this approach: ```python def get_missing_index(sequence, set_of_indexes): """ Finds the first missing index in `sequence` that is not present in `set_of_indexes`. If all indexes in the range [0, len(sequence) - 1] are present, returns None. """ present_inde...
Write a Python function `get_missing_index(sequence, set_of_indexes)` that returns the first missing index in `sequence` such that it is not present in `set_of_indexes`. If all indexes in the range `[0, len(sequence) - 1]` are present, the function should return `None`.
Here's a Python function `get_missing_index` that fulfills your requirements: ```python def get_missing_index(sequence, set_of_indexes): """ Returns the first missing index in the sequence that is not present in set_of_indexes. If all indexes in the range [0, len(sequence) - 1] are present, returns None. ...
16,030
Here's an example implementation of the function: ```python def layer_counts(layer_string): layer_types = layer_string.split(',') layer_counts = { 1: 0, # Input layer 2: 0, # Convolutional layer 3: 0, # Pooling layer 4: 0 # Fully connected layer } for layer_type in laye...
Write a Python function that takes a string and returns a list of integers. The string represents a series of comma-separated integers, where each integer represents a layer type. The function should return a list of integers, where each integer represents the number of layers of that type. The function should handle t...
You can achieve this by defining a function that maps each layer type to its corresponding index in the output list. The function will then count occurrences of each layer type based on the input string. Here's how you can implement this in Python: ```python def layer_counts(layers_str): # Mapping layer types to t...
16,031
Here is a Python function that implements this approach: ```python import statistics def spearman_rank_correlation(predictions, ground_truths): """ Computes the Spearman's rank correlation coefficient (Rho) between the predictions and ground truths. """ num_instances = len(predictions) prediction_...
Suppose you have a list of predictions and ground truth values, where each prediction and ground truth corresponds to a single instance. Each value is represented by a real number. The predictions and ground truths are ranked in ascending order (i.e., the lowest value is ranked first). Write a Python function that comp...
Certainly! Spearman's rank correlation coefficient (Rho) is a non-parametric measure of rank correlation, assessing how well the relationship between two variables can be described by a monotonic function. To calculate Rho, first, we need to rank the predictions and ground truths, then compute the correlation between t...
16,032
The function `set_bit(num, index)` should: - Check if the index is negative and raise an `IndexError` if it is. - Shift a `1` by `index` bits to the left to create a mask. - Use the bitwise OR operator `|` to set the bit at the given index. Here is one way to implement the `set_bit` function: ```python def set_bit(nu...
Write a Python function `set_bit(num, index)` that sets a bit in a number `num` at a given index `index`, where `index` is a non-negative integer. The function should use bitwise operations to perform the bit manipulation. The function should raise an `IndexError` if `index` is negative.
Certainly! The function `set_bit(num, index)` will set the bit at the specified index to 1 using bitwise operations. If the provided index is negative, it will raise an `IndexError`. Here's how you can implement that: ```python def set_bit(num, index): if index < 0: raise IndexError("Index must be a non-ne...
16,033
```python import hashlib def md5_file(file_path): md5 = hashlib.md5() with open(file_path, 'rb') as f: while True: chunk = f.read(4096) if not chunk: break md5.update(chunk) return md5.hexdigest() ```
Write a Python function that takes a file path as an argument and returns the MD5 hash of the file's contents. The function should hash the contents of the file in chunks (say 4096 bytes) to avoid loading the entire file into memory.
Certainly! Below is a Python function that takes a file path as an argument and returns the MD5 hash of the file's contents. The function reads the file in chunks of 4096 bytes to efficiently handle large files without loading the entire file into memory. ```python import hashlib def compute_md5(file_path): """Co...
16,034
The task is to process a time series of daily closing stock prices. Given a series of closing prices, calculate the average price over a rolling 30-day window. The series is a list of numbers representing closing prices for each day of the year, starting from January 1st. The function should iterate through the list, ...
The task is to process a time series of daily closing stock prices. Given a series of closing prices, calculate the average price over a rolling 30-day window. The series is a list of numbers representing closing prices for each day of the year, starting from January 1st. You should iterate through the list, calculati...
To calculate the average closing stock prices over a rolling 30-day window from a list of daily closing prices, you can iterate through the list and maintain a running sum of the last 30 days' prices. For the first 30 days, you compute the average based on all available prices. After the first 30 days, you average over...
16,035
Here is the implementation: ```python def get_num_pins(obj): try: num_pins = getattr(obj, 'num_pins') except AttributeError: return (None, False) if isinstance(num_pins, list): return (None, True) else: return (num_pins, False) ```
Create a Python function to retrieve the value of an unknown object's `num_pins` key and return it as a tuple. ```python def get_num_pins(obj): # Your code here ``` If `obj.num_pins` does not exist, return a tuple of `(None, False)`. If `obj.num_pins` is a list, return a tuple of `(None, True)`. If `obj.num_pins` i...
You can write the `get_num_pins` function as follows: ```python def get_num_pins(obj): # Try to access the num_pins attribute if hasattr(obj, 'num_pins'): num_pins = obj.num_pins # Check if num_pins is a list if isinstance(num_pins, list): return (None, True) # It's a list...
16,036
To solve this problem, you need to understand the concept of base 64 encoding and how to apply it in Python. Also, it is important to handle cases where the input is not a `bytes` object. Here is the implementation: ```python import base64 def get_encoded_image_string(image_bytes): if not isinstance(image_bytes,...
Write a Python function `get_encoded_image_string(image_bytes)` that takes in a `bytes` object that represents the binary data of an image and returns a base 64 encoded image string. If the input is not a `bytes` object, the function should return an empty string. Your code should pass the following test case: ```pyth...
To create the function `get_encoded_image_string(image_bytes)` that takes a `bytes` object representing an image and returns a base64 encoded image string, we will follow these steps: 1. **Check if the input is a `bytes` object**. If it is not, we will return an empty string. 2. **Use the `base64` module** to encode t...
16,037
Here's how we can implement this in Python: ```python def create_uri_scheme_dict(apis, upstream_hosts, upstream_ports): api_uri_schemes = {} for api, upstream_host, upstream_port in zip(apis, upstream_hosts, upstream_ports): api_uri_schemes[api] = f"{api}://{upstream_host}:{upstream_port}" return a...
Given a list of APIs and their upstream hosts and ports, create a dictionary with the APIs as keys and the corresponding backend URI schemes as values. To construct the URI scheme, use the API name, the upstream host, and the upstream port.
To create a dictionary with APIs as keys and their corresponding backend URI schemes as values, you can follow this format for constructing the URI scheme: ``` scheme://upstream_host:upstream_port/api_name ``` Here's a simple implementation for constructing the dictionary based on a provided list of APIs and their up...
16,038
To accomplish this task, you'll use a dictionary comprehension because it's a concise way to create a new dictionary while performing an operation on each value. You'll use try...except to handle any exceptions that may occur during the operation, and return None if an exception is caught. The code uses the original di...
I want to create a function that takes a dictionary and returns a new dictionary with each value being the key's value multiplied by 2. Do this using a dictionary comprehension. If an exception occurs, return None. Don't modify the original dictionary.
You can create a function that accomplishes this using a dictionary comprehension while handling exceptions gracefully. Here's an implementation in Python: ```python def double_values(original_dict): try: return {key: value * 2 for key, value in original_dict.items()} except Exception: return N...
16,039
Here is an implementation of the `render_request_template` function in Python: ```python import re def render_request_template(template: str, request: dict) -> str: pattern = re.compile(r"{{ (?P<variable>\w+) }}") return pattern.sub(lambda match: request[match.group("variable")], template) ``` This function ...
You write a function `render_request_template` that takes a template string and a `request` object as input and returns an HTML string. The function should format the template and render the current `request` context into a string. For example, given the template string `"Hello, {{ username }}!"`, the function should ...
To create the `render_request_template` function that formats a template string with the given request object, we can use Python's built-in `str.format()` method or the `string.Template` class. For this example, I'll demonstrate how to use `string.Template`, as it's specifically designed for simple string substitutions...
16,040
To calculate the optimal aspect ratio for a given window, we need to define the criteria for "best fit" and "maintaining aspect ratio." We can use the formula to calculate the optimal aspect ratio (width / height). To resize the viewport, we need to ensure that it fits within the window bounds and maintains the aspect...
Design a Python function to calculate the optimal aspect ratio for a given window size, and programmatically resize the viewport to provide the best fit while maintaining the aspect ratio. Given a window width and height in pixels, calculate the optimal aspect ratio using the formula (width / height). Then, set the vie...
To create a Python function that calculates the optimal aspect ratio for a given window size and resizes the viewport accordingly, we can follow these steps: 1. Calculate the optimal aspect ratio using the formula \( \text{aspect\_ratio} = \frac{\text{width}}{\text{height}} \). 2. Use this aspect ratio to determine th...
16,041
To implement a `map-reduce` style function in Python, you can follow these steps: 1. Create a helper function `extract_attribute(obj, attr)` to extract a given attribute value from an object, or `None` if the attribute does not exist. This function can use the built-in `getattr` function to access the attribute. 2. De...
Write a Python function to implement a simplified `map-reduce` style function that applies a given `func` to each attribute of a list of objects, applies a `reducer` function to the results, and returns the reduced value. The function should be able to handle cases where some objects may not have the given attribute.
Certainly! Below is a Python function that implements a simplified `map-reduce` style functionality. It takes a `list` of objects, an `attribute` that should be extracted from each object, a `func` to apply to the values of the given attribute, and a `reducer` to combine the results. Here’s how the implementation work...
16,042
This problem can be solved by looping through the input list. If the current element is not the same as the previous element, we append it to the new list. We can also use a `set` to store the elements that have been added to the new list, which allows us to avoid duplicates. ```python def remove_adjacent_dups(input_l...
Create a function named `remove_adjacent_dups` that accepts a list of integers and returns a new list with adjacent duplicates removed. For example, `remove_adjacent_dups([1, 2, 2, 3, 4, 4, 5])` should return `[1, 2, 3, 4, 5]`. The function should handle both integer and string types. It should also handle cases where...
Certainly! Below is a Python function named `remove_adjacent_dups` that meets all the specified criteria: ```python def remove_adjacent_dups(input_list): if not isinstance(input_list, list): raise TypeError("Input must be a list.") if not input_list: # Check if the list is empty return []...
16,043
```python class JSType: STRING = 0 NUMBER = 1 ARRAY = 2 OBJECT = 3 FUNCTION = 4 BOOLEAN = 5 NULL = 6 UNDEFINED = 7 @staticmethod def from_string(s): if s == "string": return JSType.STRING elif s == "number": return JSType.NUMBER el...
Map the categories "string", "number", "array", "object", "function", "boolean", "null", and "undefined" into an enumerated type `JSType` in Python 3.
In Python, you can create an enumerated type (enum) using the `enum` module. You can map the categories you specified into an enumerated type named `JSType`. Here’s how you can do it: ```python from enum import Enum class JSType(Enum): STRING = "string" NUMBER = "number" ARRAY = "array" OBJECT = "obje...
16,044
Here is a Python function that parses a CIGAR string into a list of tuples, where each tuple represents a CIGAR operation. ```python import re def parse_cigar_string(cigar_string): """ Parse a CIGAR string into a list of tuples, where each tuple represents a CIGAR operation. The first element of each tupl...
Write a Python function to parse a CIGAR string (a string of characters that represent sequence alignment operations) into a list of tuples, where each tuple represents a CIGAR operation. The first element of each tuple should be an integer representing the number of operations, and the second element should be a chara...
To parse a CIGAR string into a list of tuples as specified, we can iterate through the string, identify numeric values that precede the operation characters, and then collect them into tuples. Here's a Python function that accomplishes this: ```python def parse_cigar(cigar_string): import re # Use a regular ex...
16,045
Here's an example implementation of the `extract_body` function: ```python def extract_body(path): with open(path, 'r') as fin: text = fin.read() return text if text else "" ```
Write a Python function to extract the "body" or "text" of a text file at a given path. The function should accept a `path` argument, which is a string representing the file path to the text file. The function should open the file, read its content, and then close it. If the file is empty, the function should return ...
Your provided function is correct and effectively extracts the body of a text file at a specified path. Here's the function formatted cleanly and with additional suggestions for improvement, such as error handling in case the file does not exist or cannot be opened: ```python def extract_body(path): try: w...
16,046
Here is the implementation of the function: ```python def aux_to_sys(aux_indexes): return tuple(i + 1 for i in aux_indexes) def sys_to_aux(sys_indexes): return tuple(i - 1 for i in sys_indexes) ```
Write a Python function that converts between auxiliary indexes (0-indexed) and system indexes (1-indexed) for a tuple of auxiliary indexes. The auxiliary indexes are 0-indexed, and the system indexes are 1-indexed. Given a tuple of auxiliary indexes, the function should return a tuple of system indexes. Given a tupl...
You can create the required functions `aux_to_sys` and `sys_to_aux` that convert between auxiliary indexes and system indexes using the tuples as specified. Here is the implementation: ```python def aux_to_sys(aux_tuple): return tuple(aux + 1 for aux in aux_tuple) def sys_to_aux(sys_tuple): return tuple(sys -...
16,047
Based on the given instructions, we can define a Python function to verify that a string is composed only of alphanumeric characters and check if it is a palindrome. Here is an implementation of the function: ```python def verify_palindrome(string): if not string.isalnum(): return 1 if string == strin...
A Python function receives a string as an input argument. The function does the following: 1. Verifies that the string is composed only of alphanumeric characters. 2. Checks if the string is a palindrome. If it is, it assigns 0 to a variable called `exit_code`. Otherwise, it assigns 1 to `exit_code`. 3. Returns the `e...
Here's a Python function that implements the specified requirements. It checks if the input string is alphanumeric, determines if it is a palindrome, and sets the `exit_code` accordingly. ```python def verify_palindrome(s): # Check if the string is alphanumeric if not s.isalnum(): raise ValueError("Inp...
16,048
Here is how you could implement such a function: ```python def compose_functions(f, g): def composed_function(x): f_result = f(x) return g(f_result) return composed_function def square(x): return x * x def add_one(x): return x + 1 composed_function = compose_functions(square, add_one)...
Develop a Python function that takes two functions as input and returns a new function that composes the two functions. The new function should take in an argument and pass it to the first function, which returns a result that is then passed to the second function.
You can create a function that composes two functions using Python. Below is an implementation of such a function called `compose`. This function accepts two functions as inputs and returns a new function that, when called with an argument, passes that argument to the first function, then takes the result of that and p...
16,049
To look up a key in a dictionary and return its value if it exists, we can use the `in` operator to check if the key is in the dictionary. However, to avoid unnecessary iterations over the dictionary, we can use an early exit pattern. Here is the implementation of the function using an early exit pattern: ```python d...
Write a Python function that looks up a dictionary key and returns the value for that key, if it is present. If the key is not present, return `None`. Your function should use an early exit pattern to avoid unnecessary iterations over the dictionary. Your code should pass the following test case: ```python dictionary ...
You can create the function `lookup_key` with an early exit pattern to check if the key is present in the dictionary. If it is, the function will return the corresponding value; otherwise, it will return `None`. Here is the implementation: ```python def lookup_key(dictionary, key): # Check if the key is in the dic...
16,050
Here's how you can implement it in Python: ```python def create_target_map(samples): assert isinstance(samples, list), "Input must be a list of samples" for sample in samples: assert isinstance(sample, dict), "Each sample must be a dictionary" assert 'target' in sample, "Each sample must have a...
Given a list of samples, each sample is a dictionary with a target key, create a dictionary that maps each unique target to a list of samples with that target.
You can achieve this by iterating through the list of samples and organizing them into a new dictionary where keys are the unique targets and values are lists of samples corresponding to those targets. Here's a Python function that demonstrates how to do this: ```python def organize_samples_by_target(samples): tar...
16,051
Here's how you can implement this function: ```python import uuid def create_uuid(version=4, namespace=uuid.NAMESPACE_X500): if version == 4: return uuid.uuid4().hex elif version == 1: return uuid.uuid1().hex elif version in (3, 5): return uuid.uuid3(namespace, 'my_name').hex e...
Write a Python function `create_uuid` that generates a UUID in hex format. The function should accept two arguments: `version` and `namespace`. The default `version` should be 4, and the default `namespace` should be `uuid.NAMESPACE_X500`. The function should use the `uuid` module to generate the UUID. If the `version...
Certainly! Below is the Python function `create_uuid` that implements the requirements you've specified. It generates a UUID based on the provided version and namespace. ```python import uuid def create_uuid(version=4, namespace=uuid.NAMESPACE_X500, name=None): """ Generate a UUID in hex format. Args: ...
16,052
To round the values of a dictionary to two decimal places in Python, you can use the `round` function and a dictionary comprehension. The `round` function takes a number and an optional number of decimal places as arguments and returns the rounded value. Here is one possible implementation using dictionary comprehensi...
Write a Python function that takes a dictionary as input and returns a new dictionary with the values rounded to two decimal places. The function should return a new dictionary without modifying the original dictionary. Example: ```python >>> d = { "a": 1.2345, "b": -0.0005 } >>> round_values_to_two_decimals(d) {'a':...
You can achieve this by using a dictionary comprehension to create a new dictionary with the values rounded to two decimal places. Here's the function that implements this: ```python def round_values_to_two_decimals(input_dict): return {key: round(value, 2) for key, value in
16,053
To format a URL link and text into an HTML `<a>` tag, we can use the Python string formatting features. We can create a template string with the `<a>` tag, and then use string interpolation to substitute the `url` and `anchor_text` into the template. This will result in a formatted HTML tag with the specified URL and t...
Create a Python function to format a URL link and text into an HTML `<a>` tag. The function should take two string arguments, `url` and `anchor_text`, and return a string containing the HTML tag for the link. For example, `format_link('https://example.com', 'Example')` would return `<a href="https://example.com">Examp...
Certainly! You can create the function `format_link` in Python as follows: ```python def format_link(url, anchor_text): """ Formats a URL and anchor text into an HTML <a> tag. Parameters: url (str): The URL to be linked. anchor_text (str): The text to be displayed for the link. Returns: s...
16,054
Here's the Python code using dictionary comprehension and f-strings: ```python def dict_comp_fstrings(dictionary, prefix): return f"{next(value for key, value in dictionary.items() if key.startswith(prefix))}\n" if any(key.startswith(prefix) for key in dictionary) else "" ```
I want to build a function that takes a dictionary with string keys and values, and a string prefix. If the key starts with the prefix, the function should return the value appended with a newline character. Otherwise, it should return an empty string. The code should be as short as possible, and use modern Python fea...
You can achieve this by using a dictionary comprehension along with an f-string. Here’s a concise function that meets your requirements: ```python def filter_dict_by_prefix(d, prefix): return {k: f"{v}\n" if k.startswith(prefix) else "" for k, v in d.items()} ``` This function iterates over the items in the dicti...
16,055
Here's how you can implement this function: ```python def find_first_greater_than(xs, v): for i, x in enumerate(xs): if x > v: return i return -1 ```
Write a Python function to find the index of the first occurrence of a value `v` in an iterable `xs` that is greater than `v`. If such a value does not exist, return -1. Your code should pass the following assertions: ```python assert find_first_greater_than([1, 2, 3], 5) == -1 assert find_first_greater_than([1, 2, 3]...
You can implement the function `find_first_greater_than` as follows. The function will iterate over the items in the iterable `xs` and check if each item is greater than the provided value `v`. The first index found that satisfies this condition will be returned. If no such value is found, the function will return -1. ...
16,056
To create a Python function that parses command-line options and returns a boolean that indicates whether or not the user specified the `--ignore-case` option, you should follow these steps: 1. Check if the `--ignore-case` option is in the list of command-line options. 2. Return `True` if the `--ignore-case` option is...
Create a Python function that parses command-line options and returns a boolean that indicates whether or not the user specified the `--ignore-case` option. If the user did not specify the `--ignore-case` option, then return `False`. If the user did specify the `--ignore-case` option, then return `True`. The function s...
You can create a Python function called `check_ignore_case` that takes a list of command-line options and checks for the presence of the `--ignore-case` option. The function will return `True` if the option is found, and `False` otherwise. Here is the implementation of the function: ```python def check_ignore_case(op...
16,057
```python def calculate_steps_per_epoch(total_steps, epochs, batch_size, dataset_size, last_epoch_steps=None): total_batches = dataset_size // batch_size if last_epoch_steps is not None: remaining_batches = total_batches - last_epoch_steps // batch_size else: remaining_batches = total_batche...
Create a Python function that calculates the correct number of steps per epoch when training a model. Consider the following: - `total_steps`: The total number of steps taken during training, including steps from previous epochs. - `epochs`: The total number of epochs to train for. - `batch_size`: The size of each bat...
Here is a Python function that calculates the correct number of steps per epoch based on the provided parameters. The function takes into account whether it is the initial epoch or subsequent epochs and handles edge cases such as zero steps or a dataset size smaller than the batch size. ```python def calculate_steps_p...
16,058
To convert the class-based code to functional-style code, you can use higher-order functions and function composition. In functional programming, functions are treated as first-class objects, which means they can be passed around like any other value. Here's how you can convert the class-based code to functional-style...
Convert this class-based code to functional-style code: ```python class Person: def __init__(self, name, age): if age < 0: raise ValueError("Age should be non-negative") self.name = name self.age = age def get_name(self): return self.name def get_age(self): ...
You can achieve a functional-style implementation by using functions instead of class methods and returning a dictionary to represent the person's attributes. Here's how you can convert the provided class-based code into functional-style code: ```python def make_person(name, age): if age < 0: raise ValueEr...
16,059
Here is the implementation of the smooth L1 loss function: ```python import torch def smooth_l1_loss(input, target, beta=1): diff = torch.abs(input - target) loss = torch.where( diff < beta, 0.5 * diff**2, diff - 0.5 * beta ) return loss ``` In this implementation: - We first ...
Implement a function `smooth_l1_loss(input, target, beta=1)` that computes the smooth L1 loss between `input` and `target` tensors. The smooth L1 loss is defined as: $$ \text{loss}(x, y) = \begin{cases} 0.5 * (x - y)^2, & \text{if } |x - y| < \beta \\ |x - y| - 0.5 * \beta, & \text{otherwise} \end{cases} $$ where $\b...
To implement the `smooth_l1_loss` function in Python, we can use NumPy for tensor operations or PyTorch if you're working in a machine learning context. Below is the implementation using both libraries. ### Using NumPy ```python import numpy as np def smooth_l1_loss(input, target, beta=1.0): diff = np.abs(input...
16,060
To convert a string to a float, we need to handle a variety of error cases, such as invalid number formats, leading and trailing whitespace, missing or extra decimal points, and invalid characters. We'll start by defining a helper function, `is_valid_char(c)`, that checks if a given character is a valid digit or '.' (d...
Write a Python function, `convert_string_to_float(s)`, that takes a string representing a number and returns its corresponding float value. If the input string cannot be converted to a float, your function should return `False`. Your function should handle various error cases, including invalid number formats. Your co...
You can create a Python function `convert_string_to_float(s)` that attempts to convert a given string to a float and handles exceptions properly if the conversion fails. Here’s how you can implement this: ```python def convert_string_to_float(s): try: # Strip whitespace and convert the string to float ...
16,061
To create a Python function to map a JSON object, we can use the `map()` function. This function takes a mapping function that takes a single argument and returns a value that should be used for the mapped object. In our case, the mapping function takes a single `user` argument and returns a new object with 'id' and 'd...
Create a Python function to map a JSON object (representing a user) to a new object with keys 'id' and 'displayName'. The 'id' value should be the user's 'id' property, and the 'displayName' value should be the user's 'firstName' and 'lastName' properties concatenated with a space.
You can achieve this by creating a Python function that takes a JSON object (which can be represented as a dictionary in Python) and maps its properties to a new structure. Below is a sample implementation of the function: ```python def map_user_to_display(user): """ Maps a user JSON object to a new object wit...
16,062
Here's how you can implement this: ```python def get_file_info_list(d): output = [] for key, value in d.items(): if isinstance(value, dict): if "file_name" in value and "file_size" in value: output.append((value["file_name"], value["file_size"])) else: ...
I have a dictionary of dictionaries, where the inner dictionaries have two keys: file_name and file_size. I want to write a function that will take the dictionary as an input and return a list of (file_name, file_size) tuples. Additionally, I need to handle the case where the inner dictionaries do not have a file_name ...
You can write a function that extracts the `file_name` and `file_size` from each inner dictionary in the provided dictionary of dictionaries. This function will also handle cases where the required keys are missing, raising a `KeyError` as specified. Here's how you can implement this: ```python def extract_file_info(d...
16,063
```python import uuid def convert_uuid_string_to_object(uuid_string): try: uuid_object = uuid.UUID(uuid_string) except (ValueError, AttributeError): return "Invalid UUID string. Must be a 32-character hexadecimal value." return uuid_object ``` This implementation uses the `uuid.UUID()` fun...
Write a Python function that takes a UUID string formatted as a 32-character hexadecimal value and returns an appropriately converted UUID object. Handle cases where the input string is missing or malformed and return an appropriate error message.
You can create a Python function to convert a 32-character hex string into a UUID object using the `uuid` module from Python's standard library. The function will also handle cases where the input string is missing or malformed. Here's a sample implementation: ```python import uuid def convert_to_uuid(hex_string): ...
16,064
Here's how you could implement the function in Python: ```python def l2_loss(y_true, y_pred): if len(y_true) != len(y_pred): raise ValueError("The lists must have the same length.") l2 = 0 for i in range(len(y_true)): l2 += (y_true[i] - y_pred[i]) ** 2 return l2 ```
Create a Python function that calculates the L2 loss between two arrays. The function should take two parameters: `y_true` and `y_pred`, both lists of numbers. The L2 loss is defined as: $$ L2 = \sum_{i=1}^n (y_{true} - y_{pred})^2 $$ Here, n is the length of the lists. For example, if `y_true = [1, 2, 3]` and `y_pre...
Here's a Python function that calculates the L2 loss between two lists of numbers, `y_true` and `y_pred`. The function iterates over the elements of both lists, computes the squared difference for each pair, and returns the sum of those squared differences. ```python def l2_loss(y_true, y_pred): # Ensure both list...
16,065
To calculate the power of 10 with a given non-negative integer `n`, we can use a loop to multiply 10 with itself `n` times. We can also use the `pow` function from the built-in `math` module, which calculates `x` to the power `y` and returns the result. ```python import math def power_of_10(n): return math.pow(10...
Given a non-negative integer `n`, write a Python function to calculate the power of 10. If the input is 0, return 1; otherwise, return the product of 10 with itself `n-1` times. In other words, if the input is 4, the function should return 10000 (10^4).
You can create a Python function to calculate the power of 10 using a simple loop or by using the built-in power function. Here's how you can implement it: ```python def power_of_ten(n): if n == 0: return 1 else: result = 1 for _ in range(n): result *= 10 return resu...
16,066
Here is the implementation of the function `parse_timedelta`: ```python import re from datetime import timedelta def parse_timedelta(input_str: str) -> timedelta: days_re = re.compile(r"(\d+) (?:days?|day)") hours_re = re.compile(r"(\d+) (?:hours?|hour)") minutes_re = re.compile(r"(\d+) (?:minutes?|minut...
Implement a Python function `parse_timedelta` that takes a string that represents a timedelta and returns a `datetime.timedelta` object. The string may be in the format "X days, Y hours, Z minutes, A seconds", where `X`, `Y`, `Z`, and `A` are positive integers. The function should handle both singular and plural versio...
You can implement the `parse_timedelta` function to process the string input and extract the time components. It will use regular expressions to match the expected patterns and return the appropriate `datetime.timedelta` object. Below is the code that accomplishes this: ```python import re from datetime import timedel...
16,067
Here's the implementation of the function: ```python def check_starts_with_http(string: str) -> bool: return string.startswith("http://") or string.startswith("https://") ``` The `check_starts_with_http` function takes a string as input and returns a boolean value indicating whether the string starts with `http:/...
Write a Python function to check if a string starts with `http://` or `https://`. Your code should pass the following assertion: ```python assert check_starts_with_http("ftp://www.example.com") == False ```
You can create a function that checks if a given string starts with either "http://" or "https://". Here’s one way to implement this function: ```python def check_starts_with_http(url): return url.startswith("http://") or url.startswith("https://") # Example assertion to test the function assert check_starts_with...
16,068
Here is a possible implementation of the function: ```python def contains_pair(obj, key, value): if isinstance(obj, dict): if key in obj and obj[key] == value: return True return any(contains_pair(v, key, value) for v in obj.values()) if isinstance(obj, list): return any(con...
Write a Python function to check whether a given JSON object contains a specific key-value pair, recursively. The function should traverse all nested objects and arrays to find the matching pair. If the pair is found in any level, the function should return True. If the pair is not found, the function should return Fal...
To check whether a given JSON object contains a specific key-value pair recursively, we can write a Python function that traverses through the JSON structure, which can include dictionaries (objects) and lists (arrays). Below is a sample implementation for the function: ```python import json def contains_key_value_pa...
16,069
You can define a function `lookup_name` that uses the `.get()` method of a dictionary to retrieve the phone number associated with the name. If the name is not found in the dictionary, the `.get()` method will return `None`. You can raise an exception in this case. Here's an example of how you could implement this fun...
Write a Python function `lookup_name` that takes two arguments: `name`, a string representing a person's name, and `data`, a dictionary containing names and corresponding phone numbers. The function should return the phone number associated with the name, or raise an exception if the name is not found in the dictionary...
Here's a Python function called `lookup_name` that meets your requirements. This function checks if the provided `name` exists in the `data` dictionary and returns the associated phone number. If the name is not found, it raises a `KeyError` with an appropriate message. ```python def lookup_name(name, data): if na...
16,070
To count the instances of each number in the list, we can use a dictionary to store the number counts. We can iterate over the list and for each number, check if it is already present in the dictionary. If it is, we increment the count by one. If it is not, we add it to the dictionary with a count of one. This process ...
I have a list of lists of numbers. I want to count how many instances of each number are in the list. I want to store the output as a dictionary, where the keys represent the numbers and the values indicate the counts. I also want to include only the numbers that appear in the list more than once. Your code should pas...
You can achieve this by using Python's `collections.Counter` to count the occurrences of each number in your list. Then, you can create a dictionary that only includes those numbers that appear more than once. Here's how you can implement the `count_instances` function: ```python from collections import Counter def c...
16,071
Using list comprehension and the `str()` function, we can convert each integer in the list to a string and then use the `len()` function to get the length of each string. Here's a one-liner that uses list comprehension to achieve this: ```python def convert_int_to_length_str(nums): return [str(len(str(num))) for ...
Implement a Python function that takes a list or a tuple of integers and returns a new list containing the length of each integer as a string. The function should use list comprehension and be a one-liner. For example, `[123, 456, 789]` should be transformed into `['3', '3', '3']`.
You can implement the function using list comprehension as follows: ```python def lengths_of_integers(collection): return [str(len(str(num))) for num in collection] ``` This function works by iterating over each integer in the input `collection`, converting the integer to a string to determine its length, and the...
16,072
To convert a number into a hexadecimal string, you can use the built-in `hex()` function, but you need to account for the endianness of the output. To handle this, you can use the `struct` module to pack the number into a byte string with the desired endianness, and then convert each byte to a 2-digit hexadecimal value...
Create a Python function to convert a number into a hexadecimal string. The function should take a positive integer `n` and a boolean `is_little_endian` as inputs, where `n` is the number and `is_little_endian` indicates the endianness of the output. If `is_little_endian` is `True`, then the output should be in `little...
Certainly! Below is a Python function `number_to_hex` that converts a positive integer into a hexadecimal string based on the specified endianness. ```python def number_to_hex(n, is_little_endian): if n < 0: raise ValueError("Input must be a positive integer") # Convert the number to hexadecimal a...
16,073
To solve this problem, we need to iterate over the two-dimensional array `index_array`, and for each element `index_array[i, :]` in the array, we need to use it as indices for the corresponding element in the one-dimensional array `array`. Here is a simple solution to this problem: ```python import numpy as np def g...
Given a one-dimensional array `array` and a two-dimensional array `index_array`, write a function that takes `array` and `index_array` as input and returns a one-dimensional array `output` of shape `index_array.shape[0]` such that `output[i]` is equal to `array[index_array[i,0], index_array[i,1], index_array[i,2]]`.
You can achieve this by leveraging numpy's advanced indexing capabilities. Here's a function that takes a one-dimensional array `array` and a two-dimensional array `index_array`, and constructs the `output` array based on the specified indices. Here's how you could implement the function in Python: ```python import n...
16,074
Here's how we can implement this: ```python class FruitBasket: def __init__(self, fruits): self.basket = {} for fruit_name, quantity in fruits: self.basket[fruit_name] = quantity def get_total_quantity(self): total_quantity = 0 for quantity in self.basket.values(): ...
Implement a Python class named `FruitBasket` with a constructor that takes a list of `fruit_name` and `quantity` pairs. The class should include an attribute called `basket` that stores the list of fruits as a dictionary with `fruit_name` as the key and `quantity` as the value. Define a `get_total_quantity` method that...
Certainly! Below is the implementation of the `FruitBasket` class that meets the requirements specified: ```python class FruitBasket: def __init__(self, fruits): # Initialize the basket as a dictionary self.basket = {fruit_name: quantity for fruit_name, quantity in fruits} def get_tota...
16,075
You can solve this problem in linear time using the Python heapq module. First, you can use the `heapify` function to convert the array into a min-heap that orders the elements from smallest to largest. Then, you can extract the `k`th largest element by repeatedly calling the `heappop` function on the heap, which retur...
Design a Python function that takes an unsorted array and a non-negative integer `k` that is less than or equal to the length of the array, and returns the `k`th largest element in the array. You can assume that it is always possible to find a `k`th largest element. For example, given `array = [6, 2, 3, 1, 7, 5, 4]` a...
Certainly! You can use the `heapq` module from Python's standard library to efficiently find the `k`th largest element in an unsorted array. However, it's important to note that using a heap can make this task more efficient than sorting the entire list. Specifically, we can use a min-heap to maintain the `k` largest e...
16,076
Here's a Python implementation of the `create_json_output` function: ```python def create_json_output(exercises: list) -> list: output = [] for exercise in exercises: exercise_id = exercise["id"] description = exercise["description"] output.append({ exercise_id: descriptio...
Write a Python function named `create_json_output` that creates a list of dictionaries containing only the `description` field for each exercise in a given list of exercise objects. The function should take one argument: a list of exercise objects, where each exercise has a `description` field. The function should ret...
Certainly! Below is a Python function named `create_json_output` that fulfills the requirements you've specified. It takes a list of exercise objects and returns a list of dictionaries, each containing the exercise ID as the key and the description as the value. ```python def create_json_output(exercises): """ ...
16,077
To achieve the described functionality, the function must validate the type of the input parameters `x` and `y`. If they are both integers, it can proceed with the distance calculation. However, if they are both strings, then the function should return a string indicating that the input is invalid. If one parameter is ...
Given a 2-dimensional point (x,y) in a Cartesian plane, write a Python function named `get_euclidean_distance` that calculates the distance between the point and the origin. The function should accept two parameters, `x` and `y`, and use the `math` module to compute the distance. The function should return a float or ...
Here's the implementation of the `get_euclidean_distance` function in Python. This function adheres to the specifications you've provided for handling various input types. ```python import math def get_euclidean_distance(x, y): # Check if both inputs are integers or floats if isinstance(x, (int, float)) and i...
16,078
To get the object that is most likely to be the same as the reference object, you need to compare the values of specific attributes between the objects. You can write a function that takes two objects and an attribute name as arguments and returns the absolute difference between the attribute values of the objects. You...
Write a Python function named `get_most_likely_option` that takes a list of objects and a reference object as arguments. The function should return the object in the list that is most likely to be the same as the reference object, where likelihood is determined by comparing the values of specific attributes between the...
To implement the `get_most_likely_option` function with the specified functionality, we can define two helper functions as described: `compare_objects` which computes the absolute difference of specified attributes between two objects, and `most_likely_object` which finds the object in a list that is closest to a refer...
16,079
Here's how you can implement this: ```python import re def replace_program(text): return re.sub(r"program\s*er?", "programmer", text) ```
Write a Python function that takes a string as input and replaces all the occurrences of "program" with "programmer". The function should use regular expressions to perform the replacement operation. This will help you understand the concept of regular expressions in Python. Your code should pass the following asserti...
To create a Python function that replaces all occurrences of the word "program" with "programmer" using regular expressions, we can use the `re` module. Specifically, we can use the `re.sub()` function to perform the replacement. Here's how you can implement this: ```python import re def replace_program(text): # ...
16,080
Here's a possible implementation of the function in Python: ```python def custom_dict_to_list(dictionary): if not isinstance(dictionary, dict): raise TypeError('Argument must be a dictionary') if not all(isinstance(key, str) for key in dictionary): raise ValueError('Dictionary keys must be str...
Write a Python function named `custom_dict_to_list` that takes a dictionary argument and converts it to a list of key-value pairs, where each pair is a tuple `(key, value)`. The keys in the dictionary are expected to be strings. - The function should validate that the argument is a dictionary and raise a `TypeError` i...
Here's the implementation of the `custom_dict_to_list` function according to your specifications: ```python def custom_dict_to_list(input_dict): # Validate that the input is a dictionary if not isinstance(input_dict, dict): raise TypeError("Input must be a dictionary.") # Initialize an empty l...
16,081
To open a file and read its content, we can use the `open()` function and the `with` statement. The `with` statement automatically closes the file after the code block exits, which is important to avoid resource leaks. In case of an error, we can use a `for` loop to retry opening the file for a maximum of `max_attempts...
Write a function that takes a filename and an integer `max_attempts` as parameters. The function should open the file and read its content line by line, and return an array of the lines. If an error occurs during file opening, the function should retry opening the file up to `max_attempts` times. If the file can still ...
Here’s a Python function that implements the specified behavior. It takes a filename and an integer `max_attempts` as parameters, attempts to open and read the file line by line, and returns the lines as a list. If an error occurs while trying to open the file, it will retry up to `max_attempts` times. ```python def r...
16,082
To convert a time value, you can use the modulo operator to extract the number of days, hours, minutes, and seconds. Then, you can use integer division to get the number of days, hours, minutes, and seconds. Here's how you can implement the `convert_time_to_day_hour_minute_second` function: ```python def convert_time...
Create a Python function `convert_time_to_day_hour_minute_second` that converts a time value expressed in seconds to a dictionary containing the number of days, hours, minutes, and seconds, each in its own key. For example, 86400 seconds is converted to a dictionary such as `{"day": 1, "hour": 0, "minute": 0, "second":...
Certainly! Below is a Python function `convert_time_to_day_hour_minute_second` that converts a time value expressed in seconds into a dictionary containing the number of days, hours, minutes, and seconds. The function handles both positive and negative time values appropriately. ```python def convert_time_to_day_hour_...
16,083
Implementing the required Python function `convert_seconds_to_minutes(seconds)` involves several key steps: 1. The function takes a floating-point number `seconds` as input, and raises a `ValueError` if a negative number is provided. 2. The function performs the conversion from seconds to minutes by dividing the `seco...
Write a Python function `convert_seconds_to_minutes(seconds)` to convert seconds to minutes, rounding the final result down to the nearest whole number. The function should accept floating-point numbers, and raise a `ValueError` if a negative number is provided. The function should also have a function docstring explai...
Here's a Python function called `convert_seconds_to_minutes` that converts seconds to minutes while following the specified requirements. The function includes a docstring that describes the input and output types, and it raises a `ValueError` for negative input values. ```python def convert_seconds_to_minutes(seconds...
16,084
Here is a Python class that implements `A` with an optimized dictionary usage for fast lookup: ```python class A: def __init__(self): self._values = [('a', 1), ('b', 2), ('c', 3)] self._dict = {key: value for key, value in self._values} def get_value(self, key): if key not in self._dic...
I have a class `A` with a private dictionary attribute `_values`, which is initialized by a list of tuples `[('a', 1), ('b', 2), ('c', 3)]`. I will be using the dictionary repeatedly to access the values stored in `_values` by their keys. Can you implement the class `A` with an optimized dictionary usage for fast looku...
Certainly! Below is an implementation of class `A` which initializes a private dictionary `_values` from a list of tuples. The class provides a method `get_value` for fast lookup of values by their keys. Here is the implementation: ```python class A: def __init__(self): # Initialize the private dictionary...
16,085
To write a Python function for the prime number counting function, you can use the Sieve of Eratosthenes algorithm to generate all prime numbers up to `n`. The function would then count the number of prime numbers in the list and return the count. To display the result as a string with the provided format, you can use ...
The prime number counting function (also known as the prime-counting function) is the function that counts the number of prime numbers less than or equal to some positive integer `n`. Write a Python function `prime_counting(n)` to return the number of primes less than or equal to `n`. If `n` is a float, round it to the...
To implement the `prime_counting` function in Python, we will need to identify the prime numbers less than or equal to a given integer `n`. We will use a simple method to check for primality and count the number of primes. Here's how to accomplish this: 1. If `n` is a float, round it to the nearest integer. 2. Use a h...
16,086
Here's how you can implement this: ```python def filter_temperatures(climate_data, unit): if unit not in ("F", "C"): raise ValueError("Unit must be either 'F' or 'C'.") filtered_temperatures = {} for key, value in climate_data.items(): if "temperature" in value and value["temperature"].en...
Write a Python function that takes a dictionary of climate data and returns a new dictionary with only the entries that contain the key-value pair `temperature: 'temperature in (unit) F'` for a given unit. Use the provided unit conversion functions for converting between units.
To achieve the task of filtering a dictionary of climate data based on a specified temperature unit, you'll need to write a Python function that utilizes unit conversion functions. Below is an example implementation, assuming you have the required unit conversion functions available. Here's a structure for the functio...
16,087
For this instruction, we'll be creating a Python function that accepts a list of words as input and returns a new list of words containing only five random words selected from the input list. To ensure the function returns a list of five random words, we'll use the `random.sample` function from the `random` module. Th...
Create a Python function that accepts a list of words as input and returns a new list of words containing only five random words selected from the input list. For example, suppose the input list is `['apple', 'banana', 'cherry', 'durian', 'elderberry', 'fig', 'grape']`. The function should return a list of five random...
You can achieve this by using the `random.sample()` function from Python’s `random` module, which allows you to randomly select a specified number of unique elements from a list. Below is a Python function that implements your requirements: ```python import random def select_random_words(words): if len(words) < 5...
16,088
Here is an example implementation: ```python def convert_string_to_bytes(string: str) -> bytes: return bytes([ord(char) for char in string]) ``` This function takes a string and returns a byte string. The function uses a list comprehension to iterate over each character in the string and convert it to its ASCII c...
Write a Python function to convert a string into a byte string. The function should support optional type annotation and type casting. Your code should pass the following assertions: ```python assert convert_string_to_bytes("Hello") == b"Hello" assert convert_string_to_bytes("123") == b"123" ```
You can create a function to convert a string into a byte string in Python by using the `encode` method available for string objects. Below is a Python function that accomplishes this with optional type annotations: ```python def convert_string_to_bytes(input_string: str) -> bytes: """Convert a string to a byte st...
16,089
You can create a Python function that checks if a date string follows a given format (ISO 8601). Consider the following format: YYYY-MM-DD, where YYYY is the year (four digits), MM is the month (two digits), and DD is the day (two digits). The function should return True if the date string follows the given format, or ...
Write a Python function to check if a date string follows a given format (ISO 8601). Consider the following format: `YYYY-MM-DD`, where YYYY is the year (four digits), MM is the month (two digits), and DD is the day (two digits). The function should return `True` if the date string follows the given format, or `False` ...
You can make use of the `re` module in Python to check if a date string matches the desired ISO 8601 format `YYYY-MM-DD`. Here is a function that does this: ```python import re def validate_date_format(date_string): # Define the regular expression for the format YYYY-MM-DD pattern = r'^\d{4}-\d{2}-\d{2}$' ...
16,090
The sign function is a piecewise function that returns 1 for positive numbers, 0 for zero, and -1 for negative numbers. It is undefined at x=0 as it has a discontinuity there. We need to handle this special case correctly. Here is the implementation of the `sign_function` function: ```python def sign_function(x): ...
Write a Python function `sign_function(x)` that computes the sign of `x` and returns 1 for positive numbers, 0 for zero, and -1 for negative numbers. Take care to handle the special case for x = 0 correctly, as the sign function is undefined at x=0. Your code should pass the following assertions: ```python assert sign...
You can define the `sign_function` as follows: ```python def sign_function(x): if x > 0: return 1 elif x < 0: return -1 else: return 0 # Assertions to test the function assert sign_function(1) == 1 assert sign_function(0) == 0 assert sign_function(-1) == -1 ``` This function check...
16,091
The problem can be solved by splitting the input date into the year, month, and day components. Then, you can use the `calendar` module to generate the list of dates for each month in the given year. Here's the Python implementation of the `generate_a_one_year_calendar` function: ```python import calendar from dateti...
Write a Python function named `generate_a_one_year_calendar` that takes a date string in the format of "YYYY-MM-DD" as input and returns a list of strings representing a one-year calendar for the given date. Each string in the returned list represents one day of the year. Here are some examples of input and output: I...
To create a function that generates a one-year calendar based on a given date string in the "YYYY-MM-DD" format, we can follow these steps: 1. Validate the input date format. 2. Parse the input string into a date object. 3. Generate the list of dates starting from the given date for the next 365 days, taking into acco...
16,092
Here's how you can implement batch normalization in PyTorch: ```python import torch def batch_norm(x, mean, var): x = (x - mean) / torch.sqrt(var + 1e-5) return x ``` The function takes three arguments: `x`, a PyTorch tensor, `mean`, a tensor containing the mean values for each channel, and `var`, a tensor c...
Develop a Python function `batch_norm` that performs batch normalization on a tensor. The function should take three arguments: `x`, a PyTorch tensor, `mean`, a tensor containing the mean values for each channel, and `var`, a tensor containing the variance values for each channel. The function should return the normali...
Certainly! Batch normalization is a technique commonly used in deep learning to normalize the input of each layer. It helps to stabilize and speed up the training process. In PyTorch, we can implement batch normalization by following these steps: 1. Normalize the tensor using the provided mean and variance. 2. Scale a...
16,093
To rearrange a list of integers into two groups, we can iterate through the list and check if each integer is odd or even using the modulo operator (%). If the number is odd, we can append it to the odd group, and if it's even, we can append it to the even group. We can then concatenate the two groups to form the requi...
Write a Python function that takes in a list of integers and rearranges them to form two groups: one with only odd numbers and the other with only even numbers. The relative order of the numbers should be maintained within each group, and the groups should be concatenated in the same order as they appear in the input l...
Here's a Python function that performs the requested task of rearranging a list of integers into two groups: one for odd numbers and another for even numbers, while maintaining their relative order. The function also includes assertions to ensure that all elements in the input list are integers. ```python def rearrang...
16,094
To return `None` or the string `"None"`, we can check if `None` is passed in as an argument. If it is, we return `None`. Otherwise, we return the string `"None"`. Here is a Python function that implements this approach: ```python def return_none_or_string(arg): if arg is None: return None else: ...
Write a Python function to return `None` or the string `"None"`. Your code should pass the following test case: ```python # Test case with `None` as an argument assert return_none_or_string(None) is None # Test case with a non-`None` value as an argument assert return_none_or_string("example") == "None" ```
You can achieve the desired functionality with a simple function that checks the input argument. Here's how you can implement the `return_none_or_string` function: ```python def return_none_or_string(value): if value is None: return None else: return "None" # Test cases assert return_none_or_s...
16,095
To convert a decimal number between 0 and 1 to a percentage, you can multiply the input by 100 and round the result to the nearest integer. However, if the input is outside the range of 0 to 1, it's not clear how to handle it. One approach is to normalize the input to be within the range by mapping values outside the r...
Create a Python function that takes a decimal number between 0 and 1 as an input and converts it to a percentage (rounded to an integer). For example, if the input is 0.5, the output should be 50%. If the input is 0.857, the output should be 86%. The function should handle inputs outside the range of 0 to 1.
Certainly! Below is a Python function that takes a decimal number between 0 and 1, converts it to a percentage, and rounds it to the nearest integer. The function also handles inputs outside this range by returning an appropriate message. ```python def decimal_to_percentage(decimal_number): if 0 <= decimal_number ...
16,096
Here is how you could implement such a function: ```python def convert_bar_to_pa(bar: float) -> float: """Converts pressure in bars to Pascals. Args: bar (float): Pressure in bars. Returns: float: Pressure in Pascals. Example: >>> convert_bar_to_pa(1) 1000000.0 ""...
Write a Python function named `convert_bar_to_pa` that converts pressure in bars to Pascals. The function should be named `convert_bar_to_pa` and take one argument, `bar` (representing pressure in bars). The function should have a docstring that explains what the function does and how to use it. The function should ret...
Here's the Python function `convert_bar_to_pa` that converts pressure from bars to Pascals. The function includes a docstring to explain its purpose and usage. ```python def convert_bar_to_pa(bar): """ Convert pressure from bars to Pascals. Args: bar (float): Pressure value in bars. Returns: ...
16,097
Here's an example of how you could implement this function: ```python def replace_single_quotes(text): return text.replace("'", "''") ```
Design a Python function that takes a string and returns a new string with all single-quote characters ('') replaced by two single quote characters (''). Your code should pass the following assertion: ```python assert replace_single_quotes("I'm going home") == "I''m going home" ```
You can create a Python function called `replace_single_quotes` that takes a string as input and replaces all single quote (') characters with two single quotes (''). Here's the implementation of the function: ```python def replace_single_quotes(s): return s.replace("'", "''") # Test the function with the provide...
16,098
Here is how you could implement the function in Python: ```python def calculate_difficulty_rating(hashes_required: int, hashes_per_second: int) -> int: """Calculate the difficulty rating of a crypto puzzle. Args: hashes_required (int): The number of hashes required to solve the puzzle. hashes_...
Create a Python function to calculate the difficulty rating of a crypto puzzle, where the difficulty is determined by the product of the number of hashes required to solve the puzzle and the number of hashes per second. Round the difficulty to the nearest whole number. Document the function with the docstring.
Certainly! Below is a Python function that calculates the difficulty rating of a crypto puzzle based on the product of the number of hashes required to solve the puzzle and the number of hashes processed per second. The result is rounded to the nearest whole number. The function is documented with a docstring. ```pyth...
16,099