query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with creating a Python function that simulates a simple game. The game involves generating a sequence of numbers and checking for a specific pattern within the generated sequences.
Write a Python function called `check_pattern` that takes in two parameters:
- `pattern`: A list of integers representing t... | ```python
import random
def generate_sequence():
return [random.randint(1, 5) for _ in range(5)]
def check_pattern(pattern, num_sequences):
for _ in range(num_sequences):
sequence = generate_sequence()
if pattern in [sequence[i:i+len(pattern)] for i in range(len(sequence) - len(pattern) + 1)]:... | magicoder | python |
You are tasked with creating a Python script to automate the process of generating an RSA key pair and then using the public key to encrypt a message. Your script should utilize the `cryptography` library to achieve this. The RSA key pair should be generated with a key size of 2048 bits. The encrypted message should be... | ```python
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import rsa, padding
import base64
# Step 1: Generate an RSA key pair with a key size of 2048 bits
private_key = rsa.generate_private_key(
... | magicoder | python |
You are tasked with implementing a Python function that can parse and validate a range specified in a specific format. The range format is represented as a string in the form "[start..end]", where start and end are integers. The function should be able to parse the range string and return a set of all the integers with... | ```python
def parse_range(range_str):
start, end = map(int, range_str[1:-1].split('..'))
return {start, end, float(start), float(end)} | set(range(start + 1, end)) | {float(i) for i in range(start + 1, end)}
# Unit tests
import unittest
class TestRangeParser(unittest.TestCase):
def test_parse_range(self):... | magicoder | python |
You are tasked with implementing a custom error handling mechanism for a programming language. The language has a class `AttrDeclarationNode` representing an attribute declaration in the abstract syntax tree (AST). The code snippet provided is a call to the superclass constructor within the `AttrDeclarationNode` class.... | ```python
class ASTError(Exception):
def __init__(self, message, line, column):
super().__init__(f"AST Error at line {line}, column {column}: {message}")
class AttrDeclarationNode:
def __init__(self, idx, typex, expression, line, column):
if line <= 0 or column <= 0:
raise ASTError... | magicoder | python |
You are tasked with creating a Java method to generate a KeyStore from a set of key and certificate files. The method should take in the directory paths for the key and certificate files, along with their respective file extensions, and return a new KeyStore containing the key entries specified by the arguments.
You a... | ```java
import java.nio.file.*;
import java.security.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
public class KeyStoreGenerator {
static KeyStore createKeyStoreFromPemDirectories(Path keyDirPath, String keyE... | magicoder | java |
You are tasked with implementing a program to calculate the integral image of a given grayscale image. An integral image, also known as a summed area table, is a data structure used to efficiently calculate the sum of pixel values within a rectangular region of an image. The integral image is defined as follows: each p... | ```python
from typing import List
def calculate_integral_image(grayscale_image: List[List[int]]) -> List[List[int]]:
height, width = len(grayscale_image), len(grayscale_image[0])
integral_image = [[0 for _ in range(width)] for _ in range(height)]
# Calculate the first row of the integral image
integra... | magicoder | python |
You are tasked with implementing a function that removes duplicate elements from a tuple while preserving the original order of elements. You are given a code snippet that partially implements the function. Your task is to complete the implementation of the function according to the specified requirements.
You need to... | ```python
def remove_duplicated_keep_order(value_in_tuple):
new_tuple = []
for i in value_in_tuple:
if i not in new_tuple:
new_tuple.append(i)
return tuple(new_tuple)
```
The provided solution completes the implementation of the `remove_duplicated_keep_order` function. It iterates throu... | magicoder | python |
You are tasked with implementing a token generation system for a secure access control mechanism. The system should generate a unique access token based on the given MAC address and store it in a database. Additionally, the system should handle access requests and return the generated token if the request is authorized... | ```python
import random
import string
class Certify:
@staticmethod
def generate_token(mac_addr):
# Generate a unique access token based on the MAC address
token_length = 16
characters = string.ascii_letters + string.digits
access_token = ''.join(random.choice(characters) for _ i... | magicoder | python |
You are tasked with implementing a simple testing framework for asynchronous code in Swift. Your goal is to create a function that allows developers to test asynchronous operations using closures and completion handlers. The function should take a closure containing the asynchronous operation and a completion handler t... | ```swift
func testAsyncOperation(operation: @escaping () -> Void, timeout: TimeInterval, completion: @escaping (Bool) -> Void) {
var isCompleted = false
// Perform the asynchronous operation
operation()
// Create a dispatch queue to handle the timeout
let queue = DispatchQueue.global()
queue.a... | magicoder | swift |
You are working on a multimodal attention mechanism for a neural network model. The code snippet provided is a part of the multimodal attention module. The `multimodal_embed_net` function takes in concatenated images `cat_images` and produces a multimodal memory tensor. This tensor is then transposed and used as key an... | ```python
def multimodal_attend(query, key, value):
# Calculate attention scores
scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(query.size(-1))
# Apply softmax to obtain attention weights
att_weights = F.softmax(scores, dim=-1)
# Calculate the attended query using the atte... | magicoder | python |
You are tasked with implementing a custom data structure in C# that mimics the functionality of a stack but also keeps track of the minimum element in the stack at any given time. You need to design a class `MinStack` that supports the following operations:
1. `Push(int x)`: Add element x to the stack.
2. `Pop()`: Remo... | ```csharp
// The MinStack class is implemented using the provided code snippet.
// It maintains two separate stacks: one for the actual elements and another for tracking the minimum element at any given time.
// The Push operation adds the element to the stack and updates the minimum stack if the added element is small... | magicoder | csharp |
You are tasked with creating a Python function that processes and updates parameters in a configuration management system. The function will take in two parameters: `existing_parameter` and `args`. The `existing_parameter` is a dictionary containing information about an existing parameter, while `args` is a dictionary ... | ```python
def update_parameter(existing_parameter, args):
if existing_parameter['Parameter']['Value'] != args['Value']:
# Call update_parameter function with appropriate client and module information
(changed, response) = update_parameter(client, module, args)
if args.get('Description'):
... | magicoder | python |
You are working on a traffic management system for a smart city. The system includes modules for automatic lane detection and vehicle classification. The code snippet provided is from the main module that imports functionality from the `auto_lane` and `mfkd` modules.
Your task is to create a function that processes th... | ```python
from collections import defaultdict
def generate_traffic_report(image_data):
report = []
for i, image in enumerate(image_data, start=1):
lane_markings = detect_lanes(image)
vehicles = defaultdict(int)
for vehicle_image in lane_markings:
vehicle_type = classify_vehi... | magicoder | python |
You are tasked with implementing a function to parse a JSON file containing Wycheproof test data and extract specific information from it. The Wycheproof project is a collection of test cases for cryptographic algorithms, and the JSON file contains data about these test cases. Each test case includes information about ... | ```swift
import Foundation
struct WycheproofTest: Codable {
let algorithm: String
let numberOfTests: UInt32
}
func extractTestInformation(fromFile file: String) -> [(algorithm: String, numberOfTests: UInt32)]? {
guard let fileURL = Bundle.main.url(forResource: file, withExtension: "json") else {
r... | magicoder | swift |
You are tasked with implementing a custom output stream for different data types in C++. The given code snippet is a part of a larger program that handles different types of expressions and their corresponding values. The `AST_Expression` enum represents different types of expressions, and the `dv` variable holds the v... | ```cpp
#include <iostream>
#include <iomanip>
class CustomOutputStream {
public:
void output(std::ostream& os, AST_Expression::ExpressionType type, const AST_Expression::DataValue& dv) {
switch (type) {
case AST_Expression::EV_ushort:
os << dv.u.ushort_val;
break... | magicoder | cpp |
You are tasked with creating a program that processes a web page containing song lyrics and extracts the verses from it. The given code snippet is a part of the program that accomplishes this task. The snippet uses the `requests` library to fetch the web page and the `BeautifulSoup` library to parse the HTML content. I... | ```python
import requests
from bs4 import BeautifulSoup
def extract_verses_from_url(url):
response = requests.get(url)
if response.status_code == 200:
soup = BeautifulSoup(response.text, 'html.parser')
verses = [verse.get_text(separator="\n").strip() for verse in soup.find_all("font", size=True... | magicoder | python |
You are tasked with creating a Python class that manages form fields and choices for a web application. Your task is to implement the `FormManager` class with specific functionalities.
The `FormManager` class should have the following attributes and methods:
Attributes:
- `simpleformfield_salutation`: A field to stor... | ```python
class FormManager:
def __init__(self):
self.simpleformfield_salutation = []
def add_salutation_choices(self, salutations):
for salutation in salutations:
choice = {"label": salutation, "value": salutation}
self.simpleformfield_salutation.append(choice)
def... | magicoder | python |
You are tasked with creating a program that processes a given string to remove any escaped characters and extract the content within double quotes. Your program should handle both single and double quotes as delimiters and should return a list of extracted strings.
Create a function `extract_strings` that takes a stri... | ```python
import re
def extract_strings(input_str):
extracted_strings = []
pattern = r'(?<!\\)(?:"(?:\\.|[^"])*"|\'(?:\\.|[^\'])*\')'
matches = re.findall(pattern, input_str)
for match in matches:
extracted_strings.append(match.strip('\'').strip('\"'))
return extracted_strings
# Test the f... | magicoder | python |
You are tasked with implementing a reinforcement learning algorithm for a simple environment. The environment is represented by a class `Environment`, which has a method `step(action)` that takes an action as input and returns the next state, reward, and a boolean indicating whether the episode has ended. The `step` me... | ```python
class Agent:
def __init__(self, env):
self.env = env
def take_action(self, state):
# Implementing a simple random policy for illustration purposes
import random
possible_actions = [0, 1, 2] # Assuming 3 possible actions
action = random.choice(possible_actions)... | magicoder | python |
You are tasked with creating a Python test case using the `unittest` framework to test a web application using Selenium and ScreenPy. The test case should involve a series of actions performed by an actor on a web page, and assertions to verify the expected behavior of the web application.
Your task is to write a test... | ```python
import unittest
from selenium.webdriver import Firefox
from screenpy import Actor
from screenpy.abilities import BrowseTheWeb
from screenpy.resolutions import See, ContainsTheText
from screenpy.pacing import act, scene
from tasks.start import Start
from tasks.search_github import SearchGitHub
from questions.s... | magicoder | python |
You are tasked with implementing a function that takes a string as input and returns a modified version of the string based on specific rules. The function should perform the following operations:
1. Convert the input string to title case using the `TextInfo.ToTitleCase` method from the `System.Globalization` namespac... | ```csharp
using System;
using System.Globalization;
public class StringModifier
{
public string ModifyString(string input)
{
TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;
string titleCased = textInfo.ToTitleCase(input);
string[] words = titleCased.Split(' ');
Arr... | magicoder | csharp |
You are working on a project management system that involves creating and managing different types of blocks and receptions. Each block and reception has specific fields that need to be managed through an admin interface. Your task is to create a Django admin interface for the given classes `HbBlockDataAdmin` and `Rece... | ```python
from django.contrib import admin
class HbBlockDataAdmin(admin.ModelAdmin):
fieldsets = [
('BlockData', {'fields': ['ownerBlockId', 'url', 'publicKey', 'createDate']}),
('BlockDComments', {'fields': ['comments']})
]
admin.site.register(HbBlockData, HbBlockDataAdmin)
class ReceptionAd... | magicoder | python |
You are tasked with implementing a function to map points onto a 2D texture. The function should take a set of 3D points representing a spherical surface and map them onto a 2D texture, preserving their spatial relationships. The input points are represented in spherical coordinates (radius, inclination, azimuth), and ... | ```cpp
int vtkSVPlacePointsOnS2::TextureMap()
{
// Assuming inputPoints is a vector of 3D spherical coordinates (radius, inclination, azimuth)
std::vector<Point3D> inputPoints = GetInputPoints(); // Function to retrieve input points
// Perform texture mapping for each input point
for (const auto& point... | magicoder | cpp |
You are given a Java code snippet that attempts to populate a map with the number of animals affected by a certain event. However, the code contains a logical error that prevents it from functioning as intended. Your task is to identify the error and correct the code to accurately populate the map.
The original code s... | The issue in the given code snippet is that the variable `numCount` is being used without being initialized. Additionally, the logic to update the count in the map is incorrect. Below is the corrected code snippet:
```java
Map<Integer, Integer> numAffected = new HashMap<>();
// Assuming 'out' is an instance of a clas... | magicoder | java |
You are tasked with implementing a caching mechanism for an HTTP request handler in a Rust application. The provided code snippet is a part of the implementation for sending an HTTP request and handling the response. Your task is to extend this implementation to incorporate a caching mechanism using the `If-None-Match`... | ```rust
impl RequestHandler {
fn cache_handler(&self) {
let mut request_builder = Client::new()
.get("https://api.example.com/flags")
.header("Content-Type", "application/json")
.header("Authorization", self.sdk_key.clone())
.header("User-Agent", &*crate::USER... | magicoder | rust |
You are tasked with implementing a function to read an image file and perform a specific image processing operation. The function should read the image file using the provided `imread` function and then apply a series of operations to the image. The image processing operations include converting the image to grayscale,... | ```python
import os
import cv2
import numpy as np
from PIL import Image
def imread(filename):
if not os.path.exists(filename):
return None
f = open(filename, 'rb')
# Implementation of image reading using PIL or other libraries can be added here
def process_image(filename):
# Read the image usi... | magicoder | python |
You are working on a Minecraft mod that introduces a new feature to corrupt biomes within the game. The provided code snippet is a part of the mod's source code, written in a custom language that resembles Java. The code snippet includes a mixin class that extends `CorruptorAbstract` and overrides the `corruptBiome` me... | ```java
// CorruptorAbstract.java
public abstract class CorruptorAbstract {
public abstract Biome getBiome();
}
// MixinCorruptorAbstract.java
@Pseudo
@Mixin(CorruptorAbstract.class)
public abstract class MixinCorruptorAbstract {
@Shadow public abstract Biome getBiome();
@Overwrite(remap = false)
publ... | magicoder | java |
You are tasked with implementing a function that reads and processes a series of modules from a given input buffer. Each module is represented by a sequence of characters, and the function must extract and process each module individually. The input buffer is represented as a pair of pointers, `Begin` and `End`, where ... | ```cpp
#include <iostream>
#include <cassert>
// Function to read and process a module from the input buffer
// Returns 0 on success, non-zero on error
int ReadModule(char SizeofPtr, const char* Begin, const char* End) {
if (Begin == nullptr || End == nullptr || Begin > End) {
std::cerr << "Invalid input b... | magicoder | cpp |
You are tasked with implementing a utility function to create an icon object with different sizes based on the provided icon size components. The icon object should have properties for different sizes and a name.
You are given the following code snippet as a reference:
```javascript
import IconCancelSizeXs from './Ic... | ```javascript
function createIcon(sizesObject) {
const icon = { name: sizesObject.name };
for (const size in sizesObject) {
if (size !== 'name') {
icon[size] = sizesObject[size];
}
}
return icon;
}
```
The `createIcon` function iterates through the properties of the `sizesObject` and adds them ... | magicoder | javascript |
You are tasked with simulating a voting system for a contest. The contest has a specific description, and each contestant can receive votes. However, there is a constraint on the number of votes a contestant can receive. Your goal is to implement a function that validates the votes for the contestants based on the cont... | ```python
class Contestant:
def __init__(self, name, vote=0):
self.name = name
self.vote = vote
class UnderVoteException(Exception):
pass
class Contest:
def __init__(self, contest_description):
self.contest_description = contest_description
self.ballot_selections = [Contest... | magicoder | python |
You are tasked with implementing a simple evaluator factory in Python. The factory should allow the creation of evaluators for different types of entities based on their names. The code snippet provided is a function `build_evaluator` that takes a name as input and returns the corresponding evaluator from the `evaluato... | ```python
def build_evaluator(name):
evaluator_factory = {
"entity1": evaluate_entity1,
"entity2": evaluate_entity2
}
if name not in evaluator_factory.keys():
raise ValueError(f'Unknown evaluator name: {name}')
return evaluator_factory[name]
def evaluate_entity1(entity):
# ... | magicoder | python |
You are tasked with implementing a Python function to calculate the probability density function (PDF) of a multivariate normal distribution. The PDF of a multivariate normal distribution is given by the formula:
\[ pdf(\Sigma) = |\Sigma|^{\eta - 1} \]
Where \( \eta > 0 \) is a shape parameter and \( \Sigma \) is the... | ```python
from typing import List
import numpy as np
def multivariate_normal_pdf(Sigma: List[List[float]], eta: float) -> float:
det_sigma = np.linalg.det(Sigma)
pdf = det_sigma ** (eta - 1)
return pdf
```
The `multivariate_normal_pdf` function first calculates the determinant of the correlation matrix \(... | magicoder | python |
You are given a string containing HTML tags and some text. Your task is to write a program to extract the name of the person mentioned in the text enclosed within the `<NAME>` tag. The name will always appear within the `<NAME>` tag and will be followed by the word "began". You need to extract and output this name.
Fo... | ```python
import re
def extract_name_from_html(html_string):
# Define the pattern to match the <NAME> tag and the word "began"
pattern = r'<NAME>(.*?)began'
# Use regular expression to find the name within the <NAME> tag
match = re.search(pattern, html_string)
if match:
# Extract ... | magicoder | python |
You are tasked with implementing a program to process audio files using the MFCC (Mel-frequency cepstral coefficients) feature extraction technique. MFCC is a widely used method in speech and audio processing for extracting features that are well-suited for automatic speech and speaker recognition. In this problem, you... | ```python
import os
from wav2letter.feature import FeatureParams, Mfcc
def process_audio_file(audio_file_path):
# Read an audio file using the provided wav2letter library
# Assume the existence of a function to read the audio file
audio_data = read_audio_file(audio_file_path)
# Initialize the paramete... | magicoder | python |
You are tasked with implementing a Java class that applies a series of transformations to an input XML source using a chain of XSLT templates. Your task is to complete the implementation of the `Transformed` class, which is a subclass of `InputSupplier<SAXSource>`. The `Transformed` class takes an input source and a ch... | ```java
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXSource;
import java.io.IOException;
public class Transformed implements InputSupplier<SAXSource> {
private final InputSupplier<? extends ... | magicoder | java |
You are tasked with creating a web form validation function for a user profile page. The form contains two input fields: one for updating the user's phone number and another for changing the user's password. The HTML code snippet provided below shows the structure of the form:
```html
<div class="row">
<div class="c... | ```javascript
function validateForm() {
var phoneNumber = document.getElementById('input-number').value;
var password = document.getElementById('input-password').value;
// Phone number validation
var phoneNumberRegex = /^\d{10}$/; // Assuming a standard US phone number format
var isPhoneNumberValid = phoneNu... | magicoder | javascript |
You are tasked with implementing a Python class that manages links and their associated data. The class, `LinkManager`, should have the ability to create, update, and synchronize links with a database. Additionally, it should provide a method to run queries and store them for future reference.
Your task is to complete... | ```python
# Sample usage of the LinkManager class
# Create an instance of the database context
class DatabaseContext:
def runQuery(self, query):
# Simulated database query execution
print(f"Executing query: {query}")
# Instantiate the LinkManager with the database context
ctx = DatabaseContext()
li... | magicoder | python |
You are tasked with implementing a Java annotation processor to generate a unique identifier for classes annotated with a custom annotation. The annotation processor should generate a unique identifier for each annotated class and append it to the class name.
You are provided with a code snippet for the custom annotat... | ```java
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;
import javax.tools.JavaFile... | magicoder | java |
You are tasked with implementing a TypeScript class that extends the abstract class `Io<T>`. The abstract class `Io<T>` represents an I/O operation with a generic type `T` and provides methods for interacting with a database. Your task is to create a concrete class `MyIo` that extends `Io<T>` and implements the require... | ```typescript
import { Io } from 'path/to/Io';
class MyIo<T> extends Io<T> {
private data: T;
constructor(_id: string, db: string, dbName: string, data: T) {
super(_id, db, dbName);
this.data = data;
}
async sync(): Promise<void> {
console.log(`Syncing document with ID ${this.... | magicoder | typescript |
You are given an array of integers. Your task is to find the length of the longest increasing subsequence (LIS) within the array. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. An increasing subsequence is a sub... | ```java
public int longestIncreasingSubsequence(int[] nums) {
int n = nums.length;
if (n == 0) {
return 0;
}
int[] dp = new int[n];
Arrays.fill(dp, 1);
int maxcount = 1;
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j]) {
... | magicoder | java |
You are given a number `n`. Your task is to write a program to factorize the number and count the number of divisors it has.
Write a function `factorizeAndCountDivisors` that takes an integer `n` as input and returns the count of divisors of `n`.
For example, if `n = 12`, the factors of 12 are 1, 2, 3, 4, 6, and 12. ... | ```cpp
#include <iostream>
#include <vector>
int factorizeAndCountDivisors(int n) {
int count = 0;
for (int i = 1; i * i <= n; i++) {
if (n % i == 0) {
// If divisors are equal, count only one
if (n / i == i) {
count++;
} else { // Otherwise, count bo... | magicoder | cpp |
You are tasked with creating a custom template tag in Django to generate dynamic CSS classes for menu buttons based on the current application being accessed. The provided code snippet is a simplified version of the custom template tag `menubuttonclass` that takes the current context and an application name as input an... | ```python
from django import template
from django.template import TemplateSyntaxError
register = template.Library()
@register.simple_tag(takes_context=True)
def menubuttonclass(context, appname):
if not appname:
raise ValueError("Application name must be provided")
if not isinstance(appname, str) or n... | magicoder | python |
You are tasked with implementing a function that processes a set of query parameters for grouping search results in a search engine. The function should parse the given parameters and return a formatted string representing the grouping configuration.
The input parameters are provided as a JavaScript object, where the ... | ```javascript
function formatGroupingParameters(params) {
const groupingKeys = [
'group.format',
'group.ngroups',
'group.limit',
'group.truncate',
'group.field',
'group.main',
'group',
'group.sort',
'group.cache.percent',
'group.offset',
];
const formattedPairs = [];
for... | magicoder | javascript |
You are tasked with creating a Python function that simulates a simplified file descriptor management system. A file descriptor is an abstract indicator used to access a file or input/output resource. In this system, file descriptors are represented by integers, and the system should support opening, closing, and readi... | ```python
class FileOpenError(Exception):
pass
class InvalidFileDescriptorError(Exception):
pass
class FileDescriptorManager:
def __init__(self):
self.file_map = {} # Map to store open files and their descriptors
def open_file(self, file_name: str) -> int:
for descriptor, name in sel... | magicoder | python |
You are given a list of strings representing the behavior of children in a classroom. Each string consists of characters 'G' and 'V', where 'G' represents a good kid and 'V' represents a naughty kid. Your task is to write a function that processes this list and returns the count of good kids for each day.
The function... | ```python
def count_good_kids(behavior):
good_kids_count = []
for day in behavior:
good_kids_count.append(day.count("G"))
return good_kids_count
```
The `count_good_kids` function iterates through each day's behavior and uses the `count` method to count the occurrences of 'G' (good kids) in each st... | magicoder | python |
You are tasked with creating a Python class that interfaces with a SHT2X sensor using the I2C protocol. The SHT2X sensor provides temperature and humidity measurements. Your class should be able to read the temperature and humidity values from the sensor and provide methods to retrieve these values.
Your task is to im... | ```python
class SHT2X:
def __init__(self, i2c_address):
self.i2c_address = i2c_address
# Initialize the I2C communication with the sensor using the i2cmod module
# Example: i2cmod.init(i2c_address)
def read_temperature(self):
try:
# Read the temperature from the sens... | magicoder | python |
You are given a list of integers representing the scores of a game. Your task is to write a function that calculates the average score of the game, excluding the highest and lowest scores.
Write a function `calculate_average_score(scores)` that takes in a list of integers `scores` (2 <= len(scores) <= 100) and returns... | ```python
def calculate_average_score(scores):
if len(scores) < 4:
return 0 # Not enough scores to calculate average
total_score = sum(scores) - min(scores) - max(scores)
num_scores = len(scores) - 2 # Excluding the highest and lowest scores
average_score = total_score / num_scores
return... | magicoder | python |
You are tasked with creating a Python class to represent a content item in an educational platform. The class should have the following attributes and functionalities:
Attributes:
- `source_id`: a unique identifier for the content item
- `title`: the title of the content item
- `license`: the license under which the c... | ```python
class HTMLZipFile:
def __init__(self, file_path):
self.file_path = file_path
class ContentItem:
def __init__(self, source_id, title, license, files):
self.source_id = source_id
self.title = title
self.license = license
self.files = files
def add_file(self,... | magicoder | python |
You are tasked with implementing a Swift function that generates a snapshot of a given view in an iOS app. The function should handle waiting for loading indicators and should be set up with the necessary configurations.
You are provided with a code snippet that includes the initial setup and a placeholder for the `sn... | ```swift
func snapshot(_ name: String, waitForLoadingIndicator: Bool) {
if waitForLoadingIndicator {
// Wait for the loading indicator to disappear
let loadingIndicator = XCUIApplication().activityIndicators["loadingIndicator"]
if loadingIndicator.exists {
let loadingIndicatorPre... | magicoder | swift |
You are tasked with implementing a caching mechanism for method calls in a Python class. The class has a special method `__getattr__` that is invoked when an attribute is accessed but not found in the usual way. Your task is to modify the `__getattr__` method to cache and return the desired method when it is accessed.
... | ```python
class MyClass:
def __init__(self):
self._friendCache = {}
def __getattr__(self, attr):
if attr.startswith('friend_'):
if attr not in self._friendCache:
method = getattr(self, attr, None)
if callable(method):
self._friendC... | magicoder | python |
You are tasked with implementing a method to convert input data types into output column types based on certain rules. The input data types can be of different forms, including a product of types or a single type. Your task is to create a method that takes an input data type and returns a list of corresponding output c... | ```java
private List<Schema.Type> convertOutputColumnType(Type type) {
if (type instanceof Product) {
List<Type> types = ((Product) type).getTypes();
return types.stream().map(this::convertType).collect(Collectors.toList());
} else if (type instanceof OpenSearchDataType) {
return Immutab... | magicoder | java |
You are tasked with implementing a function to convert keys in a given JavaScript object to camel case. The function should handle nested objects and arrays within the input object. The keys in the input object are currently in snake_case format and need to be converted to camelCase format.
You are provided with a cod... | ```javascript
function toCamelCase(key) {
return key.replace(/_([a-z])/g, (match, group) => group.toUpperCase());
}
function camelCaseKeys(data) {
if (Array.isArray(data)) {
return data.map(camelCaseKeys);
} else if (typeof data === 'object') {
const result = {};
for (const key in data) {
const... | magicoder | javascript |
You are tasked with implementing a custom class called `CustomRandomForestRegressor` that extends a base class `BaseEstimator`. The `CustomRandomForestRegressor` class should have the following functionalities:
- It should inherit from the `BaseEstimator` class and have an `__init__` method that takes in `features`, `f... | ```python
from sklearn.base import BaseEstimator
from sklearn.ensemble import RandomForestRegressor as RandomForestRegressorImpl
class CustomRandomForestRegressor(BaseEstimator):
def __init__(self, features, fit_target, n_estimators, max_features, **kwargs):
super().__init__(features=features, fit_target=f... | magicoder | python |
You are tasked with implementing a visibility filter for a set of squares in a 2D space. The provided code snippet includes a class method `getVisibleSquares` that takes in an array of squares, space and viewport dimensions, and a location. The `getVisibleSquares` method filters the input squares based on their visibil... | ```typescript
class Square {
constructor(public x: number, public y: number, public size: number) {}
isVisible(viewportBounds: IBounds): boolean {
// Implement the logic to determine if the square is visible within the viewport bounds
const squareBounds: IBounds = {
minX: this.x,
... | magicoder | typescript |
You are tasked with implementing a scale manager for images in a computer vision application. The scale manager has two image pointers, `mdI0Ptr` and `mdI1Ptr`, which can point to either the original unscaled images or the scaled images. The scale manager also has a function `FinalScaleLevel()` that returns a boolean v... | ```cpp
void HandleScaledImage(bool mScaleI0, Image* mdI0Orig, Image* mdI1Orig, Image* mdI0Scaled, Image* mdI1Scaled, Image*& mdI0Ptr, Image*& mdI1Ptr) {
if (scaleManager.FinalScaleLevel()) {
// Use original images
mdI0Ptr = mdI0Orig;
mdI1Ptr = mdI1Orig;
} else {
if (mScaleI0) {
... | magicoder | cpp |
You are tasked with implementing a testing framework for a machine learning library. The provided code snippet is a part of a Python testing function that checks the behavior of different regressors. The `test_estimator_checks` function takes a test function `test_fn` as an argument and performs tests on two instances ... | ```python
def test_estimator_checks(test_fn):
def run_test(name, regressor):
# Perform tests on the regressor's behavior
# Example test: check if the regressor's predictions are within a certain range
predictions = regressor.predict()
assert all(0 <= pred <= 1 for pred in predictions... | magicoder | python |
You are tasked with implementing a 3D visualization tool for mathematical functions using Python. The given code snippet is a part of this tool and involves setting up the data for visualization. The `interp_mc` function is used to perform Monte Carlo interpolation, and the resulting data is used to create a 3D plot. Y... | ```python
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def plot_3d_function(xs, ys, integral, n, m, interp_mc, plot_2d=False):
integral_interp = interp_mc(xs, ys)
xs, ys = np.meshgrid(xs, ys)
zs = [integral, integral_interp, xs**(n+1) * ys**(m+1)]
zs.append... | magicoder | python |
You are tasked with creating a program that reads a text file and counts the occurrences of each word in the file. Your program should then output the word count for each unique word in the file.
Your program should have the following requirements:
- The program should be written in Java.
- The program should read a t... | ```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;
public class WordCount {
public static void main(String[] args) throws IOException {
Map<String, Integer> wordCountMap = new TreeMap<>();
try (BufferedReade... | magicoder | java |
You are tasked with creating a program that can analyze a GitHub repository's README file to extract relevant information. Your program should be able to identify the repository name, author, and a brief description of the project. The README file is assumed to be in Markdown format and may contain various sections and... | ```python
import re
def parseReadme(readme):
result = {}
# Extract repository name and author
match = re.search(r'<reponame>(\w+)/(\w+)', readme)
result["author"] = match.group(1)
result["repository"] = match.group(2)
# Extract description within double quotes
description_match = ... | magicoder | python |
You are tasked with creating a Python function that processes entry point information from distribution files in a given folder. The function should extract the distribution name and version from the file paths, and then create a dictionary mapping each distribution to its version. If the distribution name contains a h... | ```python
import os.path as osp
import glob
import itertools
def process_entry_points(folder: str) -> dict:
distribution_versions = {}
for path in itertools.chain(
glob.iglob(osp.join(folder, '*.dist-info', 'entry_points.txt')),
glob.iglob(osp.join(folder, '*.egg-info', 'entry_points.txt'))
... | magicoder | python |
You are tasked with implementing a custom enumerable class in C# that provides a strided view of an array. The strided view should allow iterating over the array with a specified step size, effectively skipping elements in between. Your task is to create a class `StrideEnumerable<T>` that implements `IEnumerable<T>` an... | ```csharp
using System;
using System.Collections;
using System.Collections.Generic;
namespace WmcSoft.Numerics
{
public class StrideEnumerable<T> : IEnumerable<T>
{
private readonly T[] _array;
private readonly int _stride;
public StrideEnumerable(T[] array, int stride)
{
... | magicoder | csharp |
You are tasked with creating a script to automate the zipping of specific files using a command-line tool. The command-line tool `cross-zip` is used to zip files with specific naming conventions. The snippet provided demonstrates the usage of `cross-zip` to zip two different files with the following naming convention:
... | ```python
def generate_zip_commands(version):
linux_command = f"../node_modules/.bin/cross-zip dwebx-{version}-linux-x64 ../dist/dwebx-{version}-linux-x64.zip"
macos_command = f"../node_modules/.bin/cross-zip dwebx-{version}-macos-x64 ../dist/dwebx-{version}-macos-x64.zip"
return linux_command, macos_comman... | magicoder | python |
You are tasked with creating a Django view function that retrieves and organizes data for rendering a web page. The view function should handle two different types of data: media coverage and data listings. The media coverage data should be ordered by date and grouped by year, while the data listings should be ordered ... | ```python
from django.shortcuts import render
from .models import media_listing, data_listing
def media_coverage_page(request):
media = media_listing.objects.all().order_by('-date')
dateobjs = media_listing.objects.dates('date', 'year', order='DESC')
years = [date.year for date in dateobjs]
return rend... | magicoder | python |
You are given a Python function that takes in a list of integers and returns the maximum sum of a contiguous subarray within the input list. Your task is to analyze the given function and optimize it to achieve a better time complexity.
The given function is as follows:
```python
def max_subarray_sum(arr):
max_su... | To achieve a time complexity of O(n), we can use Kadane's algorithm to optimize the given function. Kadane's algorithm is specifically designed to find the maximum subarray sum in an array with a time complexity of O(n).
Here's the optimized `max_subarray_sum` function using Kadane's algorithm:
```python
def max_suba... | magicoder | python |
You are tasked with creating a Python class that handles HTTP requests and responses. Your class should have a method to send a GET request to a specified URL and return the response text. Additionally, the class should allow for customizing the request by providing options for verifying SSL certificates and setting a ... | ```python
import requests
class HttpRequestHandler:
def __init__(self):
self.session = requests.Session()
def send_get_request(self, url, verify=True, timeout=10):
try:
response = self.session.get(url=url, verify=verify, timeout=timeout)
response.raise_for_status() # R... | magicoder | python |
You are tasked with implementing a Python class that preprocesses text data for input into the FastText algorithm. FastText is a library for efficient learning of word representations and sentence classification. Your task is to complete the implementation of the `PreNodeFeedText2FastText` class, which is a subclass of... | ```python
from cluster.preprocess.pre_node_feed import PreNodeFeed
import os, h5py
import numpy as np
import fasttext
class PreNodeFeedText2FastText(PreNodeFeed):
"""
This class preprocesses text data for input into the FastText algorithm.
"""
def tokenize_text(self, text):
# Tokenize the inpu... | magicoder | python |
You are tasked with creating a custom permission class for a Django REST framework application. The permission class should ensure that a user's worker is associated with the project of a specific todo item. The `Worker` model represents a user's role as a worker in the system, and the `Todo` model represents a task th... | ```python
class IsAssociatedWithTodosProject(permissions.BasePermission):
"""
Ensures that a user's worker is associated with the todo's project.
"""
def has_object_permission(self, request, view, obj):
try:
worker = Worker.objects.get(user=request.user)
if isinstance(ob... | magicoder | python |
You are given a code snippet representing a simplified version of a self-referential class in a programming language. The code snippet is as follows:
```
Self {
}
}
}
```
Your task is to implement the missing parts of the `Self` class to achieve the following functionality:
1. Create a method... | ```java
class Self {
private Map<String, Object> properties;
public Self() {
properties = new HashMap<>();
}
public void addProperty(String propertyName, Object value) {
properties.put(propertyName, value);
}
public Object getProperty(String propertyName) {
return prop... | magicoder | java |
You are tasked with creating a program to manage and store team details in Azure table storage. Your task is to implement a method that stores or updates team details in the Azure table storage. The method should take a `TeamEntity` object as a parameter and return a `Task<bool>` representing whether the team entity wa... | ```csharp
public class TeamEntity
{
// Define properties and fields for the team entity
// Example:
public string TeamId { get; set; }
public string TeamName { get; set; }
// ... other properties
}
public class TeamStorageManager
{
private CloudTable SubmitIdeaCloudTable; // Assume this is init... | magicoder | csharp |
You are tasked with creating a program that processes a given source code file and identifies the lines that do not contain specific keywords. Your program should read the source code file and output the line numbers of the lines that do not contain any of the specified keywords.
Write a function `find_lines_without_k... | ```python
from typing import List
def find_lines_without_keywords(file_path: str, keywords: List[str]) -> List[int]:
line_numbers = []
with open(file_path, 'r') as file:
for line_number, line in enumerate(file, start=1):
if all(keyword not in line for keyword in keywords):
l... | magicoder | python |
You are tasked with creating a service that interacts with a learner matching API to retrieve information about apprenticeship incentives. The learner matching API is accessed using an HTTP client and returns data in JSON format. Your goal is to implement a method that sends a request to the learner matching API and pr... | ```csharp
using Newtonsoft.Json;
using SFA.DAS.EmployerIncentives.Domain.ApprenticeshipIncentives;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
namespace SFA.DAS.EmployerIncentives.Commands.Services.LearnerMatchApi
{
public class LearnerService
{
... | magicoder | csharp |
You are working on a package manager system that handles the retrieval and processing of software packages. The system has a class with methods for retrieving and processing package information. The code snippet provided is a part of the class method that processes package data.
The method iterates through a list of p... | ```python
class PackageManager:
def __init__(self):
self.packages = []
def get_blob(self, merkle):
# Implementation of get_blob method
pass
def read_package(self, blob):
# Implementation of read_package method
pass
def get_builtin_packages(self):
# Impl... | magicoder | python |
You are tasked with implementing a function that simulates the behavior of a text editor's visual-line mode cursor movement. In visual-line mode, the cursor moves to the beginning or end of a visual line, which may differ from the actual line in the file due to word wrapping or other display considerations.
You are gi... | ```python
def visualLineCursorMovement(cpos, ZVM_MODE):
if ZVM_MODE == "VISUAL_LINE":
# Simulate moving to the beginning or end of the visual line
# Replace the following logic with the actual implementation based on the editor's behavior
if cpos % 2 == 0:
return cpos - 5 # Move... | magicoder | python |
You are tasked with implementing a custom logging middleware for a web application using Python and the Tornado web framework. The middleware should extract and log the request ID and authenticated user from incoming HTTP requests. The provided code snippet defines the constants `REQUEST_ID_HEADER` and `AUTH_USER_HEADE... | ```python
import logging
import tornado.web
REQUEST_ID_HEADER = 'X-Request-Id'
AUTH_USER_HEADER = 'X-Auth-User'
class LoggingApplication(tornado.web.Application):
def __init__(self, handlers=None, default_host="", transforms=None, **settings):
super(LoggingApplication, self).__init__(handlers, default_hos... | magicoder | python |
You are tasked with implementing a callback function for handling `#define` directives in a hypothetical programming environment. The provided code snippet outlines the prototype for the callback function `lx_macro_cb`, which is used to process `#define` directives. The function takes in a pointer to user data, the nam... | ```c
typedef int idaapi lx_macro_cb(
void *ud,
const char *name,
const char *params
);
int process_define_directive(void *ud, const char *name, const char *params) {
// Check for null pointers
if (name == NULL || params == NULL) {
return -1; // Error code for null pointer
}
... | magicoder | c |
You are tasked with creating a script to automate the configuration of a Redis server. The script should modify the Redis configuration file to bind to both the localhost (127.0.0.1) and a specific IP address (192.168.25.35), and then restart the Redis service. Your script should achieve this using shell commands.
You... | ```bash
#!/bin/bash
# Output a blank line
echo " "
# Output the word "redis" followed by another blank line
echo "redis"
echo " "
# Use the sed command to modify the Redis configuration file
sed -i 's/bind 127.0.0.1/bind 127.0.0.1 192.168.25.35/' /etc/redis/redis.conf
# Restart the Redis service using systemctl
sys... | magicoder | shell |
You are tasked with creating a program to analyze and visualize data from a SQLite database using Swift. The database contains a table with historical stock price data, including the date and closing price for each day. Your goal is to retrieve the data from the database, process it, and then generate a line chart to v... | ```swift
// Import necessary libraries
import UIKit
import Charts
import SQLite
// Connect to the SQLite database
let path = "/Users/liyafei/db.sqlite3"
let db = try! Connection(path, readonly: true)
let stocks = Table("stocks")
let date = Expression<String>("date")
let closingPrice = Expression<Double>("closing_price... | magicoder | swift |
You are tasked with implementing a custom version control system for a software project. The system should support the following operations:
1. `add_file(file_name, content)`: Add a new file with the given `file_name` and `content` to the version control system.
2. `update_file(file_name, new_content)`: Update the con... | ```python
class VersionControlSystem:
def __init__(self):
self.files = {} # Dictionary to store file versions
def add_file(self, file_name, content):
if file_name in self.files:
self.files[file_name].append(content)
else:
self.files[file_name] = [content]
d... | magicoder | python |
You are tasked with implementing a Python class to manage a hierarchical structure of nodes, similar to a SmartArt diagram in PowerPoint. Each node can have child nodes, and each node can contain text. Your task is to create a Node class and implement methods to add new nodes, set text for a node, and save the entire s... | ```python
class Node:
def __init__(self, text=""):
self.text = text
self.child_nodes = []
def add_child_node(self, text=""):
new_node = Node(text)
self.child_nodes.append(new_node)
return new_node
def set_text(self, text):
self.text = text
def save_to_f... | magicoder | python |
You are working on a music store management system that utilizes Entity Framework for data access. The code snippet provided shows the DbSet properties for various entities in the database context. Each DbSet represents a table in the database.
Your task is to create a method that retrieves the top-selling albums base... | ```csharp
public List<Album> GetTopSellingAlbums(int count)
{
var topSellingAlbums = Albums
.Include(a => a.InvoiceLines)
.OrderByDescending(a => a.InvoiceLines.Sum(il => il.Quantity))
.ThenBy(a => a.Title)
.Take(count)
.ToList();
return topSellingAlbums;
}
```
In the s... | magicoder | csharp |
You are tasked with creating a program that analyzes a given HTML file to count the occurrences of specific Font Awesome icons within the file. Font Awesome icons are represented in HTML using the `<i>` tag with a class attribute specifying the icon to be displayed. The program should read the HTML file and count the o... | ```python
from bs4 import BeautifulSoup
import re
def count_font_awesome_icons(html_file):
with open(html_file, 'r', encoding='utf-8') as file:
html_content = file.read()
soup = BeautifulSoup(html_content, 'html.parser')
icon_classes = [i['class'][0] for i in soup.find_all('i', class_=re.compile(r... | magicoder | python |
You are tasked with implementing a context manager for reading and writing data to an HDF5 file using the `h5py` library in Python. The context manager should handle the opening and closing of the HDF5 file and provide a convenient way to interact with the file's contents.
Your task is to complete the implementation o... | ```python
import h5py
from contextlib import contextmanager
from .file import H5File
@contextmanager
def open_h5file(filename, mode='r', **kwargs):
"""Context manager for reading and writing an HDF5 file as an H5File object.
Parameters
----------
filename : str
The name of the HDF5 file to ope... | magicoder | python |
You are given a Python function `germinate` that takes a set of permutations `subset` as input and returns a new set of permutations. The function is intended to generate a set of permutations by repeatedly applying certain operations to the input set. The operations include taking the inverse of each permutation in th... | ```python
from typing import Set
# Define the type for permutations
TY_PERM = ...
# Define the inverse function for a permutation
def inverse(p: TY_PERM) -> TY_PERM:
...
# Define the composition function for two permutations
def compose(p1: TY_PERM, p2: TY_PERM) -> TY_PERM:
# Implement the composition of per... | magicoder | python |
You are tasked with implementing a Python class for processing and extracting citation information from a given input file. The class contains three private methods: `_cleanup`, `_extract_raw_citation`, and `_extract_citation`. The `_cleanup` method is responsible for deleting a specified directory and logging the acti... | ```python
import shutil
import logging
import html
import json
class CitationProcessor:
def __init__(self, unzipped_directory):
self.unzipped_directory = unzipped_directory
def _cleanup(self):
shutil.rmtree(self.unzipped_directory)
logging.info("cleaned up directory: {}".format(self.un... | magicoder | python |
You are working on a project that involves reasoning over an ontology using the ELK reasoner library in Java. In this project, you need to implement a class that can visit different types of OWL entities and perform specific actions based on their type. The code snippet provided includes imports from the ELK reasoner l... | ```java
import org.semanticweb.elk.owl.interfaces.ElkClassExpression;
import org.semanticweb.elk.owl.interfaces.ElkIndividual;
import org.semanticweb.elk.owl.interfaces.ElkObjectPropertyExpression;
import org.semanticweb.elk.owl.visitors.ElkClassExpressionVisitor;
import org.semanticweb.elk.owl.visitors.ElkIndividualVi... | magicoder | java |
You are tasked with implementing a function to compute the depth from input to output in a digital circuit. The given code snippet is a part of a larger program that models a digital circuit. The `output` class has a method `computeDepthInToOut` that needs to be completed. The `output` class has an integer member varia... | ```cpp
int computeDepthInToOut() {
input* in = getInput();
int depth = 0;
while (in != nullptr) {
depth++;
in = in->getInput();
}
return depth;
}
```
The `computeDepthInToOut` method starts from the output's input and iterates through the input's connections until it reaches a null ... | magicoder | cpp |
You are working on a project that involves managing data using Core Data in Swift. You have a function `inContext` that is intended to retrieve a managed object of a specific type from a given `NSManagedObjectContext`. The function takes the context as a parameter and attempts to retrieve the object using its `objectID... | The issue with the `inContext` function is that it assumes `self` refers to an instance of `NSManagedObject`, but it's not explicitly defined within the function. To fix this issue, we need to ensure that the function is called on an instance of `NSManagedObject`. Additionally, we should handle the possibility of the o... | magicoder | swift |
You are working on a project that involves processing 3D point cloud data from RGB-D images using Python and the Open3D library. As part of the project, you need to manipulate the extrinsic camera transformation matrix and create a new point cloud from the transformed RGB-D image. Your task is to write a function that ... | ```python
import numpy as np
import open3d as o3d
def transform_point_cloud(orgbd, intrinsic, extrinsic, base_state):
# Define the rotation matrices
rotz = ... # Define the rotation matrix rotz
rot_cam = ... # Define the rotation matrix rot_cam
rotxn90 = ... # Define the rotation matrix rotxn90
... | magicoder | python |
You are tasked with implementing a version validation system for a graph database. The system should ensure that updates to nodes within the graph are only allowed if the provided version key matches the current version key of the node being updated.
You are given a `Node` class with the following methods:
- `setGrap... | ```java
public class Node {
private String graphId;
private Map<String, Object> metadata;
public void setGraphId(String graphId) {
this.graphId = graphId;
}
public void setMetadata(Map<String, Object> metadata) {
this.metadata = metadata;
}
public boolean validateUpdateOpe... | magicoder | java |
You are tasked with implementing a login feature for a mobile application using the RxSwift framework. The given code snippet is part of a Swift class that handles the login functionality. The class uses RxSwift's `Driver` and `flatMap` to manage the login process. Your task is to complete the implementation of the log... | ```swift
let logined: Driver<WLBaseResult> = input.loginTaps
.withLatestFrom(uap)
.flatMapLatest { (username, password) in
// Simulate a network request for login
return simulateLoginRequest(username: username, password: password)
.asDriver(onErrorJustReturn: .failure("An error occur... | magicoder | swift |
You are tasked with implementing a class that manages a collection of records and provides functionality to post a new record. The `postRecord` method takes a `Record` object as a parameter and returns an integer representing the status of the posting operation.
The `Record` class has the following attributes:
- `id` ... | ```java
import java.util.HashMap;
class Record {
private int id;
private String data;
public Record(int id, String data) {
this.id = id;
this.data = data;
}
public int getId() {
return id;
}
public String getData() {
return data;
}
}
class RecordManag... | magicoder | java |
You are tasked with implementing a presentation builder module in Rust. The module provides a `PresentationBuilder` struct and a `Presentation` struct for creating and managing presentations.
The `presentation` module contains the `Presentation` struct, which represents a presentation with slides and content. The `bui... | ```rust
// presentation.rs
pub struct Presentation {
slides: Vec<(String, String)>,
theme: String,
}
impl Presentation {
pub fn new(slides: Vec<(String, String)>, theme: String) -> Presentation {
Presentation { slides, theme }
}
pub fn show(&self) {
println!("Presentation Theme: {}... | magicoder | rust |
You are tasked with implementing a function that processes a sequence of numbers and handles potential errors. The function should take an array of integers as input and return a new array with the following modifications:
1. If the input array contains any negative numbers, the function should throw a custom NegativeN... | ```swift
enum NegativeNumberError: Error {
case negativeNumberDetected
}
func processNumbers(_ input: [Int]) throws -> [Int] {
guard !input.isEmpty else {
return []
}
let uniqueSortedNumbers = Array(Set(input.filter { $0 >= 0 })).sorted()
if uniqueSortedNumbers != input {
thro... | magicoder | swift |
You are working on a text processing application, and you need to implement a function that will remove all occurrences of a specific substring from a given string. The function should take two parameters: the original string and the substring to be removed. Your task is to write a function `removeSubstring` that accom... | ```python
def removeSubstring(original: str, substring: str) -> str:
return original.replace(substring, "")
```
The `removeSubstring` function uses the `replace` method of the string to remove all occurrences of the given substring from the original string. The method returns a new string with all occurrences of t... | magicoder | python |
You are tasked with implementing a doubly linked list data structure in C++. The list should support the following operations:
1. `pushTail(int value)`: Add a new node with the given value to the end of the list.
2. `insert(int index, int value)`: Insert a new node with the given value at the specified index in the lis... | ```cpp
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* prev;
Node* next;
Node(int value) : data(value), prev(nullptr), next(nullptr) {}
};
class DoublyLinkedList {
private:
Node* head;
Node* tail;
public:
DoublyLinkedList() : head(nullptr), tail(nullptr) {}
... | magicoder | cpp |
You are tasked with implementing a function that processes a dictionary of game states and returns a modified version of the dictionary based on certain conditions. The function should remove specific game states from the dictionary and update another set with those removed states. The conditions for removal are based ... | ```python
def process_states(nstates: dict) -> dict:
states = nstates.copy() # Create a copy of the input dictionary
dead = [
((b, p1), (a, p2), n)
for ((b, p1), (a, p2)), n in states.items()
if (n == 0 or p1 >= 21 or p2 >= 21)
] # Identify game states that meet removal conditions... | magicoder | python |
You are tasked with implementing a function to retrieve the default output device and its format for audio playback. The function should handle different operating systems and error conditions gracefully.
You are provided with a code snippet that includes a partial implementation of the function for non-Windows system... | ```rust
use anyhow::{anyhow, Context, Result as ResultType};
use cpal::traits::{DeviceTrait, HostTrait};
#[cfg(not(windows))]
fn get_device() -> ResultType<(cpal::Device, cpal::SupportedStreamConfig)> {
let host = cpal::default_host();
let default_device = host.default_output_device().ok_or_else(|| anyhow!("No... | magicoder | rust |
You are tasked with implementing a custom error handling mechanism for a real-time communication (RTC) system. The system has multiple streams, each identified by a non-negative integer stream number. The error handling mechanism should check if the stream number is valid and, if not, provide a descriptive error messag... | ```cpp
#include <iostream>
#include <string>
// Assume the av_err2str function is defined elsewhere
std::string av_err2str(int stream_no);
class StreamErrorChecker {
private:
int stream_no_;
public:
StreamErrorChecker(int stream_no) : stream_no_(stream_no) {}
std::string checkStream() {
if (stre... | magicoder | cpp |
You are tasked with creating a PHP interface for rendering components in a document management system. The interface, `BottomRenderInterface`, extends the `\Hx\Document\Render\ComponentInterface` and includes a method `calculateBottom` that takes an instance of `\Hx\Document\Context\Component\BottomInterface` as a para... | ```php
<?php
use \Hx\Document\Context\Component\BottomInterface;
interface BottomRenderInterface extends \Hx\Document\Render\ComponentInterface {
public function calculateBottom(BottomInterface $bottom);
}
class BottomRenderer implements BottomRenderInterface {
public function calculateBottom(BottomInterface ... | magicoder | php |
You are tasked with implementing an Animation Manager for a smart lighting system. The Animation Manager is responsible for controlling various lighting modes, such as turning the lights on or off, transitioning between different modes, activating night light mode, slow on mode, party mode, and crossfade transition mod... | ```cpp
#include <iostream>
#include <unordered_map>
#include <memory>
#include "animation.hpp"
#include "modes/off.hpp"
#include "modes/on.hpp"
#include "modes/transOffOn.hpp"
#include "modes/transOnOff.hpp"
#include "modes/nightLight.hpp"
#include "modes/slowOn.hpp"
#include "modes/party.hpp"
#include "modes/transCros... | magicoder | cpp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.