query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are working on a robotics project that involves using a Color Sensor to detect and differentiate between various colors. The Color Sensor has a function called `light_up` which sets the brightness of individual lights on the sensor. However, changing the brightness can cause the Color Sensor to switch modes, potent...
```python def determine_mode(current_mode, light_1, light_2, light_3): if light_1 == 0 and light_2 == 0 and light_3 == 0: return 0 # If all lights are set to 0 brightness, always in color detection mode if current_mode == 0 and (light_1 > 0 or light_2 > 0 or light_3 > 0): return 1 # If in colo...
magicoder
python
You are tasked with implementing a function that processes a list of strings and performs a specific operation on each string based on certain conditions. The function should take in a list of strings and return a modified list based on the following rules: 1. If a string contains the word "should" followed by the wor...
```python import re def processStrings(strings): modified_strings = [] for string in strings: modified_string = re.sub(r'should.*?be', 'be', string) modified_string = re.sub(r'always.*?drop', 'always drop', modified_string) modified_strings.append(modified_string) return modified_st...
magicoder
python
You are tasked with implementing a Python class that processes a dataset using the given code snippet as a reference. Your class should handle the dataset-specific fields and perform data processing operations. Your task is to create a class named `DatasetProcessor` with the following requirements: - The class should...
```python class DatasetProcessor: def __init__(self, reader, decoder, num_samples, items_to_descriptions, **kwargs): self.reader = reader self.decoder = decoder self.num_samples = num_samples self.items_to_descriptions = items_to_descriptions self.kwargs = kwargs self...
magicoder
python
You are tasked with implementing a function that casts an attribute to a native PHP type based on the given key and value. The function should handle various data types and return the appropriate native PHP type for the given value. You are given the following function signature to guide your implementation: ```php /*...
```php function castToNativeType(string $key, $value) { switch ($key) { case 'int': case 'integer': return (int)$value; case 'float': case 'double': return (float)$value; case 'bool': case 'boolean': return (bool)$value; cas...
magicoder
php
You are tasked with implementing a hash function that takes a string as input and produces a 64-bit hash value. The hash function should be based on the FNV-1a algorithm, which is a simple and efficient non-cryptographic hash function. The FNV-1a algorithm uses a specific prime number and a seed value to produce the ha...
```rust pub static HASH_SEED: u64 = 1145141919810; pub const FNV_PRIME: u64 = 1099511628211; fn fnv1a_hash(input: &str) -> u64 { let mut hash: u64 = HASH_SEED; for byte in input.bytes() { hash ^= u64::from(byte); hash = hash.wrapping_mul(FNV_PRIME); } hash } fn main() { let input_s...
magicoder
rust
You are tasked with implementing a Python class that simulates a simple cache with a fixed capacity. The cache should support two operations: `get(key)` and `put(key, value)`. The `get(key)` method retrieves the value associated with the given key if the key exists in the cache, and returns -1 if it does not. The `put(...
```python class LRUCache: def __init__(self, capacity): self.capacity = capacity self.cache = {} self.usage_order = [] def get(self, key): if key in self.cache: self.usage_order.remove(key) self.usage_order.append(key) return self.cache[key] ...
magicoder
python
You are tasked with implementing a custom attribute-based sorting mechanism for a collection of objects in C#. The goal is to create a sorting algorithm that can sort objects based on a specified property and direction using the provided `Direction` enum. You are given the following `Direction` enum definition and a s...
```csharp using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; namespace CustomSorting { public static class CustomSort { public static IEnumerable<T> SortByProperty<T>(IEnumerable<T> collection, string propertyName, Direction directio...
magicoder
csharp
You are tasked with implementing a class for managing goods in an e-commerce system. The provided code snippet is a part of the existing implementation and contains some method calls and conditional checks. Your task is to complete the implementation of the `Goods` class by adding the necessary methods and logic to han...
```php class Goods { private $attributes = []; public function Like() { // Implementation for the "like" feature } public function GoodsSpec() { // Implementation for managing goods specifications } public function append($additionalAttributes) { // Logic to append add...
magicoder
php
You are tasked with implementing a custom callback for a machine learning model using the LBANN (Livermore Big Artificial Neural Network) library. LBANN is a deep learning framework designed for high-performance computing environments. In this problem, you will create a callback that monitors the training process and t...
```python import lbann class SaveWeightsOnImprovement(lbann.Callback): def __init__(self, threshold_accuracy, save_path): super().__init__() self.threshold_accuracy = threshold_accuracy self.save_path = save_path self.best_accuracy = 0 def on_validation_end(self, model, epoch, ...
magicoder
python
You are working on a deployment automation system that involves managing a stack of resources. The code snippet provided is a part of the system and contains a function called `run_dependencies_deployment_loop`. This function is responsible for running a deployment loop for the stack's dependencies. Your task is to im...
```python import logging # patch FakeStack.initialize_resources def run_dependencies_deployment_loop(stack, action, initialize=False): def do_run_loop(): # Your implementation of the deployment loop goes here pass # Placeholder for the deployment loop logic def set_stack_status(stack, status)...
magicoder
python
You are tasked with implementing a reward system for a user management system. The system has a class `UserManager` with a method `incrementReward` that takes two parameters: the username of the user and the reward to be incremented. The reward is represented by an emoji, such as '🏅'. The method `incrementReward` shou...
```python class UserManager: def __init__(self): self.user_rewards = {} # Dictionary to store user rewards def incrementReward(self, username, reward): if username in self.user_rewards: self.user_rewards[username] += reward else: self.user_rewards[username] = re...
magicoder
python
You are tasked with implementing a callback system for a gaming server querying interface. The system should handle responses after requesting details on who is playing on a particular server. The interface should support querying individual servers and canceling in-progress queries to avoid potential crashes. Your ta...
```cpp #include <iostream> // Callback interface for receiving responses after requesting details on who is playing on a particular server class IServerQueryCallback { public: // Method for receiving responses after querying an individual server virtual void OnServerResponse(const std::string& serverDetails) =...
magicoder
cpp
You are tasked with implementing a custom generator function in Python that generates a sequence of prime numbers. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Your generator function should yield the next prime number each time it is called. Your task is to ...
```python def prime_generator(): yield 2 # 2 is the first prime number primes = [2] # Store the prime numbers found so far num = 3 # Start checking for primes from 3 while True: is_prime = True for prime in primes: if prime * prime > num: # No need to check beyond the squ...
magicoder
python
You are tasked with implementing a function that processes a list of tuples representing student grades and returns the average grade for each student. Each tuple contains the student's name as a string and a list of their grades as integers. Your task is to write a function `calculate_average_grades` that takes a list...
```python from typing import List, Tuple, Dict def calculate_average_grades(grades: List[Tuple[str, List[int]]]) -> Dict[str, float]: average_grades = {} count_grades = {} for student, grade_list in grades: if student in average_grades: average_grades[student] += sum(grade_list) ...
magicoder
python
You are working on a medical imaging software project and need to implement a landmark transformation algorithm. The code snippet provided is a part of the LandmarkWidget class, which is responsible for updating the properties of glyphs representing landmarks in the 3D space. The LandmarkWidget class has a method calle...
```cpp #include <iostream> #include <Eigen/Dense> // Assuming the use of Eigen library for matrix operations class Inverse { public: void Inverse() { // Implementation of Inverse constructor } void TransformPoint(const Eigen::Vector3d& position, double xyzt[4]) { // Assuming the transform...
magicoder
cpp
You are tasked with implementing a method to list all the keys stored in a secret manager. The secret manager has a method `get_key(name: str) -> Key` that retrieves a specific key by its name. Each key has a `value` attribute, which is a string in the format "prefix:key". The `prefix` indicates whether the key is encr...
```python def list_keys(self) -> list: key_names = [item['name'] for item in self._secret_keys] return key_names ``` The `list_keys` method simply retrieves the names of all the keys stored in the secret manager and returns them as a list. This solution assumes that `self._secret_keys` is a list of dictionarie...
magicoder
python
You are tasked with creating a script to manage a process called "pdb-worker" and "pdb-manager". The script should handle command-line arguments for usage and help, and it should be able to terminate these processes. Your script should accept the following command-line arguments: 1. `-h` or `--help`: Display usage inf...
```bash #!/bin/bash usage() { echo "Usage: script_name [options]" echo "Options:" echo " --help, -h Display this help message" exit 1 } # Check for command-line arguments if [ $# -eq 0 ]; then usage elif [[ "$@" = *--help* ]] || [[ "$@" = *-h* ]]; then usage fi # Terminate running instances of "pdb-w...
magicoder
shell
You are tasked with implementing a ConfigMap class that interacts with an API to manage configuration data. The class should support creating, updating, and saving configuration data to the API. Your goal is to implement the `ConfigMap` class and its methods based on the given code snippet and requirements. The `Confi...
```python class ConfigMap: def __init__(self, metadata, data): self.metadata = metadata self.data = data self._new = True @classmethod def get_or_create(cls, metadata, data): # Check if the ConfigMap instance already exists in the API # If exists, return the existing...
magicoder
python
You are tasked with creating a script to automate the setup of an Android cross-compiler toolchain. The script should locate the cross-compiler executable, extract the toolchain prefix, and set the CCACHE environment variable to the path of the ccache executable if available. Write a shell script that accomplishes the...
```bash #!/bin/bash ANDROID_TOOLCHAIN="/path/to/android/toolchain" # Replace with the actual path to the Android toolchain directory GCC=$(command ls $ANDROID_TOOLCHAIN/*-gcc | head -n1) if [ -z "$GCC" ]; then echo "ERROR: Could not find Android cross-compiler in: $ANDROID_TOOLCHAIN" exit 1 fi # Remove the '-gc...
magicoder
shell
You are tasked with creating a script to manage the startup of Python applications. The script should take the name of the application directory as an argument and start the `app.py` file within that directory if it exists. If the directory or the `app.py` file does not exist, the script should log an error message and...
```bash #!/bin/bash start() { if [[ -d $1 ]] && [[ -e "$1/app.py" ]] 2> $1.log; then python $1/app.py &>> $1.log & printf "\e[32mStarting $1\e[0m\n" else printf "\e[31m$1 does not seem to exist. Check $1.log for more information.\e[0m\n" for i in "${@:2}"; do pgrep -...
magicoder
shell
You are tasked with creating a Python program that simulates a file management system. Your program should implement a class called `FileManager` that allows users to perform various file management operations such as creating files, deleting files, listing files, and checking if a file exists. Additionally, the progra...
```python import os from pathlib import Path import argparse class FileManager: def __init__(self, output_dir): self.output_dir = output_dir def create_file(self, file_name): file_path = os.path.join(self.output_dir, file_name) with open(file_path, 'w'): pass def delet...
magicoder
python
You are tasked with creating a Django web application for a blogging platform. The application should allow users to create articles with a title, body, and tags. Each article should also have an author, and the system should automatically generate a slug for each article based on its title. Additionally, the system sh...
```python from django.db import models from django.utils.text import slugify from kite_runner.models import Tag, Profile class Article(models.Model): title = models.CharField(max_length=100) body = models.TextField() tags = models.ManyToManyField(Tag, related_name="articles") created_at = models.DateTi...
magicoder
python
You are tasked with implementing a recursive function to calculate the power of a given base to a given exponent. The function should utilize memoization to optimize performance by storing previously computed results. Write a Python function `power(x, n)` that takes in a float `x` as the base and an integer `n` as the...
```python def power(x, n, memo={}): if n in memo: return memo[n] if n == 0: return 1 if n == 1: return x if n < 0: memo[n] = power(1/x, -n) return memo[n] if n % 2 == 0: memo[n] = power(x*x, n//2) return memo[n] memo[n] = x * power(x, n-1) ...
magicoder
python
You are tasked with implementing a simplified version of a protocol handshake mechanism using asynchronous tasks in Rust. The code snippet provided demonstrates the setup for two asynchronous tasks, `task_a` and `task_b`, each responsible for performing a handshake with a protocol instance `a` and `b` respectively. Yo...
```rust use tokio::task; // Define the protocol type struct ProtocolType; // Define the protocol instance with default settings struct ProtocolInstance { protocol_type: ProtocolType, use_default_settings: bool, } impl ProtocolInstance { // Create a new protocol instance with default settings fn new_p...
magicoder
rust
You are given an array of integers, and your task is to find the maximum sum of a contiguous subarray within the array. A subarray is a contiguous segment of the array. For example, in the array [1, -2, 3, 4, -1, 2, 1, -5, 4], the subarray [3, 4, -1, 2, 1] has the maximum sum of 9. You need to write a function `maxSub...
```cpp long long maxSubarraySum(int n, long long arr[]) { long long maxSum = arr[0]; long long currentSum = arr[0]; for (int i = 1; i < n; i++) { currentSum = max(arr[i], currentSum + arr[i]); maxSum = max(maxSum, currentSum); } return maxSum; } ``` The `maxSubarraySum` function i...
magicoder
cpp
You are tasked with creating a program to manage the characteristics of a hero in a role-playing game. The program should allow the user to add or remove points from different characteristics of the hero, such as strength, agility, intelligence, etc. The user should be prompted to input the characteristic and the numbe...
```python def manage_hero_characteristics(hero: dict) -> dict: while True: print("Введите характеристику:") harak = input().strip().title() if harak not in hero: print("Нет такой характеристики, проверьте введенные данные: ") else: print(f"Введите количество п...
magicoder
python
You are tasked with creating a Python unit test for a utility function that calculates the average of a list of numbers. The utility function is provided in the `utilities.util` module, and you need to write a test case to ensure its correctness. The test case should utilize a custom logger from `utilities.custom_logge...
```python import unittest from utilities.custom_logger import CustomLogger from utilities.checkpoint import CheckPoint from utilities.util import Util class TestAverageCalculator(unittest.TestCase): def setUp(self): self.logger = CustomLogger() self.checkpoint = CheckPoint() def test_average_c...
magicoder
python
You are tasked with implementing a function that processes GPS coordinates and determines the distance traveled by a vehicle. The function will take in a series of latitude and longitude coordinates and calculate the total distance traveled based on the Haversine formula. The Haversine formula is used to calculate the ...
```java public class GPSTracker { private double prvlon = 0.0; // previous longitude private double curlon = 0.0; // current longitude private int status = 1; // status indicator public double calculateDistance(double[] latitudes, double[] longitudes) { double totalDistance = 0.0; final...
magicoder
java
You are tasked with creating a function that performs a soft delete operation on a database record. Soft delete, also known as logical delete, involves updating a specific column in the database to mark a record as deleted without physically removing it from the database. Your task is to implement a PHP function that p...
```php // Habilidad.php (Eloquent Model) <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Habilidad extends Model { use SoftDeletes; protected $table = 'habilidad'; // Assuming the table name is "habilidad" protected $primaryKey = 'idHabili...
magicoder
php
You are tasked with implementing a file system class in Python. The file system should support the addition of files and directories, as well as the ability to calculate the total size of all files within a given directory. You are provided with the following code snippet to serve as a starting point: ```python class...
```python class File: def __init__(self, name, size): self.name = name self.size = size class Directory: def __init__(self, name): self.name = name self.files = [] self.directories = [] def addFile(self, file): self.files.append(file) def addDirectory(s...
magicoder
python
You are tasked with implementing a Python script to train a neural network for image classification using the Keras library. The provided code snippet is a call to the `main` function with various command-line arguments. The `main` function is expected to perform the following tasks: 1. Load the weights of a pre-traine...
```python import argparse import h5py from keras.models import load_model from keras.callbacks import ModelCheckpoint from keras.optimizers import Adam def main(weights_folder, training_h5, validation_h5, epochs, cut): # Load pre-trained model weights model = load_model(weights_folder) # Load training and...
magicoder
python
You are tasked with implementing a custom asynchronous sequence type in Swift. The sequence should be able to produce elements from a base asynchronous sequence as long as a given predicate function returns true for the elements. Your task is to complete the implementation of the `AsyncPrefixWhileSequence` struct by pr...
```swift public struct AsyncPrefixWhileSequence<Base: AsyncSequence> { @usableFromInline let base: Base @usableFromInline let predicate: (Base.Element) async -> Bool @usableFromInline init(base: Base, predicate: @escaping (Base.Element) async -> Bool) { self.base = base self.predicate = predicate ...
magicoder
swift
You are tasked with implementing a Java class that processes input streams to generate compressed bitmap images. The class should be able to handle various input streams and apply compression options to produce the desired output. Your task is to complete the implementation of the `InputStreamAsBitmapCallable` class by...
```java import java.io.InputStream; import java.io.ByteArrayOutputStream; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; public static final class InputStreamAsBitmapCallable extends BaseBitmapCompressCallable { private InputStream mInputStream; public InputStr...
magicoder
java
You are tasked with creating a Python class that manages common content management system (CMS) functionality. The class should inherit from the `AbstractPermalink` class and should be designed to work with a user model specified in the Django settings. Your task is to complete the implementation of the `CommonCms` cl...
```python from django.conf import settings from django.db import models from django.contrib.auth import get_user_model USER_MODEL = settings.AUTH_USER_MODEL class CommonCms(AbstractPermalink): user = models.ForeignKey(USER_MODEL, on_delete=models.CASCADE) content = models.TextField() permalink = models.Ch...
magicoder
python
You are tasked with implementing a final field handler interface for a structure in a Java application. The interface `FinalFieldHandler<T>` extends the `StructureFieldHandler<T>` interface and includes a method `fillFinalField` to fill a final field from a structure. Your goal is to create a concrete class that implem...
```java public class CustomFinalFieldHandler<T> implements FinalFieldHandler<T> { @Override public T fillFinalField(T currentValue, Element element, Locale locale) { // Implement the logic to fill the final field based on the provided parameters // Example: Assuming element.getValue() returns t...
magicoder
java
You are tasked with implementing a function that calculates the total number of unique ways to climb a staircase. The staircase has a specific number of steps, and you can climb either 1 or 2 steps at a time. Your task is to write a function `countWays` that takes the number of steps as input and returns the total numb...
```python def countWays(n: int) -> int: if n <= 1: return 1 # Create an array to store the number of ways to reach each step ways = [0] * (n + 1) ways[0], ways[1] = 1, 1 # Base cases for 0 and 1 step for i in range(2, n + 1): # The number of ways to reach step i is the sum of ways t...
magicoder
python
You are tasked with creating a Python script that monitors the disk space usage on a Linux system and sends an alert if the usage exceeds a certain threshold. You will need to utilize the `psutil` library to retrieve disk usage information and the `smtplib` library to send an email alert. Your script should perform th...
```python import psutil import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart import time # Define the email configuration email_sender = 'sender@example.com' email_receiver = 'receiver@example.com' smtp_server = 'smtp.example.com' smtp_port = 587 smtp_username = 'username'...
magicoder
python
You are tasked with implementing a custom exception hierarchy for a Python application. The application is designed to handle various types of errors that may occur during its execution. Your goal is to create a set of custom exception classes that inherit from the base Python `Exception` class and provide specific err...
```python class InputError(Exception): def __init__(self): super().__init__("Error in input data.") class ProcessingError(Exception): def __init__(self): super().__init__("Error in processing data.") class OutputError(Exception): def __init__(self): super().__init__("Error in out...
magicoder
python
You are tasked with creating a Python class that performs linear fitting for categorical target variables. Your task is to implement the `LinearFitOperator` class, which takes a pandas DataFrame as input and fits a linear model to predict a categorical target variable. The class should provide methods to process the in...
```python import pandas as pd from sklearn.linear_model import LogisticRegression from sklearn.preprocessing import StandardScaler from sklearn.compose import ColumnTransformer from sklearn.pipeline import Pipeline class LinearFitOperator: def __init__(self, feature_names, target, target_type): self.featur...
magicoder
python
You are tasked with creating a Python script to preprocess text data using byte pair encoding (BPE) for language modeling. BPE is a data compression technique that replaces frequent pairs of bytes with a single byte. The given code snippet demonstrates the preprocessing steps using the GPT-2 BPE model on a small datase...
```python import os import subprocess import requests def download_file(url, filename): response = requests.get(url) with open(filename, 'wb') as file: file.write(response.content) def preprocess_with_bpe(input_file, output_file): encoder_url = 'https://dl.fbaipublicfiles.com/fairseq/gpt2_bpe/enco...
magicoder
python
You are working on a version control system and need to automate the process of updating the repository based on a new version release. Your task is to write a script that performs the necessary Git commands to update the repository to a new version. The script should pull the latest changes from the remote repository,...
```python import subprocess def update_repository_to_new_version(version): try: subprocess.run(['git', 'pull'], check=True) subprocess.run(['git', 'checkout', f'v{version}'], check=True) subprocess.run(['git', 'tag', '-d', f'v{version-1}'], check=True) subprocess.run(['git', 'push',...
magicoder
python
You are tasked with creating a Swift property wrapper to handle the storage and retrieval of user preferences for a currency type in a financial application. The property wrapper should utilize UserDefaults for storage and provide a default value of `CurrencyType.bitcoin` if no value is found in UserDefaults. Additiona...
```swift import Combine @propertyWrapper struct CurrencyType { private let key: String = "currencyType" private let defaultValue: CurrencyType = .bitcoin private let currencyTypePublisher = PassthroughSubject<CurrencyType, Never>() var wrappedValue: CurrencyType { get { if let save...
magicoder
swift
You are tasked with creating a custom binary sensor platform for the Eldes security system in Home Assistant. The Eldes security system provides various sensors that can be integrated into Home Assistant for monitoring purposes. Your goal is to implement the `async_setup_entry` function, which is responsible for settin...
```python from . import EldesDeviceEntity import logging _LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry, async_add_entities): """Set up the Eldes binary sensor platform.""" DOMAIN = 'eldes' # Assuming the domain for Eldes integration DATA_CLIENT ...
magicoder
python
You are tasked with implementing a Python class that simulates a simple stopwatch. The class should have the following functionalities: - Start the stopwatch - Stop the stopwatch - Reset the stopwatch - Get the elapsed time in seconds You are provided with a partial implementation of the Stopwatch class as follows: `...
```python import time class Stopwatch: def __init__(self): self.start_time = 0 self.elapsed_time = 0 self.stopped = True def start(self): if self.stopped: self.start_time = time.time() self.stopped = False def stop(self): if not self.stopped...
magicoder
python
You are tasked with implementing a test coverage analysis tool for a Python codebase. Test coverage is a measure used to describe the degree to which the source code of a program is executed when a particular test suite runs. One common metric is the percentage of code lines executed during testing. Your goal is to cre...
```python import inspect def calculate_coverage(module): source_lines, _ = inspect.getsourcelines(module) total_lines = 0 executed_lines = 0 for line in source_lines: line = line.strip() if line and not line.startswith("#"): total_lines += 1 if line not in ["def...
magicoder
python
You are working on a web application that uses a PHP backend with a MySQL database. Your task is to create a function that retrieves the ID of a module based on its controller name. The given code snippet shows a PHP function `getId` that takes a controller name as a parameter and constructs a SQL query to fetch the co...
```php function getId($controller) { // Establish a database connection $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "database"; $conn = new mysqli($servername, $username, $password, $dbname); // Check the database connection if ($conn->connect_e...
magicoder
php
You are tasked with implementing a user permission management system. The system should allow users to have different levels of permissions, and it should support operations to grant, revoke, and check permissions for users. You are given the following code snippet as a starting point: ```python USER_PERMISSIONS = se...
```python class PermissionManager: USER_PERMISSIONS = set() MEMBER_PERMISSIONS = set() def __init__(self): self.user_permissions = {} def grant_permission(self, user, permission): if user not in self.user_permissions: self.user_permissions[user] = set() self.user_pe...
magicoder
python
You are tasked with implementing a metadata store for managing artifacts. The metadata store allows users to define artifact types, create artifacts of those types, and retrieve artifacts by their IDs. Your goal is to create a Python class that provides methods for putting artifact types and artifacts into the store, a...
```python from typing import List import metadata_store_pb2 # Assuming the required protobuf module is imported class MetadataStore: def __init__(self): self.artifact_types = {} self.artifacts = {} def put_artifact_type(self, artifact_type) -> int: type_id = len(self.artifact_types) +...
magicoder
python
You are given a string representing a C++ code snippet that needs to be formatted according to the rules specified in the `.clang-format` file. The `.clang-format` file contains a set of rules for formatting C++ code, including indentation, line breaks, and other style preferences. Your task is to write a program that ...
```cpp #include <clang-c/Index.h> #include <string> std::string formatCode(const std::string& codeSnippet, const std::string& clangFormatRules) { // Implement the code formatting logic using libclang or other suitable libraries // Parse the clangFormatRules and apply the formatting to the codeSnippet // Re...
magicoder
cpp
You are tasked with implementing a custom loot entry deserializer for a Minecraft mod. The deserializer will parse JSON data and create corresponding loot entries based on the provided information. The loot entries can be of different types, such as empty, item, or table, and may include conditions and functions. Your...
```java import com.google.gson.*; import java.lang.reflect.Type; import net.minecraft.world.storage.loot.LootEntry; import net.minecraft.world.storage.loot.LootEntryEmpty; import net.minecraft.world.storage.loot.LootEntryItem; import net.minecraft.world.storage.loot.LootEntryTable; import net.minecraft.world.storage.l...
magicoder
java
You are given a code snippet that performs factorization of a number using the Pollard's rho algorithm. Your task is to implement a function that takes an integer `n` as input and returns the prime factors of `n` using the Pollard's rho algorithm. The Pollard's rho algorithm is an algorithm used to find the prime fact...
The `pollardsRho` function takes an integer `n` as input and returns a vector of prime factors of `n` using the Pollard's rho algorithm. The function first checks for the trivial cases where `n` is 1 or 2. Then, it generates random values for `x` and `y` and iterates through the function `f(x) = (x * x + 3) % n` to fin...
magicoder
c
You are tasked with creating a program that analyzes a given software license text to extract and display the permissions and conditions specified in the license. The license text is provided as a string, and the program should identify and display the permissions and conditions based on the following rules: - Permiss...
```python def extract_permissions_and_conditions(license_text): permissions = [] conditions = [] for line in license_text.split('\n'): if "to use" in line: permissions.append("Use") if "to copy" in line: permissions.append("Copy") if "to modify" in line: ...
magicoder
python
You are tasked with implementing a function to parse search results from a file and verify the correctness of the parsed data. The search results are expected to contain information about duplicate repositories in GitHub and Bitbucket. The function should parse the results and return the count of duplicate repositories...
```python def parse_search_results(output, repository_name, is_duplicate): # Initialize the results dictionary and count of duplicate repositories results = {} count = 0 # Check if the search results contain the repository name if repository_name in output: # Split the search results by lin...
magicoder
python
You are working for a farm management system that tracks various types of crops and their associated data. Your task is to write a Python function that processes a list of tuples, each representing a crop, and returns a dictionary containing the average yield for each unique crop type. You are given a list of tuples, ...
```python def calculate_average_yield(crop_data): crop_yield = {} crop_count = {} for crop in crop_data: crop_type = crop[0] total_yield = crop[3] acreage = crop[4] if crop_type in crop_yield: crop_yield[crop_type] += total_yield / acreage ...
magicoder
python
You are tasked with creating a program that parses and analyzes metadata from a list of strings representing software licenses and programming languages. Each string in the list contains metadata in the form of key-value pairs separated by double colons (::). The keys represent different attributes of the software, suc...
```python def parse_metadata(metadata_list): metadata_dict = {} for metadata in metadata_list: key, value = metadata.split(' :: ') if key in metadata_dict: metadata_dict[key].append(value) else: metadata_dict[key] = [value] return metadata_dict ``` The `parse...
magicoder
python
You are working on a project to automate the setup of a Vault server using Docker and shell scripting. Your task is to write a script that sets up the Vault server, copies policy files, and performs some initial configuration. Given the following code snippet as part of the setup script: ```bash -e "VAULT_DEV_LISTEN_...
```bash #!/bin/bash # Start Vault server using Docker docker run -d -e "VAULT_DEV_LISTEN_ADDRESS=0.0.0.0:8200" "vault:${VAULT_VERSION}" &> /dev/null # Copy policy files to Vault container docker cp "$DIR/policy-no-root.hcl" ${VAULT_CONTAINER_NAME}:. docker cp "$DIR/policy-delete-only.hcl" ${VAULT_CONTAINER_NAME}:. #...
magicoder
shell
You are tasked with implementing a SkipGramDataGenerator class for generating training data for a SkipGram model. The SkipGram model is used for word embedding in natural language processing. The SkipGramDataGenerator takes a text file as input and generates training data in the form of word pairs for the SkipGram mode...
```python from pathlib import Path import numpy as np from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import skipgrams class SkipGramDataGenerator: def __init__(self, datafile, batch_size): self.datafile = datafile self.batch_size = batch_size self.tokenizer...
magicoder
python
You are tasked with implementing a real-time speech-to-text transcription system. The system should continuously transcribe spoken words into text as they are being spoken. The provided code snippet is a part of the system and shows how the transcription is updated in real-time. Your task is to write a function that t...
```python from typing import Iterator import speech_to_text_library # Assume the existence of a speech-to-text library def real_time_transcription(audio_stream: Iterator[bytes]) -> Iterator[str]: speech_to_text = speech_to_text_library.initialize() # Initialize the speech-to-text library current_transcriptio...
magicoder
python
You are working on a project that involves managing entities and enums in a TypeScript application. Your task is to create a utility function that can merge and export all the entities and enums from different files into a single file for easier access. You are given a directory containing multiple TypeScript files, e...
```typescript import fs from 'fs'; import path from 'path'; function mergeAndExport(directoryPath: string): void { const files = fs.readdirSync(directoryPath); const exportStatements: string[] = []; files.forEach((file) => { if (file.endsWith('.entity.ts') || file.endsWith('.enum.ts')) { const exportN...
magicoder
typescript
You are tasked with implementing a simple authentication system using Python. The system should have a class called `AuthCodeRequestHandler` that handles the generation and validation of authentication codes. The authentication code is a 6-digit alphanumeric code that is generated and sent to the user's email for verif...
```python import random import string class AuthCodeRequestHandler: def generate_auth_code(self): code = ''.join(random.choices(string.ascii_uppercase + string.digits, k=6)) return code def send_auth_code(self, email, code): # Simulate sending the code to the user's email print...
magicoder
python
You are tasked with implementing a method to retrieve the current login information for a user in a C# application. The `GetCurrentLoginInformations` method is part of an interface, and your goal is to create a concrete implementation for this method. The `GetCurrentLoginInformations` method returns a `Task` that resol...
```csharp using System; using System.Threading.Tasks; // Define the output class to hold the current login information public class GetCurrentLoginInformationsOutput { public string Username { get; set; } public string Email { get; set; } // Add any other relevant properties for login information } // Imp...
magicoder
csharp
You are tasked with creating a function that processes a list of integers and returns the maximum sum of a contiguous subarray within the list. The function should be implemented in Swift. You are given the following code snippet as a reference: ```swift deinit { var fooParam = FooStruct() #^IN_INVALID_3^# } fun...
```swift func maxSubarraySum(_ nums: [Int]) -> Int { guard !nums.isEmpty else { return 0 } var maxSum = nums[0] var currentSum = nums[0] for i in 1..<nums.count { currentSum = max(nums[i], currentSum + nums[i]) maxSum = max(maxSum, currentSum) } return maxSum } ```...
magicoder
swift
You are tasked with creating a Python function that processes a list of database migration operations and generates a SQL script to apply those operations to a database. Each migration operation is represented as an instance of a migration class, and the SQL script should include the necessary SQL statements to execute...
```python def generate_sql_script(operations): sql_script = "" for operation in operations: if isinstance(operation, migration.AddField): field_definition = operation.field sql_script += f"CREATE TABLE {operation.model_name} ({operation.name} {field_definition.__class__.__name__....
magicoder
python
You are tasked with creating a web application using Dash, a Python framework for building analytical web applications. Your goal is to implement a dynamic page routing system that generates pages based on a given integer input. You will need to create a function that takes an integer as input and returns the name of t...
```python from dash import Dash from dash_extensions.enrich import DashBlueprint, DashProxy, html, Output, Input def page_name(i: int): return f"page{i}" app = Dash(__name__) dbp = DashBlueprint() dp = DashProxy(app, dbp) @dbp.callback(Output('page-content', 'children'), [Input('url', 'pathname')]) def display_p...
magicoder
python
You are tasked with implementing a generic interface for establishing a connection to an endpoint. The interface, `IConnectable<TType, TEndPoint>`, contains a single method `Connect` that takes an endpoint and a callback function as parameters. Your goal is to create a class that implements this interface and provides ...
```csharp using System; using System.Net; using System.Net.Sockets; namespace TubumuMeeting.Libuv { public class TcpConnector : IConnectable<Socket, IPEndPoint> { public void Connect(IPEndPoint endPoint, Action<Exception> callback) { try { Socket socket =...
magicoder
csharp
You are tasked with implementing an event handling system in Python. The system should allow registering event handlers for different types of events and unregistering them when necessary. Each event handler is associated with a unique handler ID, which is returned upon registration and used for unregistration. You ne...
```python class EventHandler: def __init__(self): self._eventHandlers = {} def registerEventHandler(self, eventType, callback): if eventType not in self._eventHandlers: self._eventHandlers[eventType] = [] handlerID = len(self._eventHandlers[eventType]) self._eventHa...
magicoder
python
You are working on a graphics rendering engine and need to implement a function to create a Metal Render Pipeline State Object (PSO) for rendering terrain. The given code snippet is a part of the implementation and provides a static function `createTerrainPSO()` that returns the Metal Render Pipeline State. Your task ...
```swift static func createTerrainPSO() -> MTLRenderPipelineState { let vertexFunction = Renderer.library?.makeFunction(name: "vertex_main") let fragmentFunction = Renderer.library?.makeFunction(name: "fragment_terrain") // Create a Metal Render Pipeline Descriptor let pipelineDescriptor = MTLRenderPipelineD...
magicoder
swift
You are tasked with implementing a Python function that processes a tree structure and interacts with the user to navigate through the tree. The tree is represented as a nested list of tuples, where each tuple contains a method name and a description. The function should allow the user to traverse the tree by selecting...
```python def process_tree(tree: list, store: str = None) -> None: """ Process the tree and interact with the user to navigate through it. :param tree: A nested list of tuples representing the tree, where each tuple contains a method name and a description. :param store: Optional parameter specifying w...
magicoder
python
You are tasked with creating a script to automate the download of software packages from the web. Your script should be able to parse a given URL and extract the filename and download link. Additionally, it should be able to handle different types of URLs and provide the user with feedback on the download progress. Wr...
```python import os import requests from urllib.parse import urlparse def download_software_package(url): parsed_url = urlparse(url) filename = os.path.basename(parsed_url.path) print(f"Downloading {filename} from - {url}") download_link = url return filename, download_link # Example usage url = "...
magicoder
python
You are tasked with implementing a card game strategy using object-oriented programming concepts. The provided code snippet is a part of a larger card game framework. Your goal is to complete the implementation of the `IlmiorStrategy` class, which represents a specific strategy for playing the card game. The `IlmiorSt...
```csharp public class IlmiorStrategy : PlayerStrategy { public override ICard ChooseCardToPlay(IPlayer myself) { // Implement the logic to choose a card to play from the player's hand // For example, you can select a random card from the hand return myself.HandCards.OrderBy(x => Guid.Ne...
magicoder
csharp
You are tasked with creating a Python class that represents a generic data structure. The class should have a property called `datatype` that returns the data type of the elements stored in the data structure. Your task is to implement the `datatype` property in the class to achieve this functionality. Create a Python...
```python class DataStructure: def __init__(self): self.data_elements = [] def add_element(self, element): self.data_elements.append(element) @property def datatype(self): if not self.data_elements: return "No data" else: data_types = {type(eleme...
magicoder
python
You are tasked with creating a script to manage the health checks and startup of Docker containers. The script should check if a specified container is running and if its health status is "healthy". If the container fails to meet these criteria, the script should perform cleanup and display an error message. Otherwise,...
```bash #!/bin/bash # Function to check if a container is running container_running() { local container_name=$1 if [[ $(docker inspect -f "{{.State.Running}}" $container_name 2>/dev/null) == "true" ]]; then return 0 # Container is running else return 1 # Container is not running fi } # Function to p...
magicoder
shell
You are tasked with implementing a function to compute trajectory features based on a given set of parameters and time range. The function `compute_trajectory_features_set1` takes four parameters: 1. `aligned_trajector_key_file`: A pandas DataFrame containing aligned trajectory key data. 2. `parameters`: A dictionary c...
```python import pandas as pd from typing import Dict def compute_trajectory_features_set1(aligned_trajector_key_file: pd.DataFrame, parameters: Dict, start_time, end_time): features_df = pd.DataFrame() # Compute trajectory features based on parameters and time range # Example computation (replace with ac...
magicoder
python
You are tasked with creating a Python program that interacts with a translation API to translate a given text from a source language to a destination language. The program should handle potential errors and exceptions that may occur during the translation process. Your task is to implement a function `translate_text` ...
The `translate_text` function makes a GET request to the translation API endpoint with the provided source language code, destination language code, and the text to be translated. It handles potential errors and exceptions that may occur during the translation process. If the translation is successful, it returns the t...
magicoder
python
You are tasked with implementing a custom serializer and handling potential data corruption during deserialization. The `Serializer` class has a method `Deserialize<T>` which deserializes a given data into an object of type `T`. However, there is a possibility of data corruption during deserialization, which should be ...
```csharp using System; public class DataCorruptedException : Exception { public DataCorruptedException(string message) : base(message) { } } public class Serializer { public T Deserialize<T>(string data) { // Implement the deserialization logic here // Check for data corruption during des...
magicoder
csharp
You are given a code snippet that imports a module called `puzzler` and uses it to run a specific puzzle called `OneSidedTetratwigsTriangle_3` from the `tetratwigs` puzzles collection. Your task is to understand the puzzle being run and create a Python function that solves it. The `OneSidedTetratwigsTriangle_3` puzzle...
```python def solve_tetratwigs_triangle(puzzle_input): # Sort the tetratwigs based on their lexicographical order puzzle_input.sort() # Check if the number of tetratwigs is a triangular number n = len(puzzle_input) k = 1 while k * (k + 1) < 2 * n: k += 1 if k * (k + 1) != 2 * n:...
magicoder
python
You are tasked with implementing a Python decorator that measures the execution time of a function and logs the result. The decorator should be designed to work with the Twisted framework, a popular event-driven networking engine. Your task is to complete the implementation of the `measure_execution_time` decorator, w...
```python from twisted.internet import reactor from functools import wraps import time def measure_execution_time(func): @wraps(func) def wrapper(*args, **kwargs): start_time = reactor.seconds() result = func(*args, **kwargs) end_time = reactor.seconds() execution_time_ms = int(...
magicoder
python
You are tasked with creating a number guessing game in Python. The game should prompt the user to guess a randomly generated number between 1 and 100. If the user guesses the correct number, the game should display a congratulatory message and terminate. However, if the user guesses incorrectly, the game should prompt ...
The provided Python program initializes a random number between 1 and 100 using the `random.randint` function. It then prompts the user to guess the number and handles non-integer inputs using a try-except block. The program keeps track of the number of attempts made by the user and displays a congratulatory message up...
magicoder
python
You are tasked with implementing a function to rotate a 2D texture matrix in a graphics application. The given code snippet is a part of a larger codebase and contains a case statement handling the left arrow key press event. Inside this case, there is a conditional check for a macro `JOHNS`, and if it is defined, a 2D...
```cpp #include <iostream> // Define the pxMatrix class with identity and rotate methods class pxMatrix { public: void identity() { // Implementation to reset the matrix to an identity matrix } void rotate(float angle) { // Implementation to apply a 2D rotation transformation by the given ...
magicoder
cpp
You are tasked with implementing a memory management system for a virtual reality application. The application uses the Oculus Rift SDK, and you need to create a class that manages the memory allocated for packets received from the Oculus Rift sensors. The class should handle the disposal of memory resources to prevent...
```csharp using System; public class OculusPacketManager : IDisposable { private IntPtr packetHandle; public IntPtr AllocatePacket() { // Allocate memory for a new packet using Oculus Rift SDK packetHandle = CAPI.ovr_AllocatePacket(); return packetHandle; } public void Fre...
magicoder
csharp
You are tasked with implementing a function to decrypt a wallet record using a set of keys. The function takes in a reference to a set of keys and returns a result containing the decrypted wallet record. The `decrypt_merged` function is used to decrypt the record's ID using the name key from the provided set of keys. H...
1. The potential issue with the code snippet is that the variable `decrypted_name` is being redeclared, which may lead to unintended behavior or loss of data. Additionally, the conversion to a UTF-8 string and subsequent transformation into an IndyResult using the `to_indy` method seems unnecessary and may not align wi...
magicoder
rust
You are tasked with creating a Python script that automates the setup process for a specific GitHub repository and its associated dependencies. The script should clone the repository, create a new conda environment, install required packages, and activate the environment. The specific steps to be performed are as follo...
```python import os import subprocess # Step 1: Clone the GitHub repository subprocess.run(["git", "clone", "https://github.com/uiuc-arc/sbi.git", "sbi"]) # Step 2: Source the conda initialization script os.system("source ~/anaconda3/etc/profile.d/conda.sh") # Step 3: Create a new conda environment subprocess.run(["...
magicoder
python
You are tasked with creating a function that validates appointment times based on specific business rules. The function should reject appointments that fall outside the allowed time range and should also handle cases where the appointment creation process throws an error. You are given a code snippet that tests the ap...
```javascript class AppError extends Error { constructor(message) { super(message); this.name = this.constructor.name; this.message = message; Error.captureStackTrace(this, this.constructor); } } const createAppointment = { run: (appointmentDetails) => { const { date, provider_id, user_id } =...
magicoder
javascript
You are tasked with implementing a data processing algorithm for a performance monitoring system. The algorithm processes data and updates a database with the results. The provided code snippet is a part of this algorithm and contains a loop that iterates over a range of rows and performs various operations. Your task ...
```python import uuid import random class BaseRateBin: def __init__(self, path, ts, val, is_valid): self.path = path self.ts = ts self.val = val self.is_valid = is_valid def get_meta_key(self): return self.path[-1] class Database: def update_rate_bin(self, base_rat...
magicoder
python
You are tasked with implementing a class method for a handwriting recognition system. The method is responsible for calculating the deviation of horizontal distances between consecutive strokes in a word. The class has an attribute `_source` which holds the source of the handwriting data. The method `_distance_deviatio...
```python import numpy as np class HandwritingRecognition: def __init__(self, source): self._source = source def _distance_deviation(self, strokes): delayed_strokes = strokes[1:] distances = [] for i in range(len(delayed_strokes)): next_stroke = delayed_strokes[i] ...
magicoder
python
You are tasked with implementing a Swift library for managing and manipulating dates and times. Your goal is to create a `DateBuilder` class that allows users to easily construct and manipulate dates and times using a fluent interface. The class should provide methods for setting the date, time, and weekday, and for re...
```swift import Foundation enum Weekday: Int { case sunday = 1, monday, tuesday, wednesday, thursday, friday, saturday } class DateBuilder { private var components = DateComponents() func at(hour: Int, minute: Int) -> DateBuilder { components.hour = hour components.minute = minute ...
magicoder
swift
You are tasked with creating a Python unit test for a function that interacts with Docker API and performs operations on a Docker container. The function to be tested is part of the `tern.load.docker_api` module. Your goal is to write a test case that ensures the correct behavior of this function. The function to be t...
```python import unittest from unittest.mock import patch, MagicMock from tern.load import docker_api class TestLoadDockerAPI(unittest.TestCase): @patch('tern.load.docker_api.create_container') def test_create_container_success(self, mock_create_container): # Mocking the create_container function ...
magicoder
python
You are tasked with implementing a memory management system for a programming language. The system should provide functionality to view the current reachable heap and obtain information about specific objects. The system also supports an optional argument for debugging purposes. Your task is to implement the `heap()` ...
```python import gc def heap(): """ Returns a view of the current reachable heap. """ return gc.get_objects() def iso(*objects, ht=None): """ Provides information about specific objects. Args: *objects: Variable number of objects for which information is requested. ht: Optiona...
magicoder
python
You are tasked with implementing a Python package for handling football (soccer) match statistics. The package should provide functionality for parsing match data, calculating various statistics, and generating reports. Your task is to create a class `MatchStatistics` within the `anstoss` package that encapsulates the ...
```python # anstoss/__init__.py class MatchStatistics: @staticmethod def parse_match_data(match_data: str) -> dict: teams = match_data.split() if len(teams) != 3 or '-' not in teams[1]: raise ValueError("Invalid match data format. Expected format: 'TeamA X-X TeamB'") team_a, ...
magicoder
python
You are tasked with creating a custom neural network model using the Keras library in Python. Your goal is to design a model that combines sequential and functional API components to create a complex architecture. The model should include LSTM, Dense, and Input layers, and it should be able to accept multiple inputs. Y...
```python import tensorflow.keras as keras class CustomNeuralNetwork: def _createSimpleSequentialModel(self): model = keras.Sequential() model.add(keras.layers.LSTM(10)) model.add(keras.layers.Dense(1, activation='sigmoid')) return model def _createNestedSequentialModel(self): ...
magicoder
python
You are working on a Django project that involves managing bibliographic records. The code snippet provided is from a test suite for the project. The test is using the pytest framework and the django_db fixture to perform database operations. The test is checking the caching behavior of a bibliographic record object. ...
```python # Solution for update_cache function def update_cache(rekord): if "NOWAK" in rekord.opis_bibliograficzny: rekord.opis_bibliograficzny_cache = rekord.opis_bibliograficzny.replace("NOWAK", "SMITH") if "KOWALSKI" in rekord.opis_bibliograficzny: rekord.opis_bibliograficzny_cache = rekord.o...
magicoder
python
You are tasked with implementing a password validation function that checks for various criteria to ensure the password's strength. The function should validate the password based on the following rules: 1. The password must be at least 8 characters long. 2. It should not contain characters repeated more than twice con...
```javascript function validatePassword(password) { const errors = []; // Rule 1: Check password length if (password.length < 8) { errors.push("TOO_SHORT"); } // Rule 2: Check for characters repeated more than twice consecutively if (/(.)\1{2,}/.test(password)) { errors.push("TOO_MUCH_REPETITION")...
magicoder
javascript
You are working on a project that involves fitting a polynomial curve to a set of data points. To achieve this, you decide to use the `np.polyfit` function from the NumPy library, which fits a polynomial of a specified degree to the given data using a least-squares approach. However, you encounter a problem with the ou...
```python import numpy as np def correct_polyfit(x, y, degree): # Fit the polynomial using np.polyfit p = np.polyfit(x, y, degree) # Reverse the order of coefficients to match np.polyfit's output p_corrected = p[::-1] return p_corrected ``` The `correct_polyfit` function first uses `np.p...
magicoder
python
You are tasked with implementing a simple iOS application that simulates a button state transition. The application will have a button that can be in one of three states: Unknown, Checking, or Success. You need to create a Swift class that represents the button's state and provides methods to transition between these s...
```swift import UIKit enum BtnType { case Unknown case Checking case Success } class ButtonState { var currentState: BtnType = .Unknown func transitionToState(newState: BtnType) { switch (currentState, newState) { case (.Unknown, .Checking): currentState = .Checkin...
magicoder
swift
You are tasked with creating a Java program that simulates a simple quiz game. The program should use the Scanner class to take input from the user for answering the quiz questions. The quiz should consist of multiple-choice questions, and the user's score should be calculated and displayed at the end of the quiz. You...
```java import java.util.Scanner; public class QuizGame { public static void main(String[] args) { String[] questions = { "What is the capital of France?", "Which planet is known as the Red Planet?", "What is the powerhouse of the cell?", "Who is the author o...
magicoder
java
You are working on a reinforcement learning project and need to implement a function to calculate derivative data for different targets in the context of a specific environment. The environment has observation and action spaces, and the derivative data will be used for training a neural network. You are given a code s...
```python import numpy as np def initialize_derivative_data(target, num_data, env_info): if target == 'state-action': derivative_data = np.zeros([num_data, env_info['ob_size'], env_info['action_size']], dtype=np.float) elif target == 'action-action': derivative_data = np.zeros([num_data, env_in...
magicoder
python
You are tasked with simulating a data collection process for an underwater vehicle's thrusters. The vehicle has multiple thrusters, each with various pulse-width modulation (PWM) values. The data collection process involves running trials for a specific duration, then resetting the thrusters, followed by a calm period ...
```python from time import time # Constants TRIAL_LENGTH = 6.0 # Seconds RESET_TIME = 4.0 CALM_TIME = 4.0 MEASUREMENT_PERIOD = 0.02 # Nested dictionary for data data = { measured_var1: { thruster1: { pwm_value1: [], pwm_value2: [], ... }, thruster2: { ...
magicoder
python
You are tasked with creating a custom decorator in TypeScript for a specific use case. The decorator should be designed to validate the providers array within a module in an Angular application. The decorator should ensure that the providers array contains a specific service called "AuthService" and that it is the firs...
```typescript function ValidateAuthService(target: any, propertyKey: string, descriptor: PropertyDescriptor) { const originalMethod = descriptor.value; descriptor.value = function (...args: any[]) { if (!Array.isArray(this.providers)) { throw new Error('Providers array is not defined'); } const ...
magicoder
typescript
You are tasked with implementing a custom neural network module in PyTorch for multi-task learning. The module, named `MultiTaskDense`, is designed to handle multiple tasks simultaneously and is initialized with the number of features and the number of tasks it will be handling. Additionally, it allows for a customizab...
```python import torch import torch.nn as nn from typing import Callable class MultiTaskDense(nn.Module): def __init__(self, features: int, n_tasks: int, kernel_init: Callable = nn.init.lecun_normal_): super(MultiTaskDense, self).__init__() self.features = features self.n_tasks = n_tasks ...
magicoder
python
You are tasked with creating a Python function that processes a generator and returns a list of items. The generator yields wallpaper items parsed from a web page using Scrapy. Each wallpaper item is represented as a dictionary containing details such as the image URL, title, and tags. Your function should take the gen...
```python from typing import Generator, Dict, Union, List def process_wallpaper_items(items_gen: Generator[Dict[str, Union[str, List[str]]], None, None]) -> List[Dict[str, Union[str, List[str]]]]: return list(items_gen) ``` The `process_wallpaper_items` function simply takes the generator `items_gen` as input and...
magicoder
python