query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with creating a Java method that securely sets up a data source for a database connection and configures a Hibernate session factory using Spring framework. The method should ensure that the database credentials are handled securely and that the session factory is properly configured for use in a web app...
```java import org.springframework.context.annotation.Bean; import org.springframework.orm.hibernate5.LocalSessionFactoryBuilder; import org.springframework.orm.hibernate5.LocalSessionFactoryBean; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.hibernate5.HibernateTran...
magicoder
java
You are tasked with implementing a Python class that performs a specific operation on a tensor using a convolutional neural network (CNN). Your task is to complete the implementation of the `CustomLayer` class, which takes a tensor as input and applies a specific operation involving a CNN. The `CustomLayer` class has ...
```python import torch import torchvision.models as models # Define a sample CNN model (ResNet18 for demonstration) cnn_model = models.resnet18(pretrained=True) cnn_model.eval() # Create an instance of the CustomLayer class custom_layer = CustomLayer(cnn_model, 0.5) # Create a sample input tensor input_tensor = torc...
magicoder
python
You are working on a project that involves writing u-boot to a SPI-NOR flash. However, you encounter an error message and need to troubleshoot the issue. The error message is as follows: ``` Unable to write u-boot. Try to unlock SPI-NOR flash via "sf probe 0:0" in loaded u-boot, then try again. ``` Additionally, there ...
The error message indicates that there is an issue with writing u-boot to the SPI-NOR flash. The suggested action is to unlock the SPI-NOR flash via the command "sf probe 0:0" in the loaded u-boot and then attempt to write u-boot again. The subsequent commands in the code snippet are unrelated to resolving the error a...
magicoder
python
You are tasked with creating a Python function that determines the type of a family based on the relationships between its members. The family is represented by a class `Family`, which contains a dictionary `persons` mapping person names to their respective instances. Each person instance has a `name` attribute and a `...
```python class Person: def __init__(self, name, relations): self.name = name self.relations = relations class Family: def __init__(self, persons): self.persons = persons def get_family_type(family, person_to_set): person = family.persons[person_to_set] relations = person.relat...
magicoder
python
You are tasked with implementing a method to remove an element at a specified index from a custom list implementation. The custom list is represented by a class with a `list` attribute to store the elements and a `count` attribute to track the number of elements in the list. The method `remove(self, index)` should remo...
```python class CustomList: def __init__(self, elements): self.list = elements self.count = len(elements) def remove(self, index): for i in range(index, self.count - 1): self.list[i] = self.list[i + 1] del self.list[self.count - 1] self.count -= 1 ``` The `...
magicoder
python
You are tasked with creating a Python program that simulates a simple game of dice. The game will involve two players taking turns to roll a six-sided die. The player with the highest total score after a specified number of rounds wins the game. Your task is to implement the game logic and provide a function to determi...
```python import random class Player: def __init__(self, name): self.name = name self.score = 0 def roll_die(self): return random.randint(1, 6) def update_score(self, points): self.score += points class Game: def __init__(self, player1_name, player2_name, rounds): ...
magicoder
python
You are tasked with implementing a Python function that processes a dictionary and handles a KeyError exception in a specific way. The function should take a dictionary as input and return a modified version of the dictionary. If a KeyError is encountered during the processing, the function should catch the exception a...
```python def process_dictionary(input_dict): modified_dict = input_dict.copy() # Create a copy of the input dictionary to avoid modifying the original for key, value in input_dict.items(): try: _ = modified_dict[key] # Attempt to access the key in the dictionary except KeyError: ...
magicoder
python
You are tasked with implementing a circular queue data structure in Python. A circular queue is a data structure that follows the FIFO (First In First Out) principle, but with a fixed size. When the queue is full and a new element is enqueued, the oldest element in the queue is dequeued to make space for the new elemen...
```python class CircularQueue: def __init__(self, size): self.size = size self.queue = [None] * size self.front = self.rear = -1 def enqueue(self, item): if (self.rear + 1) % self.size == self.front: self.dequeue() if self.is_empty(): self.front =...
magicoder
python
You are tasked with implementing a snapshot strategy for a document management system. The system allows users to create and modify documents, and the snapshot strategy should capture the state of a document at a specific point in time. To achieve this, you need to create a Java interface for the snapshot strategy and ...
```java // Define the TakeSnapshotStrategy interface public interface TakeSnapshotStrategy<T> { Snapshot<T> takeSnapshot(T document); } // Define the Snapshot class to represent the snapshot of a document public class Snapshot<T> { private T documentState; public Snapshot(T documentState) { this.d...
magicoder
java
You are tasked with implementing a Python decorator that applies a color transformation to the output of a function. The decorator will convert the returned numerical value from the function into a color representation using the HSL (Hue, Saturation, Lightness) color model. The transformed color will then be printed to...
```python import colorsys as _coloursys from functools import wraps, partial import math import random _round = round def colorize_output(hue_shift, saturation_scale, lightness_scale): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): # Call the original function ...
magicoder
python
You are tasked with creating a Python decorator that logs the execution time of a given function. Your decorator should take into account the possibility of passing custom arguments to the decorated function. The decorator should also handle functions that return either a string or a Future object that resolves to a st...
```python import time from concurrent.futures import Future from functools import wraps def log_execution_time(custom_args=None, custom_kwargs=None): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): start_time = time.time() result = func(*args, **kwargs) ...
magicoder
python
You are tasked with implementing a function that processes a list of comments and removes any commented-out code snippets. The comments are represented as strings and may contain multi-line code snippets enclosed within `/*` and `*/`. Your task is to write a function `removeCommentedCode` that takes a list of comments ...
```swift func removeCommentedCode(_ comments: [String]) -> [String] { var result: [String] = [] var inBlockComment = false for comment in comments { if let startRange = comment.range(of: "/*"), let endRange = comment.range(of: "*/") { let blockComment = comment[startRange.lowerBound...
magicoder
swift
You are tasked with implementing a simple web service that generates and returns a pair of cryptographic keys in hexadecimal format. The provided code snippet is a simplified version of a Django view that accomplishes this task. Your goal is to complete the implementation by writing the missing parts of the `PrivateKey...
```python from Crypto.PublicKey import ECC import binascii class PrivateKey: def __init__(self): self.key = ECC.generate(curve='P-256') self.pubkey = PublicKey(self.key.public_key()) def serialize(self): return self.key.export_key(format='PEM').hex() class PublicKey: def __init__(...
magicoder
python
You are working on a machine learning project and need to implement a class for handling Inverse Document Frequency Smoothing (IDFS) in a text classification system. The IDFS is a statistical measure used to evaluate the importance of a term within a collection of documents. You are provided with a code snippet from th...
```php class IDFS { protected $idfs; protected $nPos; /** * Initializes the IDFS class with default values. */ public function __construct() { $this->idfs = []; $this->nPos = 0; } /** * Updates the IDFS values based on a new document. * * @param st...
magicoder
php
You are given a string `name` containing lowercase letters. Your task is to write a function that rearranges the characters of the string to form the lexicographically smallest string possible. The rearranged string should not contain any leading zeroes. Write a function `rearrangeString` that takes in the string `nam...
```python def rearrangeString(name: str) -> str: char_count = [0] * 26 # Array to store the count of each character for char in name: char_count[ord(char) - ord('a')] += 1 # Increment the count for each character result = [] # List to store the rearranged characters for i in range(26): ...
magicoder
python
You are working on a project that involves integrating a scripting language into a Rust application. The scripting language provides a set of functions for interacting with its stack-based virtual machine. You need to implement a wrapper in Rust for these functions to facilitate seamless communication between the scrip...
```rust struct ScriptingStack { // Implement any necessary fields here } impl ScriptingStack { fn is_string(&self, idx: isize) -> bool { // Implement type-checking logic for string unimplemented!() } fn is_table(&self, idx: isize) -> bool { // Implement type-checking logic for ...
magicoder
rust
You are tasked with implementing a Python function that processes a list of arguments and performs specific operations based on the arguments provided. The function should assert the size of the arguments, extract a value, and then perform further processing based on the extracted value. Write a Python function `proce...
```python def process_arguments(args): # Assert the size of the arguments assert_sizeof(args, toward.symbol, 1) # Extract a single value from the arguments value, = args # Return a tuple containing the extracted value return (value,) ``` In the solution, the `process_arguments` function first...
magicoder
python
You are working as a software developer for a company that uses the SQLAlchemy library for database management. Your task is to write a Python function that will generate an Alembic migration script to alter a column in a database table. The column to be altered is 'sale_value_promotion' in the 'products' table. The al...
```python def generate_migration_script(table_name, column_name, new_data_type, precision, existing_nullable): migration_script = f"""op.alter_column('{table_name}', '{column_name}', existing_type=sa.REAL(), type_=sa.Float(precision={precision}), existing_nullable={exist...
magicoder
python
You are working as a DevOps engineer for a company that manages sensitive configuration files using GPG encryption. Your task is to write a script that automates the decryption of a GPG-encrypted configuration file and stores it in a specific location. The script should also ensure that the decryption process is secure...
```bash #!/bin/bash # Prompt for passphrase without echoing to the terminal read -s -p "Enter the passphrase: " passphrase echo # Decrypt the file and handle errors if gpg --quiet --batch --yes --decrypt --passphrase "$passphrase" \ --output "$HOME/secrets/config.yml" "random_word/config.yml.gpg"; then echo "File...
magicoder
shell
You are tasked with implementing a Python class that simulates a simple banking system. The class should support basic operations such as account creation, deposit, withdrawal, and balance inquiry. Additionally, the class should incorporate a Bank Communication Module (BCM) for sending notifications to account holders....
```python from .bcm import BCM class BankSystem: def __init__(self): self.accounts = {} def create_account(self, account_number, initial_balance): if account_number not in self.accounts: self.accounts[account_number] = initial_balance print(f"Account {account_number} cr...
magicoder
python
You are tasked with creating a program that processes and analyzes VM (Virtual Machine) saved state files. The VM saved state files contain crucial information about the state of a virtual machine at a specific point in time. Your program needs to extract and interpret this information to provide insights into the virt...
```python from typing import List, Any import struct def process_vm_saved_state_files(file_paths: List[str]) -> Any: results = {} for file_path in file_paths: with open(file_path, 'rb') as file: # Read and process the VM saved state file # Example: Extract CPU registers, memory ...
magicoder
python
You are tasked with creating a Bash script that processes a Genomic Transfer Format (GTF) file to extract specific information. The GTF file contains genomic annotation data, including details about gene locations, exons, and other features. Your script should take the GTF file as input and perform the following tasks:...
```bash #!/bin/bash GTF=$1 # Extract gene names and their corresponding chromosome locations awk '$3 == "gene" {print $10, $1":"$4"-"$5}' $GTF > gene_info.txt # Calculate the total number of exons for each gene awk '$3 == "exon" {exon_count[$10]++} END {for (gene in exon_count) print gene, exon_count[gene]}' $GTF > ...
magicoder
shell
You are tasked with designing a URL routing system for a web application using Django. The given code snippet represents a part of the URL configuration for the application. Each `path` function maps a URL pattern to a corresponding view function or class-based view. The `RedirectView` is used to redirect the root URL ...
To add the new URL pattern for user authentication, the following `path` function should be added to the URL configuration: ```python from django.urls import path from django.views.generic import RedirectView from . import views # Import the views module containing UserLoginView urlpatterns = [ path('question/',...
magicoder
python
You are tasked with creating a function that converts data into tags based on a given key and vocabulary. The function should handle various data types and ensure that the tags are properly formatted. You are provided with a code snippet that partially implements this functionality. You need to complete the function `...
```python def convert_to_tags(key, data, context, vocab): new_tags = data.get(key, None) # Retrieve the tags from data using the provided key if not new_tags: # Handle the case where tags are not present or empty return if isinstance(new_tags, str): # Convert a string tag to a list of tags ...
magicoder
python
You are tasked with creating a Python function to extract URLs of articles from a web gallery. The function `getGalleryArticleURLs` takes three parameters: `gallery_url` (the base URL of the gallery), `page` (the page number to scrape), and `headers` (HTTP headers for the request). The function should make an HTTP GET ...
```python import requests from bs4 import BeautifulSoup from typing import List def getGalleryArticleURLs(gallery_url: str, page: int, headers: dict) -> List[str]: response = requests.get(f"{gallery_url}?od=T31&category=0&po={page}", headers=headers) urls = [] if response.status_code == 200: html =...
magicoder
python
You are tasked with implementing a module system for a virtual reality game development platform. The platform supports importing and exporting datasets for various game elements. The code snippet provided is an example of exporting all elements from a module called "MinecraftDataSet". Your task is to create a TypeScr...
```typescript // Define a class to represent the module system class ModuleSystem { private modules: Record<string, any> = {}; // Register a new dataset module registerModule(moduleName: string, module: any) { this.modules[moduleName] = module; } // Export all elements from a registered dataset module ...
magicoder
typescript
You are tasked with creating a Django migration for a task management application. The application has a `Tag` model with a field `username` that needs to be altered. The current field is a `CharField` with a default value of 'sa' and a maximum length of 50 characters. Your task is to modify the migration file to chang...
```python class Migration(migrations.Migration): dependencies = [ ('tasks', '0022_auto_20190305_2121'), ] operations = [ migrations.AlterField( model_name='tag', name='username', field=models.CharField(default='admin', max_length=100), # Updated default...
magicoder
python
You are tasked with implementing a Python class that handles order keys for a point of sale (POS) system. The class should include a method for creating order keys from a given input. The order key is a string that represents a unique identifier for a particular order in the POS system. The input for creating the order...
```python class PosOrderKey: def __init__(self): self._pos_order_key = None @classmethod def from_alipay_dict(cls, value): return f"AlipayOrder{value['order_id']}" def create_order_key(self, input_dict): if input_dict.get("source") == "Alipay": return self.from_alip...
magicoder
python
You are tasked with implementing a Python class that performs scaling of experimental data in the context of X-ray crystallography. The provided code snippet serves as a starting point for the implementation. Your task is to complete the `Script` class by adding methods to perform the scaling algorithm and handle relev...
```python class Script(Subject): """Main script to run the scaling algorithm.""" def __init__(self, params, experiments, reflections): super(Script, self).__init__( events=["merging_statistics", "run_script", "run_scale_and_filter"] ) self.scaler = None self.scaled_m...
magicoder
python
You are tasked with implementing a class for managing snapshots from a set of cameras. The class should provide methods for triggering a full-frame snapshot for a specific camera and for retrieving snapshots for a list of cameras. You are given a partial code snippet for the class, which includes a method for triggeri...
```python import yaml class CameraManager: def __init__(self): # Initialize the camera manager with necessary attributes self.cameras = [] def TriggerFullFrameSnapshot(self, basestation, camera): # Implementation for triggering a full-frame snapshot for a specific camera # (Ass...
magicoder
python
You are tasked with implementing a custom exception class for a MongoDB client library. The provided code snippet is a partial implementation of the `MongoException` class, which is used to represent exceptions specific to MongoDB operations. Your task is to complete the implementation of the `MongoException` class by ...
```java public class MongoException extends Exception { private int code; /** * Constructs a MongoException with the specified error code. * * @param code the error code */ public MongoException(int code) { this.code = code; } /** * Returns the error code associate...
magicoder
java
You are tasked with implementing a simple application launcher that can gracefully handle deferred imports and display a dialog window. The application launcher should be able to show a dialog with a specified title and content. You are provided with a code snippet that demonstrates the usage of the application launch...
```python class ApplicationLauncher: def __init__(self): self.dialog_module = None def deferred_import(self, module_name): if self.dialog_module is None: self.dialog_module = __import__(module_name, fromlist=['']) def show_dialog(self, title, content): if self.dialog_mo...
magicoder
python
You are tasked with creating a Python script that processes gene data to identify interactions between different genes. The script should take input gene data and output the interactions between the genes. Your task is to implement the `gene2gene.py` script that processes gene data and identifies interactions between ...
```python import argparse import pandas as pd def identify_gene_interactions(input_file, threshold): # Read input gene data from the specified file into a pandas DataFrame gene_data = pd.read_csv(input_file, sep='\t') # Initialize a list to store the interactions between genes interactions = [] #...
magicoder
python
You are tasked with creating a Node.js utility function that writes a file to a specified directory. However, the function should gracefully handle potential errors that may occur during the file writing process. You are provided with a code snippet that sets up Jest spies to mock the behavior of the `fs.mkdir` and `fs...
```javascript const fs = require('fs').promises; const path = require('path'); async function writeFileToDir(outputDir, outputFile, fileContent) { try { await fs.mkdir(outputDir); // Attempt to create the directory } catch (error) { if (error.code !== 'EEXIST') { throw new Error(`Error creating direc...
magicoder
javascript
You are tasked with creating a Python function that simulates a simple banking system. The system should allow users to create accounts, deposit funds, withdraw funds, and check their balance. The function should be implemented using object-oriented programming principles. Your task is to implement the `BankAccount` c...
```python class BankAccount: def __init__(self, account_number): self.account_number = account_number self.balance = 0 def deposit(self, amount): self.balance += amount def withdraw(self, amount): if self.balance >= amount: self.balance -= amount else: ...
magicoder
python
You are tasked with creating a Python function that generates a forecast plot for stock prices based on historical data. The function should take in a pandas DataFrame containing historical stock prices and use a simple forecasting technique to predict future prices. The forecast plot should display both the historical...
```python import pandas as pd import numpy as np import matplotlib.pyplot as plt def generate_forecast_plot(df: pd.DataFrame, forecast_period: int) -> None: # Calculate simple moving average for the historical data df['Forecast'] = df['Adj. Close'].rolling(window=30).mean() # Generate forecast for the fut...
magicoder
python
You are tasked with implementing a Python function that generates a 2D grid of points using NumPy. The function should take in the center coordinates, half ranges, and the number of points along each axis, and return the meshgrid of points. Write a function `generate_meshgrid` that takes in the following parameters: -...
```python import numpy as np def generate_meshgrid(xcen, ycen, xhalfrng, yhalfrng, xnpts, ynpts): x = np.linspace(xcen - xhalfrng, xcen + xhalfrng, xnpts) y = np.linspace(ycen - yhalfrng, ycen + yhalfrng, ynpts) xx, yy = np.meshgrid(x, y) return xx, yy ``` The `generate_meshgrid` function first create...
magicoder
python
You are tasked with creating a Python class that manages a set of scales and labels for adjusting image processing parameters. The class should allow for the addition of scales and labels, as well as provide a method to retrieve the current settings for all scales. Your task is to implement the `ImageProcessingGUI` cl...
```python from tkinter import Scale, Label, Tk class ImageProcessingGUI: def __init__(self): self.scales_and_labels = [] self.root = Tk() def add_scale_and_label(self, label_text): scale = Scale(self.root) label = Label(self.root, text=label_text) scale.pack() l...
magicoder
python
You are tasked with implementing a custom layout in Android that positions a view to the right side of its parent using the RelativeLayout class. The provided code snippet demonstrates the creation of layout parameters and setting rules for positioning the view. Your task is to write a method that creates a RelativeLay...
```java import android.content.Context; import android.view.ViewGroup; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.RelativeLayout.LayoutParams; public class CustomLayoutHelper { public static RelativeLayout createRightAlignedView(Context context) { RelativeL...
magicoder
java
You are tasked with creating a script to run the clang-tidy tool on a set of source files. The script will take the path to the clang tidy binary, the path to the compile_commands.json file to use, a flag to indicate whether fixes should be applied, and a list of files to run clang-tidy on. Your task is to write a she...
```bash #!/bin/bash # Check if the required arguments are provided if [ $# -lt 4 ]; then echo "Usage: $0 <clang-tidy-binary> <compile_commands.json> <apply-fixes> <file1> [file2 ...]" exit 1 fi CLANG_TIDY=$1 COMPILE_COMMANDS=$2 APPLY_FIXES=$3 shift 3 # Iterate through the list of files and run clang-tidy for...
magicoder
shell
You are tasked with creating a simple music composition program. The program should take a series of notes and durations as input and play them using a speaker. Each note is represented by a letter (A-G) followed by an optional number indicating the octave, and each duration is represented as a fraction of a whole note...
```python class Speaker: def play(self, note, duration): print(f"Playing {note} for {duration} beats") def compose_music(notes): speaker = Speaker() for note, duration in notes: speaker.play(note, duration) # Test the compose_music function notes = [('A1', 1/4), ('D2', 1/4), ('A1', 1/4), (...
magicoder
python
You are tasked with creating a Python program to control a simple traffic light system using Raspberry Pi and the GPIO Zero library. The traffic light system consists of two sets of lights: one for incoming traffic (IN1 and IN2) and one for outgoing traffic (OUT1 and OUT2). Each set of lights has a corresponding button...
```python from gpiozero import Button, LED from signal import pause # Define GPIO pin numbers for the traffic lights and buttons IN1 = 17 OUT1 = 18 IN2 = 22 OUT2 = 23 # Initialize the traffic lights and buttons in1_button = Button(IN1, pull_up=False) out1_button = Button(OUT1, pull_up=False) in2_button = Button(IN2, ...
magicoder
python
You are tasked with implementing a rotation component for a 2D graphics library. The rotation component should allow users to rotate a given shape by a specified angle. Your task is to create a class that provides this functionality and write a method to add rotation to the component. Your task is to implement the `ad...
```python import math class RotationComponent: @staticmethod def add_rotation(shape, angle_degrees): angle_radians = math.radians(angle_degrees) rotated_shape = [] for point in shape: x = point[0] y = point[1] x_prime = x * math.cos(angle_radians) - y...
magicoder
python
You are tasked with implementing a function that processes a list of suggested trials and their corresponding parameters to generate a set of suggested parameter sets. Each trial is represented as a dictionary containing the trial's parameters, and each parameter is represented as a dictionary containing the parameter'...
```python from typing import List, Dict, Any, Tuple def generate_suggested_parameter_sets(suggested_trials: List[Dict[str, Any]]) -> Tuple[Dict[str, Any]]: suggested_parameter_sets = [] for trial in suggested_trials: parameter_set = {} for parameter in trial['parameters']: param_nam...
magicoder
python
You are given a function `getGapUntilNextRange` that takes in two parameters: 1. `ranges`: an array of arrays, where each inner array represents a range with two elements - the start and end of the range. 2. `num`: a number representing the input value. The function should return the gap until the next range if the gi...
```javascript function getGapUntilNextRange(ranges, num) { for (let i = 0; i < ranges.length; i++) { if (num >= ranges[i][0] && num <= ranges[i][1]) { if (i < ranges.length - 1) { return ranges[i + 1][0] - num; } else { return -1; } } } return -1; } ``` The `getGapUntilN...
magicoder
javascript
You are tasked with implementing a C++ program that simulates a simple HTTP server. The server will handle different types of requests and respond with appropriate data. Your task is to create a class structure for handling various types of HTTP responses. You are provided with the following code snippet as a starting...
```cpp #include <iostream> // Base class for HTTP responses class HttpResponse { public: virtual void generateResponse() const = 0; virtual ~HttpResponse() = default; }; // Subclass for handling login responses class LoginResponse : public HttpResponse { public: void generateResponse() const override { ...
magicoder
cpp
You are tasked with implementing a soft deletion mechanism for a database-backed application. Soft deletion involves marking records as "deleted" without physically removing them from the database. To achieve this, you need to modify the application's configuration to enable the soft deletion feature. The given code s...
```python # soft_deletion/apps.py from django.apps import AppConfig class SoftDeletionConfig(AppConfig): name = 'soft_deletion' def ready(self): import soft_deletion.signals # Import signals to handle soft deletion logic ``` In the solution, the `SoftDeletionConfig` class is defined within the `soft...
magicoder
python
You are tasked with creating a Java program to manage user roles within a system. The program should include classes for User, UserInfo, RoleBean, and UserHelper, as well as an interface for RequestCallBack. Additionally, you need to implement a LoginApi interface, a LoginInteractor class, and various utility classes f...
```java import java.util.ArrayList; import java.util.List; class User { private String userId; private String username; private String email; // Constructor, getters, and setters } class UserInfo { private User user; private List<RoleBean> roles; // Constructor, getters, and setters } c...
magicoder
java
You are tasked with implementing a custom content handler for managing email contact information in a content management system. The `EmailContactPartHandler` class is responsible for handling the storage and retrieval of email contact information. The class extends the `ContentHandler` and takes an `IRepository<EmailC...
```csharp using Orchard.ContentManagement.Handlers; using Orchard.Data; using YourNamespace.Models; // Replace YourNamespace with the actual namespace for EmailContactPartRecord public class EmailContactPartHandler : ContentHandler { public EmailContactPartHandler(IRepository<EmailContactPartRecord> repository) ...
magicoder
csharp
You are working on a project that involves implementing a weighted subset algorithm. The algorithm is responsible for selecting a subset of elements from a given set, where each element has an associated weight. The goal is to maximize the total weight of the selected subset while ensuring that the total weight does no...
```python from typing import List, Tuple, Union def get(index: int) -> Tuple[Union[int, float], Union[int, float]]: # Placeholder implementation for the get function pass def weighted(elements: List[Tuple[Union[int, float], Union[int, float]]], limit: Union[int, float]) -> List[Tuple[Union[int, float], Union[...
magicoder
python
You are tasked with implementing a neural network activation function and its derivative. The activation function to be implemented is the softmax function, which is commonly used in the output layer of a neural network for multi-class classification problems. The softmax function takes a vector of real numbers as inpu...
```python import numpy as np class NeuralNetworkActivation: def softmax(self, x): x = np.clip(x, -700, 700) # Clip input values for numerical stability exp_x = np.exp(x) exp_sum = np.sum(exp_x) return exp_x / exp_sum def softmax_derivative(self, x): s = self.softmax(x)...
magicoder
python
You are tasked with implementing a window management system for a text classification application. The system should create and display windows to show the classification results and then destroy these windows once the user has viewed them. You are given a code snippet that provides access to the UNICHARSET and a funct...
```cpp #include <vector> #include <iostream> // Define the Window structure struct Window { int id; // Other window attributes }; class UNICHARSET { // Define UNICHARSET members and methods }; // WindowManager class implementation class WindowManager { public: // Displays classification as the given shape_id...
magicoder
cpp
You are tasked with writing a Python function to process a large FASTA file containing DNA sequences. The goal is to batch process the sequences and write them to separate output files, with each file containing a specified number of sequences. You are provided with a code snippet that imports necessary modules and in...
```python import os from Bio import SeqIO from cupcake.io.SeqReaders import LazyFastaReader from cupcake2.io.FileIO import write_seqids_to_fasta def batch_process_sequences(input_file, num_seqs_per_batch): d = LazyFastaReader(input_file) total_seqs = len(d) num_batches = total_seqs // num_seqs_per_batch + ...
magicoder
python
You are tasked with implementing a module resolution algorithm for a simple JavaScript module system. The system uses the `export` statement to make functions, objects, or primitives available for use in other modules. When a module imports another module using the `import` statement, the module resolution algorithm mu...
```javascript function resolveModulePath(importingModulePath, importedModulePath) { if (importedModulePath.startsWith('./')) { const importingDir = importingModulePath.substring(0, importingModulePath.lastIndexOf('/') + 1); return importingDir + importedModulePath.substring(2) + '.js'; } else if (importedMo...
magicoder
javascript
You are tasked with implementing a thread-safe map data structure in C++. The map should support concurrent read and write operations without causing data corruption or race conditions. You need to design a class that encapsulates the functionality of a map while ensuring thread safety. Your task is to implement the `...
```cpp #include <map> #include <mutex> template <typename Key, typename Value> class ThreadSafeMap { public: void insert(const Key& key, const Value& value) { std::lock_guard<std::mutex> lock(mutex_); map_[key] = value; } void erase(const Key& key) { std::lock_guard<std::mutex> loc...
magicoder
cpp
You are tasked with creating a program that processes a version history log and extracts the breaking changes from a specific version. The version history log is a multi-line string where each line represents a version and its associated breaking changes. The breaking changes are denoted by lines starting with "###" fo...
```python def extract_breaking_changes(version_history, target_version): breaking_changes = [] lines = version_history.split('\n') version_found = False for line in lines: if line.startswith("### " + target_version + " breaking changes"): version_found = True elif line.starts...
magicoder
python
You are tasked with implementing a custom data structure to store question-answer pairs for a quiz application. The data structure should support adding, removing, and retrieving question-answer pairs, as well as providing the ability to check if a question exists in the structure. You need to implement a class `QAObj...
```python class QAObject: def __init__(self, question, answer): self.question = question self.answer = answer def __repr__(self): return f"Question: {self.question}, Answer: {self.answer}" class QuizDatabase: def __init__(self): self.qa_collection = [] def add_qa(self...
magicoder
python
You are tasked with implementing a function to generate all possible sequences of length N using an alphabet of size `alphabetSize`. Each sequence is represented as a string of characters from 'A' to 'A' + `alphabetSize` - 1. The sequences should be generated in lexicographical order. Write a function `generateSequenc...
```cpp #include <vector> #include <string> #include <cmath> std::vector<std::string> generateSequences(int N, int alphabetSize) { if (N == 1) { return std::vector<std::string>(); } std::vector<std::string> seqs; std::size_t base = alphabetSize; seqs.reserve(static_cast<std::size_t>(std::po...
magicoder
cpp
You are tasked with implementing a user registration feature for a web application using PHP and Laravel framework. The `AuthController` class extends the `Controller` class and contains a method `Register` to handle user registration requests. The method receives a `Request` object as a parameter, which contains the u...
```php use App\Models\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; class AuthController extends Controller { public function Register(Request $request) { // Validate the user input data $validatedData = $request->validate([ 'name' => 'required|string|max:2...
magicoder
php
You are tasked with creating a Python function that generates a random string of a specified length using a given set of allowed characters. Your function should take two optional parameters: `length` (default value of 12) and `allowed_chars` (default value of all lowercase and uppercase letters plus digits). Write a ...
```python import random import string def generate_random_string(length=12, allowed_chars=string.ascii_letters + string.digits): return ''.join(random.choice(allowed_chars) for _ in range(length)) ``` The `generate_random_string` function uses the `random.choice` method to select random...
magicoder
python
You are tasked with creating a Python program to process live video feed from a webcam and detect QR codes using the OpenCV and pyzbar libraries. Your program should capture frames from the webcam, decode any QR codes present in the frames, and display the decoded information. Your program should perform the following...
```python import cv2 import pyzbar.pyzbar as pyzbar def main(): cap = cv2.VideoCapture(0 + cv2.CAP_DSHOW) # Initialize webcam capture font = cv2.FONT_HERSHEY_PLAIN while True: _, frame = cap.read() # Capture frame from the webcam decoded_objects = pyzbar.decode(frame) # Decode any QR co...
magicoder
python
You are tasked with creating a Python program that renames directories within a specified start path by transliterating their names. Transliteration is the process of converting text from one script into another, often preserving the pronunciation of the original words. Your program should utilize the `argparse` module...
```python import os import sys import argparse import unicodedata def transliterate(text): return ''.join( c for c in unicodedata.normalize('NFD', text) if unicodedata.category(c) != 'Mn' ) def rename_directories(start_path): for root, dirs, _ in os.walk(start_path): for directory ...
magicoder
python
You are tasked with creating a program to manage domain applications and their associated signed marks. A domain application contains information about a domain name registration, and a signed mark is a cryptographic signature associated with a trademark. Your task is to implement a method to reload a domain applicati...
```java // Reloads the domain application from the database private DomainApplication reloadDomainApplication() { return ofy().load().entity(domainApplication).now(); } // Verifies the successful reloading of the domain application with the encoded signed mark @Test public void testSuccess() throws Exception { ...
magicoder
java
You are tasked with creating a file monitoring application in C#. The application should allow users to select a directory and start monitoring it for any file changes. When a file is created, modified, or deleted within the monitored directory, the application should display a message indicating the type of change and...
```csharp using System; using System.IO; using System.Windows.Forms; namespace FileMonitoringApp { public partial class Form1 : Form { private FileSystemWatcher fileWatcher; public Form1() { InitializeComponent(); fileWatcher = new FileSystemWatcher(); ...
magicoder
csharp
You are tasked with implementing a state machine in Rust using the `SmartDefault` and `MachineImpl` traits. The state machine will have three states: `Init`, `Start`, and `Stop`. Each state will have its own behavior and transitions. Your goal is to create a Rust program that defines the state machine and demonstrates ...
```rust use smart_default::SmartDefault; use state_machine::MachineImpl; #[derive(Debug, SmartDefault, MachineImpl)] pub enum StateTable { #[default] Init, Start, Stop, } impl StateTable { fn on_init(&self) { match self { StateTable::Init => { println!("Initiali...
magicoder
rust
You are tasked with implementing a degradation profile system for a software application. The degradation profile is a representation of how the performance of a system degrades over time. Your goal is to create a class that implements the `IDegradationProfile` interface and provides methods to calculate the degradatio...
```csharp public class DegradationProfile : IDegradationProfile { private List<double> historicalData; public DegradationProfile(List<double> historicalData) { this.historicalData = historicalData; } public double CalculateDegradationRate() { // Simple linear regression to calc...
magicoder
csharp
You are tasked with simulating the behavior of a debugger in a multi-threaded environment. The given code snippet is a part of a debugger script that is responsible for stepping over a specific function called `__select` to avoid terminating the thread prematurely. Your goal is to implement a simplified version of this...
```python from typing import List class Thread: def __init__(self, frames): self.frames = frames def StepOver(self): # Simulated StepOver method pass class Frame: def __init__(self, function_name): self.function_name = function_name def GetFunctionName(self): ...
magicoder
python
You are tasked with creating a Python program to simulate a simple game of sending and receiving messages between two players. The game involves sending a payload message, interacting with the opponent, and then closing the communication. Your task is to implement the `Player` class and its methods to achieve this game...
```python class Player: def __init__(self, name): self.name = name def sendline(self, payload): print(f"{self.name} sent: {payload}") def interactive(self): print(f"{self.name} is interacting with the opponent") def close(self): print(f"{self.name} closed the communica...
magicoder
python
You are tasked with implementing a function that processes a list of transactions and calculates the total balance for a specific account. Each transaction consists of a date, a description, an amount, and an account identifier. The function should take in the list of transactions and the account identifier, and return...
```rust fn calculate_balance(transactions: &[Transaction], account_id: u32) -> f64 { let mut balance = 0.0; for transaction in transactions { if transaction.account_id == account_id { balance += transaction.amount; } } balance } ```
magicoder
rust
You are tasked with creating a program that can parse and extract localized string information from a C# resource file. The resource file contains various string properties, each representing a localized string in the application. Each property has a name and a corresponding value, which is the localized string itself....
```python def parseResourceFile(resource_content: str) -> dict: properties = {} lines = resource_content.split("\n") for i in range(len(lines)): line = lines[i].strip() if line.startswith("public static string"): property_name = line.split(" ")[4].strip("{") localized...
magicoder
python
You are tasked with implementing a simplified version of a visitor pattern for an abstract syntax tree (AST) representing mathematical expressions. The AST consists of binary and unary expressions, as well as literal values. Your goal is to create a visitor that can evaluate the value of the AST based on the given expr...
```java public class Evaluator implements ExpressionVisitor { private double result; public double evaluate(Expression expression) { expression.accept(this); return result; } @Override public void visitBinaryExpression(BinaryExpression expression) { expression.getLeft().acc...
magicoder
java
You are tasked with implementing a text differencing algorithm to compare two versions of a document and generate a human-readable diff output. The algorithm should identify whether each line in the two versions is unchanged, inserted, or deleted, and provide a label for each line accordingly. You are given a code sni...
```javascript function generateARIALabel(diffEntryType, wineContent, owiginawWine, modifiedWine) { let awiaWabew = ''; switch (diffEntryType) { case DiffEntwyType.Equaw: if (owiginawWine === modifiedWine) { awiaWabew = nws.wocawize({ key: 'unchangedWine', comment: ['The pwac...
magicoder
javascript
You are tasked with implementing a function to determine the longest common prefix string amongst an array of strings. If there is no common prefix, the function should return an empty string "". You need to implement the following function: ```python def longest_common_prefix(strs: List[str]) -> str: pass ``` T...
```python from typing import List def longest_common_prefix(strs: List[str]) -> str: if not strs: return "" # Sort the list of strings strs.sort() # Compare the first and last strings in the sorted list first = strs[0] last = strs[-1] # Find the common prefix between the first an...
magicoder
python
You are tasked with creating a program that simulates a simple file system navigation tool. The program should take a series of commands as input and perform the corresponding actions. The commands will include changing directories, executing files, and displaying the current working directory. The program should supp...
```python import os def file_system_navigation(commands): current_directory = '/' output = [] for command in commands: if command.startswith('cd'): directory = command.split(' ')[1] if directory.startswith('/'): current_directory = directory else...
magicoder
python
You are tasked with creating a program that reads a file and extracts non-commented, non-empty lines that do not start with a space. Your program should read the file, ignore lines starting with '#' or containing only spaces, and store the valid lines in a vector for further processing. Write a function `extractValidL...
```cpp #include <iostream> #include <fstream> #include <vector> #include <stdexcept> std::vector<std::string> extractValidLines(const std::string& path) { std::ifstream file; file.open(path); if (!file.is_open()) { throw std::runtime_error("File not found or couldn't be opened"); } std::ve...
magicoder
cpp
You are tasked with creating a Python class that simulates a simple web service status tracker. The class should have the ability to update and retrieve the status of the web service. Additionally, it should provide a method to reset the status to a default value. Your task is to implement the class with the specified ...
```python class ServiceStatus: def __init__(self): self.status = "UNKNOWN" def update_status(self, new_status): self.status = new_status def get_status(self): return self.status def reset_status(self): self.status = "UNKNOWN" # Usage w_service = ServiceStatus() print...
magicoder
python
You are tasked with implementing a simple benchmarking tool to measure the execution time of various functions in a Python program. The provided code snippet demonstrates a basic benchmarking function and its usage. Your task is to create a Python class `Benchmark` that encapsulates the benchmarking functionality. The...
```python import time class Benchmark: def __init__(self): self.start_time = 0 self.end_time = 0 def start(self): self.start_time = time.time() def stop(self): self.end_time = time.time() def result(self): return self.end_time - self.start_time def reset(...
magicoder
python
You are given a code snippet that deals with workout data and the selection of the most suitable workout based on certain conditions. Your task is to implement a function that determines the overlapping workouts and selects the workout with the highest score. You are given the following information: - `all_workouts`: ...
```python class Window: def __init__(self, start_row, end_row, score): self.start_row = start_row self.end_row = end_row self.score = score def are_overlapping(window1, window2): return window1[0] < window2[1] and window1[1] > window2[0] def select_workout(all_workouts, all_workouts_pe...
magicoder
python
You are tasked with implementing a method to retrieve course habilitations from a given URL using the provided code snippet as a reference. The `CourseBuilder` class contains a method `getHabilitations(code, name)` that needs to be completed. The `getHabilitations` method should utilize the `BeautifulSoup` library to p...
```python from bs4 import BeautifulSoup from mwscanner.Course import Course from mwscanner.Mixins import UrlLoaderMixin from mwscanner.builders.HabilitationBuilder import HabilitationBuilder from mwscanner import BASE_URL class CourseBuilder(UrlLoaderMixin): def __init__(self): pass def getHabilitati...
magicoder
python
You are tasked with implementing a color matching algorithm for a digital art application. The algorithm should take a target color and find the closest matching color from a predefined set of colors. The colors are represented as RGB tuples, with each component ranging from 0 to 1. The distance between two colors is c...
```python import math def find_closest_color(target_color, color_set): def distance(color1, color2): return math.sqrt((color1[0] - color2[0]) ** 2 + (color1[1] - color2[1]) ** 2 + (color1[2] - color2[2]) ** 2) closest_color = color_set[0] min_distance = distance(target_color, color_set[0]) fo...
magicoder
python
You are tasked with implementing a background task processing system. The system should allow for the execution of tasks in the background, without blocking the main thread, and provide a way to handle the results of these tasks. Your task is to design and implement a `BackgroundTaskProcessor` class that provides the ...
```csharp using System; using System.Collections.Concurrent; using System.Threading; using NUnit.Framework; public class BackgroundTaskProcessor { private readonly ConcurrentQueue<Action> taskQueue = new ConcurrentQueue<Action>(); private readonly AutoResetEvent taskEvent = new AutoResetEvent(false); priva...
magicoder
csharp
You are tasked with implementing a function to calculate the divided differences for a given set of data points. Divided differences are used in polynomial interpolation and numerical analysis. The divided difference of a set of points is a way to represent the coefficients of the interpolating polynomial. The function...
```cpp namespace photospline { double divdiff(const double* x, const double* y, size_t n) { if (n == 1) { return y[0]; } else { double* temp = new double[n]; for (size_t i = 0; i < n; i++) { temp[i] = y[i]; } for (size_t j =...
magicoder
cpp
You are tasked with creating a Python module that simulates a simple particle system. The module should be able to initialize particle systems, update their positions, and render them. To achieve this, you need to implement the following classes and functions: 1. `Particle`: A class representing a single particle with...
```python class Particle: def __init__(self, position, velocity, color): self.position = position self.velocity = velocity self.color = color def update_position(self): # Update the position based on the velocity self.position[0] += self.velocity[0] self.position...
magicoder
python
You are tasked with implementing a class hierarchy for handling HTTP responses in a web application. The base class `Response` is provided, and it contains a method `blob()` that is meant to return a `Blob` object representing the response body. However, the method is not yet implemented and currently throws a `BaseExc...
```java /** * Represents an HTTP response. */ class Response { /** * Not yet implemented */ blob(): Blob { throw new BaseException('"blob()" method not implemented on Response superclass'); } } /** * Represents an HTTP response with a body. */ class HttpResponse extends Response { ...
magicoder
java
You are tasked with implementing a class that manages the layout of labels in a Windows Forms application. The class should provide a method to calculate the total width and height required to display a set of labels in a specified layout. You are given the following information: - Each label is represented by its pos...
```csharp public class LabelLayoutManager { public int MarginX { get; set; } public int MarginY { get; set; } public (int width, int height) CalculateTotalSize(List<(int x, int y, int textLength)> labels) { int maxWidth = 0; int totalHeight = 0; foreach (var label in labels) ...
magicoder
csharp
You are tasked with implementing a function that calculates the shortest line between two geometries using the PyGEOS library. PyGEOS is a Python binding for the GEOS C++ library, which provides geometric operations. The function should take two geometries as input and return the shortest line between them. If one or b...
```python import pygeos def calculate_shortest_line(geometry1, geometry2): if pygeos.is_empty(geometry1) or pygeos.is_empty(geometry2): return None else: return pygeos.shortest_line(geometry1, geometry2) ``` In the solution, the `calculate_shortest_line` function first checks if either of the i...
magicoder
python
You are tasked with creating a Python program to analyze and visualize the performance of a machine learning model. The program should utilize the Matplotlib library to plot the accuracy of the model on different datasets over multiple epochs. Additionally, the program should include a notification sound to indicate wh...
```python import matplotlib.pyplot as plt import winsound # Sample data for epochs and categorical accuracy epochs_range = [1, 2, 3, 4, 5] categorical_acc = [0.75, 0.82, 0.88, 0.91, 0.95] # Plotting the accuracy over epochs plt.plot(epochs_range, categorical_acc, 'bo', label="训练集的精确度") plt.title('不同数据集的精确度') plt.xlab...
magicoder
python
You are tasked with creating a program to visualize a Rubik's Cube using a graphical user interface (GUI). The Rubik's Cube will be represented as a 3x3x3 grid of colored stickers on each face. Your program should use the provided code snippet as a starting point and extend it to create a GUI that displays the Rubik's ...
```python import tkinter class RubiksCubeGUI: def __init__(self, master, rc): self.master = master self.rc = rc self.size = {'cubie': 50, 'space': 5} self.c = tkinter.Canvas(master, width=800, height=600) self.c.pack() self.draw_cube() def draw_cube(self): ...
magicoder
python
You are tasked with implementing a function that returns the end of the month from a given date. The end of the month is defined as the last moment of the last day of the month in the same year and month as the input date. You are provided with a code snippet that includes a function `getEndOfMonth(date)` which takes ...
```javascript /** * Gets the end of the month from date. * @param {Date} date - The input date. * @returns {Date} - The end of the month from the input date. */ function getEndOfMonth(date) { const year = date.getFullYear(); const month = date.getMonth(); // Create a new date with the date's year and month ...
magicoder
javascript
You are tasked with creating a Python class that can serialize data from a given model. The class should be able to handle different fields and models, and it should be designed to work within a larger framework. Your task is to implement a generic serializer class that can handle various models and fields. Your task ...
```python from rest_framework import serializers class GenericModelSerializer(serializers.ModelSerializer): def __init__(self, model, *args, **kwargs): self.Meta = type('Meta', (), {'model': model, 'fields': "__all__"}) super().__init__(*args, **kwargs) # Example usage device_serializer = GenericM...
magicoder
python
You are tasked with creating a Python decorator that logs the execution time of a function and handles any exceptions that may occur during its execution. The decorator should use the `logging` module to log the start and end time of the function, as well as any exceptions that occur. Additionally, the decorator should...
```python import logging import time from functools import wraps def timed_execution(log_level=logging.INFO): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): logger = logging.getLogger(func.__name__) start_time = time.time() try: r...
magicoder
python
You are working on a project that involves processing images containing multiple bounding boxes. Each bounding box is represented by its coordinates and dimensions, and you need to draw rectangles around the non-empty text regions within these bounding boxes. The code snippet provided is a part of the process that draw...
```python from typing import List, Tuple def draw_text_rectangles(n_boxes: int, text: List[str], left: List[int], top: List[int], width: List[int], height: List[int]) -> List[Tuple[int, int, int, int]]: rectangles = [] for i in range(n_boxes): if text[i].strip() != '': x, y, w, h = left[i],...
magicoder
python
You are tasked with creating a function that generates a unique key for uploading files to a cloud storage service. The key should be in the format "test-1b-{timestamp}" and should be used to upload a temporary file to a specified bucket. You need to implement a function that takes the bucket name, a configuration obje...
```rust use chrono::{Utc, Timelike}; use std::fs::File; use std::io::Read; struct Config { // Assume the necessary configuration fields } struct UploadResponse { // Assume the structure of the upload response } #[derive(Debug)] enum UploadError { // Define potential upload errors } fn create_temp_file(i...
magicoder
rust
You are tasked with implementing a simple data structure to store key-value pairs and providing a method to retrieve the value associated with a given key. The data structure should support efficient retrieval of values by their corresponding keys. You are given the following code snippet as a starting point: ```cpp ...
```cpp #include <unordered_map> #include <stdexcept> template <typename Key, typename Value> class KeyValueStore { private: std::unordered_map<Key, Value> store; public: void insert(const Key& key, const Value& value) { store[key] = value; } const Value& getValue(const Key& key) const { ...
magicoder
cpp
You are tasked with designing a database schema for a question-and-answer platform. The platform allows users to downvote questions, answers, and comments. You need to create a database schema to store downvotes, ensuring referential integrity with the users, questions, answers, and comments tables. Your task is to de...
To implement the downvoting feature in the question-and-answer platform, we can define the following database tables and relationships: 1. Table: users - Columns: - user_id (Primary Key) - username - ... 2. Table: questions - Columns: - question_id (Primary Key) - user_id (Foreign Key r...
magicoder
python
You are tasked with implementing a graph neural network (GNN) model for semi-supervised node classification using the GraphSage algorithm. GraphSage is a popular GNN model that leverages neighborhood aggregation to learn node representations in a graph. Your goal is to complete the implementation of the `Encoder` class...
```python import torch class Encoder: def __init__(self, features, num_features, hidden_dim, adj_list, agg1, gcn=False, cuda=False): self.features = features self.num_features = num_features self.hidden_dim = hidden_dim self.adj_list = adj_list self.agg1 = agg1 self....
magicoder
python
You are tasked with implementing a data structure to manage a user's topics and their associated details. The user can have multiple topics, and each topic can have a reference to the user who created it. Additionally, there is a requirement to navigate to a topic's details when a user selects a topic from a table view...
```swift class User { var topics: [Topic] = [] func addTopic(_ topic: Topic) { topics.append(topic) } func topic(at index: Int) -> Topic? { guard index >= 0, index < topics.count else { return nil } return topics[index] } } class Topic { var details...
magicoder
swift
You are tasked with implementing a Python class that processes and manipulates tagged text data. The class should be able to handle the extraction and manipulation of tagged text within a given context. You are provided with a code snippet that demonstrates the usage of a `PreTaggedContextFactory` class and a tagged s...
```python class TaggedTextProcessor: @staticmethod def extract_tagged_text(tagged_sentence): start_tag = '<NEG>' end_tag = '</NEG>' start_index = tagged_sentence.find(start_tag) end_index = tagged_sentence.find(end_tag) if start_index != -1 and end_index != -1: ...
magicoder
python
You are tasked with implementing a Pokemon database system that can store and retrieve Pokemon data. The `PokemonDb` class has a method `set` that allows you to add or update a Pokemon's information in the database. The method takes an object with the following properties: `id` (a unique identifier for the Pokemon), `a...
```javascript class PokemonDb { constructor() { this.pokemonData = []; } set(pokemon) { const existingPokemonIndex = this.pokemonData.findIndex(p => p.id === pokemon.id); if (existingPokemonIndex !== -1) { this.pokemonData[existingPokemonIndex] = pokemon; } else { this.pokemonData.pus...
magicoder
javascript
You are tasked with implementing a C++ class called `cluster_info` that will store information about a cluster in a distributed computing system. The class should have the following functionalities: 1. A constructor that initializes the cluster information with default values. 2. Methods to set and get the cluster nam...
```cpp #include <string> class cluster_info { private: std::string cluster_name; int num_nodes; double total_memory_capacity; public: // Constructor to initialize the cluster information with default values cluster_info() : cluster_name("DefaultCluster"), num_nodes(0), total_memory_capacity(0.0) {...
magicoder
cpp