query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with implementing a simple multi-threaded program that prints the numbers 1, 2, and 3 in order using three different threads. The program should ensure that the numbers are printed in ascending order, with each number being printed exactly once. Your task is to complete the implementation of the `PrintI...
```cpp #include <thread> #include <iostream> #include <gtest/gtest.h> class PrintInOrder { public: PrintInOrder() : count(1) {} void first() { printNumber(1); } void second() { printNumber(2); } void third() { printNumber(3); } private: int count; std::mu...
magicoder
cpp
You are tasked with implementing a custom extendable enumeration class in Python. An extendable enumeration is similar to the built-in `enum.Enum` class, but it allows for dynamic addition of new members at runtime. Your task is to create a class `ExtendableEnum` that supports the following functionalities: 1. Define ...
```python import enum class ExtendableEnum(enum.Enum): def add_member(self, name, value): if any(member.name == name or member.value == value for member in self.__class__): raise ValueError(f"Member with name '{name}' or value '{value}' already exists") new_member = self.__class__(name,...
magicoder
python
You are tasked with implementing a function that takes a list of tuples as input and returns a dictionary where the keys are the first elements of the tuples and the values are lists of the second elements of the tuples. If a key is already present in the dictionary, the corresponding value should be appended to the ex...
```python from typing import List, Tuple, Any, Dict def tuple_list_to_dict(input_list: List[Tuple[Any, Any]]) -> Dict[Any, List[Any]]: out_dict = {} for key, value in input_list: if key in out_dict: out_dict[key].append(value) else: out_dict[key] = [value] return out...
magicoder
python
You are working on a security application that requires encryption and decryption using the RSA algorithm. Your task is to implement a Python program that can generate RSA key pairs, encrypt a message using the public key, and then decrypt the encrypted message using the private key. Your program should perform the fo...
```python from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP import base64 def generate_key_pair(key_size): key = RSA.generate(key_size) private_key = key.export_key() public_key = key.publickey().export_key() return private_key, public_key def encrypt_message(public_key, message): ...
magicoder
python
You are tasked with creating a Python script that performs a specific file manipulation task. The script should take input from the user, execute a subprocess, and handle errors gracefully. Your task is to implement the missing functionality in the Python script based on the given requirements. You are provided with a...
```python #!/usr/bin/env python3 import optparse import pathlib import subprocess import os import shutil from tools.utils import prompt as pmt from tools.utils.subprocess_runner import subprocess_runner def main(): parser = optparse.OptionParser() parser.add_option("-d", "--directory", dest="directory", help=...
magicoder
python
You are working on a project to develop a graphics library for a new programming language. As part of this project, you need to implement a function that generates a pattern of points for drawing a border around a rectangular shape. The function takes the width and height of the shape, the border width, and a boolean f...
```python def generate_border_points(w, h, border_width, side): nw = border_width n = (h // nw) | 1 x, d = (w - 1, -nw) if side else (0, nw) return [(x + d * (i % 2), h * i // n) for i in range(n)] ``` The `generate_border_points` function calculates the number of points needed to draw the border based ...
magicoder
python
You are tasked with creating a parser for a simple programming language using the Rust programming language and the `nom` parsing library. The given code snippet is a part of the parser implementation and defines a type alias `IResult` for the `nom::IResult` type, parameterized with a lifetime `'a` and a type `T` which...
```rust // Define the type T for the parsed output type SpecificParsedOutput<'a> = /* specify the type for the specific construct */; // Implement the parse_specific_construct function fn parse_specific_construct<'a>(input: token::ParsedSpan<'a>) -> IResult<'a, SpecificParsedOutput<'a>> { // Implement the parsing ...
magicoder
rust
You are tasked with creating a recommendation system for a user based on their interests. The system will use a file containing user-specific terms to generate recommendations from a global list of recommendations. Your task is to implement the `userrecommendations` function, which takes a user's name as input and retu...
```python import random def userrecommendations(user): random_term = randomuserterm(user) genre = checkgenre(random_term) user_recommendations_list = findreccomendations(genre) return user_recommendations_list ``` Explanation: The `userrecommendations` function calls the `randomuserterm` function to ob...
magicoder
python
You are tasked with implementing a custom attribute in C# to mark properties that should not be included in the automatic property change notification mechanism in a WPF MVVM application. Create a class `NotNPC_PropertyAttribute` that inherits from `Attribute` and can be applied to properties. The attribute should pre...
```csharp using System; namespace IceCoffee.Wpf.MvvmFrame.NotifyPropertyChanged { /// <summary> /// Specifies that the property should not participate in automatic property change notification. /// </summary> [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] publ...
magicoder
csharp
You are tasked with creating a Python function that processes and visualizes data from a sports competition. The function should take in a 2D numpy array representing scores from the competition and generate a horizontal bar plot to display the average scores and confidence intervals for each participant. The function...
```python import numpy as np import matplotlib.pyplot as plt def visualize_scores(scores: np.ndarray, n_panels: int) -> None: scores_to_plot = np.nanmean(scores, axis=1) ci = np.abs( np.nanpercentile(scores, 50, axis=1) - np.nanpercentile(scores, [2.5, 97.5], axis=1) ) fig, ax = plt.subplots()...
magicoder
python
You are tasked with implementing a simple 3D vector library in C++ using the provided code snippet as a starting point. The `vecgeom` namespace is provided to encapsulate the vector operations. Your task is to define a `Vector3D` class within this namespace, which should support basic vector operations such as addition...
```cpp #include <cmath> namespace vecgeom { class Vector3D { private: double x, y, z; public: Vector3D(double x_val, double y_val, double z_val) : x(x_val), y(y_val), z(z_val) {} // Overloaded operators Vector3D operator+(const Vector3D& other) const { return V...
magicoder
cpp
You are tasked with implementing a class that represents an operation to update an extended property in a database. The provided code snippet includes a base class `UpdateExtendedPropertyOperation` and a derived class that overrides the `StoredProcedureName` property. Your task is to complete the implementation of the ...
```csharp public class ExtendedPropertyUpdateOperation : UpdateExtendedPropertyOperation { public ExtendedPropertyUpdateOperation(string schemaName, string tableViewName, string columnName, string name, object value, bool forView) : base(schemaName, tableViewName, columnName, name, forView) { V...
magicoder
csharp
You are tasked with implementing a Python class that represents a type in a programming language. The class should have the ability to write its representation to a text stream and perform a desugaring operation. The desugaring operation should return a modified type based on certain rules. Your task is to complete th...
```python from typing import TextIO class Token: def __init__(self, value: str): self.value = value class Type: def __init__(self, const_token: Token, inner_type: 'Type'): self.const_token = const_token self.inner_type = inner_type def write(self, writer: TextIO): writer.w...
magicoder
python
You are tasked with implementing a simplified encryption and decryption algorithm using modular arithmetic and exponentiation. The algorithm involves two main steps: encryption and decryption. Encryption: Given a plaintext message represented as a number `alpha` and a public key `n`, the encryption process involves co...
```python def encrypt(alpha, n, e): ctt = alpha % n beta = pow(ctt, e, n) return beta def decrypt(beta, n, d): ctt = pow(beta, d, n) alpha = ctt return alpha ``` The `encrypt` function first calculates the value `ctt` by taking the modulus of `alpha` with `n`. Then, it computes the ciphertext ...
magicoder
python
You are given an array `c` of integers and a target integer `target`. Your task is to find the maximum product of triplets `(i, j, k)` such that `i < j < k` and `c[i] * c[j] * c[k]` is maximized, where `i`, `j`, and `k` are indices of the array `c`. Write a function `max_triplet_product(c, target)` that takes in the a...
```python from itertools import permutations def max_triplet_product(c, target): max_product = 0 for i, j in permutations(range(len(c)), 2): if i < j < len(c) and c[i] < c[j] < target - c[i] - c[j]: max_product = max(max_product, c[i] * c[j] * c[target - c[i] - c[j]]) return max_product...
magicoder
python
You are given a code snippet that is part of a program to test a function `num_sol` in a class `Par`. The function `num_sol` takes an integer `n` as input and returns the number of solutions for a given problem. The code snippet includes some assertions, input handling, and time measurement. Your task is to implement ...
```python class Par: def __init__(self, max_n_pairs, nums_modulus): self.max_n_pairs = max_n_pairs self.nums_modulus = nums_modulus def num_sol(self, n): # Implement the logic to calculate the number of solutions for the given problem # You can use self.max_n_pairs and self.nums...
magicoder
python
You are tasked with implementing a function to parse and process a given byte array. The byte array represents split data, and the function should extract specific information from it. The byte array contains a series of bytes, and the function should iterate through the array to extract relevant information based on c...
```python def data_walk(split_data): stringList = [] offset = 0 config = bytearray(split_data) count = 0 while offset < len(config) and count < 2: if str(config[offset]) == '1': len_bytes = '{0}{1}'.format(chr(0), chr(config[offset + 1])) else: len_bytes = str...
magicoder
python
You are tasked with creating a Python function that processes event data based on certain filtering criteria. The function should take in two parameters: `origin_name` (string) and `uri_raw` (string). The function should retrieve event data from a database, filter it based on the provided criteria, and return the filte...
```python from flask import jsonify def process_event_data(origin_name: str, uri_raw: str) -> str: origin = get_origin_from_name(origin_name.lower()) schema = self.serializer_class( many=True, only=('subject_id', 'origin', 'created_at', 'uri') ) event_query = Event.query.filter_by(origi...
magicoder
python
You are tasked with creating a simple web application using the Sauron web framework in Rust. Sauron is a virtual-dom based web framework that allows developers to create web applications using a functional and declarative style. Your task is to create a web page that displays a greeting message and allows users to in...
```rust use sauron::prelude::*; fn main() { let app = SauronApp::new(greet_component); app.run(); } fn greet_component() -> Node<Msg> { let initial_greeting = "Hello, World!"; let mut greeting = initial_greeting.to_string(); node! { <div> <h1>{ greeting }</h1> <but...
magicoder
rust
You are tasked with implementing a balanced binary cross entropy loss function in Python. The balanced binary cross entropy loss is a modified version of the standard binary cross entropy loss, which introduces a class weighting factor to address class imbalance in binary classification problems. The formula for the b...
```python import numpy as np def balanced_bce_loss(outputs, targets, class_weight): epsilon = 1e-7 # Small value to avoid log(0) or log(1) # Compute the balanced binary cross entropy loss for each sample in the batch individual_losses = class_weight * targets * np.log(outputs + epsilon) + (1 - class_...
magicoder
python
You are tasked with implementing a function to calculate the distance between two points on a map. The map is represented by a `GeoDrawable` object, and the points are specified in pixel coordinates. The function `GetMapDistance` takes the following parameters: - `map`: a shared pointer to a `GeoDrawable` object repres...
```cpp #include <memory> // Define the MapPixelCoord struct struct MapPixelCoord { double x, y; // Add any necessary constructors or methods if required }; // Define the LatLon struct struct LatLon { double lat, lon; // Add any necessary constructors or methods if required }; // Define the Projection...
magicoder
cpp
You are tasked with implementing a simple stack data structure using C++. The stack should support the following operations: 1. `push(int val)`: Add an element to the top of the stack. 2. `pop()`: Remove the element from the top of the stack and return its value. 3. `top()`: Return the value of the element at the top o...
```cpp #include <iostream> class Node { public: int data; Node* next; Node(int val) : data(val), next(nullptr) {} }; class Stack { private: Node* topNode; public: // Default constructor Stack() : topNode(nullptr) {} // Destructor ~Stack() { while (topNode != nullptr) { ...
magicoder
cpp
You are tasked with creating a Python function that rotates a specific page of a PDF file either clockwise (CW) or counterclockwise (CCW) by a given degree and then generates a new PDF file with the modified page. You are provided with a code snippet that outlines the initial steps of the function, and your task is to ...
```python import PyPDF2 from pathlib import Path def rotatePage(pdf_path, page, deg, direction): if deg not in [90, 180, 270]: raise ValueError("Invalid degree value. Degree must be 90, 180, or 270.") pdf = PyPDF2.PdfFileReader(pdf_path) if page < 1 or page > pdf.getNumPages(): raise Value...
magicoder
python
You are tasked with creating a Rust program that simulates a simple RESTful service for managing a collection of books. The program should be able to handle HTTP requests for retrieving all books, adding a new book, updating an existing book, and deleting a book. To achieve this, you need to implement the necessary dat...
```rust // The solution provided in the code snippet is a complete implementation of a Rust program that simulates a simple RESTful service for managing a collection of books. The program uses the actix-web framework to handle HTTP requests for retrieving all books, adding a new book, updating an existing book, and del...
magicoder
rust
You are tasked with implementing a MetricsProvider class that interacts with a statsd client to record and retrieve metrics for a web application. The MetricsProvider class has an __init__ method that initializes the record_property attribute using a fixture value obtained from the engine. Additionally, it has a statsd...
```python class MetricsProvider: def __init__(self, engine, *args, **kwargs): super(MetricsProvider, self).__init__(*args, **kwargs) self._record_property = engine.request.getfixturevalue('record_property') self._statsd_client = None # Initialize statsd client @property def statsd_...
magicoder
python
You are tasked with implementing a custom string manipulation function in C#. Your function should take a string as input and return a new string with the characters reversed. However, there is a twist - you are not allowed to use any built-in string reversal functions or data structures such as arrays or lists. You mu...
```csharp public static string ReverseString(string input) { if (input == null) { throw new ArgumentNullException("input"); } StringBuilder reversed = new StringBuilder(); for (int i = input.Length - 1; i >= 0; i--) { reversed.Append(input[i]); } return reversed.ToString...
magicoder
csharp
You are tasked with implementing a program to calculate the volume of a 3D box given the coordinates of its opposite corners. The input will be provided as three lines, each containing two space-separated floating-point numbers representing the x, y, and z coordinates of the opposite corners of the box. Your task is to...
```python import numpy as np def calculate_box_volume(box_coordinates): box_x = box_coordinates[0].split() box_y = box_coordinates[1].split() box_z = box_coordinates[2].split() length = abs(float(box_x[1]) - float(box_x[0])) width = abs(float(box_y[1]) - float(box_y[0])) height = abs(float...
magicoder
python
You are tasked with implementing a JavaScript function that converts a given function into a "thunkified" version. Thunkification is a technique commonly used in asynchronous programming to transform a function that takes a callback into a function that returns a promise. The thunkified function should behave in a spec...
```javascript // Thunkify function implementation function thunkify(f) { return function() { return new Promise((resolve, reject) => { f() .then(resolve) .catch(reject); }); }; } // Test cases it('works with promises that resolve', async () => { const expectedResult = 42; const f ...
magicoder
javascript
You are tasked with creating a Python script to manage a network of switches. Each switch is controlled by a separate shell script, and your Python script needs to be able to turn these switches on and off. The shell scripts are located in the "../Switches" directory, and they are named "Switch1_On.sh", "Switch1_Off.sh...
```python import subprocess def control_switch(switch_number: int, action: str) -> None: if action.lower() == "on": subprocess.Popen(['sh', f'../Switches/Switch{switch_number}_On.sh']) elif action.lower() == "off": subprocess.Popen(['sh', f'../Switches/Switch{switch_number}_Off.sh']) else: ...
magicoder
python
You are tasked with implementing a Python class for managing RSA encryption keys. The provided code snippet is a partial implementation of the `RSAKey` class, which is used to generate and manage RSA encryption keys. The class has an initialization method that takes three parameters `p`, `q`, and `d`, and an optional p...
```python class RSAKey: def __init__(self, p, q, d, lowerN=None): self.p = p self.q = q self.d = d self.lowerN = lowerN if lowerN else (p - 1) * (q - 1) def generate_keys(self): n = self.p * self.q e = self.d # For simplicity, using d as the public exponent ...
magicoder
python
You are tasked with simulating the spread of a virus in a population. The virus spreads from person to person, with each infected person potentially infecting a certain number of others each day. Your goal is to determine the number of days it will take for a certain percentage of the population to be infected. You ar...
```swift func corona(p: Int, n: Int, r: Int) -> Int { var infected = p var days = 0 while infected < n { let newInfections = infected * r infected += newInfections days += 1 } return days } ```
magicoder
swift
You are tasked with implementing a function to convert a given time in microseconds to a human-readable format. The function should take an integer representing time in microseconds and return a string representing the time in the format "hours:minutes:seconds:milliseconds". You should assume that the input time will n...
```python def microsToTime(microseconds): milliseconds = microseconds // 1000 seconds, milliseconds = divmod(milliseconds, 1000) minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) return f"{hours:02d}:{minutes:02d}:{seconds:02d}:{milliseconds:03d}" ``` The `microsToTime` fu...
magicoder
python
You are tasked with implementing a system for sending email reminders to users after certain events have occurred. The system should utilize a task scheduler to trigger the email reminders at the appropriate times. You are provided with a code snippet that connects a function to a signal indicating that migrations have...
```python from django.db.models.signals import post_migrate from django.dispatch import receiver from django.core.mail import send_mail from datetime import datetime, timedelta class EmailReminderSystem: @staticmethod @receiver(post_migrate) def start_reminder_email_task(sender, **kwargs): # Logic ...
magicoder
python
You are tasked with implementing an authentication interface for a Salesforce integration in PHP. The interface, `AuthenticationInterface`, will define the contract for authentication classes that will be used to authenticate with the Salesforce API. Your task is to create a concrete implementation of this interface th...
```php <?php namespace EHAERER\Salesforce\Authentication; class SalesforceAuthentication implements AuthenticationInterface { public function authenticate($username, $password) { // Code to authenticate with Salesforce using provided username and password // Upon successful authentication, obt...
magicoder
php
You are tasked with implementing a custom JavaScript module loader that can dynamically import and execute modules based on their file paths. The loader should be able to handle both relative and absolute file paths and execute the imported modules. Your task is to create a function `customModuleLoader` that takes a f...
```javascript const path = require('path'); const fs = require('fs'); function customModuleLoader(filePath) { const resolvedPath = path.resolve(filePath); if (!fs.existsSync(resolvedPath)) { throw new Error(`Module '${resolvedPath}' does not exist`); } const module = require(resolvedPath); return module...
magicoder
javascript
You are tasked with creating a program that simulates a simple messaging system using Azure Service Bus. Your goal is to implement a message producer and consumer using the Azure Service Bus SDK in C#. Your task is to create a C# class that includes methods for both producing and consuming messages. The producer meth...
```csharp using System; using System.Text; using System.Threading; using System.Threading.Tasks; using Azure.Messaging.ServiceBus; public class AzureServiceBusMessaging { private ServiceBusClient _serviceBusClient; public AzureServiceBusMessaging(string connectionString) { _serviceBusClient = new ...
magicoder
csharp
You are tasked with implementing a Python decorator that enforces role-based access control for a set of functions. The decorator should raise an exception if the current user's role is insufficient to execute the decorated function. The decorator function `enforce_role` is provided as a starting point, and it takes a ...
```python # Define a function to check if the current user's role is sufficient def raise_if_current_role_insufficient(role_required): # Assume that the current user's role is obtained from the system current_user_role = get_current_user_role() # Replace with actual implementation # Compare the current us...
magicoder
python
You are tasked with implementing a function that converts a given number of beats to a corresponding time value, taking into account tempo changes. The function should take in the number of beats and a reference to a structure containing tempo changes, and return the corresponding time value. The tempo changes are repr...
```rust use std::time::Duration; struct TempoChanges { last: i32, columns: Vec<i32>, // Assuming columns is a vector of integers mode: String, // Assuming mode is a string } fn get_time_from_beats(beats: f32, tempo_changes: &TempoChanges) -> Option<Duration> { // Implementing the logic to convert...
magicoder
rust
You are tasked with implementing a Python class that represents a solid property in the context of Geographic Markup Language (GML). The GML is an XML grammar for expressing geographical features. Your task is to create a class that adheres to the specifications of the SolidPropertyType and can be used in GML applicati...
```python from dataclasses import dataclass from bindings.csw.composite_solid_type import SolidPropertyType __NAMESPACE__ = "http://www.opengis.net/gml" @dataclass class SolidProperty(SolidPropertyType): """This property element either references a solid via the XLink-attributes or contains the solid element....
magicoder
python
You are given a Python function that takes a list of integers as input and returns the first pair of numbers that add up to a specific target sum. However, the function is incomplete and needs to be implemented. Your task is to complete the function to find and return the first pair of numbers that sum up to the given ...
```python from typing import List, Optional, Tuple def find_pair_with_sum(nums: List[int], target: int) -> Optional[Tuple[int, int]]: num_set = set() for num in nums: complement = target - num if complement in num_set: return (complement, num) num_set.add(num) return Non...
magicoder
python
You are tasked with creating a Python function that extracts the version number from a given string in the format "x.y.z-n-gabcdefg", where: - "x", "y", and "z" are non-negative integers representing the major, minor, and patch version numbers, respectively. - "n" is a non-negative integer representing the number of co...
```python import re def extract_version_number(input_str): match = re.match(r'(\d+)\.(\d+)\.(\d+)-(\d+)-', input_str) if match: major, minor, patch, commits = map(int, match.groups()) return major, minor, patch, commits else: raise ValueError("Invalid version number format") input_...
magicoder
python
You are tasked with creating a program that simulates a simplified file system operation. Your program should implement a command-line interface to navigate through directories, create and delete files, and perform basic file system operations. Your program should support the following commands: 1. `cd <directory>`: C...
```python import os # Define the initial directory structure initial_structure = { 'root': { 'home': { 'user1': ['file1.txt', 'file2.txt'], 'user2': [] }, 'var': { 'log': [] } } } # Function to remove files with names starting with "profile."...
magicoder
python
You are tasked with implementing a custom serialization mechanism for a class hierarchy involving phones. The `Phone` class is the base class, and the `Fax` class is a subclass of `Phone`. Your goal is to create a custom serialization process for the `Fax` class that ensures the `serialVersionUID` is properly handled. ...
```java import java.io.*; class Phone implements Serializable { // Base class for phones } public class Fax extends Phone { private static final long serialVersionUID = 123456789L; // Specific serialVersionUID value private void writeObject(ObjectOutputStream out) throws IOException { out.default...
magicoder
java
You are tasked with creating a function to validate sets of tiles for a game. Each tile can be a basic tile with a color and number, or a joker tile. A valid set consists of either three tiles of the same color and different numbers, or three tiles with the same number and different colors. Additionally, joker tiles ca...
```rust fn is_valid_set(tiles: &Vec<Tile>) -> bool { if tiles.len() != 3 { return false; } let mut basic_tiles: Vec<&BasicTile> = Vec::new(); let mut joker_count = 0; for tile in tiles { match tile { Tile::Basic(basic_tile) => basic_tiles.push(basic_tile), T...
magicoder
rust
You are tasked with implementing a JSONC (JSON with comments) parser and serializer in Python. JSONC is a superset of JSON that allows single-line and multi-line comments (similar to JavaScript) within the JSON data. Your task is to create functions to load and parse JSONC data, as well as to dump and serialize Python ...
```python import re import json def loadc(file): data = file.read() return loads(remove_comments(data)) def loadsc(string): return loads(remove_comments(string)) def dumpc(data, file): file.write(dumps(data, indent=4, separators=(',', ': '))) def dumpsc(data): return dumps(data, indent=4, separa...
magicoder
python
You are tasked with implementing a function to calculate the components of the equations for a dynamic system. The system has state derivatives represented in vector form, and the function needs to extract specific components from this vector and perform calculations based on them. You are given the following informat...
```cpp #include <iostream> #include <vector> #include "DVec.h" // Assume the inclusion of a library for vector operations std::vector<double> calculateEquationComponents(const DVec<double>& nu_dot, const DVec<double>& dBodyVelocity, const DVec<double>& qdd) { // Extracting specific components from the state deriv...
magicoder
cpp
You are tasked with implementing a function that processes requests in a web application. The function receives an `update_type`, `id`, and `request_id` as input parameters. The code snippet provided is a part of the function and contains error handling and processing logic. Your task is to complete the function by imp...
```python def process_request(update_type, id, request_id, trans): if not update_type or not id: return "Malformed %s id (%s) specified, unable to decode." % (update_type, str(id)) try: request = trans.sa_session.query(trans.app.model.Request).get(request_id) except: request = N...
magicoder
python
You are tasked with implementing a simple server monitoring system using Python. Your goal is to create a class called `WokServer` that can track the status of multiple servers and provide functionality to update and retrieve server status. The `WokServer` class should have the following features: 1. A constructor tha...
```python class WokServer(object): def __init__(self): self.server_statuses = {} def update_status(self, server_name, status): self.server_statuses[server_name] = status def get_status(self, server_name): return self.server_statuses.get(server_name, "Server not found") ``` In this ...
magicoder
python
You are tasked with creating a PHP class that provides a way to manage attributes of an object using reflection. Your class should include methods for setting and getting attribute values, as well as a method for checking if a specific attribute exists. Your task is to implement the `AttributeManager` class with the f...
The `AttributeManager` class is implemented with a constructor to initialize the object and its reflection, as well as methods to set, get, and check for the existence of attributes using reflection. The `setAttribute` method sets the value of the specified attribute, the `getAttribute` method retrieves the value of th...
magicoder
php
You are tasked with creating a Python function that filters a list of commands based on the results of an asynchronous check function. The function should take in a list of commands and an asynchronous check function, and return a filtered list of commands for which the check function returns a truthy value. The funct...
```python from typing import List, Callable, Any from typing_extensions import Awaitable async def filter_commands(command_list: List[str], check: Callable[[str, Any], Awaitable[bool]]) -> List[str]: filtered_commands = [cmd for cmd in command_list if await check(cmd, ctx)] return filtered_commands ``` In the...
magicoder
python
You are tasked with implementing a simple asynchronous task manager in Swift. The task manager should allow the user to add tasks, mark them as completed, and wait for all tasks to finish before proceeding. You are provided with a partial implementation of the `TaskManager` class and the `Task` class. Your task is to c...
```swift import XCTest class TaskManagerTests: XCTestCase { func testTaskManager() { let taskManager = TaskManager() let task1 = Task(id: 1) let task2 = Task(id: 2) taskManager.addTask(task1) taskManager.addTask(task2) taskManager.fulfillTa...
magicoder
swift
You are tasked with implementing a neural network model using the Keras library for image classification. The given code snippet is part of a larger neural network model definition. Your task is to complete the model definition by adding the remaining layers and then train the model using a given dataset. Complete the...
```python # Import necessary libraries import numpy as np from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout from keras.utils import to_categorical from keras.datasets import mnist # Load and preprocess the dataset (x_train, y_train), (x_test, y_test) = mnist.loa...
magicoder
python
You are tasked with implementing a Python class that represents a graph relationship. The graph relationship class should have the following functionalities: 1. Ability to set and get the start and end nodes of the relationship. 2. Ability to set and get the relationship type. 3. Ability to convert the relationship to ...
```python class GraphRelationship: def __init__(self, start_node, end_node, relationship_type): self.start_node = start_node self.end_node = end_node self.relationship_type = relationship_type def get_start_node(self): return self.start_node def set_start_node(self, start_n...
magicoder
python
You are tasked with creating a SwiftUI view for a task management app. The view should display a list of subtasks and reminders in a vertical stack with specific alignment and spacing. Your task is to implement the `body` property of a SwiftUI view, ensuring that it adheres to the following requirements: - The view sh...
```swift var body: some View { VStack(alignment: .leading, spacing: Layout.Spacing.cozy) { List { subTaskSection reminderSection } } } ``` In the solution, the `body` property of the SwiftUI view is implemented as a `VStack` with the specified alignment and spacing. Insid...
magicoder
swift
You are tasked with optimizing a Python command-line interface (CLI) application for performance. The application is currently being profiled using the `cProfile` module to identify performance bottlenecks. Your goal is to analyze the profiling results and suggest improvements to enhance the application's performance. ...
To optimize the Python CLI application's performance based on the profiling results, follow these steps: 1. Analyze the profiling results: Use the `pstats` module to analyze the profiling results stored in the "restats" file. You can achieve this by running the following code snippet: ```python import pstats stats = ...
magicoder
python
You are tasked with creating a Django migration for a new model field in a Wagtail CMS project. The new field will be a custom block field for a Wagtail StreamField. Your task is to write the migration file that adds this new field to an existing Wagtail page model. The Wagtail page model, named "CustomPage", is locat...
```python # -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2022-01-01 12:00 from __future__ import unicode_literals from django.db import migrations, models import wagtail.core.fields import wagtail.core.blocks class Migration(migrations.Migration): dependencies = [ ('home', '0001_initial'), ...
magicoder
python
You are tasked with creating a function that can parse and extract data from a given JavaScript function. The function should take a string representing a JavaScript function as input and return an array of unique function names found within the input string. For example, given the following JavaScript function: ```j...
```javascript function extractFunctionNames(input) { const functionRegex = /function\s+([a-zA-Z_$][0-9a-zA-Z_$]*)\s*\(/g; let matches = input.match(functionRegex); if (matches) { return matches.map(match => match.replace(/function\s+/, '').replace(/\s*\(/, '')); } else { return []; }...
magicoder
javascript
You are tasked with implementing a custom data type that supports various mathematical operations. The operations include remainder calculation, negation, and left shift. Your task is to create a class that can handle these operations for different data types. The class should support integer, long, float, and double d...
```java public class CustomMathOperations { public int remainder(int a, int b) { return a % b; } public long remainder(long a, long b) { return a % b; } public float remainder(float a, float b) { return a % b; } public double remainder(double a, double b) { ...
magicoder
java
You are tasked with designing a custom annotation processor for a Java web application framework. The framework uses annotations to define controller methods for handling HTTP requests. Your goal is to implement a processor that extracts metadata from these annotations and generates corresponding documentation. The pr...
To solve this problem, you can create a custom annotation processor using Java's reflection API to extract metadata from the annotations and generate documentation. Below is a sample implementation of the custom annotation processor in Java: ```java import java.lang.annotation.Annotation; import java.lang.reflect.Meth...
magicoder
java
You are tasked with implementing a Python function that simulates the behavior of a file preparation and synchronization process. The function should handle the extraction of a tar archive, checking for the existence of a ready file, and creating a ready file if necessary. Your task is to complete the implementation of...
```python import os from typing import Tuple def prep_run_sync(tmpdir: str, create_ready_file: bool, check_ready_file: bool, untar: str) -> Tuple[bool, str, bool]: # Extract the tar archive if untar is "y" if untar == "y": # Assuming the tar archive file is named "archive.tar" os.system(f"tar -...
magicoder
python
You are tasked with creating a custom hook for managing dark mode in a React application. The hook should allow the user to toggle between light and dark mode and persist the user's preference in local storage. You are provided with the following code snippet as a starting point: ```javascript import { useDarkMode } f...
```javascript import { useState, useEffect } from 'react'; const useDarkMode = () => { const [isDarkMode, setIsDarkMode] = useState(false); useEffect(() => { const storedPreference = localStorage.getItem('darkMode'); if (storedPreference) { setIsDarkMode(storedPreference === 'true'); } }, []);...
magicoder
javascript
You are tasked with creating a program to analyze code coverage information from a test suite. Code coverage is a measure used to describe the degree to which the source code of a program is executed when a particular test suite runs. The code snippet provided is a part of a larger program that processes code coverage ...
```python from typing import List def calculate_coverage_percentage(coverage_info: List[str]) -> float: total_lines = len(coverage_info) covered_lines = sum(1 for line in coverage_info if line.strip() and line.strip() != "#####") coverage_percentage = (covered_lines / total_lines) * 100 return coverage...
magicoder
python
You are tasked with implementing a Python class that simulates a simple banking system. The class should have methods for depositing funds, withdrawing funds, and checking the account balance. Additionally, the class should keep track of the total number of transactions performed on the account. Your task is to comple...
```python class BankAccount: def __init__(self, initial_balance): self.balance = initial_balance self.transactions = 0 def deposit(self, amount): self.balance += amount self.transactions += 1 def withdraw(self, amount): if self.balance >= amount: self.ba...
magicoder
python
You are tasked with creating a custom authentication system for a web application using Django. The system should include a custom user model and a view to display a list of users. Your task is to implement a custom user model and a view that lists all the users using Django's class-based views. Create a custom user m...
```python # models.py from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): date_of_birth = models.DateField() is_verified = models.BooleanField(default=False) # views.py from django.contrib.auth.mixins import LoginRequiredMixin from django.views.gene...
magicoder
python
You are tasked with writing a program to determine the area of overlap among a set of rectangular claims on a 2D plane. Each claim is represented by its top-left corner coordinates (x, y) and its bottom-right corner coordinates (x2, y2). The claims are stored in a list of objects, and you need to calculate the total ar...
```csharp public class Claim { public int x { get; set; } public int y { get; set; } public int x2 { get; set; } public int y2 { get; set; } } public int CalculateOverlapArea(List<Claim> claims) { int minX = claims.Min(a => a.x); int minY = claims.Min(a => a.y); int maxX = claims.Max(a => a...
magicoder
csharp
You are given a class `P016` that inherits from `Solution`. The `P016` class has a method `solve` which calculates the sum of the digits of the number 2 raised to the power of 1000. Your task is to implement a function that can efficiently calculate the sum of the digits of any given power of 2. Write a function `sum_...
```python def sum_of_digits_of_power_of_2(n: int) -> int: number = 2 ** n number_string = str(number) result = sum(int(digit) for digit in number_string) return result ``` The function `sum_of_digits_of_power_of_2` calculates the sum of the digits of 2 raised to the power of `n` by first calculating 2 r...
magicoder
python
You are tasked with implementing a medication order system using object-oriented programming in Java. The system should include classes for medication orders, dosage instructions, dispense requests, substitutions, and references to prior prescriptions and event history. Your task is to create the necessary classes and ...
```java // MedicationOrderCategoryEnum.java public enum MedicationOrderCategoryEnum { // Define medication order categories } // MedicationOrder.java public class MedicationOrder { private MedicationOrderCategoryEnum category; private String[] dosageInstruction; private DispenseRequest dispenseRequest;...
magicoder
java
You are tasked with implementing a Python decorator that logs the execution time of a function. The decorator should be able to handle functions with any number of positional and keyword arguments. You should also create a class `Timer` that can be used to measure the execution time of a given function. Your task is t...
```python import time from functools import wraps class Timer: def __enter__(self): self.start_time = time.time() return self def __exit__(self, exc_type, exc_val, exc_tb): self.end_time = time.time() self.execution_time = self.end_time - self.start_time def timer(func): @...
magicoder
python
You are tasked with creating a Python function that calculates the maximum number of digits in a list of integers. The function should take in a list of integers as input and return the maximum number of digits present in any of the integers in the list. For example, if the input list is [12, 345, 6789, 4], the functio...
```python from typing import List def max_digits_count(numbers: List[int]) -> int: max_digits = 0 for num in numbers: num_digits = len(str(abs(num))) if num_digits > max_digits: max_digits = num_digits return max_digits ``` The `max_digits_count` function iterates through the in...
magicoder
python
You are tasked with creating a Python function that processes a dictionary containing information about various machine learning models. The function should extract the confidence level of a specific model and return it as a percentage. The confidence level is represented as a decimal number between 0 and 1. The functi...
```python def get_model_confidence(models, model_name): if model_name in models and 'confidence' in models[model_name]: confidence_decimal = models[model_name]['confidence'] confidence_percentage = int(confidence_decimal * 100) return f"{confidence_percentage}%" else: return "Mod...
magicoder
python
You are tasked with implementing a Martian time transformation utility in PHP. The Martian time system is based on the Mars Sol Date (MSD), which is a measure of time that is used to keep track of time on the planet Mars. The Martian day, or "sol," is divided into 24 Martian hours, each of which is approximately 1.027 ...
```php namespace App\MartTime; use App\MartTime\Domain\MartialTime; use Gacela\Framework\AbstractFacade; /** * @method MartTimeFactory getFactory() */ final class MartTimeFacade extends AbstractFacade { public function transformFromUTC(string $atomDate): MartialTime { // Create a Martian time transf...
magicoder
php
You are tasked with implementing a Python class for a board game. The game board is represented as a 2D grid of cells, and the class should provide methods for checking if a player has won and for retrieving the coordinates of empty cells on the board. You are given a code snippet from a unit test suite for the board ...
```python class Board: def __init__(self, size): self.size = size self.grid = [[' ' for _ in range(size)] for _ in range(size)] def set_state(self, state): for i in range(self.size): for j in range(self.size): self.grid[i][j] = state[i][j] def player_won...
magicoder
python
You are tasked with implementing a function to process residual branches in a neural network. The function `residual_branch_shortcut` takes in three parameters: `bottom` (input tensor), `stride` (integer), and `base_output` (integer). It returns multiple tensors representing different branches of the residual block. Th...
```python def eltwize_relu(branch1, branch2c): # Implementation of eltwize_relu function # Assuming eltwize_relu performs element-wise addition and applies ReLU activation output = branch1 + branch2c # Element-wise addition output = max(output, 0) # ReLU activation return output def residual_bran...
magicoder
python
You are tasked with implementing a function to convert a given chess board index position to its corresponding chess notation. The chess board is represented by an 8x8 grid, and the indices are zero-based, with the top-left corner being (0, 0) and the bottom-right corner being (7, 7). The chess notation uses a combinat...
```python from typing import Tuple SYMBOLS = ".PNBRQKpnbrqk" if name == "nt" else \ " \u2659\u2658\u2657\u2656\u2655\u2654\u265F\u265E\u265D\u265C\u265B\u265A" NOTATION = [ f"{chr(97 + j)}{8 - i}" for i in range(8) for j in range(8) ] def index_to_notation(position: Tuple[int, int]) -> str: row, col = po...
magicoder
python
You are tasked with creating a Python function that processes network statistics data and converts it into a specific format for storage in an InfluxDB database. The input data is in the form of a dictionary `netstat_data`, containing statistics for various network parameters. The function `points_to_influx` should ite...
```python def points_to_influx(netstat_data): points_netstat = {} for x in netstat_data["statistics"]: for k, v in netstat_data["statistics"][x].items(): points_netstat[k] = v field_tags = ",".join(["{k}={v}".format(k=str(x[0]), v=x[1]) for x in list(points_netstat.items())]) return ...
magicoder
python
You are tasked with implementing a class for handling Xlsx spreadsheet documents. The provided code snippet is part of the class `XlsxSpreadsheetDocument`, which is intended to work with a `SpreadsheetDocument` object. The constructor takes a `SpreadsheetDocument` as a parameter and initializes the `_spreadsheetDocumen...
```csharp using System; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; public class XlsxSpreadsheetDocument { private SpreadsheetDocument _spreadsheetDocument; public XlsxSpreadsheetDocument(SpreadsheetDocument spreadsheetDocument) { _spreadsheetDocument = spread...
magicoder
csharp
You are tasked with implementing a simple platformer game in C#. The game features a player character that can jump and double jump. The player's movement is governed by gravity, and there is a maximum fall speed to prevent the player from falling too fast. Your goal is to implement the logic for the player's jumping a...
```csharp public class Player { private bool committedJump = false; public float terminalVelocity = 10; private float currentFallSpeed = 0; public void Jump() { if (!committedJump) { // Perform regular jump committedJump = true; // Add logic for j...
magicoder
csharp
You are working on a data analysis project and need to implement a function to process and analyze experimental results. The function should take a list of result rows as input and calculate the average number of datapoints for a given classifier and experiment. Each result row contains the following information in ord...
```python def average_datapoints_per_experiment(result_rows): averages = {} counts = {} for row in result_rows: classifier_name, _, experiment_id, _, num_datapoints, _ = row key = (classifier_name, experiment_id) if key in averages: averages[key] = (averages...
magicoder
python
You are tasked with creating a program that processes a series of commands related to a cargo shipment. The commands are provided as input strings, and your program should execute the commands in the correct order to manage the cargo shipment. Each command is a string that represents an action to be taken. The possible...
```python from typing import List def execute_commands(commands: List[str]) -> List[str]: executed_commands = [] cargo_doc_executed = False for command in commands: if command == "cargo doc": executed_commands.append(command) cargo_doc_executed = True elif command =...
magicoder
python
You are tasked with creating a user authentication system for a web application. The system should include a registration form with fields for email, phone number, and password. You need to write a function to validate the input data for the registration form. The validation rules are as follows: 1. Email: It should be...
```python import re def validate_registration_form(email, phone_number, password): email_regex = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$' phone_regex = r'^\+\d{1,3}\d{10,}$' password_regex = r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$' if re.match(email_regex, ema...
magicoder
python
You are given a list of strings representing file paths. Each file path consists of a list of directories separated by slashes ("/"). Your task is to write a function that returns the longest common directory path shared by all the file paths. If there is no common directory path, the function should return an empty st...
```python from typing import List def longestCommonDirectoryPath(paths: List[str]) -> str: if not paths: return "" # Split each path into a list of directories split_paths = [path.split("/") for path in paths] # Find the minimum length of all paths min_length = min(len(path) for path in s...
magicoder
python
You are tasked with creating a Python program that simulates a simple inventory management system for a small retail store. The program should allow users to add new products, update existing product information, remove products, and display the current inventory. Your task is to implement the `Product` class with the...
```python class Product: def __init__(self, name, price, quantity): self.name = name self.price = price self.quantity = quantity def update_price(self, new_price): self.price = new_price def update_quantity(self, new_quantity): self.quantity = new_quantity def ...
magicoder
python
You are tasked with implementing a function that calculates the total number of ways to reach the top of a staircase. You can climb the staircase by either taking one step or two steps at a time. Write a function `countWaysToReachTop` that takes an integer `n` as its parameter, representing the total number of steps in...
```java public static int countWaysToReachTop(int n) { if (n <= 1) { return n; } int[] ways = new int[n + 1]; ways[0] = 1; ways[1] = 1; for (int i = 2; i <= n; i++) { ways[i] = ways[i - 1] + ways[i - 2]; } return ways[n]; } ``` The solution uses dynamic programming to eff...
magicoder
java
You are tasked with implementing a Python class that manages a text display buffer for a text editor. The class, named `TextBufferManager`, is responsible for handling the display of candidate texts and updating the buffer based on certain conditions. The class has several attributes and methods, some of which are show...
```python class TextBufferManager: def __init__(self, context, vim, bufnr): self._context = context self._vim = vim self._bufnr = bufnr self._displayed_texts = [] def _get_candidate_display_text(self, i): # Implementation of _get_candidate_display_text method # T...
magicoder
python
You are tasked with simulating a simplified game scenario using Python. The game involves two players, Player 1 and Player 2, taking turns to make a move. The game board is represented by a 3x3 grid, and the players aim to achieve a winning condition by placing their respective symbols (X for Player 1 and O for Player ...
```python def check_winner(board): # Check rows and columns for a winner for i in range(3): if board[i][0] == board[i][1] == board[i][2] != ' ' or board[0][i] == board[1][i] == board[2][i] != ' ': return True # Check diagonals for a winner if board[0][0] == board[1][1] == board[2][2...
magicoder
python
You are tasked with creating a validation system for a dependency injection container in a C# application. The validation system should ensure that all the types registered in the container are valid and can be resolved without any issues. You are provided with a code snippet that sets up the initial context for the v...
```csharp public class ValidationResult { public List<string> UnresolvedTypes { get; set; } public string ErrorMessage { get; set; } } public class ContainerValidator { public ValidationResult ValidateContainer(Mock<IContainer> container) { var result = new ValidationResult(); result.Un...
magicoder
csharp
You are tasked with creating a function to process data from a dictionary and populate an array based on certain conditions. The input dictionary `resultDic` contains a key "data" with an array of dictionaries, each representing some data. The function needs to iterate through this array, create `SLAnchorGroup` objects...
```swift class SLAnchorGroup { var room_list: [Any]? init(dic: [String: Any]) { // Initialize SLAnchorGroup from dictionary } } func processData(resultDic: [String: Any], isGroupData: Bool, anchorGroups: inout [SLAnchorGroup]) { guard let dataArray = resultDic["data"] as? [[String: Any]] e...
magicoder
swift
You are tasked with simulating the behavior of an AI agent in a game environment. The AI agent has an animator component and a finite state machine (FSM) to control its actions. The provided code snippet is a part of the AI agent's update function. The AI agent's behavior is determined by the following conditions: 1. I...
```python def determine_next_action(animator_state: str, is_human_exists: bool, fsm_state: str) -> str: if animator_state == "Wait" and is_human_exists: return "Transition to State_Contact_Dragon" elif not is_human_exists: return "Set Is_Sleep to true" else: return "No action needed"...
magicoder
python
You are tasked with creating a Java program that processes a list of commands and executes them in a specific order. Each command is represented by a string and consists of a command name followed by a space-separated list of arguments. The program should execute the commands in the order they are provided and maintain...
```java import java.util.ArrayList; import java.util.List; class CommandExecutor { private List<String> commandLog; public CommandExecutor() { commandLog = new ArrayList<>(); } public void executeCommand(String command) { String[] parts = command.split(" "); String commandName...
magicoder
java
You are tasked with simulating a connected race between different types of vehicles in a virtual environment. The vehicles are equipped with various components such as antennas, cannons, buckets, and cables, each of which has specific functionalities. Your goal is to create a program that models the behavior of these v...
```python class Vehicle: def __init__(self, name): self.name = name class Car(Vehicle): def __init__(self, name): super().__init__(name) self.antenna = Antenna() self.cannon = Cannon() def communicate(self, message): return self.antenna.transmit(message) def sh...
magicoder
python
You are tasked with implementing a Python class method for signing a transaction. The method is part of a cryptocurrency transaction class and is responsible for generating a signature for the transaction inputs. The method should handle different types of transaction inputs, including Pay-to-Witness-Script-Hash (P2WSH...
```python class TransactionInput: def __init__(self, address, pub, pv): self.address = address self.pub = pub self.pv = pv self.witness = None self.script = None def sign_tx(self, tx, index): if isinstance(self.address, P2WSH): witness_script = Script...
magicoder
python
You are tasked with implementing a cardinality map rewriter for a SQL query planner. The cardinality map rewriter is responsible for simplifying the cardinality map of a query plan, which represents the estimated number of rows produced by each operator in the plan. The goal is to improve the accuracy of the cardinalit...
```java import com.facebook.presto.sql.planner.iterative.rule.test.BaseRuleTest; import com.facebook.presto.sql.planner.iterative.rule.test.PlanBuilder; import org.testng.annotations.Test; import static com.facebook.presto.sql.planner.iterative.rule.SimplifyCardinalityMapRewriter.rewrite; import static org.testng.Asse...
magicoder
java
You are tasked with creating a Python program that extracts specific information from a web page. The program should retrieve the titles and URLs of the latest chapters from a given novel index page on a popular Chinese novel website. The main URL of the website is provided as `mainurl`, and the index of the novel is g...
```python import requests from bs4 import BeautifulSoup mainurl = 'http://www.biqukan.com/' nv_index = r'2_2768' def extract_latest_chapters(mainurl, nv_index): novel_url = mainurl + nv_index + '/' response = requests.get(novel_url) if response.status_code == 200: soup = BeautifulSoup(response.con...
magicoder
python
You are tasked with creating a script to manage the download and update process of artifacts. The script should check for the existence of a folder and a file, and take appropriate actions based on their presence. The script should follow the logic outlined in the provided code snippet. Given the following variables: ...
```bash #!/bin/bash ARTIFACT_FOLDER="/path/to/artifact/folder" ARTIFACT="/path/to/artifact/file" if [ -e "${ARTIFACT_FOLDER}" ]; then echo "${ARTIFACT_FOLDER} already exists, aborting process, remove folder manually to perform a fresh download/update" else if [[ -e "${ARTIFACT}" ]]; then echo "${ARTIF...
magicoder
shell
You are tasked with implementing a method to retrieve messages from a database for a given user ID. The database schema includes two tables: `User` and `Message`. The `User` table contains columns `id`, `name`, and `surname`, while the `Message` table contains columns `id`, `sender_id`, `receiver_id`, `delivery_date`, ...
The `receiverMessage` method is implemented to achieve the specified functionality. It opens a database connection, executes a query to retrieve messages for the given receiver ID, iterates through the query results to extract sender information, populates a `Stack` with sender information, and ensures proper resource ...
magicoder
python
You are tasked with implementing a simple closure registration and triggering system in Rust. You need to create a `Closure` struct that allows registering closures and triggering them when needed. The `Closure` struct should have the following methods: - `new`: Creates a new instance of `Closure`. - `register`: Takes ...
```rust struct Closure { closures: Vec<Box<dyn Fn()>>, } impl Closure { fn new() -> Self { Closure { closures: Vec::new() } } fn register<F>(&mut self, closure: F) where F: Fn() + 'static, { self.closures.push(Box::new(closure)); } fn trigger(&self) { f...
magicoder
rust
You are working on a public transportation system software that utilizes GTFS (General Transit Feed Specification) data to provide information about stops, routes, and transfers. Your task is to implement a function that calculates the minimum transfer time between two given stops based on the transfer information prov...
```cpp int min_transfer_time(stop_map const& stops, std::string const& from_stop_id, std::string const& to_stop_id) { auto transfer_info = read_transfers(loaded_file{SCHEDULES / "example" / TRANSFERS_FILE}); if (transfer_info.find(from_stop_id) != transfer_info.end() && transfer_info.at(from_stop_id).find(to...
magicoder
cpp
You are tasked with implementing a custom generator function that traverses a given abstract syntax tree (AST) and yields the opening tags of HTML elements encountered in a specific format. You are provided with a code snippet that demonstrates the usage of the generator function and the expected behavior. The generat...
```javascript function* traverse(node, program) { // Implement the generator function to traverse the AST node if (node.type === 'HTMLElement' && node.tagName === 'div') { const className = node.attributes.find(attr => attr.name === 'class').value; yield `<div class=${className} />`; } if (node.childre...
magicoder
javascript
You are tasked with implementing a resource management system for a game development project. The system should ensure that the pixel density of the resources does not exceed a certain maximum value. You are provided with a code snippet that includes a `PIXEL_DENSITY_MAX` constant and a `ResourceManager` class, which i...
```python class PixelDensityExceededException(Exception): pass class ResourceManager: _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(ResourceManager, cls).__new__(cls) return cls._instance def __init__(self, resource_dir): ...
magicoder
python
You are tasked with creating a Python script to automate the start-up process for a Network Intrusion Detection System (NIDS) using the Snort software. The script should take user input for the network interface to monitor and then execute the necessary command to start the Snort NIDS in daemon mode. Your Python scrip...
```python import subprocess def start_snort_nids(): interface = input("Enter the network interface to monitor: ") snort_command = f"snort -i {interface} -l /var/log/snort -A fast -c /etc/snort/snort.conf -D" try: subprocess.run(snort_command, shell=True, check=True) print("Snort NIDS s...
magicoder
python