query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with creating a Rust program that interacts with a Python script to generate files. The provided code snippet is a part of the Rust program and shows a method chaining sequence. The `status()` method is called to check the status of the Python script execution, followed by an `expect()` method to handle ...
```rust use std::process::Command; fn main() { let output = Command::new("python") .arg("script.py") .output() .expect("Failed to execute Python script."); if output.status.success() { let exit_code = output.status.code().unwrap(); println!("Python script executed succe...
magicoder
rust
You are tasked with creating a program that reads and processes binary data from a file using the Xe.BinaryMapper library in C#. The binary data represents a collection of employee records, each consisting of the following fields: - Employee ID (4 bytes, integer) - Employee Name (32 bytes, string) - Employee Age (2 by...
```csharp using System; using System.Collections.Generic; using System.IO; using Xe.BinaryMapper; public class Employee { [Data] public int ID { get; set; } [Data] public string Name { get; set; } [Data] public short Age { get; set; } [Data] public float Salary { get; set; } } class Program { stat...
magicoder
csharp
You are tasked with creating a Python function that generates configuration files for virtual hosts in a web server. The function should take in various parameters and produce the necessary configuration files based on the provided input. The function should be named `generate_virtual_host_config` and should accept th...
```python def generate_virtual_host_config(self, server_name, aliases, site_id, log_path, public_html, proxies_pass, proxies_match, secure): # Generate configuration file for virtual host in web server virtualhost_302_tpl.stream( server_name=server_name, aliases=aliases).dump(f'{self.config.wt_c...
magicoder
python
You are tasked with implementing a Python class that represents an educational module and its associated lessons. The class should have methods for string representation and generating a URL for a specific lesson. Your task is to complete the implementation of the `ModuleAula` class by adding the necessary methods. Th...
```python from django.urls import reverse class ModuleAula: def __init__(self, nome, slug): self.nome = nome self.slug = slug def __str__(self): return self.nome def get_absolute_url(self): return reverse('modulos_aulas:aula', kwargs={'slug': self.slug}) # Example usage m...
magicoder
python
You are tasked with creating a Python function that parses a given file and extracts the copyright information from the header. The copyright information is typically found within comments at the beginning of the file and follows a specific format. Your function should be able to identify and return the copyright year ...
```python from typing import Union, Tuple def extract_copyright_info(file_path: str) -> Union[Tuple[str, str], None]: with open(file_path, 'r', encoding='utf-8') as file: for _ in range(10): # Read the first 10 lines line = file.readline().strip() if line.startswith('# Copyright'):...
magicoder
python
You are tasked with implementing a function that simulates a rainbow color cycle. The function should take an integer `n` as input and return a list of RGB color values that represent a rainbow cycle. The rainbow cycle should smoothly transition through the colors of the rainbow, and the length of the returned list sho...
```python def rainbowCycleFunc(n): def rainbow(x): red = int(max(0, 255 - abs(x - 512))) green = int(max(0, 255 - abs(x - 256))) blue = int(max(0, 255 - abs(x))) return (red, green, blue) length = 7 # Number of colors in the rainbow cycle rainbow_cycle = [rainbow(i * 256 //...
magicoder
python
You are tasked with creating a program to calculate the total emissions of electricity and gas for different buildings based on their energy consumption data. The program should read the input data, perform the necessary calculations, and output the total emissions for each building. You are given a dataset `data` con...
```python import pandas as pd import numpy as np def calculate_emissions(data, electricite_emission, gaz_emission): total_donnee = data[["Consommation d'électricité (kWh)", "Consommation de gaz (kWh)", "Nom du bien"]] calcul_par_batiment = [[0, 0, ""] for x in range(len(data))] total_donnee.reset_index(inp...
magicoder
python
You are tasked with implementing a cache system for strings in Rust. The cache system should have the ability to store strings and efficiently retrieve them when needed. To achieve this, you need to implement a `CacheString` struct with the following functionalities: 1. `from_str_truncate`: A method that creates a `Ca...
```rust use std::collections::HashMap; use criterion::{black_box, criterion_group, criterion_main, Criterion}; struct CacheString { cache: HashMap<String, String>, } impl CacheString { fn from_str_truncate(s: &str) -> String { // Truncate the string to a maximum length if necessary let truncat...
magicoder
rust
You are tasked with implementing a function that can parse and validate a custom markup language used for documentation. The markup language allows the use of special syntax for inline code samples, where the code is enclosed within backticks (`) and may contain escaped braces. The syntax for escaped braces is to enclo...
```python from typing import List, Union def parse_inline_code(text: str) -> List[Union[str, List[str]]]: parsed_code = [] i = 0 while i < len(text): if text[i:i+3] == '{{{': parsed_code.append('{') i += 3 elif text[i:i+3] == '}}}': parsed_code.append('}'...
magicoder
python
You are tasked with implementing a downcasting mechanism for a widget library in Rust. The library provides a `BaseWidget` trait, and you need to create a method `try_downcast` that allows downcasting from `BaseWidget` to a specific widget type. The downcasting should be based on a pointer comparison and should return ...
```rust // The trait representing the base widget trait BaseWidget { fn ptr(&self) -> *const Self; } // The specific widget type struct SpecificWidget { ptr: *const SpecificWidget, } impl BaseWidget for SpecificWidget { fn ptr(&self) -> *const Self { self.ptr } } impl SpecificWidget { // ...
magicoder
rust
You are tasked with implementing a program to visualize the results of a clustering algorithm using a scatter plot. The clustering algorithm has already been applied to a dataset, and the results are stored in a file. Your task is to read the results from the file and create a scatter plot where each point is colored a...
```python import matplotlib.pyplot as plt # Read data from file data = [] with open('cluster_results.txt', 'r') as file: for line in file: x, y, cluster = map(float, line.split()) data.append((x, y, cluster)) # Separate data by cluster clusters = {} for x, y, cluster in data: if cluster not in...
magicoder
python
You are tasked with implementing a text layout engine that supports the manipulation of glyphs and their associated properties. The provided code snippet is a method `restore` within a Rust struct, which is responsible for restoring the state of the text layout engine based on a given `ShapedSegmentState`. The method t...
```rust impl TextLayoutEngine { pub fn restore(&mut self, state: &ShapedSegmentState) { self.glyphs.truncate(state.glyphs); self.advance_width = state.advance_width; } } ``` The `restore` method truncates the `glyphs` vector to the length specified in the `state` parameter using the `truncate` ...
magicoder
rust
You are tasked with implementing a data structure and its associated methods for managing operations and their bindings. The data structure, named `OperationManager`, should support adding operations, specifying provided bindings, and determining if a given binding is within the provided set for a specific operation. ...
```rust use std::collections::HashSet; #[derive(Debug, PartialEq, Eq, Hash)] struct Binding { name: String, value: i32, } struct OperationManager { operations: Vec<Operation>, } struct Operation { ops: Vec<String>, provided: HashSet<Binding>, cost: u32, } impl OperationManager { fn new()...
magicoder
rust
You are tasked with creating a programming problem related to implementing cryptographic signature verification using a specific library or framework. The problem will focus on understanding and implementing signature verification using the given code snippet as inspiration. You are given a code snippet that demonstra...
To solve this problem, candidates need to understand the cryptographic signature verification process and the operations performed on the signature object in the given code snippet. The solution involves the following steps: 1. Understanding the operations on the signature object: - The code snippet demonstrates th...
magicoder
python
You are tasked with creating a program that processes a given text and counts the frequency of each word. Your program should read the text from a file and output the word frequency in descending order. Additionally, the program should exclude common stop words (e.g., "the", "and", "is") from the word frequency count. ...
```python import re from collections import Counter # Define common stop words stop_words = {"the", "and", "is", "in", "it", "on", "at", "to", "of", "for", "with", "as"} # Read input text from file with open("input.txt", "r") as file: text = file.read() # Remove non-alphabetic characters and convert text to lowe...
magicoder
python
You are tasked with implementing a Python class that combines the functionality of two mixins, `LazyBrokerMixin` and `dramatiq.brokers.stub.StubBroker`. The `LazyBrokerMixin` provides lazy initialization behavior, while the `StubBroker` is a specific type of broker used in the `dramatiq` library. Your task is to creat...
```python import dramatiq.brokers.stub class LazyStubBroker(LazyBrokerMixin, dramatiq.brokers.stub.StubBroker): pass ``` The `LazyStubBroker` class inherits from both `LazyBrokerMixin` and `dramatiq.brokers.stub.StubBroker`, effectively combining their functionalities. Since the `LazyBrokerMixin` provides lazy in...
magicoder
python
You are tasked with implementing a Python class `WordSearch` that can efficiently search for words in a given word set. The class should have a method `search` that takes a single argument `word` and returns `True` if the word can be formed by concatenating one or more words from the word set, and `False` otherwise. T...
```python class WordSearch: def __init__(self, wordSet): self.wordSet = set(wordSet) def search(self, word): if word in self.wordSet: return True for idx in range(1, len(word)): if word[:idx] in self.wordSet and self.search(word[idx:]): return Tru...
magicoder
python
You are tasked with developing a validation system for a travel application. The system should enforce specific constraints on various input fields to ensure data integrity and security. The provided code snippet contains constants defining the constraints for different fields. Your task is to implement a validation fu...
```csharp public class ValidationSystem { public const string AdminRole = "Administrator"; public const string UserRole = "User"; public const string AdminPassword = "<PASSWORD>"; public const string UserPassword = "<PASSWORD>"; public const int CategoryNameMinLength = 3; public const int Categ...
magicoder
csharp
You are tasked with creating a class to represent a country in a software application. The class should have properties to store various information about the country, such as timezones, borders, native name, numeric code, currencies, languages, translations, flag, regional blocs, and the country's code used in the Int...
```csharp using System.Collections.Generic; public class Country { public IEnumerable<string> Timezones { get; set; } public IEnumerable<string> Borders { get; set; } public string NativeName { get; set; } public string NumericCode { get; set; } public IEnumerable<CountryCurrency> Currencies { get;...
magicoder
csharp
You are tasked with implementing a function to extract volume, chapter, fragment, and postfix information from a given title string. The title string may contain hyphens, which should be replaced with periods before extraction. The function should take the title string as input and return the extracted information as a...
```python import re def extract_vol_chapter_fragment_postfix(title: str) -> tuple: title = title.replace('-', '.') # Replace hyphens with periods match = re.match(r'vol\.(\d+)\.chp\.(\d+)\.frag\.(\d+)-(.+)', title) if match: volume = int(match.group(1)) chapter = int(match.group(2)) ...
magicoder
python
You are tasked with creating a program to validate and process IPv4 packets received on a network interface. An IPv4 packet is considered valid if it meets the following criteria: - The packet has a total length of at least 20 bytes. - The version field is 4. - The header length field is at least 5 (indicating a minimu...
```rust fn process_ipv4_packet(packet: &[u8], interface_name: &str) { if packet.len() < 20 { println!("[{}]: Malformed IPv4 Packet - Packet length less than 20 bytes", interface_name); return; } let version = (packet[0] & 0xF0) >> 4; if version != 4 { println!("[{}]: Malformed I...
magicoder
rust
You are tasked with creating a function that determines the longest common prefix among a set of strings. A common prefix is a string that is shared among a group of strings at the beginning. For example, the common prefix of "apple", "app", and "apricot" is "ap". If there is no common prefix, the function should retur...
```swift func longestCommonPrefix(_ strs: [String]) -> String { guard !strs.isEmpty else { return "" } var prefix = strs[0] for i in 1..<strs.count { while !strs[i].hasPrefix(prefix) { prefix.removeLast() if prefix.isEmpty { return "" } } } retu...
magicoder
swift
You are tasked with creating a function that processes a web page's HTML elements to extract specific text content. The function should handle different types of HTML elements and their corresponding text retrieval methods. Write a function `GetNodeText` that takes an `IWebElement` representing an HTML node and return...
```csharp using OpenQA.Selenium; public class NodeTextExtractor { public static string GetNodeText(IWebElement node) { if (node.Matches("input[type=submit], input[type=button]")) { return node.GetProperty("value"); } // Start with the node text, which includes all c...
magicoder
csharp
You are tasked with implementing a simplified file system manipulation library in Rust. Your goal is to create a `Move` struct that represents a move operation between two file paths and implement a method to execute the move operation. You are provided with a partial code snippet that defines the `Move` struct and it...
```rust use std::ffi::CString; use std::path::Path; use std::os::unix::ffi::OsStrExt; use std::os::raw::c_char; struct Move { source: CString, target: CString, } impl Move { pub fn new<A: AsRef<Path>, B: AsRef<Path>>(source: A, target: B) -> Move { Move { source: path_to_cstring(source...
magicoder
rust
You are tasked with creating a Python class that simulates a simple banking system. The class should have methods to deposit funds, withdraw funds, and check the balance. Additionally, the class should keep track of the account holder's name and account balance. Create a Python class `BankAccount` with the following s...
```python class BankAccount: def __init__(self, account_holder): self._account_holder = account_holder self._account_balance = 0 def deposit(self, amount): self._account_balance += amount def withdraw(self, amount): if amount > self._account_balance: print("Insu...
magicoder
python
You are tasked with implementing a custom extension mechanism for the WatchedItemQueryService in a MediaWiki environment. The WatchedItemQueryService is responsible for managing watched items, which are pages or entities that users have chosen to "watch" for changes. Your task is to create an extension mechanism that a...
To implement the extension mechanism for the WatchedItemQueryService, we can use the following approach: 1. Define an interface for extensions: ```php interface WatchedItemQueryServiceExtension { public function modifyQueryResults(IResultWrapper $results): void; // Add other extension methods as needed } ``` ...
magicoder
php
You are tasked with creating a program that simulates a simple network communication scenario using Rust. Your goal is to implement a function that processes input and output operations for a secure communication channel. The function should handle sending and receiving data over the channel and perform basic validatio...
```rust use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::codec::{BytesCodec, Decoder}; use tokio_rustls::server::TlsStream; use rustls::ServerSession; use std::io; use bytes::Bytes; async fn process_secure_channel(io: TlsStream<tokio::net::TcpStream>) -> Result<(), io::Error> { let mut io = io.into_inner()...
magicoder
rust
You are tasked with implementing a simple plugin system for a digital audio workstation (DAW). The provided code snippet contains a part of the interface for interacting with the plugin system. The `unsafe` functions `raw_begin_set_parameter`, `raw_set_parameter_normalized`, and `raw_end_set_parameter` are used to set ...
```rust // Define the ParamPtr type type ParamPtr = *const u8; // Define the Wrapper trait trait Wrapper { fn set_parameter(&self, param: ParamPtr, normalized: f32); fn get_state_object(&self) -> PluginState; } // Define the PluginState struct struct PluginState; // Implement the Wrapper trait for a concrete...
magicoder
rust
You are tasked with implementing a custom layout for a photo gallery in an iOS app using Swift. The layout should display photos in a visually appealing manner, with varying cell sizes and dynamic scrolling behavior. Your goal is to create a custom UICollectionViewLayout that achieves this effect. You are provided wit...
```swift import UIKit class UltravisualLayout: UICollectionViewLayout { private let cellHeight: CGFloat = UltravisualLayoutConstants.Cell.standardHeight private let featuredHeight: CGFloat = UltravisualLayoutConstants.Cell.featuredHeight private var cache: [UICollectionViewLayoutAttributes] = [] p...
magicoder
swift
You are tasked with implementing a Python class for provenance tracking, which records the lineage of data and activities in a computational workflow. The class, named `Provenance`, should support the following functionalities: 1. Recording a configuration using the `record_configuration` method, which takes a diction...
The solution provides a Python class `Provenance` for provenance tracking, supporting the required functionalities such as recording configuration, finishing activities, converting to JSON, managing activities with a context manager, resetting the instance, and setting an output file. The class also includes a nested `...
magicoder
python
You are tasked with implementing a documentation inserter for a Rust project. The inserter is responsible for consuming a list of documentation produced by a `DocGenerator` and inserting it into the relevant files at the relevant locations of the project. The inserter must be able to gracefully merge newly generated do...
```rust use std::collections::HashMap; struct DocInserter { // Define any necessary fields here } impl DocInserter { fn new() -> Self { // Initialize the DocInserter with any necessary setup DocInserter { // Initialize fields if needed } } fn insert_documentation(&...
magicoder
rust
You are tasked with implementing a thread-safe circular buffer in Rust. The circular buffer will be used to store kernel messages (KMSG) in a section of memory. The circular buffer should support the following operations: 1. `push_message(msg: &str)`: Adds a new message to the circular buffer. 2. `pop_message() -> Opti...
```rust use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Mutex, MutexGuard}; const KMSG_SIZE: usize = 100; struct KmsgSection { buffer: [u8; KMSG_SIZE + 1], } static mut KMSG: KmsgSection = KmsgSection { buffer: [0; KMSG_SIZE + 1], }; static BUFFER_INDEX: AtomicUsize = AtomicUsize::new(0); f...
magicoder
rust
You are tasked with implementing a Python function that calculates a spectral line index and then plots the calculated index against the center wavelength. The function should take in two parameters: `flux`, a list of flux values, and `wave`, a list of corresponding wavelength values. The `calc_and_plot` function shoul...
```python import matplotlib.pyplot as plt class SpectralAnalyzer: def calc_and_plot(self, flux, wave): # Calculate line index using the calc function line_index = self.calc(flux, wave) # Calculate center wavelength center_wave = [(wave[i] + wave[i+1]) / 2 for i in range(len(wave)-1...
magicoder
python
You are given a file named "license.txt" containing a software license agreement. Your task is to write a program that reads the contents of the file and counts the occurrences of each unique word in the license agreement. For the purpose of this problem, a word is defined as a sequence of characters separated by space...
```python import re from collections import Counter # Read the license agreement from the file with open('license.txt', 'r') as file: license_text = file.read() # Define common stop words stop_words = {'the', 'and', 'or', 'is', 'are', 'in', 'on', 'at', 'to', 'for', 'with', 'a', 'an', 'of', 'by', 'as', 'it', 'its'...
magicoder
python
You are tasked with creating a Python script that checks for the existence of a file and then creates output directories based on the file's name. Your script should take a filename as input and perform the following tasks: 1. Check if the file exists in the current directory. If the file does not exist, raise an error...
```python import os import argparse import shutil from datetime import datetime def file_exists(fname): if not os.path.isfile(fname): raise argparse.ArgumentTypeError("%r is not a valid file" % (fname,)) return fname def create_output_directories(fname): file_name, file_extension = os.path.splitex...
magicoder
python
You are tasked with creating a script to automate the setup of a user's GitHub configuration. The script should prompt the user for their GitHub email and name, set these values as global configurations for Git, update the remote origin URL for a Git repository, and append the contents of a file `gitconfig` to the user...
```bash #!/bin/bash # Prompt the user for their GitHub email and name read -p "Your GitHub email: " email read -p "Your GitHub name: " name # Set the user's GitHub email and name as global configurations for Git git config --global user.email "$email" git config --global user.name "$name" # Update the remote origin ...
magicoder
shell
You are tasked with creating a Python program that generates a simple torrent file based on a given set of data. The torrent file format is a standard way of representing and sharing files and folders in a distributed network. Your program should take a dictionary of data and produce a torrent file with the appropriate...
```python import hashlib import bencodepy def create_torrent_file(data, file_path): # Create the torrent dictionary torrent_dict = { 'info': { 'name': data['info']['name'], 'length': data['info']['length'] }, 'announce': data['announce'], 'created by': da...
magicoder
python
You are tasked with implementing a simple dependency injection container in Java. Dependency injection is a technique widely used in software development to achieve inversion of control. In this problem, you will create a basic container that can manage the lifecycle of objects and resolve dependencies between them. Y...
```java import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; public class SimpleContainer { private Map<Class<?>, Object> beans = new HashMap<>(); public void register(Class<?> clazz) { if (!beans.co...
magicoder
java
You are tasked with creating a simple distributed computing application using the HPX (High Performance ParalleX) library. HPX is a C++ standard library for parallel and distributed computing. Your goal is to implement a distributed vector addition using HPX. You are given a code snippet that initializes and finalizes...
```cpp #include <hpx/hpx_init.hpp> #include <hpx/hpx_finalize.hpp> #include <hpx/include/iostream.hpp> #include <hpx/include/parallel_algorithm.hpp> #include <hpx/include/parallel_vector.hpp> int hpx_main(int argc, char** argv) { // Initialize the HPX runtime environment hpx::parallel::execution::parallel_exec...
magicoder
cpp
You are working on a game development project and need to implement a character's special ability called "fs" (short for "force strike"). The character has a method `fs_proc` that is called when the "fs" ability is used. Additionally, there are methods `think_pin` and `charge` that are used to manage the character's re...
```python class Character: def __init__(self, conf, s1): self.conf = conf self.s1 = s1 self.fs_hits = 0 self.fs_ahits = 0 self.fs_alt_uses = 0 def fs_proc(self, e): self.update_fs_hits(self.conf[e.name+'.hit']) def update_fs_hits(self, fs_hits): self...
magicoder
python
You are tasked with creating a program to process CSV files and convert their data into SQL format. The provided code snippet initializes instances of the `CsvToSQLConverter` class for four different CSV files: `cities.csv`, `categories.csv`, `opinions.csv`, and `profiles.csv`. Each instance then calls the `export` met...
```php class CsvToSQLConverter { private $csvFilePath; private $tableName; public function __construct($csvFilePath, $tableName) { $this->csvFilePath = $csvFilePath; $this->tableName = $tableName; } public function export() { $csvData = array_map('str_getcsv', file($this->c...
magicoder
php
You are tasked with implementing a Python function that encodes a given string based on a provided mask. The mask is a list of integers, where each integer represents the number of characters to shift in the string. The encoding process involves shifting each character in the string by the corresponding amount specifie...
```python from typing import List def encode_mask_results(s: str, mask: List[int]) -> str: encoded = '' for i in range(len(s)): shift = mask[i % len(mask)] # Use modulo to cycle through the mask encoded += chr((ord(s[i]) - 97 + shift) % 26 + 97) # Shift the character and wrap around if needed...
magicoder
python
You are tasked with creating a version comparison utility for software products. The utility should compare the version of a product stored in a database with the version provided in the code and determine the most specific matching field between the two versions. You are given a `Version` class with the following str...
```java class VersionUtils { public static Field getMostSpecificMatchingField(Version dbVersion, Version codeVersion) { if (dbVersion.major != codeVersion.major) { return Version.class.getDeclaredField("major"); } else if (dbVersion.minor != codeVersion.minor) { return Versio...
magicoder
java
You are tasked with implementing a function to calculate the width of a quantum circuit. The width of a quantum circuit is defined as the maximum number of qubits used in any single layer of gates within the circuit. Your task is to write a function `get_width_of_circuit(circuit)` that takes a quantum circuit as input ...
```python def get_width_of_circuit(circuit): # Convert the circuit to a directed acyclic graph (DAG) dag = circuit_to_dag(circuit) # Initialize the width to 0 width = 0 # Iterate through the layers of gates in the DAG for layer in dag.layers(): # Calculate the number of qubits used in ...
magicoder
python
You are tasked with creating a program that simulates a simple game of rock-paper-scissors against the computer. The game should prompt the user to input their choice (rock, paper, or scissors), generate a random choice for the computer, compare the choices, and determine the winner based on the game rules. The program...
```csharp using System; class Program { static void Main() { string[] choices = { "rock", "paper", "scissors" }; Random random = new Random(); Console.Write("Enter your choice (rock, paper, or scissors): "); string userChoice = Console.ReadLine().ToLower(); if (userCho...
magicoder
csharp
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 current balance. Additionally, the class should incorporate asynchronous programming by using the `async` and `await` keywords to handle concurr...
```python import asyncio class BankAccount: def __init__(self): self.balance = 0 self.lock = asyncio.Lock() async def deposit(self, amount: float) -> None: async with self.lock: self.balance += amount async def withdraw(self, amount: float) -> None: async with ...
magicoder
python
You are tasked with implementing a custom encoding and decoding algorithm for a messaging application. The algorithm should be able to encode and decode user messages for secure transmission over the network. The encoding and decoding methods are to be implemented within a `MessageEncoder` class. The `MessageEncoder` ...
```java public class MessageEncoder { private static final int OFFSET = 3; // Fixed offset value for encoding and decoding public String encodeMessage(String message) { byte[] messageBytes = message.getBytes(); // Convert the message to a byte array byte[] encodedBytes = new byte[messageBytes.l...
magicoder
java
You are tasked with implementing a function to calculate the total number of valid triangles that can be formed from a given list of positive integers. A valid triangle is formed by selecting three integers from the list such that the sum of any two integers is greater than the third integer. Write a function `countVa...
```python from typing import List def countValidTriangles(nums: List[int]) -> int: nums.sort() # Sort the list in non-decreasing order count = 0 for i in range(len(nums) - 2): k = i + 2 for j in range(i + 1, len(nums) - 1): while k < len(nums) and nums[i] + nums[j] > nums[k]: ...
magicoder
python
You are tasked with implementing a function that parses and extracts filter controls from an HTML snippet. The HTML snippet represents a portion of a web page containing filter controls for a gallery or similar content. The filter controls are represented as list items (`<li>` elements) within a `<ul>` element with the...
```python from bs4 import BeautifulSoup def extractFilterControls(html): filter_controls = [] soup = BeautifulSoup(html, 'html.parser') ul_element = soup.find('ul', class_='mixitup-controls') if ul_element: for li in ul_element.find_all('li'): filter_value = li.get('data-filter') ...
magicoder
python
You are tasked with implementing a packet handling system for an online multiplayer game server. The server communicates with clients using a custom protocol where packets are sent and received to perform various actions. Each packet has an associated ID, and the server must be able to register handlers for specific pa...
```python class OsuEvent: handlers = {} @classmethod def register_handler(cls, packet_id): def decorator(func): if packet_id in cls.handlers: cls.handlers[packet_id].append(func) else: cls.handlers[packet_id] = [func] return func ...
magicoder
python
You are tasked with creating a custom data source for a table view in an iOS app. The data source should be able to dynamically determine the type of cell to be used for each index path in the table view. You need to implement the `cellClass` method to achieve this functionality. The `cellClass` method takes an `index...
```swift // Define a protocol or a base class for all cell types protocol DatasourceCell {} // Implement the custom data source class conforming to UITableViewDataSource class CustomDataSource: UITableViewDataSource { // Implement the cellClass method to return the appropriate cell type based on the index path ...
magicoder
swift
You are tasked with implementing a simple playbook management system for organizing and executing different types of scenarios. The system should allow the addition of various types of scenarios, such as atoms, molecules, and organisms, and provide a way to execute them in a specific order. Your task is to create a cl...
```java // Playbook class to manage and execute scenarios public class Playbook { private List<Class<?>> scenarios; public Playbook() { this.scenarios = new ArrayList<>(); } // Method to add a scenario to the playbook public void add(Class<?> scenario) { scenarios.add(scenario); ...
magicoder
java
You are tasked with creating a command-line interface (CLI) for a Bayes Network Demo program. The program should support various commands and options for users to interact with the Bayes Network Demo. Your task is to implement the functionality to parse the command-line arguments and execute the corresponding actions b...
```python import argparse def parse_command_line_args(): parser = argparse.ArgumentParser(description='Bayes Network Demo') parser.add_argument('--predict', action='store_true', help='Execute prediction functionality') parser.add_argument('-p', '--predictor', type=str, help='Specify the predictor variable ...
magicoder
python
You are tasked with implementing a custom annotation processor in Java. The goal is to create a processor that validates the usage of a custom annotation `@Validated` on classes and generates a report of all the classes that use this annotation. The processor should also ensure that the annotated classes have a specifi...
```java import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.annotation.processing.SupportedSourceVersion; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; impor...
magicoder
java
You are tasked with implementing a custom string class in C++. Your custom string class should have the following functionalities: 1. Constructor: Create a constructor that initializes the string with a given character array. 2. Length: Implement a method to return the length of the string. 3. Concatenation: Implement ...
```cpp #include <iostream> #include <cstring> class CustomString { private: char* str; public: // Constructor CustomString(const char* s) { str = new char[strlen(s) + 1]; strcpy(str, s); } // Destructor ~CustomString() { delete[] str; } // Method to return the ...
magicoder
cpp
You are tasked with creating a Python function that processes files based on their extensions. The function should take a file path as input and, if the file has a ".pdf" extension, convert it to a ".jpg" format using an external module. Your task is to implement the `do_print` function, which takes a `file_path` as a ...
```python import printer import convert_pdf_2_jpg # Import the module for PDF to JPG conversion def do_print(file_path): if file_path.endswith('.pdf'): # Check if the file has a .pdf extension jpg_file_path = convert_pdf_2_jpg.do_convert(file_path) # Convert the PDF file to JPG printer.print_fil...
magicoder
python
You are tasked with implementing a Python function to perform polynomial regression using a given set of data points. The function should take in the data points, the degree of the polynomial, and return the coefficients of the polynomial that best fits the data. Your task is to implement the `polynomial_regression` f...
```python import numpy as np def polynomial_regression(x_values, y_values, degree): n = len(x_values) X = np.array([[x**d for d in range(degree+1)] for x in x_values]) Y = np.array(y_values) coeffs = np.linalg.inv(X.T @ X) @ X.T @ Y return coeffs.tolist() ``` The `polynomial_regression` function f...
magicoder
python
You are given a Rust code snippet that is part of a function to find the smallest window in a string containing all characters of another string. Your task is to implement the missing parts of the function to complete the window search algorithm. The function takes two parameters: - `char_sequence`: A vector of tuples...
```rust fn smallest_window(char_sequence: &[(char, usize)], target_chars: &str) -> Option<(usize, usize)> { use std::collections::HashMap; let mut char_size: HashMap<char, i32> = HashMap::new(); for c in target_chars.chars() { *char_size.entry(c).or_insert(0) += 1; } let mut range: Option<...
magicoder
rust
You are tasked with creating a Python function that takes a list of IP addresses and returns a dictionary containing the count of each unique octet combination in the IP addresses. An octet is a group of 8 bits, and in the context of IP addresses, it refers to the numbers between the dots in the address. For example, i...
```python def count_octet_combinations(ip_addresses): octet_count = {} for ip in ip_addresses: octets = ip.split('.') for i in range(4): octet_combination = '.'.join(octets[:i+1]) if octet_combination in octet_count: octet_count[octet_combination] += 1 ...
magicoder
python
You are tasked with creating a Rust program that simulates a simple delivery routing system. The program should consist of two modules: `place_model` and `router`. The `place_model` module should define a data structure to represent a place, while the `router` module should implement a function to calculate the shortes...
```rust // place_model.rs pub struct Place { name: String, coordinates: (f64, f64), } // router.rs use crate::place_model::Place; pub fn calculate_shortest_route(start: &Place, end: &Place) -> String { // Implement the shortest route calculation using any appropriate algorithm // For example, you can ...
magicoder
rust
You are tasked with creating a Python class that can crawl and download video content from a given m3u8 URL. The provided code snippet is a part of the class definition and includes the initialization and run methods. Your task is to complete the class by implementing the missing methods and functionalities. Your clas...
```python import re import requests from urllib.parse import urlparse, urljoin class VideoCrawler: def __init__(self, id, m3u8_url): self.id = id self.url = m3u8_url self.path_url = self.__get_path_url() self.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleW...
magicoder
python
You are given a nested dictionary representing a file system. Each key in the dictionary represents a directory, and the value associated with each key is either another nested dictionary representing a subdirectory or a list representing files in that directory. Your task is to write a function that returns a list of ...
```python def get_file_paths(file_system): file_paths = [] def traverse(directory, path): if isinstance(directory, dict): for key, value in directory.items(): traverse(value, path + key + '/') else: for file in directory: file_paths.append...
magicoder
python
You are tasked with implementing a Redux reducer function in TypeScript for managing the state of a user's structure. The reducer function should handle a specific action type and update the state accordingly. Your task is to complete the implementation of the reducer function based on the given code snippet and requir...
```typescript // Define the UserStructureState type type UserStructureState = { // Define the structure state properties here // Example: id: number; name: string; // ... }; // Define the UserStructureActions type type UserStructureActions = { type: 'SET_USER_STRUCTURE'; payload: UserStructureState; //...
magicoder
typescript
You are tasked with creating a program to analyze and report on the properties of memory modules in a computer system. The program will receive input data in the form of various properties of the memory modules and is expected to process and present this information in a structured manner. The input data consists of t...
```csharp using System; using System.Collections.Generic; public class MemoryModuleAnalyzer { public Dictionary<string, string> AnalyzeMemoryModuleProperties(byte currentSpeed, string currentMemoryType, long installedSize, long enabledSize, string errorStatus) { Dictionary<string, string> properties = ...
magicoder
csharp
You are tasked with implementing a Java class for managing a list of employees. The class should have the following attributes for each employee: - id: a unique identifier for the employee - name: the name of the employee - rank: an integer representing the employee's rank within the company Your task is to implement ...
```java import java.util.ArrayList; import java.util.List; public class Employee { private List<EmployeeInfo> employees; public Employee() { employees = new ArrayList<>(); } public void addEmployee(String id, String name, int rank) { employees.add(new EmployeeInfo(id, name, rank)); ...
magicoder
java
You are tasked with creating a Python function that processes a list of time intervals and returns the total duration covered by these intervals. Each time interval is represented as a tuple of two integers, where the first integer denotes the start time and the second integer denotes the end time. The function should ...
```python def total_duration(tl_list): if not tl_list: return 0 # Sort the intervals based on their start times sorted_intervals = sorted(tl_list, key=lambda x: x[0]) total_duration = 0 current_start, current_end = sorted_intervals[0] for start, end in sorted_intervals[1:]: if...
magicoder
python
You are tasked with implementing a Python function that simulates a simple exception handling middleware for an asynchronous web application. The middleware function should catch any exceptions raised by the provided asynchronous request handler and return an appropriate response. Your task is to complete the implement...
```python from typing import Callable from aiohttp import web async def exception_handler_middleware(request: web.Request, handler: Callable) -> web.Response: try: response = await handler(request) return response except Exception as e: error_message = f"An error occurred: {str(e)}" ...
magicoder
python
You are tasked with creating a function that checks the validity of a given string representing a mathematical expression. The expression will consist of the four basic arithmetic operators: addition (+), subtraction (-), multiplication (*), and division (/). The expression may also contain parentheses to indicate the ...
```javascript function isValidMathExpression(expression) { const stack = []; const operators = new Set(['+', '-', '*', '/']); for (let char of expression) { if (char === '(') { stack.push(char); } else if (char === ')') { if (stack.length === 0) { return false; // Unbalanced parenth...
magicoder
javascript
You are tasked with implementing a function that will parse a given HTML snippet and return the count of all the HTML tags present in the snippet. An HTML tag is defined as a string enclosed within angle brackets, such as `<tag>`. The function should consider both opening and closing tags, and should not count self-clo...
```python import re def countHTMLTags(htmlSnippet): tag_pattern = r'<[^>]+>' tags = re.findall(tag_pattern, htmlSnippet) return len(tags) ``` The `countHTMLTags` function uses the `re` module in Python to find all occurrences of HTML tags in the given `htmlSnippet`. The regular expression pattern `<[^>]+>...
magicoder
python
You are tasked with creating a Python class that simulates a simple car dashboard interface. The class should handle button events and convert units for speed and distance. The provided code snippet includes some initial imports and variable assignments related to the car dashboard interface. Your task is to create a ...
```python from selfdrive.config import Conversions as CV from cereal import car ButtonType = car.CarState.ButtonEvent.Type ButtonPrev = ButtonType.unknown class CarDashboard: def __init__(self): self.current_speed = 0 self.current_distance = 0 def handle_button_event(self, event_type): ...
magicoder
python
You are tasked with implementing a refresh mechanism for a network topology management system. The system consists of a `TopologyReader` and a `ConnectionConfig`, and it needs to listen for refresh requests using a `tokio::sync::mpsc::Receiver`. When a refresh request is received, a response indicating the success or f...
```rust use tokio::sync::{mpsc, oneshot}; struct TopologyReader; struct ConnectionConfig; #[derive(Debug)] struct QueryError; struct NetworkTopologyManager { topology_reader: TopologyReader, connection_config: ConnectionConfig, refresh_channel: mpsc::Receiver<RefreshRequest>, } #[derive(Debug)] struct R...
magicoder
rust
You are tasked with creating a simple Python ROS (Robot Operating System) node that subscribes to a topic, processes the received data, and publishes the processed data to another topic. The node should be able to handle incoming messages and perform a specific operation on the data before publishing it. Your task is ...
```python import rospy from sensor_msgs.msg import Image from your_package.msg import ProcessedImage # Custom message type for processed data from cv_bridge import CvBridge import cv2 def image_callback(msg): # Convert ROS image message to OpenCV format bridge = CvBridge() cv_image = bridge.imgmsg_to_cv2(...
magicoder
python
You are tasked with implementing a DateIndex class that efficiently stores and retrieves data based on dates. The class should support the following operations: 1. `add(date, data)`: Add a new entry to the index with the given date and associated data. 2. `get(date)`: Retrieve the data associated with the given date. ...
```python class DateIndex: def __init__(self, default): self._tree = {} # Tree-based data structure to store entries self._backup_index = {} # Backup index to store snapshots of the index self.default = default # Default value to return when date is not found def add(self, date, data...
magicoder
python
You are given a string representing a 2D grid of characters. The grid contains only two types of characters: 'X' and 'O'. The 'X' characters represent obstacles, and the 'O' characters represent open spaces. The grid is surrounded by '}' characters on all sides. Your task is to write a function that takes the grid as ...
```python def surroundedOpenSpaces(grid: str) -> int: rows, cols = len(grid), len(grid[0]) count = 0 for i in range(1, rows - 1): for j in range(1, cols - 1): if grid[i][j] == 'O': if grid[i-1][j] == 'X' and grid[i+1][j] == 'X' and grid[i][j-1] == 'X' and grid[i][j+1] == ...
magicoder
python
You are tasked with implementing a TypeScript class factory that can create instances of `XmlBackedJSClass` based on XML files. The `XmlBackedJSClassFactory` class provides methods for obtaining instances of `XmlBackedJSClass` and `XmlTag` from XML files. Your goal is to create a TypeScript class that utilizes the `Xml...
```typescript import XmlFile = require('nashorn/com/intellij/psi/xml/XmlFile'); import XmlBackedJSClassFactory = require('nashorn/com/intellij/lang/javascript/psi/ecmal4/XmlBackedJSClassFactory'); import XmlBackedJSClass = require('nashorn/com/intellij/lang/javascript/psi/ecmal4/XmlBackedJSClass'); import XmlTag = requ...
magicoder
typescript
You are given a graph represented as an adjacency list and a starting node. Your task is to implement a function to perform a depth-first search (DFS) traversal of the graph starting from the given node. During the traversal, you need to keep track of the visited nodes to avoid visiting the same node multiple times. Y...
```python def dfs_traversal(graph, start_node): visited_nodes = set() def dfs_util(node): visited_nodes.add(node) for neighbor in graph[node]: if neighbor not in visited_nodes: dfs_util(neighbor) dfs_util(start_node) return list(visited_nodes) ``` The `dfs_...
magicoder
python
You are given a Python function that takes a list `nearest_neighbours` as input. The function is designed to find the most frequently occurring element in the list and return it. The function uses a dictionary `labels` to keep track of the frequency of each element in the input list. If an element is not already in the...
```python def find_most_frequent_element(nearest_neighbours): labels = {} # Initialize an empty dictionary to store frequencies of elements for i in range(len(nearest_neighbours)): if nearest_neighbours[i] not in labels: labels[nearest_neighbours[i]] = 1 # Add the element to the dictionary...
magicoder
python
You are tasked with implementing a custom date picker component in a mobile application. The date picker has several configurable properties and callback functions. Your goal is to create a class or struct in Swift that encapsulates the functionality of this custom date picker. The properties of the custom date picker...
```swift import UIKit struct CustomDatePicker { var minimumDate: Date? var maximumDate: Date? var minuteInterval: Int = 1 var date: Date = Date() var expandCollapseWhenSelectingRow = true var selectionStyle = UITableViewCell.SelectionStyle.default var titleFont: RFFont = RFPreferredFontForT...
magicoder
swift
You are given a Python code snippet that manipulates lists and appends elements to different lists based on specific conditions. Your task is to implement a function that achieves the same result as the code snippet, but using a more efficient and concise approach. You need to write a function `process_lists(cost_list...
```python def process_lists(cost_list, SEM_list): tRRT_SEM_list = SEM_list[0:12:2] biRRT_cost_list = cost_list[12:24:4] biRRT_SEM_list = SEM_list[12:24:4] tbiRRT_cost_list = cost_list[14:24:4] tbiRRT_SEM_list = SEM_list[14:24:4] return tRRT_SEM_list, biRRT_cost_list, biRRT_SEM_lis...
magicoder
python
You are tasked with implementing a data preloading mechanism for a web application. The application needs to load various configurations and settings before it can be used. Your task is to create a class that manages the preloading process and ensures that the necessary data is available when needed. You are provided ...
```java public class DataLoader { private boolean evalConfigLoaded; private boolean userSettingsLoaded; private boolean systemConfigLoaded; private boolean appResourcesLoaded; public void preload() { // run the methods that will preload the data preloadEvalConfig(); preloadU...
magicoder
java
You are tasked with implementing a function that counts the frequency of each character in a given string and returns a dictionary with the characters as keys and their frequencies as values. The function should ignore case sensitivity, treat uppercase and lowercase letters as the same, and ignore any non-alphabetic ch...
```python def count_characters(s: str) -> dict: # Convert the input string to lowercase s = s.lower() # Initialize an empty dictionary to store the character frequencies char_freq = {} # Iterate through each character in the string for char in s: # Check if the character is alp...
magicoder
python
You are tasked with creating a Python program to analyze event logs using process mining techniques. Process mining is a field that involves extracting insights from event data to discover, monitor, and improve real processes. In this problem, you will be using the `pm4py` library, which provides various algorithms for...
```python from tqdm import tqdm from pm4py.objects.log.importer.xes import importer as xes_importer from pm4py.algo.discovery.inductive import algorithm as inductive_miner from pm4py.algo.discovery.heuristics import algorithm as heuristics_miner from pm4py.algo.discovery.alpha import algorithm as alpha_miner def apply...
magicoder
python
You are tasked with implementing a command processing system for a shell application. The provided code snippet is part of the command processing logic. The snippet shows the initialization of a command processing operation and the handling of an already ongoing command. Your task is to implement the `ShellCommandCall...
```csharp using System; using System.Threading; public class ShellCommandCallback { private ManualResetEvent _commandCompleteEvent; public ShellCommandCallback(ManualResetEvent commandCompleteEvent) { _commandCompleteEvent = commandCompleteEvent; } public void ProcessCommand(Action comman...
magicoder
csharp
You are tasked with implementing a caching mechanism using Redis in a Spring Boot application. The provided code snippet is a partial implementation of a service class for integrating Redis caching with a WeChat service. Your task is to complete the implementation by adding the necessary methods to interact with Redis ...
```java import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import java.util.concurrent.TimeUnit; @Service("wechatService") public class WechatServiceImpl implements IWechatService { @Autowired private RedisTemplate<String, String> redisTemplate; @Ove...
magicoder
java
You are tasked with creating a web application that manages user profiles and settings. The application uses PHP and Laravel framework for server-side processing and rendering HTML templates. The code snippet provided is a part of the HTML template for the user dropdown menu. The dropdown menu is intended to display op...
```php <div class="dropdown dropdown-user"> <a href="#0" class="logged" data-toggle="dropdown p-3 m-5" title="Logged"> <img src="{{asset('storage/profil_pic/'.$user->photo)}}" alt="no photo"> </a> <div class="dropdown-menu px-1"> <ul> <li><a href="{{route('Profil')}}">Profile</a>...
magicoder
php
You are given a Python script that contains a snippet of code related to gene expression data analysis. The script reads gene expression data from a GCT file and performs a specific type of distance or similarity calculation on the data. The variables `gct_file` and `func` are used to specify the input GCT file and the...
```python import pandas as pd from scipy.spatial.distance import pdist, squareform from scipy.stats import pearsonr def calculate_distance_similarity(gct_file, func): # Read the GCT file into a pandas DataFrame data = pd.read_csv(gct_file, sep='\t', skiprows=2, index_col=0) # Transpose the DataFrame to ha...
magicoder
python
You are given a class `GraphWithReversals` that represents a graph with nodes and directed edges. The class has a method `reverse_edge` that takes two nodes as input and reverses the direction of the edge between them. You need to implement a method `is_reachable` that determines if a node is reachable from another nod...
```python class GraphWithReversals: def __init__(self, nodes, edges): self.adj_list = {i: [] for i in range(1, nodes + 1)} for edge in edges: self.adj_list[edge[0]].append(edge[1]) def reverse_edge(self, node1, node2): if node2 in self.adj_list[node1]: self.adj_l...
magicoder
python
You are working on a project that involves analyzing semantic graphs to extract meaningful information. As part of this project, you need to implement a method for object concept embedding using Python. You are given a class `SemanticGraphAnalyzer` that represents a semantic graph and provides a method `object_concept...
```python import numpy as np class SemanticGraphAnalyzer: def __init__(self, semantics_graph): self.semantics_graph = semantics_graph self.nodes = list(self.semantics_graph.nodes) self.semantics_matrix = to_numpy_matrix(self.semantics_graph) def object_concept_embedding(self, concept: ...
magicoder
python
You are tasked with implementing a type inference algorithm for a simple programming language. The language supports basic types such as integer, boolean, and float, as well as binary operations like shift left (<<), shift right (>>), and their corresponding assignment operators (<<=, >>=). The algorithm should determi...
```java @Override public BasicType getAvailableTypeFromReturnType(BasicType returnType) { if (returnType.equals(BasicType.BOOL)) { return BasicType.BOOL; // Boolean operations preserve boolean type } else if (returnType.equals(BasicType.INT)) { return BasicType.INT; // Integer operations preserve integer ty...
magicoder
java
You are tasked with implementing a function that can parse and extract information from a given HTML code snippet. The HTML code snippet represents a section of a web page containing a list of items, each with an icon, a title, and a description. Your task is to write a function that can extract this information and re...
```python from bs4 import BeautifulSoup def parseHTMLSection(html): soup = BeautifulSoup(html, 'html.parser') items = [] for li in soup.find_all('li'): icon = li.find('div', class_='icon').find_next().text.strip() title = li.find('h3').text.strip() description = li.find('p').text.st...
magicoder
python
You are tasked with implementing a simplified version of a data structure using JavaScript's Proxy object. The data structure will support adding and retrieving key-value pairs, as well as tracking the number of times a key is accessed. You need to create a class `AccessTracker` that utilizes a Proxy to achieve the fo...
```javascript class AccessTracker { constructor() { this.data = {}; this.proxy = new Proxy(this.data, { get: (target, prop) => { if (prop in target) { target[prop]++; return target[prop]; } else { return undefined; } } }); } add(key, v...
magicoder
javascript
You are tasked with implementing a custom animation library for a charting application. The animation library will be responsible for providing various animation effects for chart elements such as bars, lines, and data points. Your task is to design and implement the animation classes for the chart library. Create a c...
```csharp namespace XF.ChartLibrary.Animation { public abstract class ChartAnimation { public float Duration { get; set; } public bool IsAnimating { get; protected set; } public abstract void Start(); public abstract void Cancel(); } public class FadeAnimation : ChartAn...
magicoder
csharp
You are tasked with implementing a data structure to efficiently store and retrieve scene-specific state information for a game engine. The scene state includes various attributes such as player positions, object properties, and environmental settings. To achieve this, you need to design a class that can save and resto...
```java import java.util.HashMap; import java.util.Map; class SceneState { private Map<String, Object> stateData; public SceneState() { stateData = new HashMap<>(); } public void saveState(Map<String, Object> sceneState) { stateData = new HashMap<>(sceneState); } public void ...
magicoder
java
You are tasked with implementing a concurrent data structure using Rust's atomic operations. The data structure is a simple counter that supports two operations: `increment` and `get_value`. The `increment` operation should atomically increment the counter by 1, and the `get_value` operation should return the current v...
```rust use std::sync::atomic::{AtomicUsize, Ordering}; pub struct Counter { value: AtomicUsize, } impl Counter { pub fn new() -> Counter { Counter { value: AtomicUsize::new(0), } } pub fn increment(&self) { self.value.fetch_add(1, Ordering::SeqCst); } pub...
magicoder
rust
You are tasked with implementing a class for handling audio recordings. The class has two methods, `is_recording` and `length`. The `is_recording` method returns a boolean value indicating whether the recording is currently in progress. The `length` method returns the total length of the recording in milliseconds. The...
```python class AudioRecording: def __init__(self, recording, length_high, length_low): self.Recording = recording self.LengthHigh = length_high self.LengthLow = length_low def is_recording(self): return self.Recording > 0 def length(self): return (self.LengthHigh <...
magicoder
python
You are tasked with implementing a custom logging handler that integrates with the Rollbar error tracking service. Rollbar is a platform that provides real-time error tracking and monitoring for applications. Your goal is to create a Python class that extends the logging.Handler class and sends log records of a specifi...
```python import logging import rollbar from rollbar.logger import RollbarHandler class CustomRollbarHandler(logging.Handler): def __init__(self, access_token, environment, level=logging.ERROR): super().__init__(level) rollbar.init(access_token, environment=environment, handler='async') def em...
magicoder
python
You are tasked with implementing a TreatmentManager class in Swift, which will be responsible for managing treatments for patients in a hospital. The TreatmentManager class should have the following functionalities: 1. Add a new treatment for a patient, including the patient's name, the treatment name, and the date of...
```swift // The TreatmentManager class is implemented with the required functionalities. // It includes methods to add treatments, retrieve treatments for a specific patient, retrieve treatments for a specific date, and retrieve the latest treatment for a specific patient. // The addTreatment method adds a new treatmen...
magicoder
swift
You are tasked with implementing a program that counts the frequency of each character in a given input string and returns the characters along with their respective counts in descending order of frequency. For example, given the input string "abracadabra", the program should return the following output: "a: 5, b: 2, r...
```csharp public string CountCharacterFrequency(string inputString) { Dictionary<char, int> charFrequency = new Dictionary<char, int>(); // Convert the input string to lowercase to ignore case inputString = inputString.ToLower(); // Count the frequency of each character foreach (char c in inputStr...
magicoder
csharp
You are tasked with implementing a class to interact with the CS:GO Fast pricing API. The API provides pricing information for CS:GO (Counter-Strike: Global Offensive) items. Your task is to create a method within the `SkadiCsGoFast` class that retrieves the pricing information for a specific CS:GO item. You are provi...
```csharp using skadiprices.csgofast.Factories; using skadiprices.csgofast.Interfaces; namespace skadiprices.csgofast { /// <summary> /// Class to contact the csgofast pricing api. /// </summary> public static class SkadiCsGoFast { public class ItemPricing : IItemPricing { ...
magicoder
csharp
You are tasked with implementing a library management system in Rust. The system should allow users to add, remove, and search for books in the library. Additionally, users should be able to check out and return books. To achieve this, you need to create a module called `library` and define the necessary data structure...
```rust mod library { pub struct Book { title: String, author: String, available: bool, } impl Book { pub fn new(title: &str, author: &str) -> Book { Book { title: title.to_string(), author: author.to_string(), avai...
magicoder
rust