response_seed stringlengths 53 5.17k | instruction_seed stringlengths 29 4.02k | response stringlengths 16 8.81k | __original_row_idx int64 0 50k |
|---|---|---|---|
Here's how you can do it:
```python
def first_string_property(obj):
if obj is None:
return None
for property_name in obj.__dict__.keys():
property_value = getattr(obj, property_name)
if isinstance(property_value, str):
return property_name
return None
``` | Write a Python function that takes in any custom object, and returns the name of the first property that's a string. If none of the properties are strings, the function should return `None`.
For example, given the object:
```
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
s... | You can achieve this by using the `vars()` built-in function, which returns the `__dict__` attribute of an object as a dictionary. Then you can iterate over the items in the dictionary and check the types of the properties. Here’s how you can implement the function:
```python
def first_string_property(obj):
# Hand... | 34,700 |
Here is a Python function that implements this approach:
```python
from typing import Dict
def traverse_mapping(mapping: Dict[str, str], word: str) -> Dict[str, str]:
"""
Traverses the keys of `mapping` in the order they are given, and returns a
dictionary representing the mapping of the first key that ma... | Design a Python function that takes a dictionary `mapping` and a string `word`. The function should traverse the keys of the mapping in the order they are given, and compare each key to the given `word`. If the key is exactly the same as the word, the function should return a dictionary representing the mapping of the ... | Here is a Python function that meets your specified requirements:
```python
def map_word(mapping, word):
"""
This function takes a dictionary `mapping` and a string `word`.
It traverses the keys of the mapping in the order they are given,
and checks for an exact match with the word.
If a match... | 34,701 |
Here's how you can implement this function:
```python
import json
class CustomError(Exception):
def __init__(self, status, msg):
self.status = status
self.msg = msg
def __str__(self):
return f"Status: {self.status}, Message: {self.msg}"
def process_json_file(filename):
with open(... | Write a Python function to process a JSON file in the following format: `{"status": <int>, "message": <string>}`. If the status code is 200, return the message, otherwise raise an error with the status code and message. The custom error message should include the original message along with the status code. | You can create a Python function that processes a JSON file with the specified format. Below is an example of such a function. It reads the JSON data from a file, checks the status code, and either returns the message or raises a custom error based on the status code.
```python
import json
class CustomError(Exception... | 34,702 |
Here is the implementation:
```python
def to_hex_string(byte_array):
if len(byte_array) % 2 != 0:
raise Exception("Input byte array must be of even length")
return " ".join(f"{byte:02x}" for byte in byte_array)
``` | Write a Python function to convert a byte array to a string of hexadecimal bytes separated by spaces. The generated string should be suitable for inclusion in shell commands via string interpolation. The function should throw an exception if the input byte array is of odd length. | Here's a Python function that fulfills your requirements. It takes a byte array (bytes or bytearray type) as input and converts it into a string of hexadecimal bytes, separated by spaces. The function raises a `ValueError` if the input byte array has an odd length.
```python
def byte_array_to_hex_string(byte_array):
... | 34,703 |
To count the number of 1 bits in a 32-bit unsigned integer, we can use bitwise operations and recursion to compare the least significant bit (LSB) of the number with 1, and recursively check the remaining bits. If the LSB is 1, we increment the count by 1 and recursively call the function on the remaining bits, otherwi... | Write a function `count_nonzero_bits` that takes a 32-bit unsigned integer and returns the number of 1 bits (i.e., the number of bits set to 1 in the binary representation of the number). Your solution should use bitwise operations and recursion to achieve the desired effect. | Sure! To count the number of 1 bits (or set bits) in a 32-bit unsigned integer using bitwise operations and recursion, we can use the fact that the operation `n & (n - 1)` turns off the rightmost `1` bit of `n`. We can recursively call the function while applying this operation to count the number of bits.
Here's a Py... | 34,704 |
To load a model checkpoint in PyTorch, you can use the `torch.load` function to load the entire checkpoint object, which includes the model's state dict and the optimizer's state dict. To extract the model's state dict and the optimizer's state dict, you can use the `model.state_dict()` and `optimizer.state_dict()` met... | Write a Python function `load_model_checkpoint` that takes a single argument: `checkpoint_path`, a string representing the path to a valid PyTorch checkpoint file. The function should load the checkpoint and extract the model's state dict and the optimizer's state dict. The function should also handle potential errors ... | To create a function `load_model_checkpoint` that loads a PyTorch model checkpoint while handling errors gracefully, we can use the `torch` library. The function will try to load the checkpoint from the specified path and will return the model's state dictionary and the optimizer's state dictionary if successful. If an... | 34,705 |
Here is the implementation of the `linear_distance` function:
```python
def linear_distance(point1, point2):
if len(point1) != 3 or len(point2) != 3:
raise Exception("Invalid input: point1 and point2 must be tuples of three numbers")
x1, y1, z1 = point1
x2, y2, z2 = point2
return abs(x1 - x2)... | Write a Python function `linear_distance` that takes two arguments `point1` and `point2`, representing two points in 3D space, each represented as a tuple of three numbers. The function should calculate the distance between the two points using the linear distance formula, which is the sum of the absolute differences b... | Here's a Python function named `linear_distance` that calculates the linear distance between two points in 3D space, represented as tuples. The function also checks for the validity of the input and raises exceptions if the input is not valid:
```python
def linear_distance(point1, point2):
# Check if both points a... | 34,706 |
Here's how we can implement this:
```python
def to_dictionary(input_string):
pairs = input_string.split(';')
dictionary = {}
for pair in pairs:
key, values = pair.split('=')
key = key.strip().lower()
values = [value.strip() for value in values.split(',')]
dictionary[key] = v... | I want to convert a string containing key-value pairs delimited by `;` into a dictionary, where the keys are all lowercase. The values should be list of strings, which are delimited by `,`. The keys and values should be trimmed (whitespace removed) before being added to the dictionary.
For example, given the string `'... | You can achieve this by splitting the string based on the `;` delimiter for the key-value pairs, then further splitting each key-value pair based on the `=` separator. Finally, for the values, you'll split them by `,` and apply trimming. Here's a Python function to implement this logic:
```python
def convert_string_to... | 34,707 |
To parse a string containing a list or tuple of values, we can use the `ast` module in Python, which provides a safe way to parse Python expressions. We can parse the string as a Python expression using the `ast.literal_eval` function, and then check if the resulting object is a list or tuple, and if so, convert it to ... | Write a Python function that takes a string containing a list or tuple of values and returns a tuple containing the parsed values. The function should support all types that can be represented in JSON, including integers, floats, booleans, strings, lists, and tuples.
The function should perform type conversion, valida... | To create a Python function that parses a string representation of a list or tuple of values and returns a tuple with the parsed values while supporting all JSON-compatible types, we can use the `json` module for parsing. Additionally, we'll incorporate type validation to ensure that each parsed value is of the expecte... | 34,708 |
```python
def file_extension(filename):
parts = filename.split('.')
if len(parts) < 2:
return ""
return parts[-1]
``` | Write a Python function that takes a string representing a filename and returns the file extension (the part following the last dot) as a string. If the filename does not have an extension, the function should return an empty string. | You can achieve this by using the `rsplit` method to split the filename from the right side, based on the dot ('.') character. Here's a simple function to do that:
```python
def get_file_extension(filename: str) -> str:
# Split the filename from the right, max 1 split
parts = filename.rsplit('.', 1)
#... | 34,709 |
Here is a Python function that implements this approach:
```python
def count_lines_without_loading(filename: str) -> int:
"""
Counts the number of lines in a text file without loading the entire file into memory.
"""
num_lines = 0
with open(filename, 'r') as file:
while True:
li... | Write a Python function to count the number of lines in a text file (i.e., count the number of newlines in the file) without loading the entire file into memory.
Your code should pass the following assertion:
```python
assert count_lines_without_loading('example.txt') == 3
``` | You can count the number of lines in a text file without loading the entire file into memory by reading the file line by line and counting the newlines. Here’s a Python function that accomplishes this:
```python
def count_lines_without_loading(filename):
with open(filename, 'r') as file:
line_count = sum(1... | 34,710 |
To calculate the pixel size, we can use the following formula:
pixel_size = focal_length * (distance / sensor_size)
where sensor_size is the size of the camera sensor (for the 1920x1080 resolution, it should be 3.2mm x 1.6mm). This formula is based on the thin lens equation and the assumption that the object is at in... | Given a physical distance in millimeters and the focal length of a camera, calculate the pixel size in millimeters. The resolution of the camera is 1920x1080. If the distance is less than 100mm, raise an exception. | To calculate the pixel size in millimeters for a camera with a given resolution and focal length, we can use the following relationship:
- **Pixel Size (mm)** = **Sensor Width (mm)** / **Number of Pixels Horizontally**
However, we need to determine the sensor width first from the focal length and distance. Given that... | 34,711 |
Here's how you can implement this:
```python
def int_from_bytes(bytes, byteorder='big'):
return int.from_bytes(bytes, byteorder)
def int_of_byte(byte):
return int.from_bytes(byte, byteorder='big')
```
The `int_from_bytes()` function takes a byte array and converts it to an integer using `int.from_bytes()`. I... | Write a Python function `int_from_bytes(bytes, byteorder='big')` that takes a byte array and converts it to an integer, using the optional `byteorder` argument to specify the byte order. The function should use a helper function `int_of_byte(byte)` to convert a single byte to an integer. The `byteorder` argument should... | To implement the `int_from_bytes` function, we'll first create a helper function called `int_of_byte` that converts a single byte (in the form of a bytes object) to an integer. Then, we'll implement the main function to iterate through the byte array, convert each byte to an integer using the helper function, and const... | 34,712 |
To flatten nested iterables using iterators and generator functions, we can employ the following steps:
1. Check if the iterable object is an iterable: Use `isinstance(iterable, collections.abc.Iterable)` to check if the given object is a container type that can contain nested iterables.
2. Use a generator function: D... | Write a Python function `flatten_with_iterators(iterable)` that takes an iterable object containing nested iterables and returns a new iterable that flattens the inner iterables into a single iterable. Use iterators and generator functions to implement the solution. | To create a function `flatten_with_iterators` that flattens nested iterables into a single iterable, we can use generator functions in Python. This function will recursively iterate over the input iterable and yield each element, handling both regular elements and nested iterables.
Here is a possible implementation:
... | 34,713 |
Here's how you can implement this:
```python
def save_df_to_csv(df, path):
if df is None:
print("Input DataFrame is None. Exiting.")
return
dir_path = os.path.dirname(path)
if not os.path.exists(dir_path):
os.makedirs(dir_path)
df = df.toDF(*[c.replace(" ", "_").replace("/", "-"... | Design a Python function `save_df_to_csv(df, path)` that saves a Spark DataFrame to a CSV file at the provided path. The function should ensure that the input DataFrame `df` is valid and not `None`. Additionally, the function should create a directory for the provided path if it does not exist. The resulting CSV file s... | Here's a Python function `save_df_to_csv(df, path)` that meets your requirements for saving a Spark DataFrame to a CSV file. This function checks if the DataFrame is valid, creates the necessary directories for the output path, sanitizes the column names, and handles exceptions gracefully.
```python
import os
import r... | 34,714 |
To implement a Python decorator that memoizes the results of a function and provides a configurable retry mechanism for failed calls, the following steps are required:
1. Create the decorator function that takes the target function and the optional retry_count argument as inputs.
2. Validate the retry_count argument t... | Implement a Python decorator that memoizes the results of a function and provides a configurable retry mechanism for failed calls. The decorator should take an optional argument `retry_count` that defines the number of retries in case of a failure. If the function call fails, the decorator should retry the call up to t... | Sure! Below is a Python implementation of a decorator that combines memoization with a configurable retry mechanism. This decorator, `memoize_with_retry`, will cache the results of the function calls and handle retries if any exceptions occur during the function execution.
Here's how the decorator works:
1. It caches... | 34,715 |
```python
def is_related(objects, target):
if target in objects:
return True
for obj in objects:
if is_related(obj.relatives, target):
return True
return False
```
The `is_related` function takes a list of objects and a target object as input. It checks whether the target object... | Write a Python function that takes a list of objects and a target object as input, and returns a boolean value indicating whether the target object is directly or indirectly related to any of the input objects. Each object in the list has a `.relatives` attribute that is a list of objects. A direct relationship means t... | To determine if a target object is directly or indirectly related to any of the objects in the input list, we can implement a breadth-first search (BFS) or depth-first search (DFS) algorithm. Here's a function that performs this task using a BFS approach to explore the relationships:
```python
class ObjectWithRelative... | 34,716 |
The problem statement provides a Python function that receives a list of integers and returns the total number of bytes needed to store this list as a byte array.
The function needs to consider the following factors:
- The size of the list itself (in bytes)
- The size of each integer in the list (in bytes)
- The total... | Write a Python function that receives a list of integers (of arbitrary size) and returns the total number of bytes needed to store this list as a byte array.
Your code should pass the following test case:
```python
int_list = [1, 2, 3, 4, 5]
expected_result = sys.getsizeof(int_list) + len(int_list) * sys.getsizeof(int... | To calculate the total number of bytes needed to store a list of integers as a byte array in Python, we need to consider a couple of components:
1. The overhead of the list itself (which can be obtained using `sys.getsizeof`).
2. The size of each individual integer in the list.
Here is a function that accomplishes th... | 34,717 |
Here is an example implementation for handling this scenario:
```python
def validate_and_process_json(json_object):
if 'foo' not in json_object or 'bar' not in json_object:
raise ValueError(f"JSON object missing attributes 'foo' and/or 'bar'")
if not isinstance(json_object['foo'], list) or not isinstan... | Your code receives a JSON object from somewhere and needs to check some attributes exist. If they do not, you should raise an exception and handle it gracefully. The object has two attributes: `foo` and `bar`, which are both lists. You should check that both exist and are lists, raising an exception with a helpful erro... | You can create a function that checks for the presence of the `foo` and `bar` attributes in the JSON object and ensures that they are lists. If any of those checks fail, you can raise a custom exception and handle it gracefully. Here's how you can do that in Python:
```python
import json
class ValidationError(Excepti... | 34,718 |
Here is an example implementation of the `get_data_from_pickle` function:
```python
import pickle
def get_data_from_pickle(file_path):
try:
with open(file_path, 'rb') as f:
data = pickle.load(f)
return data
except Exception as e:
print(f'Error loading pickle data: {e}')... | Design a function named `get_data_from_pickle` that reads data from a pickle file and returns it as a Python object. The function should accept a single argument, `file_path`, which is the path to the pickle file.
The function should handle any exceptions that may occur during the reading process, including file not f... | Certainly! Below is a Python function named `get_data_from_pickle` that reads data from a specified pickle file and returns it as a Python object. I've also included a test function to check its behavior using example pickle files.
### Function Implementation
```python
import pickle
import os
def get_data_from_pickl... | 34,719 |
To perform element-wise arithmetic operations on two tensors, we can use the numpy library. We can use numpy's broadcasting features to perform addition and multiplication between the two tensors.
Here is the implementation of the function in Python:
```python
import numpy as np
def elementwise_arithmetic(x, y, z):
... | Write a Python function that performs the following element-wise arithmetic operations on two tensors and returns the result tensor as a new tensor. The function should handle tensors of any shape and data type.
$$
z = (x + y) \cdot z - (x + y)
$$ | To perform the specified arithmetic operations on two tensors in Python, you can use the `numpy` library, which provides support for multi-dimensional arrays (tensors) and element-wise operations. Below is a Python function that performs the required operations based on your formula:
```python
import numpy as np
def ... | 34,720 |
Here's how you can do it:
```python
import inspect
import urllib.parse
def generate_url_query_string(url, **kwargs):
"""Generate a URL query string from given keyword arguments.
Args:
url (str): The URL to prepend to the query string.
**kwargs: Keyword arguments to serve as key-value pairs in... | Write a Python function to compose a URL query string from given keyword arguments. The function should accept the URL to prepend to the query string as a positional argument, and each keyword argument should serve as a key-value pair in the query string. The function should also generate documentation for the function... | Certainly! Below is a Python function that composes a URL query string from given keyword arguments. It accepts a URL as a positional argument and constructs the query string based on the keyword arguments provided. Additionally, I've included docstring documentation for the function.
```python
import urllib.parse
de... | 34,721 |
Here's a Python function `convert_32_byte_integers_to_strings` that takes a list of hex strings and returns a list of strings:
```python
def convert_32_byte_integers_to_strings(hex_strings):
strings = []
for hex_string in hex_strings:
string = hex(int(hex_string, 16))
strings.append(string)
... | Write a Python function to convert 32-byte integers (represented as hex strings) to strings. Given a list of 32-byte integers in hex strings, return a list of strings that are the corresponding hex strings converted to strings. | You can convert a 32-byte integer represented as a hex string into a string by first converting the hex string into an integer and then into the corresponding ASCII string. Depending on the values of the hex string, you might get non-printable characters, so special handling may be required to ensure that only printabl... | 34,722 |
To write a Python function that takes a dictionary of objects and their properties and returns a string containing a table of values, where each row corresponds to an object and each column corresponds to a property, you can follow these steps:
1. Extract the keys of the dictionary as a list of objects.
2. Extract the... | Write a Python function that takes a dictionary of objects and their properties, and returns a string containing a table of values, where each row corresponds to an object and each column corresponds to a property. The function should support type hints for objects and properties, and allow overriding the default separ... | Certainly! Below is a Python function that takes a dictionary where each key is an object name (or identifier), and each value is another dictionary representing the properties of that object. The function will then format this into a table-like string, where each property corresponds to a column.
Additionally, the fu... | 34,723 |
To calculate the smallest angle between `a` and `b`, you can use the following formula: `(b - a) % 360`. However, if the result is negative, you need to add 360 degrees to make it positive. You can achieve this by using the `abs` function.
Here's the Python code for the `modular_angle` function:
```python
def modular... | Write a Python function `modular_angle(a, b)` that calculates the smallest angle between two angles `a` and `b` (both between 0 degrees and 360 degrees), taking into account the modulo operation. The return value should also be between 0 degrees and 360 degrees.
Your code should pass the following assertions:
```pytho... | To calculate the smallest angle between two angles `a` and `b` in degrees, we can use the modulo operation. The key idea is to compute the absolute difference between the two angles and then adjust for angles that wrap around the 360-degree mark.
Here’s how we can implement the `modular_angle` function:
1. Calculate ... | 34,724 |
In this problem, we need to implement a function that matches a given string with a predefined pattern, where the pattern consists of a sequence of characters including the following symbols:
1. `.`: matches any single character
2. `*`: matches zero or more occurrences of the preceding character
The function should r... | Write a Python function to match a given string with a predefined pattern, where the pattern consists of a sequence of characters including the following symbols:
1. `.`: matches any single character
2. `*`: matches zero or more occurrences of the preceding character
The function should return `True` if the string mat... | To match a string against a predefined pattern that includes `.` and `*`, we can use a recursive approach or employ dynamic programming to efficiently handle the matching process. Here, I'll provide a solution using dynamic programming.
The key idea is to maintain a 2D table where `dp[i][j]` is `True` if the first `i`... | 34,725 |
To group the keys based on unique values and sort them from smaller to larger, we can use the `defaultdict` module from the Python standard library. We can initialize a `defaultdict` with a list as the default value. Then, for each key-value pair in the `data` dictionary, we can append the key to the list associated wi... | Given a dictionary `data` with arbitrary number of keys, return a new dictionary `result` that groups the keys into a list for each unique value (sorted from smaller to larger). For instance, given `data = {1: 1, 2: 1, 3: 2, 4: 3}`, the function should return `result = {1: [1, 2], 2: [3], 3: [4]}`. | You can achieve this by iterating through the dictionary and populating a new dictionary where the keys are the unique values from the original dictionary and the values are lists containing the corresponding keys. Here is a Python function that implements this:
```python
def group_by_values(data):
result = {}
... | 34,726 |
To sample regularly spaced points from a log-transformed data range, we'll need to first transform the `data` according to the given `base`. Then, we'll calculate the spacing between adjacent samples based on the `step` and the transformed data range. Finally, we can sample the points by iterating over the transformed ... | Write a Python function to sample regularly spaced points from a log-transformed data range. The function takes three parameters: `data` is a list of numbers, `step` is the desired spacing between samples, and `base` is the log base to use for the transformation. The function should return a list of sampled points from... | Certainly! Below is a Python function named `sample_log_transformed_points` that accomplishes what you've requested. It takes a list of numbers, a desired step size for sampling, and a base for the logarithm. The function first transforms the data using the logarithm, then samples points based on the given step size. A... | 34,727 |
To validate an input value and coerce it if it is not of the specified type, we can define a function that takes two parameters: a value and a type. We can use the `isinstance` function to check if the value is of the specified type, and if it is not, we can try to coerce it using the `getattr` function to access the t... | Write a Python function `validate_and_coerce_value` that receives a value and a type, and validates that the value is of the specified type before returning it. If the value is not of the specified type, it should try to coerce the value to the specified type and then return it. If the coercion fails, return None. | Here's a Python function `validate_and_coerce_value` that performs the specified operations of validating a value and coercing it to the requested type:
```python
def validate_and_coerce_value(value, target_type):
"""
Validates the type of the given value against the target type.
If the value is not of th... | 34,728 |
Here is how you could implement such a lambda handler:
```python
import json
def json_logger(input_json: dict) -> str:
serialized_json = json.dumps(input_json)
with open("log_file.txt", "w") as log_file:
log_file.write(serialized_json)
return serialized_json
``` | Design a lambda handler that takes a JSON object as input, serializes it as JSON, and logs the output to a file. | To create a Lambda handler in Python that takes a JSON object as input, serializes it as JSON, and logs the output to a file, you can follow the steps below. Note that AWS Lambda has limited access to the file system, so logging to a file will be limited to the `/tmp` directory where you can write files during the exec... | 34,729 |
Here's how you can implement this:
```python
def move_snake(snake_body, direction, size):
head_x, head_y = snake_body[0]
new_head_x, new_head_y = head_x, head_y
if direction == 'up':
new_head_y -= 1
elif direction == 'down':
new_head_y += 1
elif direction == 'left':
new_hea... | Write a Python function that represents the body of a snake as a list of tuples where each tuple represents the coordinates of a snake segment. The first tuple in the list should be the head of the snake, and the remaining tuples (if any) represent the rest of the snake. Implement the `move_snake` function that takes t... | Sure! Below is an implementation of the `move_snake` function that allows a snake to move in a specified direction on a grid, while ensuring it wraps around the grid boundaries if needed. Additionally, I will implement the `remove_tail` function to remove the tail of the snake from the list by value.
```python
def mov... | 34,730 |
```python
def add_new_fingerprints(existing_fingerprints, **new_fingerprints):
for new_fingerprint in new_fingerprints.values():
fingerprint_exists = any(
existing_fingerprint.pos_id == new_fingerprint.pos_id and
existing_fingerprint.fingerprint_id == new_fingerprint.fingerprint_id
... | Write a Python function named `add_new_fingerprints` that adds new WiFi fingerprint objects to a list of existing fingerprints. The function must take a list of fingerprints and a variable number of new fingerprint objects as keyword arguments.
Your function should add the new fingerprints to the existing list if they... | Certainly! Here's a Python function named `add_new_fingerprints` that meets your requirements. This function takes a list of existing WiFi fingerprint objects and a variable number of new fingerprint objects as keyword arguments. It checks for duplicates based on `pos_id` and `fingerprint_id` before adding the new fing... | 34,731 |
To write a Python function that calculates the region of interest in a given image (2D or 3D), you need to understand the characteristics of the images and the region of interest.
A region of interest in an image is a rectangular portion of the image that we are interested in for some purpose. It could be a specific p... | Write a Python function `calc_roi(img)` that calculates the region of interest in a given image and returns a tuple of four values corresponding to the region of interest's top-left x-coordinate, top-left y-coordinate, width, and height. The function should handle a variety of input types for the `img` parameter, inclu... | To create the `calc_roi(img)` function that fulfills your requirements, we need to determine whether the input image is 2D or 3D based on the shape of the input array. In this context, a 2D image will be a matrix with two dimensions (height, width), while a 3D image will have three dimensions (height, width, channels).... | 34,732 |
To solve this problem, you can use Python's built-in `filter` function to filter out the elements of `built_ins` that match the given `func`. If the filtered list is non-empty, then `func` is in `built_ins`.
You can use the `len` function to validate the length of the list. If it is less than 1, you can raise a `Value... | Write a Python function named `is_built_in` that checks if a list of Python built-in functions contains a given function name. It should return a boolean value. For example, given `['abs', 'all', 'any', 'filter', 'map']` and `'abs'`, the function should return `True`.
The function takes two arguments: `built_ins`, a l... | Certainly! Below is a Python function named `is_built_in` that checks if a given function name exists in a list of Python built-in function names. It also validates that the input list has at least one element.
```python
def is_built_in(built_ins, func):
# Validate that built_ins is a list with at least one elemen... | 34,733 |
To convert a PyTorch tensor to an NDArray, you can use the following approach:
1. Determine the input tensor's shape and dtype.
2. Create an NDArray with the required shape and dtype based on the input tensor's shape.
3. Copy the input tensor's values to the NDArray.
To convert the NDArray back to a PyTorch tensor, y... | Write a Python function to convert a PyTorch tensor to an NDArray and back. The function should handle the following cases:
- Convert a PyTorch tensor of shape (1, 3, 256, 256) to an NDArray of shape (256, 256, 3) with values ranging from 0 to 255 and dtype uint8.
- Convert a PyTorch tensor of shape (1, 1, 256, 256) t... | To convert a PyTorch tensor to an NDArray and back, we can use the `numpy` and `torch` libraries. Below is a Python function that handles the specified cases for conversion:
1. Converts a (1, 3, 256, 256) tensor to an NDArray of shape (256, 256, 3).
2. Converts a (1, 1, 256, 256) tensor to an NDArray of shape (256, 25... | 34,734 |
Here's how we can implement this:
```python
def mean_non_null(numbers):
non_null_numbers = [num for num in numbers if num is not None]
if len(non_null_numbers) == 0:
raise Exception("All values in the list are null.")
return sum(non_null_numbers) / len(non_null_numbers)
```
In this implementation,... | Write a Python function `mean_non_null` that calculates the mean of a list of numbers, ignoring any null values. If all values in the list are null, the function should throw an exception with an appropriate message to alert the user. | Certainly! Below is the Python function `mean_non_null` that computes the mean of a list of numbers while ignoring any null (or None) values. If all values are null, the function raises a `ValueError` with a descriptive message.
```python
def mean_non_null(numbers):
# Filter out the None values from the list
n... | 34,735 |
To write a Python function that takes a list of dictionaries as input and returns a new dictionary with the desired format, you can follow these steps:
1. Initialize an empty dictionary to store the final output.
2. Iterate over each dictionary in the input list. For each dictionary:
- Construct a new key by concat... | I have data stored as a list of dictionaries. Each dictionary has values for "name", "value" and "type". I want to create a new dictionary with a key for each name and a value for each value. But I want to change the name of each key to be "name_type" instead of just "name". For example, the input might be:
```python
... | You can achieve this by defining a function that iterates through the list of dictionaries, constructs the new keys based on the "name" and "type" fields, and maps these keys to their corresponding "value". Here's a Python function that performs this task:
```python
def transform_data(data):
result = {}
for it... | 34,736 |
To write such a function, we can use regular expressions to extract the type annotation. The type annotation is typically denoted by a colon followed by a type name. We can use the following regular expression pattern: `r":\s*(\w+)"` to capture the type name after the colon.
If the string does not contain a type annot... | I want to write a function that takes a string and returns its type annotation string. If a type annotation is missing, then return None. Make sure your function handles cases when the string does not contain a type annotation, or if the type annotation is not well-formed. | To accomplish your goal, we can write a function in Python that checks if a given string has a type annotation. A type annotation in Python is typically represented using a colon (`:`) followed by the type (e.g., `x: int` or `y: str`). Our function will inspect the input string and return the corresponding type annotat... | 34,737 |
Here's how we can implement this:
```python
def multiples(number, limit):
multiples_list = []
for i in range(1, limit):
if number * i < limit:
multiples_list.append(number * i)
return multiples_list
``` | Write a function to generate a list of all the multiples of a number that are less than a given limit. For example, for a limit of 30 and a number of 3, the function should return a list containing 3, 6, 9, 12, 15, 18, 21, 24, and 27. | Here's a Python function that generates a list of all the multiples of a given number that are less than a specified limit:
```python
def find_multiples(number, limit):
multiples = []
for i in range(1, limit):
if i % number == 0:
multiples.append(i)
return multiples
# Example usage
lim... | 34,738 |
```python
import re
import os
import tempfile
def parse_and_format_html_template(template: str, data: dict) -> str:
for key, value in data.items():
template = re.sub(rf'\{{{key}\}}', str(value), template)
temp_dir = tempfile.mkdtemp()
file_path = os.path.join(temp_dir, 'template.html')
with ope... | Write a Python function to parse and format a given string into an HTML template. The function should accept a `template` string and a `dictionary` of key-value pairs. The function should iterate through the dictionary and replace any instances of `{key}` in the template with the corresponding value from the dictionary... | To accomplish the task of parsing and formatting a string into an HTML template using key-value pairs from a dictionary, we can use Python's `re` module for regular expression replacement. We'll also use the `tempfile` module to create a temporary directory for storing the rendered template file.
Here's a complete fun... | 34,739 |
The function `apply_neighbour_filter` takes in three parameters: `data`, `target`, and `neighbour_filter`. The `data` and `target` parameters are NumPy arrays of shape (N, 3) and (N,), respectively, where N is the number of particles. The `neighbour_filter` parameter is a function that takes two slices as input and ret... | Develop a Python function `apply_neighbour_filter(data, target, neighbour_filter)` that takes in three parameters: a 2D NumPy array `data`, a 1D NumPy array `target`, and a filter function `neighbour_filter`. The function should apply the given filter to all particles in `data` and return the filtered particles in a ne... | You can implement the `apply_neighbour_filter` function as described. This function will iterate through the 2D `data` array and apply the `neighbour_filter` function to pairs of particles specified by the `target` array. Here's how you can accomplish that:
```python
import numpy as np
def apply_neighbour_filter(data... | 34,740 |
Here's how you could do it:
```python
def concatenate_unique(list1, list2):
unique_set = set(list1)
for item in list2:
unique_set.add(item)
return list(unique_set)
```
This function uses a `set` to ensure unique values in the resulting list, and then converts it back to a list. The `extend` method... | Write a Python function to concatenate two lists while ensuring no duplicates occur in the resulting list. Duplicates in the second list should be ignored, and the function should return the merged list without creating any intermediate data structures. Your function should handle the case where either list may be empt... | Certainly! Below is a Python function that concatenates two lists, ensuring that no duplicates appear in the resulting list. Duplicates in the second list are ignored. The function does not create any intermediate data structures and directly constructs the merged list.
```python
def concatenate_unique_lists(list1, li... | 34,741 |
Here is the implementation of the `extract_groups` function:
```python
import re
def extract_groups(regex_pattern, text):
match = re.search(regex_pattern, text)
if match:
return match.groups()
else:
return None
```
In the `extract_groups` function:
- The `re.search(regex_pattern, text)` c... | Create a Python function `extract_groups(regex_pattern, text)` that takes a regular expression pattern and a string as input. The function should parse the string using the given pattern and return a tuple of groups extracted from the first match. If no match is found, return None. For example:
```python
pattern = r"(... | You can implement the `extract_groups` function using the `re` module in Python, which provides support for regular expressions. Below is the code for the function as per your requirements:
```python
import re
def extract_groups(regex_pattern, text):
# Use re.search to find the first match
match = re.search(r... | 34,742 |
To solve the shortest path problem, we can use dynamic programming to cache and reuse sub-solutions for sub-problems, thereby avoiding recomputing them again. Here's how we can apply dynamic programming to find the shortest path in an undirected weighted graph using Python:
1. We will use a function `find_shortest_pat... | Write a Python function `find_shortest_path(g, u, v)` to find the shortest path from u to v in an undirected weighted graph g using dynamic programming. The function should return a list of nodes on the shortest path, including both u and v. You can assume the graph is connected and the weights are positive integers. | To find the shortest path in an undirected weighted graph using dynamic programming (DP), a common approach is to use Dijkstra's algorithm. Although Dijkstra's algorithm is typically implemented using a priority queue, I will provide a straightforward implementation of the algorithm that still adheres to the concept of... | 34,743 |
Here is the corrected code:
```python
def convert(digits):
if not isinstance(digits, str):
raise TypeError(error(digits))
return int(digits)
def error(digits):
if not isinstance(digits, str):
return "Not a string"
return "Not a digit"
```
The first bug was fixed by checking the type o... | In the following program, the identification of the error is required. The code is supposed to take a string of digits and convert it into an equivalent integer value. For example, the string "123" should be converted to the integer 123. The program has two bugs: one in the `error()` function that returns a different e... | To address the problem, I will provide a sample implementation of the program along with identifying and fixing the bugs in the `error()` and `convert()` functions.
Let's assume the original code structure looks something like this:
```python
def error():
return "Invalid input: only strings of digits are allowed... | 34,744 |
Here's how you could do it:
```python
import numpy as np
def check_matrices_after_transposition(A, B):
A_transposed = A.transpose()
B_transposed = B.transpose()
return np.array_equal(A_transposed, B_transposed)
```
This function transposes both numpy matrices, `A` and `B`, and then compares them using th... | Write a Python function that accepts two numpy matrices, `A` and `B`, and returns True if they are equal after transposition, otherwise False. | You can create a Python function that utilizes the NumPy library to check if two matrices, `A` and `B`, are equal after transposition. Here's how you can implement that:
```python
import numpy as np
def are_transposes_equal(A, B):
"""
Check if two matrices A and B are equal after transposition.
Parameter... | 34,745 |
1. The function should take a post object as an argument, which should have a `.title` and `.content` attribute.
2. The function should construct an HTML snippet using a template string with the title and content wrapped in an `<h2>` tag and a `<p>` tag, respectively.
3. The function should escape special characters in... | Write a Python function that takes a post object (with a `.title` and `.content` attribute) to generate an HTML snippet of the post's title and content. The function should construct a template string with the title and content wrapped in an `<h2>` tag for the title and a `<p>` tag for the content, respectively. Escape... | To create a Python function that generates an HTML snippet from a post object while escaping special characters, you can use the `html` module, which provides a method for escaping HTML characters. Below is the implementation you can use:
```python
import html
class Post:
def __init__(self, title, content):
... | 34,746 |
Here's how you can implement the `get_average_of_three_factors` function in Python:
```python
def get_average_of_three_factors(df):
average = df[['factor_one', 'factor_two', 'factor_three']].mean().mean()
return float(average)
```
The `mean` method of a pandas dataframe is used to calculate the arithmetic ave... | Write a Python function `get_average_of_three_factors` that computes the arithmetic average of three factors in a pandas dataframe. The factors are determined by the columns called `factor_one`, `factor_two`, and `factor_three`. The function should return the average value as a float. | You can create the function `get_average_of_three_factors` that takes a pandas DataFrame as input and computes the arithmetic average of the three specified columns. Here's one way to implement this function:
```python
import pandas as pd
def get_average_of_three_factors(df: pd.DataFrame) -> float:
# Check if the... | 34,747 |
To solve this problem, we can iterate through the list of dictionaries and use a regular expression to remove HTML tags from the definition. Then, we can convert the label to lowercase and replace spaces with underscores.
Here is a Python function that implements this approach:
```python
import re
def clean_labels_a... | I have a list of dictionaries, each representing a label and its corresponding definition. The label is stored as a string value and the definition is stored as a list of strings. Neither the label nor the definition can contain any HTML tags.
Write a Python function that converts the label to a lowercase string with ... | You can achieve this by creating a function that processes each dictionary in your list. The function will modify the label to convert it to lowercase and replace spaces with underscores, and it will also remove any HTML tags from the definition. To remove HTML tags, you can use the `re` module, which provides support ... | 34,748 |
To implement this function, we'll use a list comprehension. The list comprehension will process each triple in the input list and select the values at the odd indices, that is, where `is_odd` is True.
Here's the code for this function:
```python
def select_odd_values(triples):
return [value for index, value, is_o... | Write a Python function that takes a list of triples of the form `(index, value, is_odd)`, where `index` and `value` are integers and `is_odd` is a boolean, and returns a list of the values at the indices where `is_odd` is True.
Your code should pass the following test case:
```python
triples = [(0, 0, False), (1, 1, ... | You can create a function that extracts values from the list of triples based on the `is_odd` flag. Here is a possible implementation of the `select_odd_values` function:
```python
def select_odd_values(triples):
# Use a list comprehension to filter and extract values where is_odd is True
return [value for ind... | 34,749 |
To generate all possible binary strings of length `n`, we can use a recursive approach. We start with an empty string and repeatedly append `0` and `1` to it until the length of the string reaches `n`.
```python
def generate_binary_strings(n):
if n == 0:
return []
result = []
def helper(s, remaini... | Create a Python function that takes an integer `n` as input and returns a list of all possible binary strings of length `n`. Each string should be padded with leading zeroes to ensure a length of `n`. The return list should exclude `0` and `1`. | You can create a Python function that generates all possible binary strings of a specified length `n`. The function will then filter out the strings '0' and '1', as you requested. Here's how you can do this:
```python
def generate_binary_strings(n):
if n <= 1:
return [] # There are no binary strings of le... | 34,750 |
Here's how you could implement the `euclidean_rhythm` function in Python:
```python
def euclidean_rhythm(n, k):
rhythm = [] # Initialize an empty list to store the rhythm
while n > 0:
if len(rhythm) < k - 1:
rhythm.append(1)
n -= 1
else:
rhythm.append(n)
... | Implement a Python function `euclidean_rhythm` that generates a rhythm based on the Euclidean algorithm. The function should take two arguments: `n` and `k`. The function should return a list of integers corresponding to the generated rhythm. The rhythm is generated by dividing `n` beats into `k` groups, with the first... | The Euclidean rhythm is a way of distributing `n` beats into `k` groups, using the concept of division and remainder, which provides a regular, repeating pattern that is often used in music and percussion.
Here's a Python implementation of the `euclidean_rhythm` function that achieves this:
```python
def euclidean_rh... | 34,751 |
Here's how you could do it:
```python
import json
def read_json_values(file_path):
with open(file_path, 'r') as f:
json_data = json.load(f)
values = []
for obj in json_data:
values.append(obj['value'])
return values
``` | Write a Python function to read a JSON file, extract only the values from the "value" field, and return them as a list. | You can use the built-in `json` module in Python to read a JSON file and extract specific values. Below is a Python function that reads a JSON file and extracts the values from the "value" field:
```python
import json
def extract_values_from_json_file(file_path):
try:
with open(file_path, 'r') as file:
... | 34,752 |
To write this function, you need to iterate through the list of items and check each item against the condition function. If the condition is met for an item, you append it to the result list. If no items meet the condition, the function returns `None`.
Here's an example of how you can write this function in Python:
... | Write a Python function `get_matching_items(items, condition)` that takes a list of items and a `condition` function. The `condition` function takes one item as an argument and returns `True` if the condition is met for that item, and `False` otherwise. The function should return a list of all the items that meet the c... | You can implement the `get_matching_items` function as described using a simple list comprehension. Here's how you can do it:
```python
def get_matching_items(items, condition):
# Use a list comprehension to filter items that meet the condition
matching_items = [item for item in items if condition(item)]
... | 34,753 |
Here's how you could implement this in Python:
```python
import struct
def binary_to_list(binary_file_path):
with open(binary_file_path, 'rb') as binary_file:
binary_data = binary_file.read()
data_format = f'{len(binary_data) // 4}i'
unpacked_data = struct.unpack(data_format, binary_data)
... | I have two files, one is a binary file and the other is a text file. The text file is a list of integers, and the binary file is a serialization of that same data. I want to read the binary file and convert it to a list of integers. I know the binary file is a serialization of the original list, so I know what it shoul... | Certainly! To read a binary file that is a serialization of a list of integers, you can use Python's built-in `pickle` module, which is commonly used for serializing and deserializing Python objects. Below is a Python function that takes the path to the binary file and returns a list of integers.
```python
import pick... | 34,754 |
```python
import json
def indented_repr(obj, indent):
return json.dumps(obj, indent=indent)
``` | Write a Python function that takes a dictionary object `obj` and an integer `indent` as input, and returns a string representation of the dictionary where each key-value pair is indented by `indent` spaces.
The function should recursively process the dictionary and use the `json` module to format the resulting string.... | You can accomplish this using the `json` module in Python, which provides a convenient way to format Python objects into JSON strings. Below is a Python function that takes a dictionary and an integer for indentation, then returns a formatted string representation of the dictionary.
Here’s how you can implement this:
... | 34,755 |
Here's a possible implementation:
```python
def format_ages(ages):
output = []
for name, age in ages.items():
if age is None:
output.append(f"{name} is unknown.")
else:
output.append(f"{name} is {age} years old.")
return output
``` | Design a Python function that takes a dictionary with the following structure, where each key is a person's name and the corresponding value is their age, and returns a list of strings in the format `<name> is <age> years old.`. If the age is not available, replace it with the string "unknown".
```
{
'Alice': 25,
... | You can achieve this by defining a function that iterates over the dictionary items and formats the strings accordingly. Here's how you can implement such a function:
```python
def format_age_statements(age_dict):
output = []
for name, age in age_dict.items():
if age is None:
age_str = "unk... | 34,756 |
To check whether an object has a certain attribute, you can use Python's built-in `getattr()` function. This function takes an object, an attribute name, and an optional default value. If the attribute exists, it returns the attribute's value. If it does not exist, it returns the default value.
For exception handling,... | Write a Python function to check whether an object has a certain attribute. If the attribute exists, return its value, otherwise return a default value (0 in this case). The function should handle exceptions properly. | You can create a function to check for an attribute in a given object using the built-in `hasattr()` function. If the attribute exists, the function will return its value; otherwise, it will return a default value (0). Additionally, to handle cases where accessing the attribute might raise an exception, you can use a t... | 34,757 |
To implicitly convert a string to a bytes representation, you can use the `str.encode` method or the `int` constructor. The `str.encode` method accepts the encoding as an argument and returns a bytes object. The `int` constructor accepts the string as an argument and returns an integer representation of the string.
He... | You have a function that accepts a string and returns its byte representation. It's defined as follows:
```python
def str_to_bytes(s):
return bytes(s, 'utf-8')
```
Write a Python function `str_to_bytes_implicit` that accepts a string and returns its byte representation in a similar manner, but without explicitly ... | You can achieve the desired byte representation of a string without explicitly calling the `bytes()` constructor by utilizing the `str.encode()` method. Here's how you can implement the `str_to_bytes_implicit` function:
```python
def str_to_bytes_implicit(s):
return s.encode('utf-8')
# Test assertions
assert str_... | 34,758 |
The requirement for the function states that if the value of `current` is less than or equal to zero, then the function should return the zero value. This is a special case that needs to be handled.
Here is the implementation of the Python function, along with a test case that validates its behavior for various input ... | Create a Python function named `calculate_delta` that calculates the difference between two inputs, `current` and `previous`. The function should calculate the delta value as `current - previous`. However, if the value of `current` is less than or equal to zero, then the function should return the zero value instead.
... | Below is the implementation of the `calculate_delta` function, along with some test cases to validate its behavior.
```python
def calculate_delta(current, previous):
"""
Calculate the delta between current and previous values.
Parameters:
current (float or int): The current value.
previous (fl... | 34,759 |
The following Python code provides an implementation of the `escape_next_to_curly_brackets` function:
```python
def escape_next_to_curly_brackets(input_str):
result = ""
for i, c in enumerate(input_str):
if c == '{':
result += "\\{"
elif c == '}':
result += "\\}"
... | Write a Python function `escape_next_to_curly_brackets` that takes a string as input, escapes any next-to-curly-bracket characters, and returns the modified string.
* **Escape**: represent a special character in a program as a character literal. For example, `"\n"` escapes the newline character.
* **Next-to-curly-br... | To create the function `escape_next_to_curly_brackets`, we need to traverse the input string and check for characters that are immediately adjacent to curly brackets `{` or `}`. If we encounter any such character, we will escape it by prefixing it with a backslash `\`.
Here’s how we can implement this in Python:
```p... | 34,760 |
You can achieve this by splitting the input string into lines using the `splitlines()` method, and then using a list comprehension to convert each line into a list of boolean values.
Here's how you can do it in one line of Python code:
```python
def parse_binary(input_str):
return [[bool(int(bit)) for bit in line... | Write a Python function to parse an input string and return a list of boolean values. The input string contains multiple lines, where each line represents a binary number in the form of 1s and 0s. The function should split the input string into lines, convert each line into a list of boolean values, and return the resu... | Certainly! Below is a Python function called `parse_binary` that takes an input string containing multiple lines with binary numbers and converts each line into a list of boolean values. Here’s how the function works:
1. It splits the input string into lines.
2. For each line, it converts each character ('1' or '0') i... | 34,761 |
The question asks you to determine whether the percentage of positive numbers in a list of numbers is greater than 50%. You can approach this problem by calculating the total number of positive numbers in the list and comparing it to the total number of elements in the list.
Here's a Python function that does this:
`... | Given a list of numbers, determine whether the percentage of positive numbers is greater than 50%. The function should return `True` if it is, `False` otherwise.
Simplify the formula to eliminate unnecessary calculations:
$$
\frac{\sum_{x \in L} \mathbb{I}(x > 0)}{n} > \frac{1}{2} \Rightarrow \sum_{x \in L} \mathbb{I... | To determine whether the percentage of positive numbers in a list is greater than 50%, we can simplify our approach based on the inequality you provided. Instead of calculating the total number of positive numbers and dividing by the total length of the list, we can work with counts directly.
The criteria is:
- We wil... | 34,762 |
Here is the implementation of the function in NumPy:
```python
import numpy as np
def repeat_2d_array(arr):
rows, cols = arr.shape
new_rows = rows * 2
new_cols = cols * 2
new_arr = np.repeat(arr, 2, axis=0) # Repeat along the rows
new_arr = np.repeat(new_arr, 2, axis=1) # Repeat along the column... | Write a Python function that takes a 2D array and returns a new array that is the element-wise repetition of the input array along the first axis (rows) and second axis (columns). The shape of the new array should be the sum of the original shape in each dimension.
Your code should pass the following test case:
```pyt... | You can achieve element-wise repetition of a 2D array in Python using the `numpy` library. The function will take the input 2D array, determine its shape, and then create a new array that duplicates the elements along both axes as specified.
Here's the implementation of the `repeat_2d_array` function:
```python
impor... | 34,763 |
Here is an example implementation of the Python function:
```python
def sql_query_generator(column_names, table_name):
columns_string = ', '.join(column_names)
query = f'SELECT {columns_string} FROM {table_name};'
return query
```
This implementation uses the `join()` method to concatenate the column name... | Write a Python function that takes a list of PostgreSQL table column names and returns a valid SQL query to retrieve data from the table.
Your code should pass the following test case:
```python
column_names = ['col1', 'col2', 'col3']
table_name = 'my_table'
expected_query = 'SELECT col1, col2, col3 FROM my_table;'
ac... | You can write the function `sql_query_generator` to construct a valid SQL query based on the provided column names and table name. Below is the implementation of that function which should pass the provided test case.
```python
def sql_query_generator(column_names, table_name):
# Join the column names into a singl... | 34,764 |
Here's how you could implement the `div_list_comp` function using list comprehension:
```python
import numpy as np
def div_list_comp(x, y):
if isinstance(y, list):
y = np.array(y)
elif not isinstance(y, np.ndarray):
raise TypeError("y must be a list or numpy array.")
return [x / element fo... | Develop a Python function `div_list_comp(x, y)` to compute the division of two floating-point numbers `x` and `y` using list comprehension. The function should return a list of elements, where each element is the result of dividing `x` by the corresponding element in the list `y`. Your implementation should support bot... | Certainly! You can create a function `div_list_comp(x, y)` in Python that performs element-wise division of the number `x` by each element in `y`, which can be either a list or a numpy array. The function will utilize list comprehension to achieve this.
Here's how you can implement this function:
```python
import num... | 34,765 |
In Python, an iterable is any object that can be iterated over using a `for` loop or through the `iter` function. The `next` function retrieves the next item from an iterator, and it is essential for implementing the functionality of the `iterate_twice` function.
The `iterate_twice` function is designed to take an ite... | Create a Python function `iterate_twice(iterable)` that takes an iterable and calls the `next` function on it twice, returning the resulting value or raising a `StopIteration` exception. The function should handle any input type, including those without a `next` method. Include documentation in the function's header to... | Certainly! Below is the implementation of the `iterate_twice` function in Python, along with appropriate documentation:
```python
def iterate_twice(iterable):
"""
Retrieves the second element from an iterable by calling `next` twice.
Args:
iterable (iterable): An iterable object, such as a lis... | 34,766 |
Here is the implementation of the function:
```python
def compute_batch_accuracy(true_labels, predictions):
num_samples = len(true_labels)
num_correct = 0
for i in range(num_samples):
predicted_label = predictions[i].index(max(predictions[i]))
if predicted_label == true_labels[i]:
... | Write a Python function `compute_batch_accuracy` to calculate the accuracy of a batch of predictions given the true labels. The function should take two arguments: `true_labels`, a list of integers representing the true labels, and `predictions`, a list of lists of floats, where each sublist represents a prediction vec... | To compute the batch accuracy given the true labels and the prediction vectors, you can follow these steps:
1. Determine the predicted class for each sample by identifying the index of the maximum probability in each prediction vector.
2. Compare these predicted classes with the true labels to count the number of corr... | 34,767 |
You can create a Python function that swaps every two consecutive elements in a linked list by using a tail call to repeatedly swap pairs of elements.
Here's how you could do it:
```python
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def swap_pairs(head):
... | Develop a Python function `swap_pairs` to swap every two consecutive elements in a linked list. For example, given `1 -> 2 -> 3 -> 4`, return `2 -> 1 -> 4 -> 3`. Implement the function with a tail call. Your function must also provide type hints for the input and output parameters. | To implement the `swap_pairs` function for a linked list in Python, we first need to define a `ListNode` class that represents a node in the linked list. Then, we will create the `swap_pairs` function.
Here's the complete implementation with type hints:
```python
class ListNode:
def __init__(self, value: int = 0... | 34,768 |
Here's how you can implement this:
```python
def add_numbers_assert_int_type(a: int, b: int) -> int:
"""
Add two integers together.
Args:
a (int): The first integer to add.
b (int): The second integer to add.
Returns:
int: The sum of the two integers.
Raises:
Valu... | Write a Python function `add_numbers_assert_int_type` that takes two integers as input and adds them together. The function should use type hints and assert statements to validate the inputs are of type int, and if not, raise a ValueError with a descriptive error message. Ensure the function has a clear and informative... | To create a function `add_numbers_assert_int_type` that adds two integers and includes type hints and assertions, we will follow these requirements:
1. The function should take exactly two inputs, both expected to be integers.
2. It should assert that both inputs are of type `int`; if not, it will raise a `ValueError`... | 34,769 |
Here is the implementation:
```python
from datetime import datetime
def timestamp_duration(start_ts, end_ts):
start_dt = datetime.fromtimestamp(start_ts)
end_dt = datetime.fromtimestamp(end_ts)
duration = end_dt - start_dt
return int(duration.total_seconds())
```
In this implementation:
- `start_dt =... | Write a Python function to calculate the duration between two timestamps in seconds. The function should take two arguments `start_ts` and `end_ts`, where `start_ts` and `end_ts` are Unix timestamps in seconds. The function should return the duration as an integer.
Your code should pass the following assertions:
```py... | You can create the `timestamp_duration` function in Python that calculates the duration between two Unix timestamps in seconds. Here is the implementation of that function:
```python
def timestamp_duration(start_ts, end_ts):
return end_ts - start_ts
# Assertions to test the function
assert timestamp_duration(1665... | 34,770 |
In order to implement a function that calculates the amount of sodium in a given salt solution, we need to follow the provided instructions and consider the following details:
- The provided `mass` and `conc` parameters represent the mass of the salt in grams and the concentration of the salt in mol/L, respectively.
-... | Implement a Python function that calculates the amount of sodium (Na) in a given salt solution in mg/L. The function should accept two parameters: `mass` (mass of the salt in grams) and `conc` (concentration of the salt in mol/L). The function should return the amount of sodium in mg/L.
Use the following conversion fa... | You can implement the function to calculate the amount of sodium in a given salt solution in mg/L using the specified formula and defaults. Here's the code:
```python
def calculate_sodium(mass=10, conc=0.1):
# Constants
molar_mass_Na = 23 # grams per mole
molar_mass_salt = 58.5 # grams per mole for commo... | 34,771 |
You can solve this task by utilizing the `slice` data type to extract the substring, capitalize it, then concatenate the modified substring with the rest of the text.
Here's how you can do it in Python:
```python
def capitalize_substring(text, start, end):
if start < 0 or end >= len(text):
return text
... | Create a Python function `capitalize_substring(text, start, end)` that capitalizes a substring of given text `text` between indices `start` and `end` (inclusive), and returns the modified text. If `start` or `end` is out of range, the function should return the original text.
Your code should pass the following assert... | Here's a Python function `capitalize_substring(text, start, end)` that meets the requirements outlined in your request:
```python
def capitalize_substring(text, start, end):
# Check if the range is valid
if start < 0 or end >= len(text) or start > end:
return text
# Capitalize the substring
mo... | 34,772 |
Here is a Python function that implements this approach:
```python
def extract_first_line(text: str) -> str:
if text.startswith("\n"):
return text.split("\n")[1]
else:
return text
``` | Write a Python function to extract the first line of a string if the string starts with a line break character, otherwise return the entire string. For example:
```python
extract_first_line("\nHello, world!") -> "Hello, world!"
extract_first_line("Hello, world!") -> "Hello, world!"
``` | You can implement the desired functionality in a simple Python function. Below is a function called `extract_first_line` that adheres to your requirements:
```python
def extract_first_line(s: str) -> str:
# Check if the string starts with a line break character
if s.startswith('\n'):
# Split the string... | 34,773 |
Here's an implementation of the function using list slicing and element erase operations:
```python
def move_negatives(lst):
new_lst = lst[:] # Making a shallow copy of the input list
for i, num in enumerate(lst):
if num < 0:
new_lst.remove(num)
new_lst.append(num)
return n... | Write a Python function that takes a list of numbers and returns a new list with all negative numbers at the back. The function should utilize list slicing and element erase operations to construct the new list.
Your code should pass the following assertions:
```python
assert move_negatives([0, 0, 0, 0, 0]) == [0, 0, ... | You can create a function called `move_negatives` that uses list slicing and element removal to separate negative numbers from non-negative numbers. Below is one way to implement this:
```python
def move_negatives(numbers):
# Create two lists: one for non-negative numbers and one for negative numbers
non_negat... | 34,774 |
```python
def sort_tuples_by_rank_and_shift(tuples):
sorted_tuples = sorted(tuples, key=lambda x: (x[0], x[1]))
return sorted_tuples
```
The custom comparison function `lambda x: (x[0], x[1])` defines a tuple containing the rank and shift of the current tuple being compared. The `sorted()` function will sort t... | Write a Python function to sort a list of tuples by their rank and shift. The rank and shift of a tuple are two numbers representing its position in a matrix. The function should sort the tuples in ascending order based on the rank and shift values, with the rank taking precedence.
Use lambda functions to define a cus... | You can achieve sorting a list of tuples by their rank and shift values in ascending order using Python's built-in `sorted()` function along with a lambda function that specifies the sort keys. Here’s how you can define such a function:
```python
def sort_tuples(tuples):
# Sort the list of tuples by rank (first el... | 34,775 |
To fix this issue, you can modify the `extract_secret_code` function to handle the `PASSWORD` type differently. Here is the updated code:
```python
def extract_secret_code(data):
code_types = ['OTP', 'UUID', 'PASSWORD']
code_dict = {code_type: '' for code_type in code_types} # Initialize code_dict with empty ... | I have a function `extract_secret_code(data)` that takes in a string. The data format is `TYPE:DATA`, where the type can be `OTP`, `UUID`, or `PASSWORD`. The function should extract the data portion of each of these types into 3 separate strings. If the type is not recognized, the function should return an empty string... | Based on your description, it seems that the function is supposed to | 34,776 |
To calculate the area of intersection between two boxes, we can first calculate the coordinates of the intersection box. Then, we can use the `set()` type to calculate the area of the intersection box by subtracting the area of the union of the two boxes from the sum of the areas of the two boxes. This ensures that the... | Write a Python function `get_area_of_intersection` that takes two arguments: `box_1` and `box_2`, which are two tuples representing the coordinates of the diagonally opposite corners of a box. For example, `box_1 = (1, 2, 3, 4)` represents a box with a top-left corner at (1, 2) and a bottom-right corner at (3, 4), and ... | Certainly! Here's a Python function that calculates the area of intersection between two rectangular boxes defined by their diagonal corners. The function `get_area_of_intersection` will return the area of overlap if there is any, or zero if there is no intersection.
```python
def get_area_of_intersection(box_1, box_2... | 34,777 |
Here's how we can implement this function:
```python
def enclose_in_comment(string: str, file_name: str) -> str:
comment = f"""
-- This file contains sensitive information. Do not share or modify it. --
{file_name}
"""
with open(file_name, 'w') as f:
f.write(string)
return comment
``` | It's important to keep code that contains passwords or sensitive information secure. I want to create a Python function that encloses a string in a multi-line comment. The function should also store the string in a file and add a placeholder in the comment for the name of the file. Here is the function signature:
```p... | You can implement the `enclose_in_comment` function as follows. This function will write the provided string to the specified file and then return a multi-line comment containing a placeholder for the file name. Here's the complete implementation:
```python
def enclose_in_comment(string: str, file_name: str) -> str:
... | 34,778 |
```python
def clamp(value, lower_bound, upper_bound):
return max(lower_bound, min(upper_bound, value))
def clamp(value, lower_bound, upper_bound):
return lower_bound if value < lower_bound else upper_bound if value > upper_bound else value
```
The two implementations above utilize different approaches to clamp... | Create a Python function `clamp` that takes three arguments: `value`, the value to be clamped, `lower_bound`, the lower bound of the range, and `upper_bound`, the upper bound of the range. The function should return the value, clamped between the lower and upper bounds (inclusive). | Certainly! You can create a `clamp` function in Python that limits a given value to a specified range defined by the lower and upper bounds. Below is an implementation of the `clamp` function:
```python
def clamp(value, lower_bound, upper_bound):
"""Clamp the value to be within the specified bounds."""
return ... | 34,779 |
Your instructions clearly indicate the purpose of the function: to reduce a list of integers to a single integer using repeated addition. We can implement this function using a `while` loop to iterate over the list and add each element to the accumulator, which is initialized with a zero value.
Here is the implementat... | Implement a Python function named `reduce_integer_list` that takes a list of integers and reduces it to a single integer using repeated addition. You can use the built-in `reduce` function from the `functools` module. Your function should return an integer value.
Your code should pass the following assertions:
```pyth... | To implement the `reduce_integer_list` function using the `reduce` function from the `functools` module, you can follow these steps:
1. Import `reduce` from `functools`.
2. Define the `reduce_integer_list` function that takes a list of integers.
3. Use `reduce` to sum the integers in the list by providing a lambda fun... | 34,780 |
Here is a Python function that solves this problem:
```python
def format_tags(tags):
"""
Formats a list of tags into a single string containing all tag names separated by commas.
If any tag name contains a comma, the entire list is enclosed in double quotes.
"""
if any(',' in tag.name for tag in tag... | Write a Python function to format a list of tag objects (each with a `.name` attribute) and into a single string containing all tag names separated by commas (no spaces), where tag names containing commas are first enclosed in double quotes. The difficulty of the function should be calculated as the average difficulty ... | To solve your problem, we can create a Python function that takes a list of tag objects and formats their names accordingly. We'll also assume each tag has an additional `difficulty` attribute, which we'll use to calculate the average difficulty. The function will then return both formatted tag names as a string and th... | 34,781 |
To generate a list of 50 random integers between 1 and 100 that contain only even numbers, we need to follow these steps:
1. Use the `random` module and its `randint` function to generate random integers between 1 and 100.
2. Use list comprehension to filter out odd numbers.
3. Use the built-in `len` function to check... | Write a Python function to generate a list of 50 random integers between 1 and 100 (inclusive) that contain only even numbers. The function should not use any external libraries such as NumPy or random. Use the built-in `random` module and list comprehension to create the list.
Your code should pass the following test... | Certainly! Below is a Python function that generates a list of 50 random even integers between 1 and 100 (inclusive). The function uses Python's built-in `random` module and list comprehension to achieve this.
```python
import random
def generate_list_of_even_numbers():
return [random.choice(range(2, 101, 2)) for... | 34,782 |
Here is how you could implement the function `format_text`:
```python
def prepare_word(word):
return word.replace('-', '_').lower().capitalize()
def format_text(text):
if not text:
return ''
words = text.split('-')
prepared_words = map(prepare_word, words)
return '_'.join(prepared_words)
`... | Write a Python function `format_text` to format a text string with the following rules:
- Replace all instances of the string `-` with the string `'_'` (underscore).
- Convert all words in the string to lowercase.
- Capitalise the first letter of each word.
For example, the function should transform the string `this-... | Certainly! Below is a Python function named `format_text` that adheres to the specified formatting rules. It handles empty strings by returning an empty string. The function replaces all instances of `-` with `_`, converts all words to lowercase, and then capitalizes the first letter of each word.
```python
def format... | 34,783 |
Here's a possible implementation of the function that extracts the note number from a MIDI message:
```python
def get_note_number(message):
if len(message) != 2 or (message[0] & 0b10000000) == 0:
return None
note_number = message[1]
return note_number
```
In this implementation, we check if the re... | Write a Python function that receives a MIDI message and returns the corresponding note number of the message, assuming the message is a valid MIDI message for a note-on or note-off event. The function should return `None` if the received message is not a valid note message. | To create a Python function that extracts the note number from a MIDI message, we need to first understand the structure of MIDI messages. Specifically, note-on and note-off messages in the General MIDI specification have specific status byte values and payload structure. Here’s a breakdown:
1. **Note-On Message**: Th... | 34,784 |
To compute the signed area of a triangle, we can use the formula provided in the instruction. This formula involves taking the cross product of two vectors that define the triangle's base and height, and dividing by two. We can represent the three 2D points as vectors and use their coordinates to compute the area.
Her... | Implement a Python function to compute the signed area of a triangle given three 2D points, with the triangle described by the three points in counterclockwise order. Use the formula for the triangle area: `area = 0.5 * ((x1 * y2 - x2 * y1) + (x2 * y3 - x3 * y2) + (x3 * y1 - x1 * y3))`. | To compute the signed area of a triangle given three 2D points, you can implement a Python function using the formula you provided. Each point will be represented as a tuple of (x, y) coordinates. Here's how you can implement the function:
```python
def signed_area(point1, point2, point3):
"""
Calculate the si... | 34,785 |
To solve this problem, we need to first understand the input requirements, which involve processing a list of strings containing only numbers and signs, and then parsing and evaluating them to get the desired output. We can use the `eval()` function in Python to evaluate the expressions, which allows us to handle paren... | Write a Python function to process a list of strings containing only numbers and signs, and return the sum of all those strings. The function should be able to handle positive and negative numbers, including parentheses, and should return the result as an integer. Ensure your code is properly formatted and follows good... | Certainly! Below is a Python function that processes a list of strings containing numbers and signs, handles both positive and negative numbers (including those specified in parentheses), and returns the sum of all those strings as an integer.
```python
def sum_strings(number_strings):
"""
This function takes ... | 34,786 |
You can use the `numpy.where` function to find the indices of elements in a 1D array `x` that are not present in a second 1D array `y`.
Here's how you could do it:
```python
import numpy as np
def find_indices_not_in_y(x, y):
return np.where(~np.isin(x, y))[0]
```
This function uses the `numpy.where` function t... | Implement a Python function to find the indices of elements in a 1D array `x` that are not present in a second 1D array `y`. Use the `numpy.where` function for this purpose. | You can implement a Python function to find the indices of elements in one 1D array `x` that are not present in another 1D array `y` using the `numpy.where` function along with `numpy.isin`. Here's how you can do it:
```python
import numpy as np
def find_missing_indices(x, y):
"""
Find indices of elements in ... | 34,787 |
Here's a concise solution using list comprehensions and string formatting:
```python
def binary_to_urls(binary_list):
return [f'https://example.com/api/binary/{value:0>6b}' for value in binary_list]
```
In this implementation, we use list comprehensions to iterate over the given `binary_list` and generate the cor... | Develop a Python function that takes a list of integers representing binary values and returns a list of strings with the corresponding URLs. The function should use functional programming techniques, such as list comprehensions, and string formatting to generate the URLs.
The URLs should follow the template: `https:/... | You can achieve this functionality by using a combination of list comprehensions and string formatting in Python. Below is a function that takes a list of integers representing binary values (0 and 1) and converts them into the desired URL format:
```python
def generate_binary_urls(binary_list):
return [
f... | 34,788 |
To create a function `update_database(filename)` that reads a text file containing a list of book titles, one per line, and generates a unique ID for each, we can utilize the following steps:
1. Open the text file in read mode using the `open()` function.
2. Read the contents of the file line by line using the `readli... | Write a function `update_database(filename)` that reads a text file containing a list of book titles, one per line, then updates the database by adding the new book titles and generating a unique ID for each. The function should return a list of dictionaries with the new book titles and their corresponding IDs. | To accomplish the task of updating a database with new book titles and assigning unique IDs, we can write a function `update_database(filename)`. This function will read from a text file specified by `filename`, create unique IDs for each book title, and return a list of dictionaries containing the book titles and thei... | 34,789 |
To merge two dictionaries and update the values of shared keys, we can use a for loop to iterate over the keys in one of the dictionaries. For each key, we check if it exists in the other dictionary. If it does, we concatenate the values from both dictionaries and update the value in the resulting dictionary. If the ke... | Create a Python function to merge two dictionaries and update the values of shared keys. For this function, the input parameters should be two dictionaries, `dict_1` and `dict_2`. The function should return a new dictionary that combines the key-value pairs from both dictionaries. If a key exists in both `dict_1` and `... | Here's a Python function that merges two dictionaries according to your specifications. The function will concatenate the values for shared keys and include all keys from both dictionaries.
```python
def merge_dictionaries(dict_1, dict_2):
# Create a new dictionary to hold the merged values
merged_dict = {}
... | 34,790 |
To build a valid HTTP response, you need to follow the format specified by the HTTP protocol. The message body must be separated from the headers by a double newline (CRLF). The first line of the response contains the protocol version, status code, and the reason phrase, which is the standardized description of the sta... | Write a Python function to build a valid HTTP response with a message and a status code. The function takes two arguments: `message`, which is the response message body, and `status_code`, which is the HTTP status code of the response. The status code should be an integer and the message body should be a string. The fu... | You can create the `build_http_response` function in Python as follows:
```python
def build_http_response(message, status_code):
# Define a dictionary to map status codes to their respective status messages
status_messages = {
200: "OK",
404: "Not Found",
500: "Internal Server Error",
... | 34,791 |
Here's how you can implement this:
```python
import numpy as np
def flatten_image(image):
return np.ravel(image)
``` | Write a Python function `flatten_image(image)` that takes a 2D array as input representing an image, and returns a 1D array by taking all the pixels and merging them into a single row. The function should not modify the original image array. | You can flatten a 2D array in Python by using the `numpy` library, which provides a convenient way to handle arrays. However, if you want to implement the function without any external libraries, you can manually iterate through the 2D array and append the elements to a new list.
Here is a sample implementation of the... | 34,792 |
Here's the code for the `filter_data_with_conditions` function:
```python
def filter_data_with_conditions(data, *conditions, default_value=None):
def condition_fn(d):
return all(condition(d) for condition in conditions)
if not conditions:
return default_value or data
return [d for d in data... | Write a Python function `filter_data_with_conditions` that takes a list of dictionaries `data`, a variable number of conditions `conditions`, and a `default_value`. The function is to return a list of dictionaries that satisfy all conditions. A condition is a function that takes a dictionary as input and returns a bool... | You can achieve the desired functionality by using Python's built-in functions and the `functools` module. Below is the implementation of the `filter_data_with_conditions` function. The function uses function composition to combine all the provided conditions, allowing you to filter the list of dictionaries as required... | 34,793 |
Here is how you can implement the function using the `datetime` module:
```python
import datetime
def unix_to_readable(unix_timestamp: int) -> str:
readable_timestamp = datetime.datetime.fromtimestamp(unix_timestamp)
return readable_timestamp.strftime('%Y-%m-%d %H:%M:%S')
```
The `unix_to_readable` function ... | Write a Python function that converts a Unix timestamp (integer) into a readable format (e.g., '2019-01-01 12:34:56') using `datetime.datetime.fromtimestamp`. | Certainly! Below is a Python function that takes a Unix timestamp as an integer and converts it into a readable date and time format using the `datetime` module:
```python
from datetime import datetime
def convert_unix_timestamp(timestamp):
# Convert the Unix timestamp to a datetime object
dt_object = datetim... | 34,794 |
To convert a list of integer numbers to their bit representation, you can utilize the `format` function with the `b` flag. This flag converts the integer to its binary representation. However, the default behavior is to pad the string to a length of 1. To pad each number to a length of 32 bits, you can use the `zfill` ... | Implement a Python function `format_bits` that takes a list of integer numbers and converts them to their bit representation as a string. The function should pad each number to a length of 32 bits and return a list of 32-bit strings.
For example:
```
>>> format_bits([1, 2, 3])
["00000000000000000000000000000001", "00... | To implement the `format_bits` function that converts a list of integers to their 32-bit binary representations, you can use Python's built-in formatting capabilities. Below is the code for the function:
```python
def format_bits(numbers):
return [format(num, '032b') for num in numbers]
# Example usage:
print(for... | 34,795 |
To implement this function, we can use a list comprehension to iterate through the input list and check whether the number meets the conditions. We'll use the `sorted` function to sort the digits of a number and then use `count` to count the occurrences of each digit. If there is at least one digit that occurs more tha... | Write a Python function called `filter_numbers_with_duplicates` that filters a list of numbers based on whether they have duplicate digits.
Input: A list of integers.
Output: A list of integers.
The function should return a list of integers that meet all of the following criteria:
- Each integer in the input list
-... | To create the `filter_numbers_with_duplicates` function, we need to follow these steps:
1. Iterate through each integer in the input list.
2. For each integer, convert it to a string and check if it contains duplicate digits.
3. If it does contain duplicate digits, collect it into a new list.
4. Finally, sort the new ... | 34,796 |
Here's an example implementation of the specified function:
```python
import importlib
from typing import Any
def load_and_call(name: str, *args, **kwargs) -> Any:
module_name, func_name = name.rsplit('.', 1)
module = importlib.import_module(module_name)
func = getattr(module, func_name)
return func(*... | Write a Python function to automatically load a module and call a function from that module given its name. The function should have a single parameter called `name` that represents the module and function names to be loaded, and return the result of the function call. For example, if the module `utils.math` has a func... | You can achieve this by using Python's `importlib` module to dynamically import the module and then call the specified function. Below is a Python function that implements this behavior:
```python
import importlib
def load_and_call(name):
"""
Load a module and call a function from that module given its name.
... | 34,797 |
To convert a string of digits, separated by commas and/or spaces, into an array of integers, we can use the `split()` method to split the string into a list of substrings, and then use the `join()` method to join the list with the `','` separator to remove the commas and spaces. We can then use the `int()` function to ... | Write a function that converts a string of digits, separated by commas and/or spaces, into an array of integers.
Your code should pass the following test case:
```python
string = "1, 2, 3, 4, 5"
assert convert_string_to_array(string) == [1, 2, 3, 4, 5]
``` | You can create a function called `convert_string_to_array` that takes a string of digits, separated by commas and/or spaces, and converts it into an array of integers. Here's how you can implement it:
```python
def convert_string_to_array(string):
# Split the string by commas and then by spaces, and filter out any... | 34,798 |
Here is the implementation of the `trim_indentation(text)` function:
```python
def trim_indentation(text):
lines = text.splitlines()
trimmed_lines = []
for line in lines:
trimmed_line = line.lstrip() # Remove leading spaces
trimmed_line = trimmed_line.rstrip() # Trim trailing spaces
... | Write a Python function `trim_indentation(text)` that removes leading spaces from each line in the given `text`. The function should remove any leading spaces from each line, and trim the trailing spaces on the line. The function should handle the case where the input contains leading spaces, but not trailing spaces. | You can create a function `trim_indentation(text)` that processes the input text line by line. The idea is to strip leading spaces from each line and also trim any trailing spaces. Here's how you can implement this:
```python
def trim_indentation(text):
# Split the input text into lines
lines = text.splitlines... | 34,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.