query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with implementing a method to clear a specific property in a builder class. The builder class is used to construct instances of a data structure, and the method should reset the property to its default value and update the builder's internal state accordingly. You are given a code snippet that partially...
```java public Builder ClearPropertyName() { PrepareBuilder(); if (SupportFieldPresence(descriptor_->file())) { result.hasPropertyName = false; } result.propertyName_ = defaultValue(); return this; } ``` In the solution, `ClearPropertyName` is the completed method based on the given code snippet. The meth...
magicoder
java
You are tasked with implementing a configuration management system for a web application. The system should allow registering configuration parameters with various flags to control their behavior. Each parameter can have different flags, such as `FLAG_REQUIRED`, `FLAG_NOSTORE`, `FLAG_ALLOW_EMPTY`, and `FLAG_PRIORITIZE_...
```python class ConfigurationError(Exception): pass class ConfigurationManager: def __init__(self): self.config_params = {} def register(self, name, default=None, type=None, flags=0): self.config_params[name] = { 'default': default, 'type': type, 'flags'...
magicoder
python
You are tasked with implementing a custom serialization and deserialization algorithm for a specific data structure. The data structure consists of a list of brawlers, each represented by a unique identifier and a name. The serialization algorithm should encode the data structure into a compact binary format, while the...
```python class Brawler: def __init__(self, id, name): self.id = id self.name = name def serialize(self): serialized_id = self._writeVInt(self.id) serialized_name_length = self._writeVInt(len(self.name)) serialized_name = self.name.encode('utf-8') return serializ...
magicoder
python
You are tasked with creating a PHP class that manages the publishing of configuration files for a Laravel application. The class should include a method to publish a specific configuration file when the application is running in the console. Your task is to implement the `publishConfigFile` method within the given `Co...
```php <?php class ConfigPublisher { protected $app; public function __construct($app) { $this->app = $app; } public function publishConfigFile() { if ($this->app->runningInConsole()) { $this->publishes([ __DIR__ . '/../config/config.php' => config_...
magicoder
php
You are tasked with implementing a function to retrieve comments from a YouTube video using the YouTube Data API. The function should handle pagination by retrieving subsequent pages of comments using a page token. You are given a code snippet that partially implements the comment retrieval function. The function take...
```python import requests def comment(id, page_token=''): url = "https://youtube.googleapis.com/youtube/v3/commentThreads" params = { "part": "snippet,replies", "videoId": id, "key": KEY } if page_token: params["pageToken"] = page_token comments = [] while True...
magicoder
python
You are tasked with implementing a custom directive in reStructuredText using the `docutils` library in Python. The custom directive will create a new admonition type called "helloworld" that can be used in reStructuredText documents. Your task is to create a class `helloworld` that inherits from `nodes.Admonition` an...
```python from docutils import nodes from docutils.parsers.rst import Directive from docutils.parsers.rst import directives class helloworld(nodes.Admonition, nodes.Element): pass def visit_helloworld_node(self, node): self.visit_admonition(node) class HelloWorldDirective(Directive): has_content = Tru...
magicoder
python
You are tasked with creating a web-based system for managing drawing files and certificates for Amadeus Marine Ltd. The system should provide a solution to the risk of lost or misplaced drawing files and should have the capability to manage certificates, completed and work-in-progress drawings. Your task is to design a...
```python from flask import Flask, request, jsonify from flask_sqlalchemy import SQLAlchemy from sqlalchemy import Column, Integer, String, Boolean app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///drawing_database.db' db = SQLAlchemy(app) class Drawing(db.Model): id = Column(Integer, prima...
magicoder
python
You are tasked with creating a Python script to manage the start and stop operations of an OpenResty server. The script should utilize the `subprocess` module to execute commands and handle any errors that may occur during the process. Additionally, the script should replace specific placeholders in configuration files...
```python import os import subprocess class OpenRestyManager: @staticmethod def replace_text(file_path, placeholder, replacement): with open(file_path, 'r') as file: file_data = file.read() file_data = file_data.replace(placeholder, replacement) with open(file_path, 'w')...
magicoder
python
You are tasked with implementing a function to find the smallest amicable pair of numbers. Amicable numbers are two different numbers so related that the sum of the proper divisors of each is equal to the other number. The proper divisors of a number are all positive divisors excluding the number itself. You need to i...
```python def sum_of_divisors(n): divisors_sum = 1 # 1 is always a proper divisor for i in range(2, int(n**0.5) + 1): if n % i == 0: divisors_sum += i if i != n // i: # avoid counting square root twice divisors_sum += n // i return divisors_sum def find_ami...
magicoder
python
You are tasked with creating a program to simulate a simple messaging system using RabbitMQ. Your program should establish a connection to a RabbitMQ server, create a queue for receiving messages, and then publish a message to the queue. Your program should use the RabbitMQ .NET client library. The code snippet provid...
```csharp var factory = new ConnectionFactory() { HostName = "localhost" }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { channel.QueueDeclare(queue: "PedidosClientes", durable: false, exclusive: false, ...
magicoder
csharp
You are tasked with implementing a class for loading spatial data for a machine learning model. The class, `SpatialDataLoader`, is responsible for loading training and testing data for a computer vision model. The provided code snippet initializes an instance of `SpatialDataLoader` and prints the length of the training...
```python import torch from torch.utils.data import DataLoader from torchvision import datasets, transforms class SpatialDataLoader: def __init__(self, batch_size, use_multiprocessing, data_root_path, ucf_split, testing_samples_per_video, width, height, num_workers): self.batch_size = batch_size se...
magicoder
python
You are given a string `input_str` containing a series of words separated by spaces. Your task is to write a Python function `capitalize_vowels(input_str)` that capitalizes all the vowels in the string. The function should return the modified string with capitalized vowels. For example, if the input string is "hello w...
```python import re def capitalize_vowels(input_str: str) -> str: vowels = "aeiou" modified_str = '' for char in input_str: if char.lower() in vowels: modified_str += char.upper() else: modified_str += char return modified_str ```
magicoder
python
You are tasked with implementing a class that represents a collection of variable-sized square matrices. The class should provide methods for adding matrices to the collection, retrieving the count of matrices in the collection, and performing a specific operation on the matrices. You are given a code snippet from a u...
```csharp using System; using System.Collections.Generic; public class vssdCollection { private List<int[,]> matrices; public vssdCollection() { matrices = new List<int[,]>(); } public void AddMatrix(int[,] matrix) { if (matrix.GetLength(0) == matrix.GetLength(1)) // Check if ...
magicoder
csharp
You are tasked with implementing a game of life simulation using Rust. The game of life is a cellular automaton devised by the British mathematician John Horton Conway. The universe of the Game of Life is an infinite two-dimensional orthogonal grid of square cells, each of which is in one of two possible states, alive ...
```rust use fixedbitset::FixedBitSet; pub struct Universe { width: u32, height: u32, cells: FixedBitSet, } impl Universe { pub fn new(width: u32, height: u32) -> Universe { let size = (width * height) as usize; let cells = FixedBitSet::with_capacity(size); // Initialize the uni...
magicoder
rust
You are tasked with implementing a function that compresses an image using the JPEG format. The function should take an input image and a quality parameter, and return the compressed image data as a byte array. The JPEG compression process involves converting the input image into a compressed format by reducing the fi...
```python from PIL import Image from io import BytesIO def compress_image(image: Image, quality: int) -> bytes: with BytesIO() as output: image.save(output, format='JPEG', quality=quality, optimize=True) return output.getvalue() ``` The `compress_image` function takes an input image and a quality p...
magicoder
python
You are tasked with implementing a Minimum Latency Constrained Minimum Spanning Tree (MLCMST) algorithm for a communication network. The MLCMST problem involves finding a spanning tree in a weighted graph that minimizes the sum of edge latencies, subject to the constraint that the maximum latency of any path in the tre...
```cpp #include <iostream> #include <memory> #include "MLCMST_Solver.h" #include "Star.h" #include "MLCCNetwork.h" #include "MLCST.h" class MLCMST_Improver { public: MLCMST_Improver(); MLCMST_Improver(std::unique_ptr<MLCMST_Solver> init_solver); network::MLCST run(const network::MLCCNetwork &mlcc_network);...
magicoder
cpp
You are tasked with implementing a matrix multiplication function for 4x4 matrices. The matrix is represented as a 1D array of 16 elements, where the elements are stored in row-major order. The multiplication should be performed according to the standard matrix multiplication rules. You need to write a function that ta...
```cpp TMatrix44 TMatrix44::operator*=(TMatrix44 &m){ auto tmp = new float[16]; for(int i = 0; i < 4; i++){ for(int j = 0; j < 4; j++){ int dest = i * 4 + j; tmp[dest] = 0; for(int k = 0; k < 4; k++){ tmp[dest] += _mat[i * 4 + k] * m._mat[k * 4 + j]; ...
magicoder
cpp
You are tasked with implementing a class for a game environment that features a lava floor. The provided code snippet outlines a part of the implementation for the `LavaFloor` class. Your goal is to complete the class by adding necessary member functions and variables to simulate the behavior of a lava floor in a game....
```cpp #include <SFML/Graphics.hpp> class LavaFloor { public: void SetPosition(float x, float y) { floor_shape_.setPosition(x, y); } void Update(float delta_time) { if (is_ignited_) { // Simulate heat emission based on elapsed time and emission rate // Example: floo...
magicoder
cpp
You are tasked with implementing a generic cache class in C#. The cache should have the ability to store and retrieve items of any type, and it should support a maximum capacity, evicting the least recently used item when the capacity is exceeded. You need to implement the `Cache<TItem>` class with the following method...
```csharp using System.Collections.Generic; public class Cache<TItem> { private readonly int capacity; private readonly Dictionary<string, LinkedListNode<(string, TItem)>> cacheMap; private readonly LinkedList<(string, TItem)> lruList; public Cache(int capacity) { this.capacity = capacity;...
magicoder
csharp
You are tasked with creating a Python function that parses a given software license text and extracts the conditions specified in the license. The license text is provided as a string, and the conditions are listed as numbered points followed by a period and space. Your function should return a list of the extracted co...
```python from typing import List def parse_license_conditions(license_text: str) -> List[str]: conditions = [] lines = license_text.split('\n') for line in lines: if line.strip().startswith('#'): condition = line.split('. ')[1].strip() conditions.append(condition) retur...
magicoder
python
You are tasked with creating a program that parses a given URL and extracts specific components from it. Your program should take a URL as input and then parse it to extract the protocol, domain, port (if specified), path, and query parameters. The URL will be in the format: `protocol://domain:port/path?query`, where t...
```java import java.util.HashMap; import java.util.Map; public class ParseURL { public static Map<String, String> parseURL(String url) { Map<String, String> parsedComponents = new HashMap<>(); String[] parts = url.split("://|/|\\?|:"); parsedComponents.put("protocol", part...
magicoder
java
You are tasked with implementing a network traffic monitoring system. The system should track the start times of connections between network ports and capture snapshots of the traffic for different services. You are given a code snippet that connects network ports and records the event of a connection being built. You...
```python from typing import List, Tuple SERVICES = ['http', 'ssh', 'dns', 'ftp'] # Example list of service names start_times = [] snapshots = {port: [] for port in SERVICES} def record_start_time(src_port: int, dest_port: int, timestamp: int) -> None: start_times.append((src_port, dest_port, timestamp)) def r...
magicoder
python
You are working on a multilingual chat application that supports different languages. The application uses a file named `localized.chat.php` to store language-specific phrases and messages. The file contains multiple "define" rows, each representing a different phrase in different languages. Your task is to write a scr...
```php function updatePhrase($originalPhrase, $newPhrase, $languages) { $updatedPhrases = []; foreach ($languages as $language) { $updatedPhrases[] = 'define("' . $originalPhrase . '", "' . $newPhrase . '"); // ' . $language; } return $updatedPhrases; } ```
magicoder
php
You are tasked with implementing a loot modifier system for a game entity that triggers only when the entity is killed by a player using a specific weapon. The loot modifier should have the option to consider the damage dealt by the weapon and its NBT data. Your task is to create a method that adds this loot modifier t...
```java public void addLootModifier(Entity internal, String name, String weapon, boolean matchDamage) { internal.addLootModifier(name, (entity, source, damageSource) -> { if (source instanceof PlayerEntity) { ItemStack weaponStack = ((PlayerEntity) source).getMainHandStack(); if (wea...
magicoder
java
You are tasked with implementing a Python class that interacts with an API endpoint to retrieve information about a shop. The provided code snippet is a part of a Python SDK for the Pokepay partner API. The `GetShop` class is responsible for making a GET request to the `/shops/{shop_id}` endpoint to fetch details about...
```python # Import necessary classes from the SDK from pokepay_partner_python_sdk.pokepay.request.request import PokepayRequest from pokepay_partner_python_sdk.pokepay.response.shop_with_accounts import ShopWithAccounts class GetShop(PokepayRequest): def __init__(self, shop_id): self.path = "/shops" + "/" ...
magicoder
python
You are tasked with creating a function to find the nth digit of a given number. The function should take two parameters: the number and the index of the digit to be found. The index is 0-based, meaning the least significant digit is at index 0, the next digit is at index 1, and so on. If the index is out of range for ...
```csharp public int FindNthDigit(int number, int index) { if (index < 0) { return -1; // Invalid index } string numStr = Math.Abs(number).ToString(); // Convert number to string, ignoring the negative sign if (index >= numStr.Length) { return -1; // Index out of range } ...
magicoder
csharp
You are tasked with implementing a function to find the top N most frequently occurring words in a given string. The function should take two parameters: a string `s` containing space-separated words and an integer `n` representing the number of top words to return. The function should return a list of tuples, each con...
```python def count_words(s, n): # Split the input string into individual words s = s.split(' ') # Create a list of tuples containing each word and its frequency counted_words = [(w, s.count(w)) for w in set(s)] # Sort the list based on frequency in descending order, and then lexicographic...
magicoder
python
You are tasked with implementing a function that processes a given string to extract specific information. The string contains a question related to evaluating suspected non-conformity in the context of Health IT Module certification. Your task is to write a function that extracts and returns the key information from t...
```java import java.util.regex.Matcher; import java.util.regex.Pattern; public class EvaluationInfoExtractor { public static void main(String[] args) { String input = "If a suspected non-conformity resulted from the non-disclosure of material information by the developer about additional types of costs or ...
magicoder
java
You are tasked with implementing a data structure to manage a stack of boolean expressions. Each boolean expression is associated with a set of variables. Additionally, you need to implement a method to retrieve a failure case based on a given name. You are given a partial code snippet for the data structure and the m...
```rust use std::collections::{HashSet, VecDeque}; #[derive(Debug)] struct IfCase { vars: HashSet<String>, // Add any other fields needed for the boolean expression } struct StackManager { stack: VecDeque<IfCase>, } impl StackManager { fn new() -> Self { StackManager { stack: VecD...
magicoder
rust
You are tasked with implementing an asynchronous caching system for user data in a web application. The system involves managing user data, user sockets, socks, and a cache. Additionally, it requires handling WebSocket users and a PostgreSQL connection pool. The provided code snippet initializes the necessary asynchron...
```rust use async_trait::async_trait; #[derive(Debug)] struct CacheError(String); #[async_trait] trait Cacheable { async fn cache_user_data(&self, user_id: u64) -> Result<(), CacheError>; } #[derive(Clone)] struct AsyncUsers; #[derive(Clone)] struct AsyncUserSocks; #[derive(Clone)] struct AsyncSocks; #[derive...
magicoder
rust
You are tasked with implementing a Python function for segmenting ECG (electrocardiogram) signals to detect R peaks using the Pekkanen algorithm. The algorithm is based on the work of Kathirvel et al. (2001) with some modifications, primarily involving the robust estimation of the rectified signal cutoff threshold. Yo...
```python import numpy as np from scipy.signal import butter, filtfilt def segmenter_pekkanen(ecg, sampling_rate, window_size=5.0, lfreq=5.0, hfreq=15.0): def butter_bandpass_filter(data, lowcut, highcut, fs, order=5): nyquist = 0.5 * fs low = lowcut / nyquist high = highcut / nyquist ...
magicoder
python
You are tasked with creating a Laravel controller method that handles the process of resetting the password for an admin user. The controller contains several methods, including `resetarSenhaAdmin()` and `AllresetarSenhaAdmin()`, which are responsible for rendering the views for resetting the admin password. Your task ...
```php public function resetarSenhaAdmin(Request $request) { $admin = Admin::where('email', $request->email)->first(); if ($admin) { $token = Str::random(60); // Generate a random token DB::table('password_resets')->insert([ // Store the token in the password_resets table 'email' =>...
magicoder
php
You are given a list of integers. Write a function `find_max_number` to find and return the maximum number in the list. You are not allowed to use any built-in functions or methods that directly provide the maximum value. Function Signature: `def find_max_number(arr: List[int]) -> int` Example: Input: [5, 8, 3, 12, 9...
```python from typing import List def find_max_number(arr: List[int]) -> int: max_num = arr[0] # Initialize max_num with the first element of the list for num in arr: if num > max_num: max_num = num return max_num ```
magicoder
python
You are working on a project that involves using the Opticks library for geometric modeling and ray tracing. The Opticks library provides functionalities for Constructive Solid Geometry (CSG) operations and analysis. You are tasked with creating a Python script that utilizes the Opticks library to define CSG objects an...
```python from opticks.ana.base import opticks_main from opticks.analytic.csg import CSG args = opticks_main(csgpath="$TMP/$FUNCNAME", testobject="$(tlens-testobject)", container="$(tlens-container)" ) # Define a CSG container object representing a box with specific parameters container = CSG("box", param=[-1, 1, 0...
magicoder
python
You are tasked with implementing a class that simulates a virtual user making multiple requests and storing the results. The class should have the following functionalities: 1. Initialize a virtual user and an array to store request results. 2. Provide a method to make a request and store the result. 3. Calculate the ...
```csharp public class VirtualUserSimulator { private VirtualUser _virtualUser; private RequestResult[] _requestResults; private int _requestCount; public VirtualUserSimulator(int logLength) { _virtualUser = new VirtualUser(); _requestResults = new RequestResult[logLength]; ...
magicoder
csharp
You are tasked with creating a Python function that validates and processes connection information for a relational database management system (RDBMS). The function should take a dictionary containing connection details as input and return a modified dictionary with the connection information formatted according to spe...
```python import unittest from unittest.mock import patch, Mock from your_module import process_connection_info class TestProcessConnectionInfo(unittest.TestCase): @patch('your_module.scraper._create_rdbms_connection') def test_process_connection_info(self, mock_connect): input_connection_info = { ...
magicoder
python
You are tasked with creating a Django REST framework API for managing messages and provinces. The given code snippet is a part of the URL configuration for the API. The `v1_api` is being used to register resources for handling sent messages, trashed messages, and provinces. The `urlpatterns` variable is used to include...
```python # models.py from django.db import models class SentMessage(models.Model): message = models.TextField() sender = models.CharField(max_length=100) sent_at = models.DateTimeField(auto_now_add=True) class TrashMessage(models.Model): message = models.TextField() trashed_at = models.DateTimeFi...
magicoder
python
You are tasked with implementing a generic view builder in Swift. The provided code snippet is a part of a generic view builder framework. The `buildEither` function is intended to create an instance of `EirtherView` which can hold either a `TrueView` or a `FalseView`. The `TrueView` and `FalseView` are both subclasses...
```swift static public func buildEither<TrueView:ViewRoot, FalseView:ViewRoot>(trueView:TrueView) -> EirtherView<TrueView,FalseView> { return EirtherView(trueView: trueView, falseView: nil) } ``` In the solution, the `buildEither` function is completed by creating an instance of `EirtherView` with the provided `Tru...
magicoder
swift
You are tasked with implementing a Python class to manage email messages. The class should have the following functionalities: - Store the sender's email address, subject, and message body. - Provide a method to return a string representation of the email message in the format "From: sender_address\nSubject: subject\nM...
```python class EmailMessage: def __init__(self, sender_address: str, subject: str, message_body: str): self.sender_address = sender_address self.subject = subject self.message_body = message_body def __repr__(self) -> str: return "From: {}\nSubject: {}\nMessage: {}".format(self...
magicoder
python
You are tasked with creating a program to determine the travel restrictions for different Australian states and territories based on the given rules. The rules are provided in the form of HTML snippets, each containing the travel restrictions for a specific region. The restrictions include being open to all, closed to ...
```python from bs4 import BeautifulSoup html_snippets = """ <p>Northern Territory: Open to everywhere but Victoria and Sydney, which must do hotel quarantine</p> <p>South Australia: Closed to Victoria, NSW arrivals must self-isolate, rest are open</p> <p>Tasmania: Closed to Victoria, everywhere else must do hotel quar...
magicoder
python
You are tasked with creating a Python function that organizes a dataset by moving files from multiple directories into a single directory based on specific criteria. Your task is to complete the implementation of the `organize_dataset` function. You are given the following code snippet as a starting point: ```python ...
```python import shutil from pathlib import Path def organize_dataset(source_dirs, destination_dir, file_extension): """ Move files from source directories to the destination directory based on the file extension. Args: source_dirs (list): List of source directories to search for files. destinatio...
magicoder
python
You are tasked with implementing a method to retrieve a list of epics that a subscriber is subscribed to. The code snippet provided is a part of a method that aims to achieve this functionality. The method `GetEpicsSubscribedTo` takes a `subscriberID` as a parameter and is expected to return a collection of `Domain.Mod...
```csharp public IEnumerable<Domain.Models.Epic> GetEpicsSubscribedTo(int subscriberID) { var subscriptions = _context.Subscriptions .Include(w => w.Writer) .ThenInclude(r => r.RoleNavigation) .Include(s => s.Subscriber) .Where(s => s.SubscriberId == subscriberID); var m_subscri...
magicoder
csharp
You are tasked with implementing a class for handling binary data storage and retrieval. The class should support writing and reading binary data to and from a file. The provided code snippet is a part of the class, showcasing the `write` and `read` methods. The `write` method is responsible for writing binary data to ...
```python import struct class BinaryDataHandler: def __init__(self, file_path): self.N = 0 self.WF = None self.file_path = file_path def write(self, n, c, h, w, packed): self.N += n if self.WF is None: self.WF = open(self.file_path, 'wb', buffering=1024*102...
magicoder
python
You are tasked with creating a Swift extension for a custom AWS API plugin that facilitates querying GraphQL requests. The extension should be able to handle requests of various types and provide a listener for the results. Your task is to implement the `query` method within the `AWSAPIPlugin` extension to support this...
```swift import Amplify public extension AWSAPIPlugin { func query<R: Decodable>(request: GraphQLRequest<R>, listener: GraphQLOperation<R>.ResultListener?) -> GraphQLOperation<R> { let operation = GraphQLOperation<R>(api: self, request: request) operation.resultListene...
magicoder
swift
You are given a list of intervals, where each interval is represented as a pair of integers `[start, end]`. Your task is to write a function that merges overlapping intervals and returns a new list of non-overlapping intervals. For example, given the input list of intervals: ``` intervals = [[1, 3], [2, 6], [8, 10], [...
```python def merge_intervals(intervals): if not intervals: return [] intervals.sort(key=lambda x: x[0]) # Sort intervals based on the start value merged = [intervals[0]] # Initialize the merged list with the first interval for interval in intervals[1:]: if merged[-1][1] >= interval...
magicoder
python
You are tasked with creating a Python program that processes a dataset using a pre-trained TensorFlow model. The program should accept command-line arguments for batch size and the path to the pre-trained model. The model should then be loaded using TensorFlow's `tf.saved_model.load` function, and the dataset should be...
```python import argparse import tensorflow as tf def process_dataset_with_model(batch_size, model_path): # Load the pre-trained model model = tf.saved_model.load(model_path) # Process the dataset in batches using the loaded model and batch size # Replace the following code with actual dataset process...
magicoder
python
You are tasked with creating a program that processes the output of an Optical Character Recognition (OCR) system to identify and handle empty text elements. The OCR system has already extracted text from an image and stored it in a JSON file. Your program needs to read this JSON file, identify any empty text elements,...
```python import cv2 import json from pathlib import Path def tesseract_ocr(image_path, ocr_path): image = cv2.imread(image_path.as_posix()) with open(ocr_path, 'r') as f: ocr_data = json.load(f) empty_index = [i for i, ele in enumerate(ocr_data['text']) if ele == ""] return empty_index ``` ...
magicoder
python
You are tasked with implementing a class for managing academic subjects in a database. The class has a method for saving subject information to the database. Your task is to complete the implementation of the `save` method by adding the necessary code to insert subject information into the database table. You will also...
```php public $active = 1; // default is active(1) public function __construct() { parent::__construct(); $this->db = & get_instance()->db_mgr; $this->load->config('db_constants'); $this->table = TBL_ACADEMIC_SUBJECTS; } public function save() { // Construct the insert data array $insert_dat...
magicoder
php
You are tasked with implementing a function that checks the validity of HTML tags in a given string. The function should return `true` if all the opening and closing tags in the string are properly nested and balanced, and `false` otherwise. The function should consider only the following tags: `<div>`, `</div>`, `<s...
```cpp #include <iostream> #include <stack> #include <string> bool isValidHTML(const std::string& input) { std::stack<std::string> tagStack; size_t pos = 0; while (pos < input.length()) { if (input[pos] == '<') { size_t endPos = input.find('>', pos); if (endPos == std::stri...
magicoder
cpp
You are tasked with creating a custom transformer class in Python for data preprocessing. The transformer should implement a fit method that calculates the mean and standard deviation of each feature in the input data and a transform method that standardizes the input data based on the calculated mean and standard devi...
```python import numpy as np from sklearn.base import BaseEstimator, TransformerMixin class DummyTransformer(BaseEstimator, TransformerMixin): def __init__(self): TransformerMixin.__init__(self) BaseEstimator.__init__(self) self.means = None self.stds = None def fit(self, X, y=...
magicoder
python
You are tasked with implementing a gradient descent algorithm for a function with one variable. Gradient descent is an iterative optimization algorithm used to find the minimum of a function. The goal is to minimize a given function by adjusting its input parameter iteratively. Your task is to implement the gradient de...
```python import numpy as np def gradient_descent_for_function(f, x0, step_size, max_iterations=1000, epsilon=1e-6): x = x0 f_history = [] x_history = [] for _ in range(max_iterations): gradient = (f(x + epsilon) - f(x - epsilon)) / (2 * epsilon) x = x - step_size * gradient f_...
magicoder
python
You are tasked with implementing a custom vector class, `EuclideanVector`, which represents a mathematical vector in n-dimensional space. The class should support type conversion to and from `std::vector<double>`. Your task is to implement the conversion operator from `EuclideanVector` to `std::vector<double>`. The `E...
```cpp #include <vector> class EuclideanVector { public: // Other member variables and methods // Conversion operator from EuclideanVector to std::vector<double> operator std::vector<double>() const noexcept { return magnitudes_; } // Other member variables and methods }; ``` In the solu...
magicoder
cpp
You are tasked with creating a Rust function that generates code for validating floating-point numbers based on certain options. The function should take in three parameters: `range` of type `ValidatorRangeOption`, `nan` of type `ValidatorOption`, and `f` of type `f64`. The `ValidatorRangeOption` enum has two variants:...
```rust use quote::quote; enum ValidatorRangeOption { Limited(f64, f64), NotLimited, } enum ValidatorOption { Allow, Must, } fn generate_validation_code(range: ValidatorRangeOption, nan: ValidatorOption, f: f64) -> proc_macro2::TokenStream { let handle_range = match range { ValidatorRange...
magicoder
rust
You are tasked with implementing a class for multidimensional arrays and overloading mathematical operations for it. Specifically, you need to implement the `log` function for the NDArray class, which computes the natural logarithm of each element in the array. You are given a code snippet that tests the `log` functio...
```swift class NDArray<T: FloatingPoint> { let shape: [Int] let elements: [T] init(shape: [Int], elements: [T]) { self.shape = shape self.elements = elements } func log() -> NDArray<T> { let loggedElements = elements.map { Swift.log($0) } return NDArray(shape: shape...
magicoder
swift
You are working on a project that involves downloading and clipping raster files. Your task is to implement a function that downloads a file from a given URI, then clips it based on a specified bounding box. If the bounding box covers the entire file, the function should create a hardlink instead of clipping the file. ...
```python import os import shutil from osgeo import gdal, ogr, osr def download_and_clip(file_uri, download_dir, bounding_box, target_file_path): # Create download directory if it doesn't exist if not os.path.exists(download_dir): os.makedirs(download_dir) # Download the file from file_uri to down...
magicoder
python
You are tasked with implementing a Python class method that processes media requests and returns a DeferredList object. The method takes in two parameters: `item` and `info`. The `get_media_requests` method retrieves media requests for the given item and info, and `arg_to_iter` converts the result into an iterable. The...
```python class MediaProcessor: def _process_request(self, request, info): # Implementation of processing a single media request # Example: Assuming request is a URL, this method could download the media content and return the result pass def process_media_requests(self, item, info): ...
magicoder
python
You are tasked with creating a function that will parse and extract the button text from a given HTML code snippet. The button text is enclosed within the `<button>` tag and may contain additional attributes. Your function should be able to handle different variations of the `<button>` tag and extract the text content ...
```javascript function extractButtonText(htmlCode) { const buttonRegex = /<button[^>]*>(.*?)<\/button>/; const match = htmlCode.match(buttonRegex); if (match) { const buttonContent = match[1]; // Remove any HTML tags within the button content const buttonText = buttonContent.replace(...
magicoder
javascript
You are tasked with implementing a class hierarchy for vectors in a 2D space. The code snippet provided is a part of a program that uses this class hierarchy to read input from a file, create vector objects using different factories, and then perform a parallel test on the vectors. Your task is to complete the impleme...
```cpp #include <iostream> #include <fstream> #include <vector> #include <string> using namespace std; class CFabricVektor { public: virtual CVektor* Create() = 0; }; class CFabricVektor0 : public CFabricVektor { public: CVektor* Create() override { return new CVektor0(); } }; class CFabricVekto...
magicoder
cpp
You are working on a project that involves building and deploying a Docker image using a specific set of commands. Your task is to write a script that automates this process by extracting a tar.gz file, building a Docker image, and then cleaning up the extracted files. You are given the following commands as a startin...
```bash #!/bin/bash # Step 1: Extract the contents of the file Eagle_v2.4.1.tar.gz tar xvzf Eagle_v2.4.1.tar.gz # Check if the extraction was successful if [ $? -eq 0 ]; then echo "Extraction successful" else echo "Extraction failed" exit 1 fi # Step 2: Build a Docker image with the tag quay.io/cmarkello/eagle...
magicoder
shell
You are tasked with implementing a simplified version of an OAuth constructor in PHP. The OAuth constructor takes an object implementing the `RequestInterface` and initializes the OAuth client with the provided request object. Your task is to create a PHP class `OAuth` with a constructor that accepts an object impleme...
```php <?php // Define the RequestInterface interface RequestInterface { public function getEndpoint(): string; public function getHeaders(): array; // Other method signatures may exist } // Implement the OAuth class class OAuth { private $request; /** * OAuth constructor. * @param Requ...
magicoder
php
You are tasked with implementing a custom navigation drawer for a mobile application. The navigation drawer should have the ability to animate its opening and closing. You are provided with a code snippet from the constructor of a class responsible for creating the custom navigation drawer. Your task is to complete the...
```java public class AnimNavigationDrawer extends View { private boolean isOpen = false; public AnimNavigationDrawer(Context context, AttributeSet attrs) { super(context, attrs); // Initialize the view and attributes } public void openDrawer() { // Implement the animation for o...
magicoder
java
You are tasked with creating a Python function that interacts with the Binance Futures Testnet API to retrieve the current price of a specified cryptocurrency pair. The Binance Futures Testnet API is used for testing purposes and simulates the behavior of the actual Binance Futures API. The base URL for the testnet is ...
```python import requests def get_current_price(crypto_pair: str) -> float: base_url = "https://testnet.binancefuture.com" endpoint = "/fapi/v1/ticker/price" url = f"{base_url}{endpoint}?symbol={crypto_pair}" try: response = requests.get(url) data = response.json() current_pric...
magicoder
python
You are working on a project to develop an image classification model using TensorFlow. As part of the data preprocessing pipeline, you need to implement a function to perform data augmentation on the test dataset. The code snippet provided below is a part of the data preprocessing pipeline for the test dataset. ```py...
```python import tensorflow as tf import numpy as np def test_aug(x): # Random horizontal flipping with probability 0.5 x = tf.image.random_flip_left_right(x) # Random rotation by a random angle between -15 and 15 degrees angle = tf.random.uniform([], minval=-15, maxval=15, dtype=tf.float32) x = t...
magicoder
python
You are given a directory containing a large number of FASTA files, each representing genetic sequences. Your task is to write a script that efficiently compresses each file using gzip and then removes the original uncompressed file. Additionally, the script should print "Job is done." after completing the compression ...
```bash #!/bin/bash if [ $# -ne 1 ]; then echo "Usage: $0 <directory_path>" exit 1 fi directory_path=$1 if [ ! -d "$directory_path" ]; then echo "Error: Directory not found." exit 1 fi cd "$directory_path" || exit for file in *.fasta; do if [ -f "$file" ]; then gzip "$file" && rm "$file...
magicoder
shell
You are tasked with creating a program that reads a text file and counts the occurrences of each word in the file. For the purpose of this problem, a word is defined as a sequence of alphanumeric characters (letters and digits) separated by any non-alphanumeric character. The program should then output the list of uniq...
```python import re import sys from collections import Counter def count_word_frequency(file_path): try: with open(file_path, 'r') as file: text = file.read() words = re.findall(r'\b\w+\b', text.lower()) word_counts = Counter(words) sorted_word_counts = dict(...
magicoder
python
You are tasked with implementing a command-line tool that processes batch data based on various options provided by the user. The code snippet provided is a part of the command-line tool's configuration, which uses the Swift Argument Parser library for parsing command-line arguments. Your task is to create a Swift pro...
```swift import ArgumentParser struct BatchProcessor: ParsableCommand { @Option(name: "limit", short: "l") var limit: Int? @Option(name: "id") var id: UUID? @Flag(name: "before") var processBefore: Bool func run() { if let limit = limit { print("Processing...
magicoder
swift
You are tasked with implementing a priority queue data structure using a linked list in Python. The priority queue should support the following operations: 1. `insert(value, priority)`: Insert a new element with the given value and priority into the priority queue. 2. `pop()`: Remove and return the element with the hig...
```python class Node: def __init__(self, value, priority): self.value = value self.priority = priority self.next = None class PriorityQueue: def __init__(self): self.head = None def insert(self, value, priority): new_node = Node(value, priority) if not self....
magicoder
python
You are given a list of edges representing a graph and their corresponding weights. Your task is to implement a function that finds the shortest path from a given source node to all other nodes in the graph using Dijkstra's algorithm. The graph is represented as a list of edges, where each edge is a tuple in the forma...
```python import heapq def dijkstra_shortest_path(graph, source): distances = {node: float('inf') for edge in graph for node in edge[:2]} distances[source] = 0 queue = [(0, source)] while queue: current_distance, current_node = heapq.heappop(queue) if current_distance > distances[curr...
magicoder
python
You are tasked with creating a file upload validation system for a web application. The system should ensure that the uploaded files meet certain criteria before they are stored. Specifically, the system should validate that the uploaded files are images (in JPEG, PNG, JPG, GIF, or SVG format) and that they are require...
```php public function pictureStore(Request $request) { $this->validate($request, [ 'foto.*' => 'required|image|mimes:jpeg,png,jpg,gif,svg', ]); if ($request->hasfile('foto')) { foreach ($request->file('foto') as $file) { $name_file = "Lumban-Gaol_Foto-" . rand() . "-" . time() ....
magicoder
php
You are tasked with implementing a Python program that simulates a simple banking system. The program should allow users to create accounts, deposit and withdraw funds, and check their balance. The program should also ensure that account balances are not allowed to go negative. Your task is to implement the `BankAccou...
```python class BankAccount: def __init__(self, initial_balance): self.balance = initial_balance def deposit(self, amount): self.balance += amount def withdraw(self, amount): if self.balance >= amount: self.balance -= amount else: print("Insufficient...
magicoder
python
You are tasked with implementing a simplified version of an authentication handler for a tunneling system. The provided code snippet is a partial implementation of an authentication handler trait for a simple acknowledgment-based authentication mechanism. The `SimpleAckAuthenticationHandler` struct implements the `Aut...
```rust impl SimpleAckAuthenticationHandler { fn authenticate_listen_side<'a>( &'a self, channel: Box<dyn TunnelStream + Send + Unpin + 'a>, tunnel_info: TunnelInfo, shutdown_notifier: &'a CancellationListener, ) -> BoxFuture<'a, Result<TunnelName, AuthenticationError<Self::Error...
magicoder
rust
You are tasked with implementing a resource locking mechanism in a multi-threaded environment. The resource locking mechanism should prevent multiple threads from accessing the same resource simultaneously. You are given a code snippet that attempts to lock a resource using a `Lock` object and handles errors using a ca...
```python import threading class ResourceLockManager: def __init__(self): self.locks = {} self.locks_lock = threading.Lock() def acquire(self, resource_id: str): with self.locks_lock: if resource_id in self.locks: self.locks[resource_id].acquire() ...
magicoder
python
You are tasked with implementing a function that checks the validity of a given JavaScript code snippet. The code snippet will consist of a series of lines, each containing a JavaScript statement or comment. Your function should determine if the code snippet follows a specific pattern, and return true if it does, and f...
```javascript function isValidCodeSnippet(code) { const lines = code.split('\n'); let openingBraceCount = 0; let closingBraceCount = 0; for (let line of lines) { line = line.trim(); if (line.includes('{')) { openingBraceCount++; if (!line.includes('}')) { return false; } }...
magicoder
javascript
You are given the definition of a binary tree node and a Python class `Solution` that will be used to solve a specific problem related to binary trees. Your task is to implement a method within the `Solution` class that checks whether a given binary tree is symmetric. A binary tree is symmetric if it mirrors around it...
```python class Solution: def isSymmetric(self, root: TreeNode) -> bool: def isMirror(left: TreeNode, right: TreeNode) -> bool: if not left and not right: return True if not left or not right: return False return (left.val == right.val) and...
magicoder
python
You are tasked with creating a function that generates a form for selecting interactions within a course management system. The interactions include options such as "view," "edit," and "delete" for various course elements. The function `print_interactions_selector_form` takes a `course` object as a parameter and should...
```php function print_interactions_selector_form($course) { echo "<form>"; echo "<h2>{$course->title}</h2>"; echo "<p>{$course->description}</p>"; echo "<label><input type='checkbox' name='interaction[]' value='view'>View</label><br>"; echo "<label><input type='checkbox' name='interaction[]' value='...
magicoder
php
You are given the definition of a ListNode class and a function addTwoNumbers that takes in two linked lists representing non-negative integers. The function should return a new linked list representing the sum of the two input lists. Definition of ListNode class: ```python class ListNode: def __init__(self, val=0...
```python def addTwoNumbers(l1: ListNode, l2: ListNode) -> ListNode: dummy = ListNode(0) current = dummy carry = 0 while l1 or l2 or carry: sum_val = carry if l1: sum_val += l1.val l1 = l1.next if l2: sum_val += l2.val l2 = l2.next...
magicoder
python
You are tasked with implementing a Python function that simulates a command execution environment with retry functionality. The function will take in a list of commands, a retry interval, and a choice of shell, and execute the commands in the specified shell environment. If a command fails, the function should retry th...
```python from typing import List, Dict import subprocess import time def execute_commands_with_retry(commands: List[str], retry_interval: int, shell: str, environment: Dict[str, str] = {}) -> List[str]: output = [] for command in commands: while True: try: process = subproc...
magicoder
python
You are tasked with designing a file download manager in Android that utilizes OkHttp for downloading files. Your goal is to implement a solution that ensures the file downloads occur in a background thread to prevent blocking the main UI thread. Your task is to create a class that manages file downloads using OkHttp ...
```java import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class FileDownloadManager { private OkHttpClient client; pu...
magicoder
java
You are tasked with implementing a game state management system using the Memento design pattern. The Memento pattern allows an object's state to be captured and restored at a later time without violating encapsulation. Your goal is to create a Java program that utilizes the Memento pattern to save and restore the stat...
```java // Memento class to store the state of the game class Memento { private StateOfTheGame state; public Memento(StateOfTheGame state) { this.state = state; } public StateOfTheGame getState() { return state; } } // Originator class to create and restore mementos class Originat...
magicoder
java
You are tasked with creating a Python function that simulates the behavior of a simple text-based game. The game involves a player navigating through a grid-based world, collecting treasures, and avoiding obstacles. The player's position and the layout of the world are represented by a 2D grid. The player can move up, ...
```python def play_game(grid, moves): rows, cols = len(grid), len(grid[0]) player_pos = None collected_treasures = 0 for r in range(rows): for c in range(cols): if grid[r][c] == 'P': player_pos = (r, c) break directions = {'U': (-1, 0), 'D': (1, ...
magicoder
python
You are tasked with implementing a data aggregation system for a distributed computing environment. The system consists of an aggregator and multiple worker nodes. The aggregator is responsible for collecting and processing data from the worker nodes. Each worker node runs a specific task and sends its results to the a...
```cpp #include <iostream> #include <vector> #include <mutex> // Define the type for the final output using FinalT = int; // Define the type for the worker parameters struct WorkerParams { int result; // Add any other relevant parameters here }; class AggregatorT { private: FinalT aggregatedValue; st...
magicoder
cpp
You are tasked with implementing a custom operator pipeline system for a data processing framework. The framework provides a base class `OperatorBase` for creating custom operators, and it supports multiprocessing for parallel execution. The code snippet provided initializes some shared resources and data structures fo...
```python from multiprocessing import Process, Manager from typing import List, Dict, Any, Callable from tethys.core.nodes.operators.operator_base import OperatorBase class OperatorPipeline: def __init__(self): self.operators: List[OperatorBase] = [] self._cursors = Manager().dict() def regist...
magicoder
python
You are tasked with implementing a class for information retrieval evaluation metrics. The class should include methods for calculating precision at k (p@k) and average precision (AP) for a given set of retrieved items and relevant items. You are provided with a code snippet representing the attributes of the class: ...
```python class InformationRetrievalMetrics: def __init__(self): self.item_list = None self.discovered_answer = None self.description = None self.answer_dict = None self.measure_p_at_k = None self.measure_ap = None def calculate_p_at_k(self, k): relevant_...
magicoder
python
You are given a sequence of integers representing the operations performed on a tape. The operations include pushing and popping elements from the tape. Your task is to implement a function that simulates the operations and returns the final state of the tape after all the operations have been applied. The tape is ini...
```javascript function simulateTapeOperations(arr) { const tape = []; for (let i = 0; i < arr.length; i++) { if (arr[i] < 0) { tape.pop(); if (tape.length === 0) break; } else { tape.push(arr[i]); } } return tape; } // Test the function console.log(simulateTapeOperations([5, -2, 7...
magicoder
javascript
You are tasked with creating a custom admin interface for managing different types of financial transactions in a web application. The provided code snippet registers various models with the admin interface in Django, a popular web framework for Python. Each registered model is associated with a specific ModelAdmin cla...
```python from django.contrib import admin from .models import Expense class ExpenseModelAdmin(admin.ModelAdmin): list_display = ('date', 'amount', 'category', 'description') list_filter = ('date', 'category') search_fields = ('description',) list_per_page = 20 admin.site.register(Expense, ExpenseMode...
magicoder
python
You are tasked with creating a Python function that processes form data submitted via a POST request in a web application. The function should handle the form data and perform specific actions based on the input. Write a Python function `process_application_form` that takes in a `request` object representing the HTTP...
The `process_application_form` function first checks if the request method is 'POST'. If it is, the function extracts the form data from the request and validates it using the `ApplicationForm` from the `springaid2012.forms` module. If the form data is valid, it creates an `ApplicationEntry` object using the validated ...
magicoder
python
You are tasked with implementing a program that can efficiently count the occurrences of a given word in a large text file. The program should be able to handle files of any size and provide the count of occurrences for the specified word. Your task is to write a function `countWordOccurrences` that takes two paramete...
```python def countWordOccurrences(filePath, targetWord): count = 0 with open(filePath, 'r') as file: for line in file: # Convert both the line and target word to lowercase for case-insensitive matching line = line.lower() targetWord = targetWord.lower() #...
magicoder
python
You are tasked with implementing a simplified version of a page store management system. The system is responsible for storing and deleting pages identified by unique page IDs. The provided code snippet is a part of the existing implementation and contains the `delete` method, which removes a page from the page store. ...
```java import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PageStore { private static final Logger LOG = LoggerFactory.getLogger(PageStore.class); private Map<PageId, Page> mPageStoreMap = new HashMap<>(); publi...
magicoder
java
You are tasked with creating a Python class that simulates a simple catalog system. The catalog should be able to update its count and calculate the relative count based on the previous count. Your task is to implement the `Catalog` class with the following methods: 1. `update_count(count)`: A method that takes an int...
```python from unittest.mock import patch import unittest class Pulse: def __init__(self, count): self.count = count class Catalog: def __init__(self): self.count = 0 self.previous_count = 0 def update_count(self, count): self.previous_count = self.count self.count...
magicoder
python
You are tasked with implementing a social media app's navigation system. The app has a tab bar controller with three tabs: Home, Mentions, and Profile. Each tab corresponds to a navigation controller with a view controller for displaying tweets. The provided code snippet initializes the view controllers for the Home an...
```swift // Instantiate the view controller for the Profile tab let profileTweetsNC = storyboard.instantiateViewController(withIdentifier: "TweetsNavigationController") as! UINavigationController let profileTweetsViewController = profileTweetsNC.topViewController as! TweetsViewController profileTweetsViewController.cha...
magicoder
swift
You are tasked with creating a Bash script that handles errors and displays error messages in Japanese. Your script should define three functions: `error_message`, `error_handler`, and `main`. The `error_message` function takes an error message as an argument and prints it in red, along with the command name. The `erro...
```bash #!/bin/bash cmdname=$(basename "$0") error_message() { printf '\e[31m%s: エラー: %s\e[m\n' "${cmdname}" "${1}" 1>&2 printf '\e[31m%s: 終了します\e[m\n' "${cmdname}" 1>&2 } error_handler() { error_message "不明なエラー" } main() { error_handler exit 1 } main ``` When the above script is executed, it will produ...
magicoder
shell
You are tasked with implementing a Python function that visualizes data using a line plot with two distinct collections of points. The function should take in two sets of data points, a title for the plot, and the x-axis limits. The function should then create a line plot with two distinct collections of points, set th...
```python import matplotlib.pyplot as plt from matplotlib.collections import PathCollection def visualize_data(pc_blue, pc_red, title, times): # Create a new plot plt.figure() # Add the blue and red point collections to the plot plt.gca().add_collection(pc_blue) plt.gca().add_collection(pc_red...
magicoder
python
You are tasked with implementing a simple adapter pattern in Rust. The adapter pattern is a structural design pattern that allows the interface of an existing class to be used as another interface. It is often used to make existing classes work with others without modifying their source code. In this problem, you are r...
```rust pub trait Adapter { fn specific_request(&self) -> String; } pub mod adapter { pub struct Wrapper<T> { wrapped: T, } impl<T> Wrapper<T> { pub fn new(wrapped: T) -> Self { Wrapper { wrapped } } } impl<T: Adapter> Adapter for Wrapper<T> { fn sp...
magicoder
rust
You are tasked with implementing a tax registry system for different types of documents. The tax registry system will allow the registration of tax rules for specific document types and conditions. Your goal is to create a class that can build a tax registry and register tax rules for a given document type. You are pr...
```csharp using System; using System.Collections.Generic; public enum Condition { NonEmptyReference, // Other conditions can be added here } public class TaxRule { public string Name { get; set; } public Condition Condition { get; set; } public int Value { get; set; } } public class TaxRegistry<T...
magicoder
csharp
You are tasked with implementing a function to determine whether a user has access to a specific feature based on their roles. The function takes in the user's information and a set of roles, and it should return true if the user has access to the feature, and false otherwise. The user's roles are stored as an array of...
```csharp using System; using System.Linq; public class User { public string SteamId { get; set; } public string[] Roles { get; set; } } public class AccessControl { public bool HasAccess(User user, string forSteamId, string[] rf) { if (user == null) return false; if (forSteamId != nu...
magicoder
csharp
You are tasked with creating a web application that manages a database of products. The application should have an admin interface with specific functionality and security measures. To achieve this, you need to implement a ModelView class and its associated methods. You are provided with a code snippet that includes a...
```python class myModelView(AccessMixIn, ModelView): can_delete = False form_base_class = SecureForm column_display_pk = True def index(self): return self.render('/admin/index.html') def is_accessible(self): # Implement logic to check if the user is authenticated and has admin priv...
magicoder
python
You are given a string `s` consisting of lowercase letters. Your task is to write a function to find the minimum number of cuts needed to partition the string into substrings such that each substring is a palindrome. A palindrome is a string that reads the same forwards and backwards. For example, given the string "ab...
```python def minPalindromeCuts(s: str) -> int: n = len(s) memo = {} def isPalindrome(sub: str) -> bool: return sub == sub[::-1] def helper(l: int, r: int) -> int: if l >= r or isPalindrome(s[l:r+1]): return 0 if s[l:r+1] in memo: return memo[s[l:r+1]] ...
magicoder
python
You are tasked with implementing a logging system for a software application. The system should be able to log messages at different levels of severity and support logging to multiple destinations, such as the console, files, and network services. Your goal is to design and implement a flexible and extensible logging s...
```cpp #include <iostream> #include <fstream> #include <vector> #include <memory> // Base class for log levels class LogLevel { public: virtual void log(const std::string& message) = 0; virtual ~LogLevel() {} }; // Derived classes for specific log levels class InfoLevel : public LogLevel { public: void lo...
magicoder
cpp
You are tasked with implementing a Python module that handles user authentication and authorization for a web application. The module should include the following functionalities: 1. User Registration: Implement a function `register_user(username: str, password: str) -> bool` that registers a new user with the given u...
```python # core/user/views.py # User authentication and authorization module registered_users = {} # Dictionary to store registered users and their passwords user_roles = {} # Dictionary to store user roles def register_user(username: str, password: str) -> bool: if username in registered_users: retur...
magicoder
python
You are tasked with implementing a custom annotation parser for a PHP application. Annotations are a form of metadata that can be added to classes, methods, or properties in PHP code. These annotations are enclosed in special comment blocks and can be used to provide additional information or instructions to the applic...
```php class AnnotationParser { public function parseAnnotations(string $phpCode): array { $annotations = []; $matches = []; preg_match_all('/\/\*\*(.*?)\*\//s', $phpCode, $matches); // Match PHPDoc comments foreach ($matches[1] as $comment) { preg_match_all('/@(\w+)...
magicoder
php