query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with creating a program that simulates a simple banking system. The program should be able to create and manage bank accounts, allowing users to deposit and withdraw funds, as well as check their balance. Your task is to implement a BankAccount class with the following functionalities: 1. A constructor ...
```python class BankAccount: def __init__(self, initial_balance): if initial_balance < 0: raise ValueError("Initial balance cannot be negative") self.balance = initial_balance def deposit(self, amount): if amount < 0: raise ValueError("Deposit amount cannot be ne...
magicoder
python
You are tasked with creating a custom Capacitor iOS plugin for a mobile application. The plugin should utilize the MLKit framework to perform text recognition on images. Your goal is to implement a method in the plugin that takes an image file path as input, performs text recognition using MLKit, and returns the recogn...
```swift @objc(MLKitPlugin) public class MLKitPlugin: CAPPlugin { @objc func performTextRecognition(_ call: CAPPluginCall) { guard let imagePath = call.getString("imagePath") else { call.error("Invalid image path") return } guard let image = UIImage(contentsOfFile: ...
magicoder
swift
You are tasked with creating a program that simulates a simple user interface layout using Swift. The given code snippet is a part of a function that sets up a horizontal stack view (`sv`) and configures its distribution to be equally filled. The function returns the configured stack view. Your task is to complete the ...
```swift import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() setupUI() } func setupUI() { let sv: UIStackView = { let sv = UIStackView() sv.axis = .horizontal sv.distribution = .fillEqually ...
magicoder
swift
You are tasked with implementing a game handler module that processes JSON data to manage game questions. The game handler has two methods: `startQuestion` and `questionAnswerable`. The `startQuestion` method initializes a new question in the game, while the `questionAnswerable` method processes the answer to a questio...
```swift struct Game { var currentQuestionNumber: Int // Other game properties and methods } func questionAnswerable(in game: Game, withData data: Data) -> Game { do { if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any], let questionNumber = json["qu...
magicoder
swift
You are tasked with implementing a Univariate Marginal Distribution Algorithm (UMDA) to find the minimum of a given objective function. The UMDA is a probabilistic optimization algorithm that samples from a normal distribution to iteratively update the probability distribution of the search space. Your task is to writ...
```python import numpy as np def umda_minimize(objective): # Initialize parameters population_size = 100 num_generations = 100 search_space_dim = 1 # Assuming univariate objective function # Initialize probability distribution parameters mean = 0 std_dev = 1 # Initialize probability ...
magicoder
python
You are tasked with creating a script to automate the Dynamic Client Registration (DCR) process for a secure API gateway. The DCR process involves sending a POST request to a specific endpoint, parsing the response to extract the client ID and client secret, and then using these credentials for subsequent API requests....
```bash #!/bin/bash # Define variables gateway_hostname="example.com" api_gateway_rest_endpoint_port="8443" dcr_api_context="/dcr" dcr_authorization_header="your_auth_header" dcr_request_payload='{"client_name":"example_client"}' # Construct the DCR endpoint dcr_endpoint="https://$gateway_hostname:$api_gateway_rest_e...
magicoder
shell
You are tasked with implementing a function to process seismic data stored in a 4D NumPy array and write it to a SEG-Y file using the `segyio` library. The seismic data represents a 3D survey with inline and crossline sorting. The function takes the following parameters: - `path`: A string representing the file path wh...
```python import segyio import numpy as np import itertools as it def write_seismic_data_to_segy( path: str, ilines: int, xlines: int, offsets: int, samples: int, sorting: segyio.TraceSortingFormat, ) -> None: data = np.zeros((ilines, xlines, offsets, samples), np.float32) for i, x, o, ...
magicoder
python
You are tasked with implementing a load balancer algorithm for a web server. The load balancer needs to select a subset of URLs from a given list based on a specific version and then distribute the traffic among the selected URLs. The load balancer's selection process is influenced by the version of the URLs and is per...
```java public class LoadBalancer { public List<URL> performLoadBalancing(List<URL> urls, String version) { List<URL> filteredUrls = filterVersion(urls, version); List<URL> resultUrls = select(filteredUrls); return resultUrls; } private List<URL> filterVersion(List<URL> urls, String...
magicoder
java
You are tasked with implementing a class for Depth-First Search (DFS) traversal in a graph simulation. The given code snippet provides the skeleton of the DFS class with some methods and attributes. Your task is to complete the implementation of the DFS class by adding a new method and modifying the existing methods as...
```python import random class DFS: def __init__(self, deferred_stash='deferred'): super(DFS, self).__init__() self._random = random.Random() self._random.seed(10) self.deferred_stash = deferred_stash def setup(self, simgr): if self.deferred_stash not in simgr.stashes: ...
magicoder
python
You are tasked with implementing a deformable convolution operation for a deep learning framework. Deformable convolutions are a type of convolutional operation that allows the network to learn spatial transformations of the input feature map. The code snippet provided is a part of the implementation for the deformable...
```cpp if (sparse) { param.sparse = DeformableConv::Param::Sparse::SPARSE; param.filter_shape = Shape({batch, 2 * deformable_group * fh * fw, oh, ow}); param.offset_shape = Shape({batch, deformable_group * fh * fw, oh, ow}); } else { param.sparse = DeformableConv::Param::Sparse::DENSE; param.filter_...
magicoder
cpp
You are tasked with implementing a lexer for a simple regular expression language. The regular expression language consists of the following tokens: star (*), plus (+), option (?), begin (^), end ($), or (|), symbol (any non-special character), and any (.) which matches any single character. The lexer should take a str...
```java import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class RegexLexer { public static List<String> tokenizeRegex(String input) { List<String> tokens = new ArrayList<>(); int i = 0; while (i < input.length()) { char currentChar = input.charAt...
magicoder
java
You are tasked with implementing a generic text storage transition function in Rust. The function should be able to convert a text object from one storage type to another while maintaining the text content. You are given a code snippet that includes a test case for the `storage_transition` function. The function is ca...
```rust use std::convert::TryFrom; // Define the Text type with generic kind and dynamic storage types struct Text<K, D> { content: String, kind: K, dynamic: D, } // Implement the storage_transition function for the Text type impl<K, D, NewD> Text<K, D> where D: StorageType, NewD: StorageType, { ...
magicoder
rust
You are tasked with creating a Python function that parses a configuration file and extracts the password associated with a specific host. The configuration file is in the format of a Python dictionary, where keys and values are separated by colons and enclosed in single quotes. The password is represented by the `<PAS...
```python def extract_password(config: dict, host: str) -> str: for key, value in config.items(): if key.startswith('host') and value == host: password_key = 'password' + key[4:] if password_key in config: return config[password_key].strip('<>') return "Password n...
magicoder
python
You are tasked with implementing a custom error handling mechanism for a UEFI (Unified Extensible Firmware Interface) library in Rust. The provided code snippet is a part of the `result.rs` file in the `libs/uefi/src` directory. The code defines a custom `Result` type and a function for creating a result from a UEFI st...
```rust pub enum CustomError { UefiError(efi::Status), OtherError, } pub(crate) fn from_status_to_custom_error(status: efi::Status) -> Result<(), CustomError> { match status { efi::Status::SUCCESS => Ok(()), _ => Err(CustomError::UefiError(status)), } } ```
magicoder
rust
You are given a code snippet that involves mathematical operations. Your task is to write a program that can evaluate the value of the given expression for specific input values of `x`, `y`, `z`, and `pi`. The expression is defined as follows: ```plaintext f[2] = (1 + 3*pi2)*cos(z)*sin(x)*sin(y); ``` Where: - `pi2` is...
```python import math def calculate_f(x, y, z, pi): pi2 = pi ** 2 f_2 = (1 + 3 * pi2) * math.cos(z) * math.sin(x) * math.sin(y) return f_2 # Example usage x_input = 1.5 # Replace with actual input value for x y_input = 2.0 # Replace with actual input value for y z_input = 0.8 # Replace with actual inpu...
magicoder
python
You are working on a database management system and need to implement a query parser for a simplified SQL-like language. Your task is to write a function that parses a given SQL query and extracts the table name, columns, and conditions from the query. You are given a code snippet that represents a part of the query p...
```cpp #include <iostream> #include <string> #include <vector> #include <sstream> void parseQuery(const std::string& query) { std::string columns, table, conditions; std::istringstream iss(query); std::string select, from, where; iss >> select >> columns >> from >> table >> where >> conditions; //...
magicoder
cpp
You are tasked with implementing a multi-threaded I/O service manager using the Boost.Asio library in C++. The provided code snippet outlines the initial setup for managing multiple I/O service instances and associated work objects. Your task is to extend this setup by creating a class that manages a pool of I/O servi...
```cpp #include <boost/asio.hpp> #include <boost/thread.hpp> #include <boost/bind.hpp> #include <boost/ptr_container/ptr_vector.hpp> class IOServiceManager { public: IOServiceManager(size_t numThreads) : m_ioServices(numThreads), m_works(numThreads) { for (size_t i = 0; i < numThreads; ++i) { m...
magicoder
cpp
You are tasked with implementing a file upload and processing functionality for a Progressive Web App (PWA) manifest manager. The given code snippet is part of a PHP script that handles the file upload process and updates the PWA manifest with the uploaded file's URL. Your task is to complete the implementation by writ...
```php // Process the uploaded logo file if (!empty($_POST['save'])) { if (!empty($_FILES['logo']['name'])) { // Process the uploaded logo file $logoUploaded = media_handle_upload('logo', 0); $logoUrl = wp_get_attachment_url($logoUploaded); // Update the PWA manifest with the URL of...
magicoder
php
You are tasked with creating a networking service for a beer app using Combine framework in Swift. Your goal is to implement a method that fetches beer data from a JSON file and returns an array of Beer objects. Each Beer object contains information about a specific beer, such as its name, type, and alcohol content. Y...
```swift import Combine import Foundation struct Beer: Decodable { let name: String let type: String let alcoholContent: Double } class MockNetworkingAPI: NetworkingService { func getBeerFromJson(_ api: BeerAPI) -> AnyPublisher<[Beer], Error> { return Future<[Beer], Error> { promise in ...
magicoder
swift
You are tasked with implementing a class that simulates a 2D object's movement. The class should have methods to set and get the direction of the object's movement. The direction is represented by a 2D vector. Additionally, the class should calculate and store the delta vector, which is the difference between the curre...
```csharp public class MovementSimulator { private Vector2 Direction; private Vector2 StartPosition; private Vector2 Delta; /// <summary> /// Set the direction of movement and calculate the delta vector. /// </summary> /// <param name="direction">The new direction of movement</param> pu...
magicoder
csharp
You are tasked with creating a program to generate all possible permutations of a given set of numbers and then count the total number of permutations. Write a Python function called `generate_permutations` that takes an integer `n` as input and returns a list of all possible permutations of the numbers from 1 to `n`...
```python def generate_permutations(n): def backtrack(nums, path, res): if len(path) == n: res.append(path[:]) return for num in nums: if num not in path: path.append(num) backtrack(nums, path, res) path.pop() ...
magicoder
python
You are tasked with implementing a custom `Future` type in Swift, which represents a value or error that will be available at some point in the future. The `Future` type should support chaining operations and handling both successful and failed outcomes. Your task is to implement the `Future` type with the following r...
```swift // Define the Future type class Future<T, E: Error> { private var successCallback: ((T) -> Void)? private var failureCallback: ((E) -> Void)? private init() {} // Create a Future that will eventually succeed with a value static func eventuallySuccessfull() -> Future<T, E> { ...
magicoder
swift
You are tasked with creating a script that processes a list of numbers and performs various operations on them. The script should be able to handle addition, subtraction, multiplication, and division of the numbers in the list. Additionally, it should be able to handle potential errors that may occur during the operati...
```bash #!/bin/bash # Function to calculate the sum of numbers in the list calculate_sum() { local sum=0 for num in "$@"; do ((sum += num)) done echo "$sum" } # Function to calculate the difference between the maximum and minimum numbers in the list calculate_difference() { local max=$(printf "%s\n" "$@...
magicoder
shell
You are tasked with implementing a custom loss function for a machine learning framework. The framework uses a decorator to register different loss functions, and you need to create a new loss function called "MeanSquaredError" for regression tasks. Your task is to complete the implementation of the "MeanSquaredError"...
```python @register_classification_loss_fn(name="mean_squared_error") class ClsMeanSquaredError(BaseCriteria): """Mean Squared Error for regression tasks""" def __init__(self, opts, *args, **kwargs) -> None: super(ClsMeanSquaredError, self).__init__(opts, *args, **kwargs) def __call__(self, predic...
magicoder
python
You are tasked with implementing a custom namespace management system in C++. Your goal is to create a class that allows for the creation, retrieval, and deletion of namespaces. A namespace is a declarative region that provides a scope to the identifiers (names of types, functions, variables, etc) inside it. Each names...
```cpp #include <iostream> #include <unordered_map> #include <memory> namespace chrgfx { class Namespace { // Define the contents of the namespace }; class NamespaceManager { private: std::unordered_map<std::string, std::unique_ptr<Namespace>> namespaces; public: void crea...
magicoder
cpp
You are tasked with creating a Python program that allows users to select an image file and display it in a graphical user interface (GUI) using the Tkinter library. The provided code snippet is a part of the program and contains global variables and a file dialog for selecting an image file. Your task is to complete t...
```python import tkinter as tk from tkinter import filedialog from PIL import Image, ImageTk def select_image(): file_path = filedialog.askopenfilename(initialdir="/Aulas-Tkinter", title="Selecionar Arquivo", filetypes=(("Image files", "*.png;*.jpg;*.jpeg;*.gif"), ("All f...
magicoder
python
You are tasked with implementing a Python class that simulates a simple bank account. The class should have methods for depositing funds, withdrawing funds, and checking the current balance. Additionally, the class should have a method for generating a summary of the account's transaction history. Your task is to comp...
```python class BankAccount: def __init__(self, initial_balance): self.balance = initial_balance self.transactions = [] def deposit(self, amount): self.balance += amount self.transactions.append(f"Transaction: deposit of {amount}") def withdraw(self, amount): if amo...
magicoder
python
You are tasked with creating a script to automate the testing process for a Dart project. The script should execute unit tests and integration tests, and if the code contains compiler warnings, it should run a specific analysis command and then exit with an error code. Your task is to write a Bash script that accompli...
```bash #!/bin/bash # Check for compiler warnings if grep -q 'warning: ' <path_to_code>; then echo 'Code contains compiler warnings' ${ANALYZE_CMD} exit 1 fi # Run unit tests dart -c --package-root=build/test/packages build/test/all_tests.dart # Run integration tests test/integration/run_tests.sh ``` In the s...
magicoder
shell
You are tasked with creating a custom error handling system for a cryptocurrency wallet application. The application needs to handle various types of errors related to address validation, encoding, miniscript, BIP32, ECDSA, and JSON serialization/deserialization. Each error type is represented by an enum variant and is...
```rust use bitcoin::consensus::encode::Error as EncodeError; use miniscript::Error as MiniscriptError; use bitcoin::util::bip32::Error as Bip32Error; use bitcoin::secp256k1::Error as Secp256k1Error; use crate::descriptor::error::Error as DescriptorError; use crate::wallet::address_validator::AddressValidatorError; #[...
magicoder
rust
You are tasked with creating a Java class that implements a custom JSP tag to populate a select dropdown with options from a database table. The tag should establish a connection to the database, retrieve records from a specified table, and generate the HTML options for the select dropdown based on the retrieved record...
```java import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.TagSupport; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; public class select extends TagSupport { private Connection con; private String sSelectedCode = "0"; ...
magicoder
java
You are given a C++ class `Threshold` that represents a threshold value and a number associated with it. The class has the following structure: ```cpp class Threshold { public: int m_threshold; int m_number; }; ``` You need to implement a function `findMaxThreshold` that takes a vector of `Threshold` objects ...
```cpp int findMaxThreshold(const std::vector<Threshold>& thresholds) { int maxThreshold = INT_MIN; // Initialize with the smallest possible value for (const auto& threshold : thresholds) { if (threshold.m_threshold > maxThreshold) { maxThreshold = threshold.m_threshold; } } ...
magicoder
cpp
You are tasked with implementing a Python function that filters out certain names from a given list based on specific criteria. The function should take a list of strings as input and return a new list containing only the strings that do not meet the filtering criteria. The filtering criteria are as follows: 1. Exclud...
```python from typing import List def filter_names(names: List[str]) -> List[str]: filtered_names = [name for name in names if name not in ['In', 'Out', 'get_ipython', 'exit', 'quit'] and not name.startswith('_')] return filtered_names # Test the function input_names = ['In', 'Out', 'get_ipython', 'exit', 'qu...
magicoder
python
You are tasked with implementing a custom router component in a React application. The router component, `WiseRouter`, is provided with a set of props, `WiseRouterProps`, which define various configuration options for routing. Your goal is to create the `WiseRouter` component that utilizes these props to handle routing...
```jsx import React from 'react'; import { Route, Redirect, Switch } from 'react-router-dom'; const WiseRouter: React.FC<WiseRouterProps> = (props) => { const { redirectTo, defaultRedirect, fallback, debug, passRouteProps, rest } = props; // Implement routing logic based on the WiseRoute...
magicoder
jsx
You are tasked with creating a Rust program that processes JSON data representing exit statuses of various processes. The program should deserialize the JSON data into Rust structs using the `serde_json` crate and perform specific operations on the deserialized data. The JSON data represents exit statuses of processes...
```rust use serde_json::{Value, from_str}; use chrono::{DateTime, Utc, NaiveTime, Timelike}; #[derive(Debug, Deserialize)] struct ExitStatus { exitTime: String, statusCode: i32, } pub fn calculate_average_exit_time(data: &str) -> Option<String> { let statuses: Vec<ExitStatus> = match from_str(data) { ...
magicoder
rust
You are tasked with implementing a generic rectangle class in C++ that can handle rectangles of different data types and dimensions. The provided code snippet includes the definition of two typedefs: `rect2i_t` for a rectangle with integer coordinates in 2D space, and `rect2f_t` for a rectangle with floating-point coor...
```cpp #include <iostream> #include <array> template <typename T, size_t N> class rect_tt { private: std::array<T, N> dimensions; public: rect_tt() { dimensions.fill(T{}); } rect_tt(const std::array<T, N>& dims) : dimensions(dims) {} const std::array<T, N>& getDimensions() const { ...
magicoder
cpp
You are working on a data analytics platform that processes and aggregates various metrics from user sessions. The platform uses a custom query language to define aggregate functions for different metrics. Each aggregate function takes a list of arguments, which can be of different types such as UUID and UInt. Your t...
```python class AggregateFunction: def __init__(self, name, args): self.name = name self.args = args def parse_metrics(code_snippet): metrics = {} # Split the code snippet by comma and iterate over the parts for part in code_snippet.split(","): # Remove leading and trailing whit...
magicoder
python
You are tasked with creating a Python program that simulates a simple banking system. The system should be able to handle basic banking operations such as account creation, deposit, withdrawal, and balance inquiry. To achieve this, you need to implement a `Bank` class with the following methods: 1. `__init__(self, nam...
```python from typing import Union class Bank: def __init__(self, name: str): self.name = name self.accounts = {} def create_account(self, account_number: int, initial_balance: float) -> str: if account_number in self.accounts: return "Account number already in use" ...
magicoder
python
You are tasked with creating a Python script to process images using a pre-trained object detection model. The script should utilize command-line arguments to specify the label map file and the model directory. The label map file contains the mapping of class IDs to class names, while the model directory contains the p...
```python import argparse import cv2 import numpy as np import tensorflow as tf from object_detection.utils import label_map_util from object_detection.utils import visualization_utils as vis_util # Parse command-line arguments parser = argparse.ArgumentParser() parser.add_argument('--label_map', type=str, default='da...
magicoder
python
You are working on a natural language processing (NLP) project and need to fine-tune a pre-trained language model for a specific task. The code snippet provided is a command-line argument indicating the start of the fine-tuning process. Your task is to implement a Python function that simulates the fine-tuning process ...
```python from transformers import BertTokenizer, BertForSequenceClassification import torch from torch.utils.data import Dataset, DataLoader from sklearn.model_selection import train_test_split from transformers import AdamW class SentimentDataset(Dataset): def __init__(self, texts, labels, tokenizer, max_length)...
magicoder
python
You are tasked with implementing a function that performs a specific type of array manipulation. The function takes two input arrays, `in_array` and `out_array`, and four integer parameters: `ylo`, `yhi`, `xlo`, and `xhi`. The function is expected to copy a sub-array from `in_array` and paste it into a specified region...
```python def copy_and_paste(in_array, out_array, ylo, yhi, xlo, xhi, ymin, ymax, xmin, xmax): out_array[ylo:yhi, xlo:xhi] = in_array[ymin:ymax, xmin:xmax] return out_array ``` The solution involves using array slicing to extract the sub-array from `in_array` and then assigning it to the specified region of `o...
magicoder
python
You are tasked with implementing a function that converts a given amount of time into a human-readable format. The function should take an integer `amount` representing the time in seconds and return a list of tuples, each containing the value and unit of time. The time should be broken down into years, days, hours, mi...
```python INTERVALS = { 'years': 31536000, 'days': 86400, 'hours': 3600, 'minutes': 60, 'seconds': 1 } NAMES = [ (31536000, 'years'), (86400, 'days'), (3600, 'hours'), (60, 'minutes'), (1, 'second') ] def convert_time(amount): result = [] for unit in NAMES: a = ...
magicoder
python
You are tasked with creating a program that simulates a simple library management system. The system should allow users to add, remove, and search for books in the library. Additionally, users should be able to view a list of all the books currently in the library. Your task is to implement the `Library` class, which ...
```python from typing import List class Library: def __init__(self): self.books = {} def add_book(self, title: str, author: str): self.books[title] = author print("Book added successfully!") def remove_book(self, title: str): if title in self.books: del self.bo...
magicoder
python
You are tasked with implementing a function that calculates the number of patches required to cover a given area with a specific patch size. The function should take in the dimensions of the area to be covered and the dimensions of the patch, and return the minimum number of patches needed to cover the entire area. Th...
```python def calculate_patches(area_width: int, area_height: int, patch_width: int, patch_height: int) -> int: patches_needed_width = (area_width + patch_width - 1) // patch_width # Calculate patches needed for width patches_needed_height = (area_height + patch_height - 1) // patch_height # Calculate patches...
magicoder
python
You are tasked with creating a Python class that simulates a simple text-based game. The game involves a player navigating through a grid-based world, collecting items, and avoiding obstacles. Your task is to implement the `Player` class with specific methods and attributes to facilitate the game's functionality. The ...
```python class Player: def __init__(self, x, y): self.x = x self.y = y self.items = [] def move_up(self): self.y += 1 def move_down(self): self.y -= 1 def move_left(self): self.x -= 1 def move_right(self): self.x += 1 def collect_item...
magicoder
python
You are working on a web application that allows users to send messages to attorneys for legal advice. The application is built using PHP and the Laravel framework. The code snippet provided is from a controller in the application. The controller handles the sending and receiving of messages between users and attorneys...
The `getUserMessagesToAttorneys` method retrieves all the messages sent by a specific user to any attorney. It first filters the `user_messages` table based on the provided `$userId`. Then, it joins the `attorneys` table to retrieve the names of the sender and recipient attorneys. The method selects the sender's name, ...
magicoder
php
You are tasked with creating a Bash script to automate the setup of a MongoDB URI for a meeting room booking service. The script should take in the necessary parameters and construct the URI accordingly. Write a Bash script named `setup_mongodb_uri.sh` that takes three command-line arguments: `username`, `password`, a...
```bash #!/usr/bin/env bash set -e if [ "$#" -ne 3 ]; then echo "Usage: $0 <username> <password> <host>" exit 1 fi username=$1 password=$2 host=$3 # Escape special characters in username and password escaped_username=$(printf %s "$username" | jq -s -R -r @uri) escaped_password=$(printf %s "$password" | jq -s -R ...
magicoder
shell
You are tasked with implementing a Kalman filter algorithm for tracking the position of a moving object. The Kalman filter is a recursive algorithm that estimates the state of a dynamic system from a series of noisy measurements. In this problem, you are given a code snippet that performs the update step of the Kalman ...
```python import numpy as np def kalman_filter(initial_means, initial_covariances, initial_time, measurement_noise, process_noise, measurements): means = initial_means covariances = initial_covariances t = initial_time for measurement in measurements: # Measurement update step measurem...
magicoder
python
You are tasked with implementing a Python class to manage hierarchical deterministic wallets (HD wallets) and perform BIP44 derivation for cryptocurrencies. BIP44 (Bitcoin Improvement Proposal 44) defines a multi-account hierarchy for deterministic wallets. Your task is to create a class that can handle the clean-up of...
```python from typing import NamedTuple class BIP44Derivation(NamedTuple): cryptocurrency: str account: int change: bool address: int class BIP44HDWallet: def __init__(self): self.derivation_indexes = {} # Store cleaned derivation indexes/paths def clean_derivation(self): sel...
magicoder
python
You are tasked with creating a program that calculates the square root of a series of numbers and then formats the results as a comma-separated string. The formula for calculating the square root is given by: \[ \text{result} = \text{round}(\sqrt{2 \times c \times \text{number}/h}) \] Where: - \( c \) is a constant v...
```python import math def calculate_square_root(items, c, h): value = [] for d in items: result = int(round(math.sqrt(2 * c * float(d) / h)) value.append(str(result)) return ','.join(value) # Example usage input_numbers = [100, 150, 180] c_value = 50 h_value = 30 output_string = calculate_...
magicoder
python
You are tasked with implementing a custom formatter for a specific type in C++ using the fmt library. The provided code snippet contains a template specialization for formatting a type `ae::virus::Name` using the fmt library. Your task is to write a complete implementation for the custom formatter for the `ae::virus::N...
```cpp #include <fmt/format.h> namespace ae { namespace virus { struct Name { std::string name; // Define any necessary member functions and constructors for the ae::virus::Name type // ... // Define the custom formatter for ae::virus::Name temp...
magicoder
cpp
You are given a triangle represented as a list of lists, where each list represents a row of the triangle. The triangle has a total of `n` rows. You need to find the minimum path sum from the top to the bottom of the triangle. Each step you may move to the adjacent numbers on the row below. Write a function `minimumTo...
```python from typing import List def minimumTotal(triangle: List[List[int]]) -> int: size = len(triangle) dp = [0] * size for i in range(size): dp[i] = triangle[size - 1][i] for i in range(size - 2, -1, -1): for j in range(i + 1): dp[j] = min(dp[j], dp[j + 1]) + triangle[i]...
magicoder
python
You are tasked with implementing a command-line utility called `proj` that facilitates navigation and management of project directories. The `proj` command is designed to be used within a Unix-like shell environment. The `proj` command is expected to support the following functionalities: - When invoked without any ar...
```bash proj () { current=$(cut -d/ -f5 <<< "${PWD}") # Extract the current directory name if [ $# -eq 0 ]; then # If no arguments are provided cd $PROJECTS_DIR # Change the current working directory to PROJECTS_DIR elif [ $1 == 'new' ] && [ $2 ]; then # If the first argument is 'new' and a project name i...
magicoder
shell
You are tasked with implementing a class hierarchy to represent different types of geometric shapes. The base class `Shape` should have methods to calculate the area and perimeter of a shape. The derived classes `Circle` and `Rectangle` should inherit from `Shape` and implement the area and perimeter calculation method...
```java // Define the SolidityVisibility enumeration public enum SolidityVisibility { Public, Internal } // Define the Shape class public abstract class Shape { protected SolidityVisibility visibility; public Shape(SolidityVisibility visibility) { this.visibility = visibility; } public abstra...
magicoder
java
You are tasked with implementing a Python function to determine whether a given set of cards forms a valid "Set" according to the rules of the Set card game. In the game of Set, each card has four features: color, shape, number, and shading. A set of three cards is considered valid if, for each feature, the three cards...
```python class Card: def __init__(self, color, shape, number, shading): self.color = color self.shape = shape self.number = number self.shading = shading def values_consistent(a, b, c): return a == b == c or a != b != c def check_set(c1, c2, c3): return (values_consistent(...
magicoder
python
You are tasked with implementing a class to represent a payment channel in a blockchain network. The class should encapsulate the properties and functionality of a payment channel, allowing for the management of balances and settings. Your task is to create a Python class called `PaymentChannel` with the following pro...
```python class PaymentChannel: def __init__(self, remote_node_id, active, private, capacity, local_balance, remote_balance, unsettled_balance, local_channel_settings): self.remote_node_id = remote_node_id self.active = active self.private = private self.capacity = capacity s...
magicoder
python
You are tasked with creating a program that uses TensorFlow to build a simple neural network for classifying handwritten digits from the MNIST dataset. The MNIST dataset consists of 28x28 pixel grayscale images of handwritten digits (0-9) along with their corresponding labels. Your goal is to construct a neural network...
```python import tensorflow as tf import numpy as np # Load the MNIST dataset mnist = tf.keras.datasets.mnist (train_images, train_labels), (test_images, test_labels) = mnist.load_data() # Preprocess the dataset train_images = train_images / 255.0 test_images = test_images / 255.0 # Build the neural network model mo...
magicoder
python
You are tasked with implementing a preference management system for a software application. The system should allow users to store and retrieve their preferences using a key-value pair approach. To achieve this, you need to create a class called `PreferenceManager` that provides methods for setting and getting preferen...
```java import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class PreferenceManager { private Map<String, String> preferences = new ConcurrentHashMap<>(); public synchronized void setPreference(String key, String value) { preferences.put(key, value); // Code to persiste...
magicoder
java
You are tasked with implementing a connectivity calculation function for a neuroimaging analysis tool. The function, `calculate_connectivity`, takes several parameters including a table name, file paths, an atlas file, threshold values, and a scrubbing flag. Your goal is to create a Python function that can accurately ...
```python def calculate_connectivity(table, fd_files, ts_files, atlas_file, thres_mean_FD, scrubbing): # Placeholder for the actual implementation # Your implementation here # Perform connectivity calculation using the provided parameters # Return the result of the connectivity calculation pass ``` ...
magicoder
python
You are given a list of characters representing individuals standing in a line. Each individual is either a police officer ('P') or a thief ('L'). The objective is to find the maximum number of thieves that can be caught given a specific capture distance. Write a function `max_thieves_captured` that takes in two para...
```python def max_thieves_captured(distancia, individuos): max_thieves = 0 n = len(individuos) for i in range(n): if individuos[i] == 'P': start = max(0, i - distancia) end = min(n, i + distancia + 1) for j in range(start, end): if individuos[j] ==...
magicoder
python
You are tasked with implementing a class that represents an image. The class should have a constructor that takes a URL as a parameter. Additionally, the class should have a method to retrieve the image's dimensions and a method to display the image. Create a PHP class called `Image` with the following specifications:...
```php class Image { private $url; public function __construct($url) { $this->url = $url; } public function getDimensions() { list($width, $height) = getimagesize($this->url); return $width . " x " . $height; } public function display() { echo "<img src='" . $t...
magicoder
php
You are tasked with implementing a method for a custom class `ActionType` in a Java application. The method `withActionConfigurationProperties` is intended to allow the addition or modification of configuration properties for a specific action type. The method takes an array of `ActionConfigurationProperty` objects as ...
```java import java.util.ArrayList; import java.util.Collection; public class ActionType { private Collection<ActionConfigurationProperty> actionConfigurationProperties; // Other class members and constructors public ActionType withActionConfigurationProperties(ActionConfigurationProperty... actionConfig...
magicoder
java
You are tasked with simulating the behavior of a simple CPU. The CPU has a program counter (pc) and can execute a series of steps. Each step involves calling the `cpu_step` function. The CPU is expected to stop when the program counter reaches the value `0x017E`. Your task is to write a function that simulates the CPU ...
```javascript function simulateCPU(steps, c) { for (let i = 0; i < steps; i++) { c.cpu_step(); if (c.registers.pc === 0x017E) { return true; } } return false; } ``` The `simulateCPU` function iterates through the CPU steps, calling `cpu_step` and checking if the program counter reaches `0x017E`...
magicoder
javascript
You are tasked with creating a custom form field for a Django model that allows users to input and validate phone numbers. The form field should utilize the `phonenumber_field` library and be integrated into a Django model form. Your task is to complete the implementation of the custom form field and integrate it into...
```python # Step 1: Define a custom form field named CustomPhoneNumberField class CustomPhoneNumberField(PhoneNumberField): def __init__(self, *args, **kwargs): # Step 2: Implement CustomPhoneNumberField to enforce a specific country code and formatting kwargs['region'] = 'US' # Set the default cou...
magicoder
python
You are tasked with creating a program to process and display species information from a file. The file contains data about various species, and the program needs to read this data and present it in a structured and visually appealing manner. The provided code snippet is part of the program responsible for writing the ...
```cpp #include <iostream> #include <fstream> #include <string> #include <iomanip> void processSpeciesInfo(const std::string& fileName) { std::ifstream inputFile(fileName); if (inputFile.is_open()) { std::cout << "----------------------------------------\n"; std::cout << " Species Information\...
magicoder
cpp
You are tasked with implementing a Python class that simulates a simple inventory management system for a small retail store. The system should allow users to add, remove, and update products in the inventory, as well as retrieve information about specific products and the overall inventory. Your task is to implement ...
```python class Inventory: def __init__(self): self.inventory_items = {} def add_product(self, product_id, name, unit_price, stock_quantity): self.inventory_items[product_id] = { "name": name, "unit_price": unit_price, "stock_quantity": stock_quantity ...
magicoder
python
You are tasked with creating a program that parses and analyzes HTTP headers. HTTP headers are key-value pairs sent by a client or server in the HTTP protocol. Each header is separated by a newline character, and the key and value are separated by a colon and optional whitespace. Your program should take a string repr...
```python def parse_http_headers(input_string): headers = input_string.split('\n') header_pairs = [header.split(': ') for header in headers if ': ' in header] total_headers = len(header_pairs) longest_key_length = max(len(pair[0]) for pair in header_pairs) longest_value_length = max(len(pair[1]...
magicoder
python
You are tasked with creating a simulation to compare the performance of two different probability distributions in predicting binary outcomes. You will need to generate random samples from these distributions, calculate the area under the ROC curve (AUC) for each trial, and then analyze the distribution of AUC values. ...
```python import numpy as np import sklearn.metrics import matplotlib.pyplot as plt def simulate_and_analyze(sample_size_x, sample_size_y, n_trials, x_distr, y_distr): np.random.seed(1234235) aucs = np.empty(n_trials) labels = np.concatenate([np.ones(sample_size_x), np.zeros(sample_size_y)]) for t...
magicoder
python
You are given a Python function that takes in two numpy arrays `inputs` and `input_bdfs`, and a scalar `result_bdf`. The function is responsible for processing the input arrays and updating the `result` array based on certain conditions. The `inputs` array contains numerical data, while the `input_bdfs` array contains ...
```python import numpy def process_inputs_custom(inputs, input_bdfs, result_bdf, result): ''' Update the result array based on the input arrays and result_bdf value. Parameters: inputs: numpy read-only float array - input numerical data input_bdfs: numpy read-only float array - missing-data value ...
magicoder
python
You are given a code snippet that is part of a quicksort algorithm implementation using a stack-based approach. The code snippet shows the process of partitioning a given array `aVector` within the range of indices `aLow` and `aHigh`. The partitioning process involves selecting a pivot element, rearranging the elements...
```cpp int InternalPartition(int aVector[], int aLow, int aHigh) { int pivot = aVector[aHigh]; // Select the pivot element as the last element int i = aLow - 1; // Initialize the index of the smaller element for (int j = aLow; j < aHigh; j++) { if (aVector[j] < pivot) { i++; // Incre...
magicoder
cpp
You are tasked with creating a Python class that manages version compatibility for a specific software. The class should be able to compare the compatibility of different versions based on their major, minor, and patch numbers. The class should also provide a method to check if a given version is compatible with a mini...
```python class VersionCompatibility: def __init__(self, major: int, minor: int, patch: int): self.major = major self.minor = minor self.patch = patch def is_compatible(self, other_version: 'VersionCompatibility') -> bool: return self.major == other_version.major and self.minor ...
magicoder
python
You are given a list of directed edges representing a graph. Each edge is represented as a list of two vertices, where the first vertex is the source and the second vertex is the destination. Your task is to write a function that determines whether the given graph contains a cycle. Write a function `has_cycle(graph: L...
```python from typing import List def has_cycle(graph: List[List[str]]) -> bool: def dfs(node, visited, rec_stack): visited[node] = True rec_stack[node] = True for neighbor in graph[node]: if not visited[neighbor]: if dfs(neighbor, visited, rec_stack): ...
magicoder
python
You are tasked with creating a Rust function that handles various errors related to making HTTP requests and deserializing JSON responses. The function should take a URL as input and return a Result containing either the deserialized JSON data or an error indicating the specific issue encountered during the process. Y...
```rust use reqwest; use serde_json; use bytes; #[derive(Debug)] enum FetchError { ExecuteRequestError(reqwest::Error), ResponseBytesError(reqwest::Error), DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, } fn fetch_and_deserialize(url: &str) -> Result<serde_json::V...
magicoder
rust
You are tasked with implementing a class that publishes assets to an Azure DevOps NuGet feed. The class `AzureDevOpsNugetFeedAssetPublisher` is responsible for publishing assets and implements the `IAssetPublisher` interface and the `IDisposable` interface. The class has several private fields, including `TaskLoggingHe...
```csharp using System; using System.Collections.Generic; using Microsoft.DotNet.Build.Tasks.Feed; public class AzureDevOpsNugetFeedAssetPublisher : IAssetPublisher, IDisposable { private readonly TaskLoggingHelper _log; private readonly string _targetUrl; private readonly string _accessToken; private ...
magicoder
csharp
You are tasked with implementing a function that processes a dictionary containing information about game objects in a strategy game. The dictionary has two keys, "spawns" and "towers", each mapping to a list of objects. Each object is represented as a dictionary with "name", "type", and "position" keys. The "position"...
```python def process_game_objects(game_objects): spawn_count = len(game_objects["spawns"]) tower_count = len(game_objects["towers"]) spawn_total_x = sum(obj["position"][0] for obj in game_objects["spawns"]) spawn_total_y = sum(obj["position"][1] for obj in game_objects["spawns"]) tower_total_x = s...
magicoder
python
You are tasked with implementing a function that simulates a double stack navigator for a web application. The navigator is responsible for managing the navigation history and state of the application. The provided code snippet contains the setup for creating a mock double stack navigator and a related function. Your t...
```typescript // Solution for createDoubleStackMock function function createDoubleStackMock<T>() { let items: T[] = []; return { hasSingleStack: () => items.length <= 1, hasSingleItem: () => items.length === 1, getTopItem: () => items[items.length - 1], popUntil: (condition: (item: T) => boolean) =...
magicoder
typescript
You are tasked with creating a tip calculator app for a restaurant. The app should allow users to input the total bill amount and select a tip percentage using a segmented control. The segmented control has three options: 15%, 20%, and 25%. When the user selects a tip percentage, the app should calculate and display th...
```swift import UIKit class TipCalculatorViewController: UIViewController { @IBOutlet weak var tipControl: UISegmentedControl! @IBOutlet weak var billAmountTextField: UITextField! @IBOutlet weak var tipAmountLabel: UILabel! @IBOutlet weak var totalAmountLabel: UILabel! override func viewD...
magicoder
swift
You are tasked with creating a function to validate and process the input parameters for updating a SMS signature in a messaging system. The function should take in the following input parameters: - `ProjectId` (str) - Project ID, default to the default project if not provided. Sub-accounts must provide this parameter...
```python import base64 def validateAndProcessSignature(ProjectId, SigContent, SigId, SigPurpose, SigType, CertificateType, Document, File): # Validate input parameters if not isinstance(ProjectId, str): return "Error: ProjectId should be a string." if not isinstance(SigContent, str): retur...
magicoder
python
You are tasked with implementing a simple distributed key-value store using the Paxos consensus algorithm. The key-value store will be replicated across multiple nodes to ensure fault tolerance and consistency. Your goal is to implement the logic for handling client requests, replicating the state across nodes, and ach...
```rust // Define the key-value store data structure struct KeyValueStore { data: HashMap<String, String>, } impl KeyValueStore { fn new() -> Self { KeyValueStore { data: HashMap::new(), } } fn get(&self, key: &str) -> Option<&String> { self.data.get(key) } ...
magicoder
rust
You are working on a Python project that involves using data classes and their serialization methods. You have a class that includes the `__getstate__` and `__setstate__` methods for customizing the serialization and deserialization process. Additionally, there is a method `set_name` that takes two parameters: `full_na...
```python def set_name(self, full_name: str, peer_prefix: str) -> None: self.full_name = f"{full_name} {peer_prefix}" ``` In the solution, the `set_name` method takes the `full_name` and `peer_prefix` parameters and sets the `full_name` attribute of the object by combining the two parameters with a space in betwee...
magicoder
python
You are tasked with creating a Java program that reads a file and calculates the frequency of each character present in the file. Your program should take the file path as input and output the frequency of each character in the file. Your program should adhere to the following requirements: - Use the provided code sni...
```java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; public class CharacterFrequencyCalculator { public static void main(String[] args) { String filePath = "input.txt"; // Replace with the actua...
magicoder
java
You are tasked with creating a custom code editor plugin for a new programming language called "Substance." The plugin needs to provide code completion functionality for the language. The given code snippet is a part of the plugin implementation using the Monaco Editor API. Your task is to implement the `provideComple...
```javascript function provideCompletion(model, position, context, token) { // Implement the logic to provide completion items based on the user's input const completionItems = []; // Example completion items for the Substance language completionItems.push({ label: "function", kind: monaco.languages.Co...
magicoder
javascript
You are tasked with implementing a data binding mechanism in a Java application using the Eclipse Data Binding framework. The Eclipse Data Binding framework provides a powerful and flexible API for connecting UI elements to data models. In this problem, you will be working with a simplified version of a data binding se...
```java // Model class public class Model { private String usageModelFileName; public String getUsageModelFileName() { return usageModelFileName; } public void setUsageModelFileName(String usageModelFileName) { this.usageModelFileName = usageModelFileName; } } // UI class public c...
magicoder
java
You are tasked with creating a custom security filter for a web application using Spring Security. The filter should ignore certain properties based on a configuration provided by the `FilterIgnorePropertiesConfig` bean. Your task is to implement the logic for the custom filter and ensure that it correctly ignores the ...
```java @Autowired private FilterIgnorePropertiesConfig filterIgnorePropertiesConfig; @Override protected void configure(HttpSecurity http) throws Exception { ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http.formLogin().loginPage("/authentication/require...
magicoder
java
You are given a dataset `df_station` containing information about different stations, including the hour and weekday of each entry. The code snippet provided is a part of a function that processes this dataset. The function takes three inputs: `df` (a DataFrame), `rank` (an integer), and `weekends` (a list of integers ...
```python def process_data(df: pd.DataFrame, rank: int, weekends: List[int]) -> pd.DataFrame: if rank == 7: # Your implementation for rank 7 goes here # For example, you can return a subset of the DataFrame based on certain conditions return df[df['Some_Column'] > 10] # Replace with your sp...
magicoder
python
You are tasked with implementing a custom error handling system for a command-line application. The system should define specific error types and provide a way to handle and display these errors to the user. Your task is to create a Rust program that demonstrates the usage of this error handling system. Your custom er...
```rust // Define the custom error enum enum CustomError { NoWhitespace, NoCommand, } // Implement the process_input function fn process_input(input: &str) -> Result<(), CustomError> { if !input.contains(' ') { return Err(CustomError::NoWhitespace); } if !input.starts_with("command") { ...
magicoder
rust
You are tasked with implementing a Python function that performs a 2D discrete cosine transform (DCT) on a given matrix. The discrete cosine transform is a technique used in signal processing and image compression to convert spatial data into frequency data. The 2D DCT is applied to 2D matrices to analyze frequency com...
```python from typing import List from fewbit.fft import dct def perform_2d_dct(matrix: List[List[float]]) -> List[List[float]]: rows = len(matrix) cols = len(matrix[0]) # Apply 1D DCT to each row dct_rows = [dct(row) for row in matrix] # Transpose the result to apply 1D DCT to each column tr...
magicoder
python
You are given a string representing a sequence of characters. Your task is to write a function or method to find the longest palindromic substring within the given string. A palindrome is a sequence of characters that reads the same forwards and backwards. For example, "radar" is a palindrome. Your function should tak...
```python def longest_palindromic_substring(s: str) -> str: if len(s) < 2: return s start = 0 max_len = 0 for i in range(len(s)): if i - max_len >= 1 and s[i - max_len - 1:i + 1] == s[i - max_len - 1:i + 1][::-1]: start = i - max_len - 1 max_len += 2 ...
magicoder
python
You are tasked with creating a simple snake game in Go. The game should be able to run with a specified frames-per-second (FPS) rate, and the game window dimensions should adjust based on the terminal size. Your task is to implement the main game loop and handle user input to control the snake's movement. You are prov...
```go package main import ( "fmt" "os" "os/exec" "runtime" "time" "github.com/eiannone/keyboard" ) type point struct { x, y int } type snakeGame struct { width, height int snake []point fps int direction string } func (g *snakeGame) init() { g.width, g.height = getTerminalSize() ...
magicoder
go
You are tasked with creating a Python script that dynamically imports modules based on a given version number. Your script should be able to handle different versions of a hypothetical `netapp` package and import the appropriate module based on the provided version. Write a function `import_netapp_module(version: str)...
```python from typing import Any def import_netapp_module(version: str) -> Any: module_name = f"v{version}" try: return globals()[module_name] except KeyError: return None ``` The `import_netapp_module` function takes a version string as input and attempts to retrieve the corresponding mod...
magicoder
python
You are tasked with implementing a function that processes a method call in a custom programming language. The method call is represented by a series of code snippets, and your task is to extract relevant information from the code and perform specific operations based on the extracted data. The code snippet provided i...
```cpp void processMethodCall(int m_ciTemp, int m_objectTemp, int pcount) { // Print method call information // Example: m_nameExp->outputCPP(cg, ar); // Example: cg_printf(")"); // Example: cg_printf(")"); // Example: cg_printf(");\n"); // Construct method call package cg_printf("MethodCal...
magicoder
cpp
You are given a list of integers representing the scores of a game. Your task is to implement a function `findMaxScore` that takes in the list of scores and returns the maximum score achieved by a player. The maximum score is defined as the highest sum of consecutive scores in the list. Function signature: ```java pu...
```java import java.util.List; public int findMaxScore(List<Integer> scores) { int maxSum = Integer.MIN_VALUE; int currentSum = 0; for (int score : scores) { currentSum = Math.max(score, currentSum + score); maxSum = Math.max(maxSum, currentSum); } return maxSum; } ``` The `findM...
magicoder
java
You are tasked with implementing a function that serializes a key-value pair into a byte array. The function takes in a key, a value, and a flag indicating whether the value is new or not. The key and value are both serialized into byte arrays, and the flag is represented as a single byte in the serialized output. The...
```java import java.nio.ByteBuffer; public class KeyValueSerializer { private static final int NEWFLAG_SIZE = 1; public byte[] serializeKeyValue(String key, Object value, boolean isNewValue) { byte[] serializedKey = key.getBytes(); // Serialize the key into a byte array byte[] serializedValue ...
magicoder
java
You are tasked with implementing a custom hook for managing a graph in a React application. The hook should provide access to the graph's properties and enable the use of imperative handles for external manipulation. Additionally, the hook should utilize context to access the graph configuration and determine the enabl...
```javascript import React from 'react'; function useGraphManager() { const propsAPI = usePropsAPI<NodeData, EdgeData, PortData>(); const graphConfig = React.useContext(GraphConfigContext); const enabledFeatures = propsAPI.getEnabledFeatures(); const propsAPIRef = React.useRef(null); React.useImperativeHand...
magicoder
javascript
You are working on a game development project and need to implement a system to parse and process various game events. The game events are defined in a structured format, and you need to extract specific information from each event. Each game event is represented as a tuple containing the following elements: 1. Event ...
```python from typing import Tuple, Dict, Union def extract_event_info(event: Tuple) -> Dict[str, Union[str, int]]: event_id, event_name, _, _, parameters, pattern = event extracted_info = {} for param, pattern_part in zip(parameters, pattern.split('+')[1:]): variable, type_indicator = pattern_par...
magicoder
python
You are tasked with implementing a custom exception hierarchy for a PDF processing application. The application needs to handle different types of errors that can occur during the PDF processing workflow. Your task is to create the custom exception classes based on the given code snippet and define their relationships ...
```python class PdfRelayException(Exception): """Base exception for PDF processing errors""" class JobError(PdfRelayException): """Exception raised for issues with the parameters of the conversion job""" class EngineError(PdfRelayException): """Exception raised for engine process spawning/execution errors...
magicoder
python
You are tasked with implementing a custom error type and associated conversion traits in Rust. Your goal is to create a custom error type `MyError` and implement the `From` trait to convert a string into this error type. Additionally, you need to implement the `TryFrom` trait for a reference to a string to convert it i...
```rust use std::convert::TryFrom; // Define a custom error type MyError #[derive(Debug)] struct MyError; // Implement the From trait to convert a string into MyError impl From<&str> for MyError { fn from(_: &str) -> Self { MyError } } // Define a type ServerName struct ServerName; // Implement the ...
magicoder
rust
You are tasked with implementing a function that performs arithmetic operations on large numbers using the `BigNumber` library. The function takes in three parameters: `a`, `b`, and `calcType`. The `a` and `b` parameters are large numbers represented as strings, and `calcType` is a string representing the type of arith...
```javascript const BigNumber = require('bignumber.js'); function performArithmeticOperation(a, b, calcType) { const bigNum = new BigNumber(`${a}`); return bigNum[calcType] ? bigNum[calcType](b).toString() : '--'; } console.log(performArithmeticOperation('12345678901234567890', '98765432109876543210', 'plus')); ...
magicoder
javascript
You are tasked with implementing a path following system for a simulated entity in a game engine. The system is responsible for updating the position and rotation of the entity as it follows a predefined path. The given code snippet is a part of the implementation and contains a function `_follow_path` that is called t...
```cpp inline void _follow_path(f64 dt) { system.update_position = true; system.update_rotation = true; if (system.mover.state >= system.mover.steps[system.mover.num_points - 1].time){ system.position = system.mover.steps[system.mover.num_points - 1].position; system.rotation = system.mover.steps[system....
magicoder
cpp
You are tasked with creating a Python function that processes news data from a database and returns a list of news articles in a specific format. The function should also include asynchronous background tasks for starting and cleaning up the news listener. You are provided with a code snippet that includes a function ...
```python import asyncio from datetime import datetime async def main_news_task(db_connection): # Assume the existence of a function to fetch news data from the database news_data = await fetch_news_data(db_connection) news = [] for row in news_data: news.append({ "title": row[...
magicoder
python
You are tasked with creating a program that manages a database of employees using CoreData in Swift. The program should allow the user to add new employees, retrieve employee information, update employee details, and delete employees from the database. You need to implement the following functionalities: 1. Add a new...
```swift import CoreData // Define the Employee entity class Employee: NSManagedObject { @NSManaged var id: Int @NSManaged var name: String @NSManaged var age: Int @NSManaged var position: String @NSManaged var salary: Double } // Create a function to add a new employee to the database func addEmp...
magicoder
swift