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 in Python:
```python
def positive_int_to_hex(num):
if num < 0:
return ""
hex_str = ""
while num > 0:
remainder = num & 15
hex_str = hex_str + "0123456789ABCDEF"[remainder]
num = num >> 4
return hex_str[::-1]
``` | Write a Python function to convert a positive integer to its corresponding hexadecimal string representation. If the given number is negative, return an empty string.
Your code should pass the following assertions:
```python
assert positive_int_to_hex(-1) == ""
assert positive_int_to_hex(255) == "FF"
assert positive_i... | You can create a Python function to convert a positive integer to its hexadecimal string representation using the built-in `hex()` function, while ensuring to handle the negative numbers as specified. Below is the implementation:
```python
def positive_int_to_hex(n):
if n < 0:
return ""
else:
#... | 15,600 |
Here's a Python implementation of the `is_power_of_two_bitwise` function:
```python
def is_power_of_two_bitwise(n):
return n > 0 and (n & (n - 1)) == 0
```
The `n > 0` check ensures that the number is positive so we can apply the bitwise operations. Then, the `(n & (n - 1)) == 0` check is used to determine if all... | Write a Python function `is_power_of_two_bitwise` that checks whether an integer `n` is a power of two using bitwise operations.
Your code should pass the following assertions:
```python
assert is_power_of_two_bitwise(4096) == True
assert is_power_of_two_bitwise(32768) == True
assert is_power_of_two_bitwise(64) == Tru... | You can determine if a number is a power of two using bitwise operations. Specifically, a number \( n \) is a power of two if it is greater than zero and \( n \& (n - 1) \) equals zero. This works because a power of two has a single bit set in its binary representation, and subtracting one from it flips all the bits af... | 15,601 |
To write this Python function, you must understand the GeoJSON format, which is a standardized way to represent geographic data in JSON format. In GeoJSON, a `Feature` is a [GeoJSON object](https://geojson.org/geojson-spec.html#feature-objects) that represents a spatially bounded entity, and a `FeatureCollection` is a ... | Write a Python function that takes a list of dictionaries representing GeoJSON `Feature` objects and returns a dictionary representing a GeoJSON `FeatureCollection`. Each `Feature` must have a `geometry` field, which is a `Point`, `LineString`, or `Polygon`, and a `properties` field, which is an arbitrary mapping of st... | To create a Python function that constructs a GeoJSON `FeatureCollection` from a list of dictionaries representing GeoJSON `Feature` objects, you can follow these steps:
1. Ensure that each feature in the input list has the required structure with `geometry` and `properties` fields.
2. Create a dictionary with the typ... | 15,602 |
The first step in solving this problem is to understand the structure and format of the input data. The point cloud is represented as a list of tuples, with each tuple representing a 3D coordinate. Each coordinate is a tuple of three floating point values.
The second step is to understand the desired output. The outpu... | Develop a Python function that converts a point cloud into a robotics-specific matrix representation. The point cloud is represented as a list of tuples of 3D coordinates, and each coordinate is a tuple of three floating point values. The function should return a 3x4 matrix, where the first three columns represent the ... | To convert a point cloud represented by a list of 3D coordinates into a robotics-specific matrix representation using a homogeneous transformation matrix, we'll need to extract the x, y, and z coordinates from the 3D points and organize them in a 3x4 matrix format.
Here's the code to achieve that:
```python
import nu... | 15,603 |
Here is the implementation of the function:
```python
def remove_kth_element(lst: list, k: int) -> list:
"""
Removes the kth element from the given list.
If k is negative, count from the end of the list.
If k is greater than the length of the list, return the original list.
Args:
lst (list... | Write a Python function that takes a list and an integer `k` as input and returns a new list that contains all the elements in the input list except for the kth element. If `k` is negative, count from the end of the list. If `k` is greater than the length of the list, return the original list.
For example, given the i... | Certainly! Below is a Python function that excludes the kth element from a given list, with appropriate handling for both positive and negative values of `k`. The function includes a detailed docstring and a test case.
```python
def exclude_kth_element(lst, k):
"""
Excludes the k-th element from the list.
... | 15,604 |
To calculate the average without using the built-in `sum` and `len` functions, you can iterate through the list and calculate the sum and the number of elements manually. You can handle the case of an empty list by returning `None` or raising an error, and handle the case of non-numeric values by checking each element ... | Write a Python function that takes a list of numbers as input and returns the average of the numbers without using the built-in `sum` and `len` functions. Handle the case where the list is empty or contains non-numeric values. | You can create a function that calculates the average of a list of numbers without using Python's built-in `sum` and `len` functions. In this function, you should also handle cases where the list is empty or contains non-numeric values. Below is an example implementation:
```python
def average(numbers):
if not num... | 15,605 |
1. Check if the object has the attribute of the given method name using the built-in `hasattr` function.
2. If the method exists, use the built-in `getattr` function to retrieve it.
3. If the method does not exist, return `None` and a boolean `False` value.
4. Return a tuple containing the method and a boolean `True` v... | Write a Python function `verify_method` that accepts an object and a method name as arguments. It should check whether the object has an attribute of the given method name, and if so, return a tuple containing the method and a boolean `True` value. If the method does not exist, return a tuple containing `None` and a bo... | You can accomplish this by defining the `verify_method` function in the following way. The function will utilize the `hasattr` function to check for the existence of the method, and if it exists, it will return the method reference along with `True`. If not, it will return `None` along with `False`.
Here's how you can... | 15,606 |
Here is a Python function that converts a dictionary to a list of JSON objects:
```python
import json
def convert_to_json_list(book_dict):
json_object = json.dumps(book_dict)
json_list = [json.loads(json_object)]
return json_list
```
In this implementation:
- We use `json.dumps()` to convert the dictiona... | Create a Python function `convert_to_json_list(book_dict)` that converts a dictionary containing book information into a list of JSON objects. The dictionary should be structured as follows:
```python
{
'title': 'The Title',
'author': 'The Author Name',
'pages': 99,
'price': 99.99,
'isbn': '9999999... | To create a Python function that converts the dictionary containing book information into a list of JSON-like objects, we can use the built-in `json` module to facilitate the conversion to a JSON format. Below is the implementation of the `convert_to_json_list(book_dict)` function according to your specifications:
```... | 15,607 |
Here's how you could define the `serialize_binary` function:
```python
import struct
def serialize_binary(ints):
return struct.pack('<{}I'.format(len(ints)), *ints)
```
The function uses the `struct.pack` function to pack the integers into a binary format. The `'<'` specifier indicates little-endian byte orderin... | Write a Python function `serialize_binary` that takes a list of integers and returns a byte string representing the same integers in binary format.
For example, given the list `[1, 2, 3]`, the function should return the bytes `b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00'`. Note that each integer is 4 bytes and ... | To achieve the serialization of a list of integers to a byte string in little-endian format, we can utilize the `struct` module in Python. This module allows us to convert Python values to C structs represented as Python bytes objects. Given that we want each integer to take 4 bytes and to use little-endian format, we ... | 15,608 |
To solve this problem, you can use regular expressions to match the time pattern in the string. The time pattern can be of the format "hh:mm" where "hh" represents the hour and "mm" represents the minute.
Here's how you could implement the function using regular expressions:
```python
import re
def find_time(input_s... | Write a Python function that takes a string and returns the first time in the format "hh:mm" it appears in the string. If the string does not contain a valid time, return "None".
For example, given the input string "The first time is 12:34, the second time is 19:00", the function should return "12:34". | You can achieve the desired functionality by using regular expressions in Python. Below is a function that takes a string as input and returns the first valid time in the "hh:mm" format, or "None" if no valid time is found:
```python
import re
def find_first_time(s):
# Define the regex pattern for "hh:mm" format
... | 15,609 |
The `itertools` library provides a number of functions for working with iterators, including `itertools.islice()`, which slices an iterable based on a start and stop position. In this case, you need to drop the first `n` items from the iterable, so the start position should be `n`.
Here's how you could use `itertools.... | Write a Python function that takes an iterable and an integer `n` as its arguments, and returns an iterable with the first `n` items dropped. The function should be fast, memory efficient, and not modify the input iterable.
If you are familiar with the `itertools` library, you can use one of the code snippets from the... | You can create a Python function that uses the `itertools.islice` function to achieve this in a memory-efficient manner. The `islice` function allows you to return a slice from an iterable without converting it to a list, which helps in keeping the memory usage low.
Here’s how you can implement this function:
```pyth... | 15,610 |
To create a Python function `is_abstract_base_class` that takes a Python object as input and returns a boolean value indicating whether it is an abstract base class (ABC), you can follow these steps:
1. Import the `abc` module to use the `ABCMeta` metaclass for checking if an object is an ABC.
2. Define the `is_abstra... | Write a Python function `is_abstract_base_class` that takes a Python object as input and returns a boolean value indicating whether it is an abstract base class (ABC). The function should be a guard function that checks if the object is an ABC, and if it is, it returns `True`. If the object is not an ABC, the function ... | To determine if a given object is an abstract base class in Python, we can leverage the `abc` module, specifically the `ABCMeta` metaclass. Here, I will provide a function named `is_abstract_base_class` that checks if the input is a class and then checks if it uses `ABCMeta` as its metaclass.
Here's how you can implem... | 15,611 |
Here's how you can implement this:
```python
def calculate_total_value(items):
total_value = 0
for item in items:
if not isinstance(item, dict):
continue
if 'value' not in item:
print("Error: Item missing 'value' key")
return None
total_value += item[... | Write a Python function named `calculate_total_value` that takes a list of item objects and returns their total value.
The function should check the item data type to ensure it is a valid item object before calculating the value. This is necessary because the list may include non-item objects, which should be ignored ... | You can define the `calculate_total_value` function to iterate over a list of item objects and calculate the total value while ensuring that only valid item objects with a `value` key are considered. Below is a Python implementation of this function:
```python
def calculate_total_value(items):
total_value = 0
... | 15,612 |
To generate all permutations of the digits from 1 to `n` (inclusive), we can employ a recursive approach utilizing backtracking. At each step, we consider a digit from 1 to `n` and check if it has been used. If not, we add it to a list of digits and proceed to generate permutations of the remaining digits. When all dig... | Implement a Python function `generate_all_permutations(n)` that returns a generator object with all permutations of the digits from 1 to `n` (inclusive). For example, `generate_all_permutations(2)` should return `['12', '21']`. | To generate all permutations of the digits from 1 to n, we can use Python's built-in `itertools.permutations` which is efficient and straightforward. We can create a generator function that yields all permutations of the string formed by the digits from 1 to n.
Here's how you can implement the `generate_all_permutatio... | 15,613 |
Here's the implementation of the `pairwise_product()` function:
```python
def pairwise_product(numbers):
product = 1
for a, b in zip(numbers, numbers[1:]):
product *= a * b
return product
```
In this implementation, we use the `zip()` function to iterate over two sequences simultaneously: `numbers... | Write a Python function `pairwise_product` that takes a list of numbers `numbers` as an argument. The function should return the product of all consecutive pairs of numbers in `numbers`.
For example, if `numbers` is `[1, 2, 3, 4, 5]`, the function should return `1 * 2 * 2 * 3 * 3 * 4 * 4 * 5 = 1440`. | To create the `pairwise_product` function that computes the product of all consecutive pairs of numbers in a given list, you can follow these steps:
1. Iterate through the list and compute the product of each pair of adjacent elements.
2. Use a loop to multiply these products together.
Below is the implementation of ... | 15,614 |
Here is a Python function that implements Horner's method:
```python
from typing import List
def evaluate_polynomial(coefficients: List[float], x: float) -> float:
"""
Evaluates a polynomial given its coefficients and a value for x. The coefficients
are represented as a list of floats, where the first ele... | Write a Python function to calculate the value of a polynomial at a given point x, where the polynomial coefficients are given in a list. The function should support any number of coefficients and be able to calculate the value of a polynomial of any degree. | Certainly! You can calculate the value of a polynomial at a given point \( x \) using the list of coefficients where each coefficient corresponds to a term in the polynomial. The coefficient at index \( i \) of the list corresponds to the term \( a_i x^i \).
Here's a Python function that implements this:
```python
de... | 15,615 |
Here's an example of how you could implement the `replace_pattern_in_file` function:
```python
import re
def replace_pattern_in_file(pattern, replacement, filename):
try:
with open(filename, 'r+') as file:
file_contents = file.read()
match = re.search(pattern, file_contents)
... | Write a Python function `replace_pattern_in_file(pattern, replacement, filename)` to replace a specific pattern in a file using regular expressions. The function should take in three arguments: `pattern` is the regular expression pattern to match, `replacement` is the value to be used as a replacement, and `filename` i... | Certainly! Below is a Python function that replaces a specified pattern in a file using regular expressions. It takes in a `pattern`, `replacement`, and `filename`, and it handles exceptions that may arise during file operations.
```python
import re
import traceback
def replace_pattern_in_file(pattern, replacement, f... | 15,616 |
Here's one way to implement the `navigate_until_match` function:
```python
import re
def navigate_until_match(my_dict, reg_exp):
if my_dict is None or reg_exp is None:
raise ValueError("Invalid input: One or more arguments are None")
if not my_dict:
return None
pattern = re.compile(reg_exp... | Write a Python function `navigate_until_match` that traverses a nested dictionary and returns the first value that matches a given regular expression. The function should take two arguments: `my_dict`, a nested dictionary to traverse, and `reg_exp`, a regular expression to match.
If the dictionary is empty, return `No... | Certainly! Below is a Python function named `navigate_until_match` that traverses a nested dictionary to find the first value that matches a given regular expression. The function adheres to the requirements you've outlined:
```python
import re
def navigate_until_match(my_dict, reg_exp):
# Check for None inputs
... | 15,617 |
To clean up a given string `s` in a specific way, you first need to understand the expected behavior. The function should replace every instance of the character `*` by the empty string and remove any whitespace from the beginning and end of the string.
The following Python function `clean_up_text` accomplishes this t... | Write a Python function to clean up text in a specific way. Given a string `s`, the function should replace every instance of the character `*` by the empty string. The function should also remove any whitespace from the beginning and end of the string. | You can create a Python function to achieve this by using the `str.replace()` method to remove the `*` characters and the `str.strip()` method to trim the whitespace from the beginning and end of the string. Here’s how you can implement this function:
```python
def clean_text(s):
# Replace every instance of '*' wi... | 15,618 |
To count the number of variables in a given Python code snippet, we can use a regular expression to match the variable assignment patterns within the code. To exclude variables defined within comments, we can use a regular expression to match comments and replace them with empty strings before counting the variables.
... | Create a Python function to count the number of variables in a given Python code snippet, excluding any variables defined within comments. The function should take the code snippet as a string and return the number of variables found.
For example:
```python
def my_function():
# This is a comment
variable1 = 1... | To solve the problem of counting the number of variables in a given Python code snippet while excluding any variables defined within comments, we can follow these steps:
1. Strip out comments from the code snippet. This includes both single-line comments (starting with `#`) and multi-line comments (within `'''` and `"... | 15,619 |
The key steps involved in implementing the `encode_hex_recursive` function are as follows:
1. The `encode_hex_recursive` function takes a single argument `data`, which represents the input bytes.
2. The function needs to convert the input bytes to hexadecimal strings. To do this, it iterates through each byte in the i... | Write a Python function `encode_hex_recursive` to encode an input `bytes` object into a hexadecimal string, using recursive list processing. The function should take a single argument `data` and return a string with the hexadecimal representation of the data. You are allowed to use the `join` method of the string class... | You can create a function `encode_hex_recursive` which recursively processes the input `bytes` object and constructs the hexadecimal string representation. Here is how you can implement that:
```python
def encode_hex_recursive(data):
if not data: # Base case: if there's no data, return an empty string
ret... | 15,620 |
To solve this problem, you need to iterate through the list of cities and extract the name and population attributes of each city. You can then use these values as the key-value pairs in the dictionary.
Here's how you can write the function in Python:
```python
def cities_to_dict(cities):
return {city.name: city.... | Write a Python function that takes a list of cities and returns a dictionary with the names of the cities as keys and their populations as values. The cities are represented as objects with two attributes: `name` and `population`. | Sure! Below is a Python function that takes a list of city objects and returns a dictionary where the keys are the names of the cities and the values are their populations.
Here is the implementation:
```python
class City:
def __init__(self, name, population):
self.name = name
self.population = po... | 15,621 |
To create a Python function `map_attribute(objects, attribute)` that accepts a list of objects and an attribute name and returns a list of the corresponding attribute values, you can follow these steps:
1. Define a function that takes an object as an argument and returns the value of the specified attribute (e.g., `att... | Create a Python function `map_attribute(objects, attribute)` that accepts a list of objects and an attribute name and returns a list of the corresponding attribute values. The function should use a list comprehension to iterate over the objects and extract the specified attribute from each object. | Certainly! Below is a Python function named `map_attribute` that takes a list of objects and an attribute name as arguments. It uses a list comprehension to return a list of the corresponding attribute values.
```python
def map_attribute(objects, attribute):
"""
Extracts the specified attribute from a list of ... | 15,622 |
To create a Python function that takes a list of numbers as input and returns a new list with each element squared. If the squared value is greater than or equal to 500, divide it by 3 instead, you can follow these steps:
1. Create an empty list to store the squared values.
2. Use a loop to iterate over each element i... | Write a Python function that takes a list of numbers as input and returns a new list with each element squared. But, if the squared value is greater than or equal to 500, divide it by 3 instead. Use a conditional statement to implement the logic.
Your code should pass the following assertion:
```python
assert square_d... | You can create the desired function as follows:
```python
def square_divide(numbers):
result = []
for num in numbers:
squared = num ** 2
if squared >= 500:
result.append(squared / 3)
else:
result.append(squared)
return result
# Test the assertion
assert squa... | 15,623 |
```python
def get_array_of_divisors(n):
if not isinstance(n, int) or n <= 0:
raise ValueError("n must be a positive integer.")
return [i for i in range(1, n+1) if n % i == 0]
```
This implementation checks that the input `n` is a positive integer before proceeding with the main logic. If `n` is not a p... | Implement a Python function `get_array_of_divisors(n)` that takes a positive integer `n` as input and returns a list of all positive divisors of `n`. Use a list comprehension to create the list. If `n` is not a positive integer, raise a `ValueError` exception with a meaningful message. | Here's a Python function `get_array_of_divisors(n)` that meets your requirements. This function checks whether the input `n` is a positive integer and, if so, returns a list of all positive divisors of `n` using a list comprehension. If `n` is not a positive integer, it raises a `ValueError` with a helpful message.
``... | 15,624 |
This problem requires you to handle nested lists of arbitrary depth, which means you need a recursive approach to flatten the list, remove the duplicates, and sort it.
Here's a Python function that achieves the desired result:
```python
def flatten_and_sort_unique(input_list):
flattened_list = [item for sublist i... | Write a Python function that takes a list of lists as input and returns a new list with all unique items, sorted in ascending order. The function should have O(n) time complexity for lists of size n.
The function should be able to handle nested lists of arbitrary depth with no duplicates and no other types of data.
Y... | To achieve a time complexity of O(n) while flattening and sorting unique items from a list of lists, we'll use a combination of a set to store unique items and then subsequently convert it to a sorted list. Here's how you can implement it:
```python
def flatten_and_sort_unique(nested_list):
unique_items = set() #... | 15,625 |
Here's how you can implement the function using list comprehensions and conditional expressions:
```python
def read_delimited_file(filename, delimiter):
with open(filename) as f:
return [line.rstrip().split(delimiter) for line in f if line.rstrip() and line.rstrip(delimiter)]
```
The function opens the fi... | Write a Python function that reads a delimited text file and returns a list of lists. The function should accept two parameters: the filename and the delimiter character. The function should then read the file, parse each line into a list of fields, and return a list of lists, each inner list corresponding to a line.
... | Certainly! Below is the Python function that reads a delimited text file and returns a list of lists, as specified. The function uses list comprehensions and handles empty lines appropriately.
```python
def read_delimited_file(filename, delimiter):
with open(filename, 'r') as file:
# Read all lines from th... | 15,626 |
Here's how you can implement this in Python:
```python
import numpy as np
def random_action_smoothing(Q, epsilon):
rows, cols = Q.shape
def random_noise(N, L):
return np.random.uniform(N - L, N + L)
Q_smooth = np.zeros_like(Q)
for i in range(rows):
for j in range(cols):
Q... | Design a Python function `random_action_smoothing(Q, epsilon)` that applies random action smoothing to a Q-value matrix `Q` given an initial exploration rate `epsilon`. The function should return a new `Q_smooth` matrix with random noise added to the `Q` values.
To achieve this, first define a `random_noise` function ... | Certainly! Below is a Python function called `random_action_smoothing` which implements the random action smoothing for a Q-value matrix `Q`. It incorporates an internal helper function `random_noise` to add random noise based on the `epsilon` parameter.
Here's how it is structured:
1. `random_noise(N, L)`: Generates... | 15,627 |
Here is the implementation of the `is_dictionary_contains_all_keys` function in Python:
```python
def is_dictionary_contains_all_keys(dictionary, keys):
for key in keys:
if key not in dictionary:
return False
return True
``` | Create a Python function `is_dictionary_contains_all_keys` that takes two arguments: a dictionary and a list of keys. The function should return a boolean value indicating whether the given dictionary contains all the keys from the given list.
Here is an example of a dictionary and a list of keys:
```python
my_dictio... | You can create the function `is_dictionary_contains_all_keys` as described. Below is the implementation of the function:
```python
def is_dictionary_contains_all_keys(my_dict, keys):
# Check if all keys are in the dictionary
return all(key in my_dict for key in keys)
# Example usage:
my_dictionary = {"key1": ... | 15,628 |
To split a list on a specified value, we first need to iterate through the list and identify the indices where the value occurs. We can store these indices in a list called `indices`. Then, we can use the `indices` list to split the list into sublists, where each sublist is separated by the specified value.
Here's how... | Write a Python function `split_list_by_value` that splits a list on a specified value. The function takes two parameters: a list called `lst` and a value called `v` to split the list on. The function should return a list of tuples, where each tuple represents a sublist of `lst` that is separated by `v`. If there are no... | Here is a Python function `split_list_by_value` that splits a list at each occurrence of a specified value. The function processes the list and returns a list of tuples with the desired sublists:
```python
def split_list_by_value(lst, v):
# Initialize an empty list to hold the sublists
sublists = []
#... | 15,629 |
Here is a Python function that implements this approach:
```python
def flatten_nested_structure(nested_structure):
"""
Flattens a nested data structure that contains a list of dictionaries,
each with a key named `items` that maps to a list of strings. Returns
a new list of all the strings, including th... | You are given a nested data structure that contains a list of dictionaries, each with a key named `items` that maps to a list of strings. You need to create a function that takes this data structure as input and returns a new list of all the strings, including those nested within the inner lists.
You can use any built... | To tackle the problem of extracting strings from a nested data structure, where the structure consists of a list of dictionaries each containing a list of strings under a key named `items`, we can implement a recursive function.
Here’s a step-by-step outline of the approach:
1. Define the main function that will be ... | 15,630 |
Here's a simple implementation of the `log_shape_volume` function in Python:
```python
import math
def log_shape_volume(shape, volume):
"""
Logs the shape and its volume, and returns the logarithm of the volume.
Parameters:
shape (str): The shape of the volume.
volume (float): The volume.
Re... | Develop a Python function `log_shape_volume` that takes a shape as a string and a volume as a float, logs the shape and its volume, and returns the logarithm of the volume. The function should throw an exception if the volume is negative. The function should log the shape and volume to a file called `shape_volume.log` ... | Here's a Python function `log_shape_volume` that meets your requirements. This function takes a shape as a string and a volume as a float, logs the shape and volume to a file, and returns the logarithm of the volume. Additionally, if the volume is negative, it raises a `ValueError`. I've also included a docstring and a... | 15,631 |
Here is an example implementation of a Python function using the `sqlite3` library:
```python
import sqlite3
from typing import List, Tuple
def get_table_columns(db_path: str) -> List[Tuple[str, str, str]]:
"""
Returns a list of tuples containing the table name, column name, and column type in each table of t... | Write a Python function to inspect a SQLite database and return the name and type of each column in each table. The function should take the database path as an argument and return a list of tuples, where each tuple contains the table name, column name, and column type. | You can create a Python function that uses the `sqlite3` module to connect to the SQLite database and retrieve the table and column information. Below is a function that accomplishes this:
```python
import sqlite3
def inspect_sqlite_db(db_path):
"""
Inspect a SQLite database and return the name and type of ea... | 15,632 |
```python
import csv
def convert_csv_to_int_list(path, max_rows=1000, skip_rows=0):
with open(path, "r") as f:
reader = csv.reader(f)
for _ in range(skip_rows):
next(reader)
return [[int(item) for item in row] for row in reader][:max_rows]
``` | Write a Python function to convert a CSV file containing columns of numerical data to a list of lists of integers.
The function should accept the following arguments:
- `path` - the path to the CSV file
- `max_rows` - the maximum number of rows to be read (default: 1000)
- `skip_rows` - the number of rows to be skippe... | Certainly! Below is a Python function that reads a CSV file, skips a specified number of rows, and converts the remaining data into a list of lists of integers. The function uses the `csv` module for reading the CSV file and handles potential exceptions that may arise during the conversion process.
```python
import cs... | 15,633 |
Here's the implementation of the function:
```python
import json
def format_and_write_json(input_string):
key_value_pairs = input_string.split(",")
data = {}
for key_value_pair in key_value_pairs:
key, value = key_value_pair.split("=")
data[key] = value
json_string = json.dumps(data, i... | Write a Python function that takes a string as input and formats it as a JSON object and saves it to a file. The input string should be a comma-separated list of key-value pairs. For example, given `"name=John,age=30,city=New York"` as input, the function should return the following JSON object and save it to the file ... | You can create a Python function that takes a comma-separated string of key-value pairs, converts it into a dictionary, and then saves it as a JSON object in a file. Here's how you can achieve this:
```python
import json
def save_to_json(input_string, filename='output.json'):
# Split the input string into key-val... | 15,634 |
You can use a Python decorator to attach a class attribute to a function and return the same function with the class attribute attached.
Here's how you could do it:
```python
def with_class_attribute(attribute):
def decorator(func):
func.attribute = attribute
return func
return decorator
``` | Write a Python decorator that attaches a class attribute to a function, and returns the same function with the class attribute attached. | Certainly! In Python, a decorator is a function that wraps another function to enhance or modify its behavior. To create a decorator that attaches a class attribute to a function, we can define a decorator that takes an attribute name and value, and sets that attribute on the function.
Here’s an example of how to crea... | 15,635 |
To solve this problem, we can use the `str.format` method to join the strings in `strs` with separator `sep`. We can also use default values for `strs` and `sep` to make the function more versatile.
Here's how you can implement the function in Python:
```python
def join_and_format(strs=["a", "b", "c"], sep=" "):
... | In this problem, assume you have a list of strings `strs` and a string `sep` representing a separator. Write a Python function that takes these as parameters and returns a string by joining the strings in `strs` with separator `sep` and then formatting it using the `str.format` method. The function should have default ... | Here's a Python function that meets the requirements specified in your problem. The function `join_and_format` takes a list of strings and a separator and uses the `str.join` method to concatenate the strings with the specified separator. It also has default values to accommodate the assertions provided.
Here's the co... | 15,636 |
You can create a Python function that finds the longest string by concatenating all the provided strings in different orders.
Here's how you could do it:
```python
def longest_concatenated_string(string_list):
longest_string = ''
for i in range(len(string_list)):
for j in range(i + 1, len(string_list)... | Write a Python function that takes in a list of strings and returns the longest string which can be formed by concatenating all the strings from the list in any order. If no such sequence exists, return an empty string.
Your code should pass the following test case:
```python
string_list = ['abc', 'def', 'ghi']
longes... | To achieve the task of finding the longest string that can be formed by concatenating the strings in the list, we can use a simple approach. Since string concatenation can happen in any order, we can sort the strings in such a way that when we concatenate them, the result is the lexicographically largest string possibl... | 15,637 |
Here's an implementation of the `normalize_address` function in Python:
```python
import re
def normalize_address(address: str) -> str:
address = address.strip()
address = address.upper()
address = re.sub(r'\W', ' ', address)
address = re.sub(r'\s+', ' ', address)
return address
``` | Create a Python function `normalize_address(address)` that takes a string representing a postal address as input and returns a normalized version of the address. The function should remove any leading and trailing whitespace from the address, and convert it to uppercase. Additionally, the function should replace any no... | Certainly! Below is the implementation of the `normalize_address` function that adheres to your specifications. It cleans and normalizes the address by removing extra spaces, converting to uppercase, and replacing non-alphanumeric characters with spaces.
```python
import re
def normalize_address(address):
# Remov... | 15,638 |
The function should take a dictionary of data and return a JSON string and its size. The JSON string should be serialized using the JSON library and should support both types of data. Additionally, the function should also return a tuple of two elements, the first being the JSON string and the second being the size of ... | Design a Python function `encode_data_for_communication(data)` that takes a dictionary of data and returns a JSON string that can be used to send it as a POST request to a remote server through an API. The JSON string should support both types of data and should be serialized using the JSON library. Additionally, the f... | To implement the `encode_data_for_communication(data)` function, we'll use the `json` library to serialize the dictionary into a JSON string. We'll also compute the size of the resulting JSON string in bytes. Here's how you can do this:
```python
import json
def encode_data_for_communication(data):
# Serialize th... | 15,639 |
The key to solving this problem is to ensure that each randomly generated filename is unique by using a `set` data structure to store the filenames as they are generated. You will need to generate random filenames until you get a unique one. There is a chance that you will not be able to generate 100 unique filenames, ... | Build a Python function `random_file_names` that returns a list of 100 randomly generated filenames with the extension '.txt' while ensuring that no two files share the same name. In other words, the function should return a list of 100 distinct filenames.
Each filename should be a combination of 10 random lowercase E... | You can create a Python function `random_file_names` that generates 100 unique filenames with the desired characteristics. Here’s a complete implementation using the `random` and `string` modules.
Here's the complete code:
```python
import random
import string
def random_file_names(count=100):
# Create a set to ... | 15,640 |
```python
import numpy as np
def sparse_matrix_calc(A, B):
A = np.nan_to_num(A)
B = np.nan_to_num(B)
mult = A * B
add = A + B
sub = A - B
return (mult, add, sub)
``` | Write a Python function `sparse_matrix_calc(A, B)` that takes two sparse matrices in the form of `numpy.ndarray` objects `A` and `B`, and performs element-wise multiplication, addition, and subtraction between them. The function should return a tuple of three `numpy.ndarray` objects, representing the results of multipl... | To perform element-wise operations on sparse matrices represented as `numpy.ndarray` objects, you can leverage NumPy's capabilities for element-wise calculations. You need to handle the sparse nature of the matrices, which means you'll only want to consider non-zero elements in the calculations to improve efficiency. H... | 15,641 |
Here's how you can implement the function:
```python
def case_insensitive_filter(dict_list, comparison_key):
filtered_list = []
for dictionary in dict_list:
if dictionary["key"].lower() == comparison_key.lower():
filtered_list.append(dictionary)
return filtered_list
``` | Create a Python function to filter out all the None values from a list of dictionaries. The function should apply a case-insensitive string comparison, comparing the `key` attribute of the dictionaries with the given `comparison_key`. Return the filtered list, which should include only dictionaries that match the compa... | Certainly! Below is a Python function that filters out dictionaries from a list based on a case-insensitive comparison of their `key` attribute with a specified `comparison_key`. It removes dictionaries where the `key` is `None` or does not match the `comparison_key`.
```python
def filter_dictionaries(dicts, compariso... | 15,642 |
The `convert_cp1252_to_unicode` function will take a byte string as input, and convert it to a Unicode string. To do this, it will first check if the byte string contains invalid bytes in the range 0x80~0x9F. If it does, it will replace those bytes with the appropriate Unicode characters.
Here is the implementation of... | Write a function `convert_cp1252_to_unicode` that takes a byte string as an argument and converts it to a Unicode string. The byte string may contain invalid bytes that are in the range of 0x80~0x9F. Your function should replace them with the appropriate Unicode characters. | To convert a byte string encoded in CP1252 encoding to a Unicode string while handling invalid bytes (specifically the ones in the CP1252 range of 0x80 to 0x9F), you can create a mapping for these invalid byte values. In CP1252, bytes in the range of 0x80 to 0x9F are typically control characters or special symbols that... | 15,643 |
Here's how we can implement this:
```python
def transform_to_first_letter_as_symbol(data, rule):
transformed_data = []
for element in data:
for rule_letter, rule_symbol in rule:
if element.startswith(rule_letter):
transformed_data.append(rule_symbol)
break
... | Create a Python function `transform_to_first_letter_as_symbol(data, rule)` to transform the given data to the first letter as symbol. The function should process the data according to the given rule, which is a list of tuples, where each tuple represents a rule to transform the data. The first element of the tuple is a... | You can achieve the desired functionality by defining the `transform_to_first_letter_as_symbol` function according to the specified rules. This function will iterate over the provided `data` and check each element against the list of rules. If a rule matches, the corresponding transformation will be applied. If no rule... | 15,644 |
To create a Python function that reads the contents of a file and creates a dictionary from it, you can follow these steps:
1. Open the file for reading using `open(file, 'r')`.
2. Initialize an empty dictionary `dictionary` to store the key-value pairs.
3. Read each line from the file using `readline()`.
4. Split the... | Write a Python function `read_dictionary(file)` that creates a dictionary from the contents of a file. The file should contain one word per line, where the first word is the key and the rest of the words are the values. The function should return a dictionary of key-value pairs, where the value is a list of the words f... | To create a function that reads from a file and constructs a dictionary from its contents, we can follow these steps:
1. Open the file for reading.
2. Read each line of the file.
3. Split each line into a key and its corresponding values.
4. Store the key and its values in a dictionary.
Here is the implementation of ... | 15,645 |
To sort the keys of a JSON object, you'll need to perform the following steps:
1. Convert the JSON object to a Python dictionary.
2. Extract the keys from the dictionary.
3. Sort the keys in ascending order.
4. Create a new dictionary with the sorted keys and their corresponding values from the original dictionary.
5.... | Write a Python function named sort_json_object_keys to sort the keys of a JSON object in ascending order. The function takes a single argument, which is a JSON object (dictionary) to be sorted. The function should return a new JSON object with the keys sorted in ascending order. Do not modify the original JSON object. | To achieve the task of sorting the keys of a JSON object (which is represented as a Python dictionary), we can create a function named `sort_json_object_keys` that takes a dictionary as an argument. The function will create a new dictionary with the keys sorted in ascending order, and return that new dictionary.
Here’... | 15,646 |
Here is the implementation of the `float_equal` function:
```python
import math
def float_equal(a: float, b: float) -> bool:
if math.isnan(a) or math.isnan(b):
return False
diff = abs(a - b)
return diff <= 1e-10
``` | Implement a Python function `float_equal` that takes two floating point numbers and returns `True` if they are equal within a tolerance of 1e-10. The function should return `False` otherwise.
Handle NaNs (Not a Number) properly: if either number is NaN, the function should return `False`.
Your code should pass the fo... | To implement the `float_equal` function that compares two floating point numbers with a specified tolerance and properly handles NaNs, we can follow these steps:
1. **Check for NaN**: We will use the `math.isnan()` function to determine if either of the numbers is NaN.
2. **Calculate the absolute difference**: We will... | 15,647 |
Here's how you can implement this function:
```python
def encode_integer_to_chars(value: int) -> str:
if value == 0:
return chr(63)
encoded_chars = []
while value > 0:
chunk = (value & 31) + 63
value >>= 5
if value > 0:
chunk |= 32
encoded_chars.append(c... | Here is a dictionary:
```python
data = {
"a": "01100001",
"b": "01100010",
"c": "01100011",
"d": "01100100",
"e": "01100101",
"f": "01100110",
"g": "01100111",
"h": "01101000",
"i": "01101001",
"j": "01101010",
"k": "01101011",
"l": "01101100",
}
```
For the value of ea... | To convert the binary values in the given `data` dictionary to their corresponding hexadecimal representations and sort the dictionary based on those values, we can follow these steps:
1. Convert each binary string to an integer.
2. Convert the integer to a hexadecimal string.
3. Create a new dictionary with the keys ... | 15,648 |
To write a Python function that returns prime factors of a given integer, we can use the following steps:
1. Validate that the input is a positive integer.
2. Initialize a list to store the prime factors.
3. Check if `n` is a prime number by dividing it by all integers between 2 and `n - 1`.
4. If `n` is prime, return... | Write a Python function named `get_prime_factors` that takes an integer `n` as input and returns a list of prime factors. The function should raise a `ValueError` if `n` is not a positive integer.
Your code should pass the following assertions:
```python
assert get_prime_factors(4) == [2, 2]
assert get_prime_factors(2... | Here's a Python function named `get_prime_factors` that meets the specified requirements. This function calculates the prime factors of a given positive integer `n` and raises a `ValueError` if `n` is not a positive integer.
```python
def get_prime_factors(n):
if n <= 0 or not isinstance(n, int):
raise Val... | 15,649 |
To create such a function, we can iterate over the list of dictionaries and check if the `parent_id` key exists. If it does, we add the `parent_id` to the parent set. If it does not, we add the `id` key to the child set.
```python
def get_parent_child_mappings(dict_list):
parents = set()
children = set()
f... | Create a Python function named `get_parent_child_mappings` that takes a list of dictionaries as input, where each dictionary represents a child object and has a `parent_id` key. The function should return two sets: one set containing all parent IDs, and the other set containing all child IDs. The function should also e... | Certainly! Below is a Python function named `get_parent_child_mappings` that achieves what you've described. It processes a list of dictionaries, extracts parent and child IDs, and ensures that parent IDs are included even if they do not have corresponding children in the input list.
```python
def get_parent_child_map... | 15,650 |
Here's how we can implement this:
```python
def truncate_or_pad(string, length):
if len(string) <= 0:
return string
elif len(string) > length:
return string[:length]
else:
return string.ljust(length, ' ')
```
In this implementation, we first check if the string's length is less tha... | Write a Python function `truncate_or_pad` that takes a string and truncates it to a specific length. The function should truncate the string if its length is greater than the given length, or pad it with spaces if its length is less than the given length. If the string's length is exactly equal to the given length, the... | Certainly! Here is a Python function `truncate_or_pad` that follows your specifications:
```python
def truncate_or_pad(string, length):
# Early exit if the string's length is less than or equal to zero
if len(string) <= 0:
return string
if len(string) > length:
# Truncate the string if... | 15,651 |
Here is a Python function that implements this approach:
```python
def fibonacci_last_digit(n: int) -> int:
"""
Calculates the last digit of the nth Fibonacci number using dynamic programming.
"""
fib_last_digits = [0, 1]
for i in range(2, n + 1):
fib_last_digits.append((fib_last_digits[i ... | Given a number `n`, write a function that calculates the last digit of the `n`th Fibonacci number. The function should use dynamic programming to calculate the last digit of each Fibonacci number from 0 to `n` in one pass, and then return the last digit of the `n`th Fibonacci number.
Your code should pass the followin... | You can achieve this by implementing a function that utilizes dynamic programming to calculate the last digit of Fibonacci numbers efficiently. The key observation is that you only need the last digit of the previous two Fibonacci numbers to compute the last digit of the current Fibonacci number.
Here's a Python func... | 15,652 |
1. Check if the dictionary is empty. If it is, return the maximum integer.
2. If the dictionary is not empty, get the minimum and maximum values by iterating through the keys and comparing the values.
3. If the minimum and maximum values are the same, then return a list of the key and value.
4. Otherwise, return a list... | Create a Python function to get the minimum and maximum values from a dictionary, where the keys are unique and can be sorted. The function should first check if the dictionary is empty, and return the maximum integer if so. Otherwise, it should get the minimum and maximum values by iterating through the keys and compa... | Here is a Python function that meets the specified requirements:
```python
def get_min_and_max_values(d):
if not d:
return float("inf")
min_key = min(d, key=d.get)
max_key = max(d, key=d.get)
min_value = d[min_key]
max_value = d[max_key]
if min_value == max_value:
... | 15,653 |
Here's how you can implement it:
```python
import numpy as np
def get_matrix_norm(tensor):
"""
Computes the Frobenius norm of a tensor using NumPy.
"""
return np.sqrt(np.sum(np.square(tensor)))
``` | Write a Python function `get_matrix_norm` that takes a tensor as input and computes its Frobenius norm. The function should perform matrix arithmetic operations like addition, subtraction, and multiplication.
Your code should pass the following test case:
```python
tensor = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
... | To compute the Frobenius norm of a matrix (or tensor in this case), we take the square root of the sum of the absolute squares of its elements. The formula for the Frobenius norm \( ||A||_F \) of a matrix \( A \) is given as:
\[
||A||_F = \sqrt{\sum_{i=1}^{m}\sum_{j=1}^{n} |a_{ij}|^2}
\]
Here's a Python function `get... | 15,654 |
To determine if two line segments in 2D space intersect, you need to check if they overlap. There are different ways to do this, such as using the intersection of their endpoints.
Here's one way to implement this in Python:
```python
def line_segments_intersect(segment_1, segment_2):
p1, p2 = segment_1
q1, q2... | Given two line segments in 2D space, determine if they intersect. Each line segment is represented by an array of two points that define its endpoints. Return true if the line segments intersect or false otherwise. | To determine whether two line segments intersect in 2D space, we can use the orientation method combined with the concept of bounding boxes to effectively check for intersection. Each line segment can be represented by its two endpoints.
Here's how you can do it:
1. **Define the points**: Let the line segments be rep... | 15,655 |
Here's an implementation of the `get_rank` function using binary search:
```python
def get_rank(nums, target):
left = 0
right = len(nums) - 1
while left <= right:
middle = left + (right - left) // 2
if nums[middle] >= target:
right = middle - 1
else:
left = m... | Develop a Python function named `get_rank` that takes a list of integers `nums` and returns the index of the first number in the list that is greater than or equal to a given target number `target`. If no such number exists or the list is empty, return `-1`.
For example, if `nums = [1, 2, 5, 7, 9]` and `target = 6`, t... | To solve the problem of finding the index of the first number in a list that is greater than or equal to a given target number, we can create a function named `get_rank`. This function will iterate through the list of integers and check each number against the target value, returning the index of the first number that ... | 15,656 |
To extract the first word from a file, we can use the `with open` statement to open the file in read mode and use the `readline()` method to read a single line from the file. Then, we can use the `split()` method to split the line into a list of words and return the first word from that list.
Here is a Python function... | Write a function called `extract_first_word_from_file` that takes a single argument which is a path to a text file. The function should return the first word in the file. You can assume that a single word will be on each line. | Here is a Python function called `extract_first_word_from_file` that reads a text file and returns the first word it finds. The function assumes that each line of the file contains a single word.
```python
def extract_first_word_from_file(file_path):
try:
with open(file_path, 'r') as file:
firs... | 15,657 |
To achieve this task, we can use the `defaultdict` class from the Python `collections` module. A `defaultdict` is a special type of dictionary that allows you to specify a default value for a key that does not exist. This is useful in our case because we can set the default value to be an empty list, which is then appe... | Write a Python function `add_new_element_to_dict` that accepts two keyword arguments: `default_dict` and `new_element`. The `default_dict` argument is a dictionary with default values. The `new_element` argument is a single key-value pair that represents a new element to be inserted into the dictionary. If the new key ... | Here’s a Python function called `add_new_element_to_dict` that meets your requirements:
```python
def add_new_element_to_dict(default_dict, new_element):
if not isinstance(new_element, dict) or len(new_element) != 1:
raise ValueError("new_element must be a dictionary with a single key-value pair.")
... | 15,658 |
Here is the implementation of the Python function using Python type annotations and tuple unpacking:
```python
from typing import List, Tuple
def convert_coords(coords: List[List[int]]) -> List[Tuple[int, int]]:
return [(x, y) for x, y, _ in coords]
```
The function `convert_coords` takes a list of lists of 3D c... | Create a Python function that takes a list of lists: `[[x1, y1, z1], [x2, y2, z2], [x3, y3, z3]]` of 3D coordinates, and returns a list of tuples: `[(x1, y1), (x2, y2), (x3, y3)]` of 2D coordinates.
Implement the function logic using Python type annotations to ensure the correctness of the input and output data types.... | Here is the implementation of the function that converts a list of 3D coordinates into a list of 2D coordinates, along with type annotations and tuple unpacking:
```python
from typing import List, Tuple
def convert_coords(coords: List[List[float]]) -> List[Tuple[float, float]]:
# Using a list comprehension to cre... | 15,659 |
Here's how you could do it:
```python
def create_question_answer_pair(user_id, question, answer):
return f"{user_id}: {question}? {answer}"
``` | Write a Python function that takes a `user_id` string, a `question` string, and an `answer` string as input, and returns a question-answer pair in the format: `"{user_id}: {question}? {answer}"`. | Certainly! Below is a Python function that achieves this:
```python
def create_qa_pair(user_id: str, question: str, answer: str) -> str:
return f"{user_id}: {question}? {answer}"
# Example usage
user_id = "user123"
question = "What is the capital of France"
answer = "The capital of France is Paris."
qa_pair = cr... | 15,660 |
Here's how we can implement this:
```python
def pairwise_generator(iterable):
for item, next_item in zip(iterable, iterable[1:]):
yield item, next_item
if len(iterable) % 2 == 1:
yield iterable[-1], iterable[-1]
``` | Write a Python function `pairwise_generator(iterable)` that takes an iterable and returns a generator object. The generator object should iterate over the iterable in pairs and yield the current item and the next item. If the iterable has an odd number of elements, the last element should be yielded twice. Use `zip` an... | Sure! Below is the implementation of the `pairwise_generator` function that meets the specified requirements using `zip` and a generator expression.
```python
def pairwise_generator(iterable):
# Create an iterator from the iterable
it = iter(iterable)
# Create pairs using zip and the iterator, also handle ... | 15,661 |
To create a Python function that takes two integer arguments and returns their product, you can use the `*` operator to multiply the two numbers. If any of the input parameters is not an integer, you can raise a `TypeError` exception with the message `"Input must be integers."`.
Here's how you could create the `create... | Create a Python function `create_product(x: int, y: int)` that takes two integer arguments and returns their product. If any of the input parameters is not an integer, the function should raise a `TypeError` exception with the message `"Input must be integers."` | Here is a Python function that fulfills your requirements:
```python
def create_product(x: int, y: int) -> int:
"""Returns the product of two integers.
Raises:
TypeError: If either of the inputs is not an integer.
"""
if not isinstance(x, int) or not isinstance(y, int):
raise TypeError... | 15,662 |
You must use the Newton-Raphson method to implement the calculation. The function needs to return the result as a float with a precision of 2 digits after the decimal point. The initial estimate `(x + n / x) / 2` and the formula `(x + n / x) / 2` are provided.
Here's how you could implement the function using the Newt... | Write a Python function to calculate the square root of a positive number. The function should return the result as a float with a precision of 2 digits after the decimal point. You must use the Newton-Raphson method to implement the calculation.
Use `(x + n / x) / 2` as an initial estimate and calculate the square ro... | Certainly! Below is the Python function that calculates the square root of a positive number using the Newton-Raphson method. The function includes detailed docstrings to document its inputs, outputs, and working.
```python
def square_root(n):
"""
Calculate the square root of a positive number using the Newton... | 15,663 |
To solve this challenge, you can utilize the conditional expression to determine whether to format the given string or not. Python provides a convenient way to handle conditional statements using the `if-else` expression.
Here's how you can implement the `format_string_with_conditional` function in Python:
```python
... | Develop a Python function `format_string_with_conditional` that takes a string `s` and returns a formatted string based on a given conditional expression. The function should use a conditional expression to determine whether to format the string or not.
If the conditional expression evaluates to True, the function sho... | You can create the function `format_string_with_conditional` as specified. This function takes a string and a conditional expression as arguments, and it formats the string based on the evaluation of that expression. Here's how you can implement this:
```python
def format_string_with_conditional(s, condition):
"""... | 15,664 |
Here's how you could implement the `approximate_sqrt()` function in Python:
```python
def approximate_sqrt(x: float, tol: float) -> float:
"""
Approximates the square root of a non-negative floating-point number within a tolerance.
Args:
- x (float): The non-negative floating-point number.
- tol (... | Write a Python function `approximate_sqrt(x: float, tol: float) -> float` to approximate the square root of a non-negative floating-point number `x`, within a tolerance `tol`. The function should employ Newton's iterative method to compute the square root, with the initial guess `x / 2`. The function should return the ... | Here is a Python function that approximates the square root of a non-negative floating-point number using Newton's iterative method. The function accepts a number `x` and a tolerance `tol`, returning the approximate square root within the specified tolerance.
```python
def approximate_sqrt(x: float, tol: float) -> flo... | 15,665 |
Here is a possible implementation:
```python
def is_http_client_error(status_code: int) -> bool:
return divmod(status_code, 100)[0] == 4
``` | Write a Python function `is_http_client_error` that takes an integer `status_code` as an argument and returns `True` if it matches any of the following status codes:
1xx---Informational
2xx---Success
3xx---Redirection
4xx---Client error
5xx---Server error
Your code should pass the following assertions:
```python
asse... | Sure! You can define the function `is_http_client_error` to check if the given status code falls within the client error range (4xx). The function will return `True` if the status code is in the 400-499 range, and `False` otherwise.
Here's the implementation:
```python
def is_http_client_error(status_code: int) -> b... | 15,666 |
In this case, the instructions are a bit more complex. You first need to understand what the function is supposed to do and then think about how to implement it.
The function takes a list of people, which should be represented as a list of dictionaries. Each dictionary should have two keys: `name` and `age`. The funct... | Write a Python function `get_average_age` that takes a list of people as input and returns their average age. The function should first check if the input is a valid list of people. If it is not, the function should raise a `TypeError`. Each person in the input list should be represented as a dictionary with two keys: ... | Certainly! Below is a Python function `get_average_age` that meets the specified requirements:
```python
def get_average_age(people):
# Check if the input is a list
if not isinstance(people, list):
raise TypeError("Input must be a list of people.")
total_age = 0
count = 0
# Iterate th... | 15,667 |
You can create a Python function to swap all adjacent elements of a list of integers using tuple unpacking and destructive assignment. By using tuple unpacking, you can easily swap the elements without creating any temporary variables.
Here's how you could do it:
```python
def swap_adjacent_elements(nums):
for i ... | Write a function `swap(nums)` to swap all adjacent elements of a list of integers. For example, given the input `[1, 2, 3, 4]`, the function should return `[2, 1, 4, 3]`. You are allowed to use tuple unpacking to swap the elements, and you are encouraged to use destructive assignment for efficiency. Name the function a... | Here is a Python function named `swap_adjacent` that takes a list of integers and swaps all adjacent elements. The function handles cases where the list has an odd number of elements by leaving the last element in its original position if there's no adjacent element to swap with.
```python
def swap_adjacent(nums):
... | 15,668 |
To achieve this task, you can use the built-in `json` module to load the JSON file into a Python dictionary, then use the `html` module to remove the HTML tags from the string values of the dictionary.
Here's how you can solve the problem:
```python
import json
from html.parser import HTMLParser
def load_json_conten... | Write a Python script to read the content from a JSON file and convert it to a Python dictionary. Return the content as a string after stripping out all HTML tags. | To read content from a JSON file, convert it to a Python dictionary, and then strip out all HTML tags, you can use the following Python script. This script uses the built-in `json` module to read the JSON file and the `re` module from the standard library to strip HTML tags.
Here's a complete Python script for this ta... | 15,669 |
To design a Python function to process a sequence of length 10 by a batch size of 3 and return a list of lists, you can follow these steps:
1. Define a `lambda` function to create a batch of `n` elements from a given sequence `l` and starting index `i`, using `l[i:i+n]`.
2. Determine the number of batches required bas... | Design a Python function to process a sequence of length 10 by a batch size of 3, and return a list of lists. The function should take a list `l` and a batch size `n` as input and return a list of lists. The first batch should be from `l[0]` to `l[2]`, the second batch should be from `l[3]` to `l[5]`, and so on. The la... | You can create a function that processes the list into batches of size `n` by using a lambda function within a list comprehension. Below is a Python function that does this:
```python
def batch_process(l, n):
# Create a lambda function to generate the batches
batch_creator = lambda i: l[i:i + n]
# Use list... | 15,670 |
Here's an example of how you can implement the function using conditional code and list comprehension in Python:
```python
class ModelLayer:
def __init__(self, name):
self.name = name
def initialize_layers(layer_names):
if not layer_names:
return []
return [ModelLayer(name) for name in lay... | Create a Python function to initialize a list of `ModelLayer` objects. The input to the function is a list of strings that represent the names of the layers to be initialized. The function should first check if the input list is empty. If it is, then the function should return an empty list. Otherwise, it should initia... | Certainly! Below is a Python function that meets your requirements. It checks if the input list is empty, and if not, it uses list comprehension to create a list of `ModelLayer` objects.
For the purpose of this code, I will assume that a `ModelLayer` class is defined elsewhere in your codebase.
Here is the implement... | 15,671 |
First, you need to understand the structure of the input dictionary and what values you need to extract. The `id`, `name`, `address`, `date_of_birth`, and `country` keys are required.
Here's how you can create the function:
```python
def extract_features_from_data(data):
features = {
'id': [data['id']],
... | Write a function `extract_features_from_data(data)` that receives a dictionary object and returns a new dictionary of features. The function must extract the following values from the input dictionary:
- `id`
- `name`
- `address`
- `date_of_birth`
- `country`
The function should also wrap each value in a list. | Certainly! Below is an implementation of the function `extract_features_from_data(data)` that extracts the specified values from a dictionary and returns them wrapped in a list:
```python
def extract_features_from_data(data):
# Creating a new dictionary to hold the extracted features
extracted_features = {
... | 15,672 |
Here is the implementation of the function in Python:
```python
def shift_bits(n: int) -> int:
if n < 0:
return n << 1
elif n > 0:
return n >> 1
else:
return 1
``` | Write a function that takes an integer, `n` and performs the following steps:
1. If `n` is negative, shift its bits to the left by 1.
2. If `n` is positive, shift its bits to the right by 1.
3. If `n` is zero, set its bits to 1.
Your code should pass the following assertions:
```python
assert shift_bits(0) == 1
asser... | You can implement the function `shift_bits` using conditional statements to handle each case for the integer `n`. Here's how you can do it:
```python
def shift_bits(n):
if n < 0:
# If n is negative, shift its bits to the left by 1
return n << 1
elif n > 0:
# If n is positive, shift its ... | 15,673 |
Here is a Python function that implements this approach:
```python
def highlight_match(text: str, match: str) -> str:
"""
Highlights a substring `match` in the given `text` string by surrounding it with a pair of asterisks.
"""
highlighted_text = text.replace(match, f'**{match}**')
return highlight... | Write a function `highlight_match(text, match)` that takes a string `text` and a substring `match`, and returns a copy of `text` with the `match` substring highlighted. To highlight `match` in the output, surround it with a pair of asterisks `**` on either side.
For example, the function should return `**match**` when... | You can achieve this by using the `replace` method of strings in Python. The following function `highlight_match` takes a string `text` and a substring `match`, and returns a modified version of `text` with the `match` substring surrounded by asterisks.
Here's how you can implement the function:
```python
def highlig... | 15,674 |
The `gradient_descent_step_size` function takes four arguments: `x` (the current point), `gradient` (the gradient at the current point), `step_size` (the desired step size), and `max_step_size` (the maximum allowed step size). The function then performs the following actions:
1. Assert that `x`, `gradient`, and `step_s... | Write a Python function `gradient_descent_step_size(x, gradient, step_size, max_step_size=1)` that calculates and returns the step size for gradient descent. Here, `x` is the current point, `gradient` is the gradient at the current point, and `step_size` is the desired step size, which should be a positive float. The f... | Here's a Python function called `gradient_descent_step_size` that implements the requirements you described. The function takes the current point `x`, the `gradient` at that point, the desired `step_size`, and an optional `max_step_size`. It includes assertions to validate the inputs.
```python
def gradient_descent_st... | 15,675 |
1. Parse the input string using a regular expression.
2. Extract the name and address from the input string using the regular expression groups.
3. Validate the extracted values. Raise an exception if the input string is empty or malformed.
4. Return the tuple `(name, address)`.
Here is the implementation using Python... | Write a Python function that takes a string in the following format: "name: address" and returns a tuple `(name, address)` where `name` and `address` are the corresponding parts.
For example, given `input = ": 123 Main St"` as input, the function should return `("", "123 Main St")` as output. The function should raise... | Certainly! Below is a Python function that meets your specifications. The function checks for the format of the input string, splits it into `name` and `address`, and handles exceptions for empty or malformed inputs.
```python
def parse_name_address(input_str):
# Check if the input string is empty
if not input... | 15,676 |
To find the center point of a given screen resolution, you need to know the screen's width and height. Once you have those, you can calculate the center coordinates as the half of the width and height.
To calculate the position of an element with a given width and height to be centered in the screen, you need to subtr... | Write a Python function to determine the center point of a given screen resolution and calculate the position of an element with a given width and height to be centered in the screen. Given a screen resolution as a tuple of two integers, `screen_width` and `screen_height`, and the width and height of an element to be c... | You can achieve this by creating a Python function that takes the screen resolution and the dimensions of the element as parameters. The function will compute the center point of the screen and then determine the top-left corner position of the element by subtracting half of the element's width and height from the cent... | 15,677 |
To write a Python function `save_pickle(obj, filepath)` that saves a Python object to the specified file path in binary format using pickle, follow these steps:
1. Extract the directory path, file name, and extension from the filepath.
2. Check if the directory path exists, and throw a `FileNotFoundError` if it does n... | Write a Python function `save_pickle(obj, filepath)` that saves a Python object to the specified file path in binary format via pickle. The function should raise a `FileNotFoundError` if the file path does not exist or a `TypeError` if the object's type is not supported. Include type hints in the function definition to... | Certainly! Below is a Python function `save_pickle` that saves a Python object to a specified file path using the pickle module. The function includes type hints for clarity, and it raises a `FileNotFoundError` if the specified directory does not exist, and a `TypeError` if the object's type is not supported for pickli... | 15,678 |
To solve this problem, we can use the following steps:
- Compute the optimal coefficients `w` that minimize the sum of squared errors.
- Create a linear regression function `f(x)` that takes an input `x` and returns the predicted `y` value.
- Return the linear regression function `f(x)`.
Here is a Python function that... | Create a Python function that takes a 2D NumPy array `X` and a 1D NumPy array `y`, and return a linear regression function `f(x)` that minimizes the sum of squared errors between the actual `y` values and the predicted `y` values computed by `f(x)`. | To create a linear regression function that minimizes the sum of squared errors between the actual `y` values and the predicted values, we can use the normal equation from linear regression.
Here's how to implement this in Python using NumPy:
1. Compute the coefficients (weights) using the normal equation.
2. Create... | 15,679 |
To convert a tuple of indices (i, j) in a matrix to a single index in a corresponding one-dimensional array, follow these steps:
1. Compute the offset of (i, j) from the top-left corner: `offset = i * N + j`. This is the number of elements in the matrix that precede (i, j).
2. Compute the array index: `array_index = o... | Write a Python function `convert_matrix_index_to_array_index` that converts a tuple of indices in a matrix to a single index in a corresponding one-dimensional array. Assume the matrix dimensions are (M, N).
Your code should pass the following assertions:
```python
assert convert_matrix_index_to_array_index(0, 1, 1, 2... | To convert a matrix index (i, j) into a corresponding index for a one-dimensional array, you can use the following formula:
\[ \text{array\_index} = i \times N + j \]
where \( i \) is the row index and \( j \) is the column index, and \( N \) is the total number of columns in the matrix.
Using this formula, we can d... | 15,680 |
To create a dictionary where each key is an object's id, you can iterate through the list of objects, and for each object, check if its id already exists in the dictionary. If it does, then continue to the next object; otherwise, add the object to the dictionary using its id as the key.
Here's how you can implement th... | Write a Python function `create_dict(objects)` that takes a list of objects and returns a dictionary where each key is the object's id and the value is the first object with that id. Here's an example:
```python
objects = [Obj(1, "a"), Obj(2, "b"), Obj(1, "c")]
assert create_dict(objects) == {1: Obj(1, "a"), 2: Obj(2... | To create a function `create_dict(objects)` that takes a list of objects and constructs a dictionary with the object's ID as the key and the first occurrence of that object as the value, you will first need to define the structure of the `Obj` class. Here's how you can implement this:
```python
class Obj:
def __in... | 15,681 |
To implement the `pop_all` function in the given format, we can follow these steps:
1. Define an empty list to store the popped elements.
2. While the list is not empty:
a. Call `lst.pop()` to remove the last element of the list.
b. Append a tuple `(True, element)` to the result list, where `element` is the po... | Python has a function `list.pop()` that removes an element from the end of a list and returns it. If the list is empty, the function raises an IndexError. However, I want to return an empty list in this case instead of raising an error. Can you help me write a function `pop_all(lst)` that takes a list and returns all e... | Sure! You can create the `pop_all(lst)` function that will implement this logic. The function will pop all elements from the list until it is empty, while also handling the case when it tries to pop from an empty list.
Here's how you can implement this function:
```python
def pop_all(lst):
result = []
while T... | 15,682 |
Here is the implementation of the function:
```python
import math
def calculate_altitude_difference(lat1, lon1, lat2, lon2, radius):
"""
Calculate the difference in altitude between two points on the Earth's surface.
Parameters:
lat1: Latitude of the first point (degrees)
lon1: Longitude of the f... | Write a Python function to calculate the difference in altitude between two points on the Earth's surface. The function should accept the latitude and longitude coordinates of the two points and a radius (in meters) of the Earth. The function should calculate the distance between the two points using the Haversine form... | Certainly! Below is the Python function that calculates the difference in altitude between two points on the Earth's surface using the Haversine formula for distance calculation. This function assumes that altitude values are provided in meters.
```python
import math
def haversine(lat1, lon1, lat2, lon2, radius):
... | 15,683 |
Here's a Python implementation of the function:
```python
def get_top_n_words_from_dict(word_dict, n):
sorted_dict = sorted(word_dict.items(), key=lambda item: item[1], reverse=True)
return sorted_dict[:n]
``` | Create a Python function `get_top_n_words_from_dict(word_dict, n)` to return the top `n` pairs of words and their frequencies from a given dictionary. The dictionary has words as keys and their frequencies as values. The function should sort the dictionary in descending order by frequency, then return the top `n` pairs... | You can achieve this by using the built-in `sorted` function in Python along with a lambda function to sort the dictionary items based on frequency. Here's the implementation of the `get_top_n_words_from_dict` function:
```python
def get_top_n_words_from_dict(word_dict, n):
# Sort the dictionary by frequency in de... | 15,684 |
Here's an implementation of the `get_leaf_values` function:
```python
def get_leaf_values(trie, prefix=""):
leaf_values = []
try:
for key, value in trie.items():
if not value: # If the value is an empty dictionary, it's a leaf node
leaf_values.append(prefix + key)
... | Implement a Python function `get_leaf_values(trie, prefix="")` that retrieves all leaf values in a trie data structure. The function should take two arguments: `trie`, a trie data structure represented as a dictionary; and `prefix`, a string that represents the current path in the trie (defaulted to ""). The function s... | To implement the `get_leaf_values` function for a trie data structure, we will recursively traverse the trie, accumulating leaf node values into a list. A leaf node in this context is a node that has no children, meaning its associated value is an empty dictionary.
Here’s the implementation:
```python
def get_leaf_va... | 15,685 |
To achieve this, you can create a dictionary and iterate over each character in the list using a for loop. The key of the dictionary will be the character itself, and the value will be set to 0. You can use a default dictionary from the `collections` module to handle various types of characters, including non-ASCII cha... | Develop a Python function `create_char_set(chars)`, where `chars` is a list of characters in the form of strings. The function should return a dictionary consisting of all characters in `chars` as keys with a default value of 0.
The function should be able to handle various types of characters, including non-ASCII cha... | You can create the `create_char_set` function as described. This function will take a list of character strings and return a dictionary where each character is a key and its corresponding value is set to 0. Here is how you can implement this function in Python:
```python
def create_char_set(chars):
return {char: 0... | 15,686 |
To write a function that will return a list of the specified attribute if it exists on an object, we need to use reflection to access the attribute on each object in the list and handle the cases where the attribute is `None` or not accessible.
The `default_value` and `attribute_name` arguments provide a way to specif... | I want to write a function that will take a list of objects and return a list of the specified attribute (given by the `attribute_name` argument) if it exists on the object. If not, or if the attribute is `None`, the function should replace the value with the provided `default_value`, if specified. The function should ... | You can create a function that accomplishes this in Python using the following approach. The function will iterate over the list of objects, try to access the specified attribute, handle potential `AttributeError`, and manage the default value appropriately.
Here’s how you can write such a function:
```python
def get... | 15,687 |
To convert a list of key-value pairs into a dictionary, you can use a `for` loop to iterate through each pair and add it to the dictionary.
Here's an example:
```python
def convert_pairs(pairs):
dictionary = {}
for pair in pairs:
key, value = pair.split()
dictionary[key] = float(value)
r... | I need to convert a list of key-value pairs into a dictionary. The key-value pairs are stored in a text file, and the values are all numerical. When you read the file, you need to use `.split()` to separate the key from the value. Use `float` to convert the value string into a float.
Your code should pass the followin... | You can create a function called `convert_pairs` that takes a list of strings, where each string consists of a key and a value separated by a space. The function will split each string, convert the value to a float, and construct a dictionary from these pairs.
Here’s how you can write the function:
```python
def conv... | 15,688 |
Here is one way to implement the function:
```python
def categorize(elements):
first_list, second_list = [], []
moved_elements = set()
for element in elements:
if element['difference'] >= 0:
first_list.append(element['name'])
else:
second_list.append(element['name']... | Given a collection of `n` elements, where each element is a dictionary with three keys: `name`, `difference`, and `coefficient`, the function should return a list of two lists. The first list contains the names of all elements where the `difference` value is greater than or equal to zero, in descending order of `differ... | To solve the problem, we will define a function that processes a list of dictionaries as specified. The function will separate the elements into two lists based on their `difference` values, update the `difference` values accordingly when elements are moved between lists, and finally return the names in the desired ord... | 15,689 |
Implementing the `DirectoryFilter` class involves two key steps:
1. The class should have a constructor `__init__` that takes an `extension` parameter and saves it as an instance variable.
2. The `__contains__` method should be implemented to check if the provided path points to a file with the configured extension. T... | Implement a Python class `DirectoryFilter` that filters files based on their extension, similar to the `DirectoryFilter` class in the Python standard library `fnmatch`. The class should implement a `__contains__` method that takes a path string and returns `True` if the path points to a file with the configured extensi... | To implement a `DirectoryFilter` class that filters files based on their extensions and supports the `__contains__` method for checking if a path matches the specified extension, we can follow this design:
1. **Initialization**: The class will take a single extension during initialization. This can be specified with o... | 15,690 |
To implement a BFS approach, you will need to explore the graph layer by layer. You will use a queue to store the nodes to be explored and a set to track which nodes have been visited. You will start by adding the starting node to the queue and the set, and then begin iterating through the queue until it is empty. For ... | Implement a function that determines if two given nodes in a graph are connected by a path, using a Breadth-First Search (BFS) approach. Your function should take three arguments: the starting node, the target node, and a list of edges that make up the graph. The list of edges is a list of pairs, where each pair repres... | To implement the function `bfs_path` that determines if there is a path between two nodes in an undirected graph using a Breadth-First Search (BFS) approach, we can follow these steps:
1. **Initialize a queue** for BFS, starting with the starting node.
2. **Use a set** to keep track of visited nodes to avoid revisitin... | 15,691 |
Here's an implementation of the `time_to_epoch_date()` function:
```python
import datetime
def time_to_epoch_date(timestamp):
timestamp_datetime = datetime.datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S.%f')
unix_epoch_date = str(int(timestamp_datetime.timestamp()))
return unix_epoch_date
``` | Write a Python function `time_to_epoch_date(timestamp)` that takes a string representing a datetime and returns an integer representing the corresponding Unix Epoch date as a string. The input timestamp string must be in the format 'YYYY-MM-DD HH:MM:SS.ms', where the milliseconds are optional.
Your code should pass th... | To write the `time_to_epoch_date(timestamp)` function, we will use the Python `datetime` module to parse the timestamp and convert it to a Unix Epoch time, which is the number of seconds since January 1, 1970. Below is the implementation that meets the specified requirements.
```python
import datetime
def time_to_epo... | 15,692 |
Here's how you can implement this:
```python
def convert_to_float_or_none(x):
if not x:
return []
try:
result = []
for item in x:
float_item = float(item)
result.append(None if float_item < 0 else float_item)
except ValueError:
raise ValueError("List... | Write a Python function that takes a list of integers `x` and returns a list of floating-point numbers where the items that are less than 0 are replaced by `None`. If `x` is empty, the function should return an empty list. If `x` contains non-numeric values (e.g., strings), the function should raise a `ValueError` indi... | You can achieve this by implementing a function that checks each element in the list, converting it to a float if it's a valid number, and replacing negative values with `None`. Here's the implementation:
```python
def convert_and_filter(x):
if not isinstance(x, list):
raise ValueError("Input must be a lis... | 15,693 |
To write a Python function that returns the contents of a file as a string, you can follow these steps:
1. Handle the case where the file does not exist by returning `None`.
2. Open the file in read-only mode using the `open()` function.
3. Read the contents of the file using the `read()` method, and return it as a st... | Write a Python function `get_file_contents(filename)` that takes a `filename` as input and returns the contents of that file as a `str`. If the file does not exist, return `None` without printing an error message.
Your code should pass the following test case:
```python
contents = get_file_contents('test.txt')
assert ... | You can implement the `get_file_contents` function as follows. This function will attempt to open the specified file and read its contents. If the file does not exist, it will catch the `FileNotFoundError` and return `None`. Here's the code:
```python
def get_file_contents(filename):
try:
with open(filenam... | 15,694 |
To extract the host name from a URL, we need to parse the URL using a library that can handle different URL formats. One such library is the `urlparse` module from the standard library.
Here's how we can implement the `get_host` function using `urlparse`:
```python
from urllib.parse import urlparse
def get_host(url)... | Write a Python function `get_host(url)` to extract the host name from a URL. The function should handle any valid URL and return the host name without the scheme or port number.
For example, given `url = 'https://www.example.com:8080/path/to/file.html?param=123'`, the function should return `'www.example.com'`. | You can use Python's `urllib.parse` module to easily extract the host name from a given URL. Below is the implementation of the `get_host` function that fulfills the requirement:
```python
from urllib.parse import urlparse
def get_host(url):
# Parse the URL
parsed_url = urlparse(url)
# Extract the ho... | 15,695 |
To solve this problem, we can use regular expressions to search for integers represented by the prefix `int:` in a list of strings. Regular expressions are a powerful tool for pattern matching and allow us to define complex patterns for strings.
Here is a possible implementation of the `search_int` function using regu... | Develop a Python method to search for an integer in a list of strings. The integer is represented by a string with a prefix `int:`. For example, `['2', 'int:8', 'int:4']` contains two integers `2` and `8`. The function should return a list of all integers it found.
# | You can create a Python method to search for integers represented by a prefix `int:` in a list of strings. The method will iterate through the list, check if each string starts with the prefix `int:`, and if so, it will convert the corresponding substring to an integer and add it to the results.
Here's a sample implem... | 15,696 |
Here is a Python function that implements this approach:
```python
from typing import Callable
def is_bijection(f: Callable[[int], int]) -> bool:
"""
Returns True if `f` is a bijection (one input maps to at most one output and
each possible output is the image of at least one input) and False otherwise.
... | Write a Python function `is_bijection(f)` that takes a function `f` as input and returns `True` if the function is a bijection (each input corresponds to exactly one output and vice versa) and `False` otherwise. A function `f` is a bijection if it is both injective (one input maps to at most one output) and surjective ... | To determine whether a given function \( f \) is a bijection, we need to check if it is both injective and surjective.
1. **Injective (One-to-One)**: A function \( f \) is injective if different inputs map to different outputs. This means \( f(a) = f(b) \) implies \( a = b \).
2. **Surjective (Onto)**: A function \(... | 15,697 |
Here's how you could do it:
```python
def get_average_sales_volume(data, month):
if month not in data:
return 0.0 # Month does not exist in data, return 0.0
sales_volumes = data[month] # Get the list of sales volumes for the given month
average_volume = sum(sales_volumes) / len(sales_volumes) #... | Assume there is a Python dictionary `data` consisting of sales record keyed by the month, in the format of `yyyy-mm`. Given the dictionary `data` and a string variable `month` representing a year and month in the same format, write a function to calculate the average sales volume for the given month. If the month does ... | Certainly! Below is a Python function that takes a dictionary of sales records and a month string as inputs, and calculates the average sales volume for the specified month. If the month does not exist in the dictionary, the function will return 0.0.
```python
def average_sales(data, month):
# Check if the month e... | 15,698 |
Here's how you can implement this function in Python:
```python
def min_path_sum_dp(matrix):
m, n = len(matrix), len(matrix[0])
dp = [[0] * n for _ in range(m)]
dp[0][0] = matrix[0][0]
for i in range(1, m):
dp[i][0] = dp[i - 1][0] + matrix[i][0]
for j in range(1, n):
dp[0][j] = dp[0... | Given a 2D array `matrix`, write a function to return the minimum path sum from the top-left corner to the bottom-right corner. The minimum path sum is the sum of all values along the path with the smallest sum. You can only move either right or down along the path. | To find the minimum path sum in a 2D array (matrix) from the top-left corner to the bottom-right corner, we can use dynamic programming. The idea is to create a new 2D array where each cell `(i, j)` will store the minimum path sum to reach that cell from the starting cell `(0, 0)`.
Here’s a function that implements th... | 15,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.