query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with implementing a custom iterator for a specific data structure. The data structure is a custom collection called `CustomCollection` that stores integers. The iterator should iterate through the collection and perform a specific action on each element based on a given condition. The `CustomCollection`...
```java private class CustomIterator implements Iterator<Integer> { private int cursor; @Override public boolean hasNext() { return cursor < elements.size(); } @Override public Integer next() { int element = elements.get(cursor); cursor++; if (element % 2 == 0) ...
magicoder
java
You are tasked with implementing a generic interface for type conversion in Java. The interface, named `Converter`, has a single method `convert` that takes an input of type `F` and returns an output of type `T`. Your goal is to create a class that implements this interface and provides a specific conversion functional...
```java public class TemperatureConverter implements Converter<Double, Double> { @Override public Double convert(Double src) { throw new UnsupportedOperationException("Method not supported. Use convertToFahrenheit or convertToCelsius instead."); } public Double convertToFahrenheit(Double celsi...
magicoder
java
You are given a set of instructions to move in a 3D space. The instructions consist of three types: "forward", "up", and "down", each followed by a distance to move. The starting position is at the origin (0, 0, 0) in 3D space. The "forward" instruction moves the position along the horizontal axis, the "up" instruction...
```python from typing import List, Tuple def calculate_position_product(instructions: List[Tuple[str, int]]) -> int: hor_axis: int = 0 depth: int = 0 for instruction in instructions: match instruction[0]: case "forward": hor_axis += instruction[1] case "up":...
magicoder
python
You are tasked with creating a class that represents a customizable theme for a user interface. The theme class should have properties for header color, body color, body weight, and header font family. Your goal is to implement a method that checks if the theme properties are valid according to certain criteria. You a...
```csharp public class UserInterfaceTheme { public virtual string HeaderColor { get; set; } = "hsla(0,0%,0%,0.87)"; public virtual string BodyColor { get; set; } = "hsla(0,0%,0%,0.78)"; public virtual string BodyWeight { get; set; } = "300"; public virtual List<string> HeaderFontFamily { get; set; } = n...
magicoder
csharp
You are tasked with implementing a Java class that extends the functionality of an archival writer for table data. The archival writer is responsible for exporting table data to an output stream using specified archival options. Your task is to complete the implementation of the `ArchivalWriter` class by providing the ...
```java import org.tms.api.TableElement; import org.tms.api.TableProperty; import org.tms.io.options.ArchivalIOOptions; abstract class ArchivalWriter<T extends ArchivalIOOptions<T>> extends LabeledWriter<T> { public ArchivalWriter(TableExportAdapter tea, OutputStream out, T options) { super(tea, out, opt...
magicoder
java
You are tasked with implementing a simplified version of Conway's Game of Life, a cellular automaton devised by the mathematician John Conway. The game is played on a grid of cells, each of which can be in one of two possible states: alive or dead. The game proceeds in discrete time steps, with the state of each cell i...
```python def Grid.Conway(off_color, on_color, surface, pause): # Define the grid size and cell dimensions grid_width = 50 grid_height = 50 cell_size = 10 # Initialize the grid with random initial state or predefined patterns # For example, using a 2D list to represent the grid and initializing...
magicoder
python
You are given a list of integers representing the daily stock prices of a company. Your task is to write a function to calculate the maximum profit that can be obtained by buying and selling the stock at most once. If it is not possible to make any profit, return 0. Create a function `maxProfit` that takes in a list o...
```python def maxProfit(prices): if not prices: return 0 max_profit = 0 min_price = prices[0] for price in prices: if price < min_price: min_price = price else: max_profit = max(max_profit, price - min_price) return max_profit ``` The `m...
magicoder
python
You are tasked with creating a Python script to automate the process of deleting a Kafka topic and producing messages to a specified topic using the Kafka command-line tools. Your script should handle the execution of these commands and provide appropriate error handling. Your script should perform the following tasks...
```python import subprocess def delete_kafka_topic(topic_name, zookeeper_address): try: subprocess.run(['./bin/kafka-topics.sh', '--delete', '--topic', topic_name, '--zookeeper', zookeeper_address], check=True) print(f"Kafka topic '{topic_name}' deleted successfully.") except subprocess.CalledP...
magicoder
python
You are tasked with creating a Python script to automate the process of waiting for specific services to become available and then generating load using a load generation script. The script should utilize the `wait-for-it` tool to wait for the availability of two services, MySQL and Debezium, with a timeout of 60 secon...
```python import subprocess import os import sys import time def wait_for_service(service, port, timeout): start_time = time.time() while True: try: subprocess.check_call(['wait-for-it', '--timeout', str(timeout), '--service', f'{service}:{port}']) break except subproces...
magicoder
python
You are tasked with implementing a function that interacts with Google BigQuery (GBQ) to load a file from a specified path into a GBQ table. The function should handle the connection to GBQ and the file loading process. You are provided with a code snippet that includes a function `give_file_gbq` and a partial code blo...
```python import google.cloud.bigquery as bigquery def give_file_gbq(path_to_file, bq_configuration): try: client = bigquery.Client(**bq_configuration) dataset_id = bq_configuration['dataset_id'] table_id = bq_configuration['table_id'] job_config = bigquery.LoadJobConfig() ...
magicoder
python
You are tasked with implementing a connection pool for an HTTP client in Java. The goal is to create a class, `HttpClientUtils`, that manages a pool of HTTP connections for efficient reuse. The `HttpClientUtils` class should have the following features: 1. A private static final Logger named `LOG` for logging purposes...
```java import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class HttpClientUtils { private static final Logger LOG = Logge...
magicoder
java
You are tasked with implementing a function to calculate the size of a grid based on the number of dots and validating whether the size of the grid is valid for a given screen size. The grid consists of dots arranged in rows and columns, and the size of the grid is determined by the number of dots. You need to impleme...
```python import math def calculate_size(num_dots): """ Calculate the size of the grid based on the number of dots. Args: num_dots (int): The number of dots in the grid. Returns: tuple: A tuple (rows, columns) representing the size of the grid. """ side_length = int(math.sqrt(...
magicoder
python
You are tasked with implementing a simple tokenization system for a text processing application. The `Token` class has been provided as a starting point. Your task is to extend this class and create a tokenizer function that splits a given input text into individual tokens based on a specified delimiter. You need to i...
```python from dataclasses import dataclass @dataclass class Token: token_value: str def is_valid(self): return self.token_value.isalnum() def tokenizer(text, delimiter): tokens = text.split(delimiter) return [Token(token) for token in tokens if Token(token).is_valid()] ``` The solution exten...
magicoder
python
You are tasked with implementing a function to calculate the similarity between a query vector and a list of vectors using different distance metrics. The function should take the query vector, the list of vectors, and the type of distance metric as input and return a list of tuples, where each tuple contains the simil...
```python import numpy as np def get_similarity(query_vec, vec_list, metric_type='cos'): similarity = None if metric_type == 'cos': vec_arr = np.asarray(vec_list) query_arr = np.asarray(query_vec) similarity_arr = np.dot(vec_arr, query_arr.reshape(1, -1).T) similarity_arr_arg = ...
magicoder
python
You are given a 2D board representing a word search puzzle and a word to search for. The board consists of lowercase English letters and the word is a string of lowercase letters. Your task is to write a function that determines if the word can be found in the board. The word can be constructed from letters of sequenti...
```java public boolean exist(char[][] board, String word) { for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { if (dfs(board, i, j, word, 0)) { return true; } } } return false; } private boolean dfs(char[][] board, in...
magicoder
java
You are tasked with creating a Python function that parses a list of classifiers and returns a dictionary containing the classification categories and their corresponding values. Each classifier is represented as a string in the format "Category :: Value". The function should extract the category and value from each cl...
```python def parse_classifiers(classifiers): parsed_dict = {} for classifier in classifiers: category, value = classifier.split(" :: ") parsed_dict[category] = value return parsed_dict # Test the function with the given example classifiers = [ "Development Status :: 5 - Production/Stab...
magicoder
python
You are tasked with implementing a function that processes a list of vertices representing a polygon and performs specific operations when the polygon is closed by the user. The function should add a patch to a figure and update a grid map based on the closed polygon. You are given the following information: - The fun...
```python def process_closed_polygon(verts, figure, grid_map): """ Adds a patch to the figure and updates the grid map based on the closed polygon. Args: verts: List of tuples representing the vertices of the closed polygon. figure: The figure to which the patch should be added. grid_map: The g...
magicoder
python
You are tasked with implementing a signal decomposition algorithm for solar data analysis. The provided code snippet imports the necessary modules and a specific signal decomposition function from the `solardatatools` library. Your goal is to create a Python function that utilizes the imported `tl1_l2d2p365` function t...
```python import numpy as np from solardatatools.signal_decompositions import tl1_l2d2p365 from typing import Tuple def solar_signal_decomposition(solar_signal: np.ndarray) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: try: # Perform signal decomposition using tl1_l2d2p365 function deco...
magicoder
python
You are tasked with creating a program that utilizes reflection to analyze and manipulate the properties of a given class. Reflection is a powerful feature in C# that allows you to inspect and manipulate assemblies, modules, types, and members at runtime. In this problem, you will create a class with properties and use...
```csharp using System; using System.Reflection; public class Person { public string Name { get; set; } public int Age { get; set; } } public class ReflectionDemo { public static void ModifyProperty(Person person, string propertyName, object newValue) { PropertyInfo propertyInfo = typeof(Perso...
magicoder
csharp
You are tasked with implementing a Python class that can parse a specific file format and extract metadata and strings from it. The file format is structured in a way that metadata is stored at the beginning of the file, followed by a section containing strings. Your task is to create a class with a method that can par...
```python from dataclasses import dataclass, field import re @dataclass class Metadata: # Define the structure of the Metadata class based on the actual metadata fields in the file field1: str field2: int # Add more fields as per the actual metadata structure @dataclass class Strings: # Define the...
magicoder
python
You are tasked with creating a web scraper to extract data from a given website. The website "https://www.saoroque.sp.gov.br/portal/diario-oficial" contains a list of links to the official gazette publications. Your goal is to write a Python program using the Scrapy library to extract the titles and URLs of these gazet...
```python import scrapy class GazetteSpider(scrapy.Spider): name = 'gazette_spider' start_urls = ['https://www.saoroque.sp.gov.br/portal/diario-oficial'] def parse(self, response): publications = response.css('.publicacao') for publication in publications: title = publication.c...
magicoder
python
You are tasked with creating a program that simulates a simple text-based adventure game. The game will involve the player navigating through different rooms, encountering obstacles, and making decisions that affect the outcome of the game. Each room will have specific attributes such as a description, possible actions...
```python class Room: def __init__(self, name, description): self.name = name self.description = description self.exits = {} self.items = [] def add_exit(self, direction, room): self.exits[direction] = room def remove_exit(self, direction): if direction in s...
magicoder
python
You are tasked with implementing a Python function that simulates a 1-dimensional convolution operation with padding. The function should take in a 1-dimensional input array, a 1-dimensional kernel array, and a padding type as input, and return the result of the convolution operation. The function signature should be:...
```python def convolve_1d_with_padding(input_array, kernel_array, padding_type): input_size = len(input_array) kernel_size = len(kernel_array) output_size = input_size if padding_type == "valid" else input_size if padding_type == "same": pad_left = (kernel_size - 1) // 2 pad_right = ker...
magicoder
python
You are tasked with implementing a custom error handling system for a token validation module in a Swift application. The module should be able to handle various error cases related to token validation. Your task is to create a custom error type and implement the necessary error handling logic. Define a custom error t...
```swift // Define a custom error type TokenError conforming to the Error protocol enum TokenError: Error { case invalidTokenLength(message: String) } // Implement the validateToken function func validateToken(token: String) -> Result<String, TokenError> { let validTokenLength = 16 if token.count == validT...
magicoder
swift
You are tasked with creating a Python function that extracts test case names from a given test file. The test file contains test cases defined using the `parameterized` module from the `absl.testing` library. Each test case is defined using the `parameterized.parameters` decorator. Your function should parse the test f...
```python from typing import List import ast def extract_test_case_names(test_file_path: str) -> List[str]: with open(test_file_path, 'r') as file: tree = ast.parse(file.read()) test_case_names = [] for node in ast.walk(tree): if isinstance(node, ast.Call) and isinstance(node.func, ast.Att...
magicoder
python
You are tasked with implementing a function to calculate the nth Fibonacci number. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. The function should take an integer n as input and return the nth Fibonacci number. For example, giv...
```python def fibo(n): if n <= 0: return "Invalid input" elif n == 1: return 0 elif n == 2: return 1 else: a, b = 0, 1 for _ in range(2, n): a, b = b, a + b return b print(fibo(4)) # Output: 3 print(fibo(5)) # Output: 5 print(fibo(6)) # Out...
magicoder
python
You are tasked with implementing a parallel evolutionary algorithm for optimizing a given problem. The provided code snippet is a part of a Python class that manages the parallel processing of the evolutionary algorithm. Your task is to complete the implementation of the `run_evolve` method, which will execute the evol...
```python def run_evolve(self, algo, pop): # Distribute the population across the processing pool distributed_pop = self.pool.map(algo.evaluate, pop) # Perform selection, crossover, and mutation in parallel selected_pop = self.pool.map(algo.select, distributed_pop) crossovered_pop = self.pool.map(a...
magicoder
python
You are tasked with implementing a Vector2 class in Python to represent 2D vectors and providing various functionalities for vector manipulation. The class should support operations such as vector addition, subtraction, magnitude calculation, angle calculation, and conversion to a tuple. Your task is to implement the ...
```python import math class Vector2: def __init__(self, x, y): self.x = x self.y = y def __eq__(self, other): return self.x == other.x and self.y == other.y @property def magnitude(self): return math.sqrt(self.x ** 2 + self.y ** 2) @property def theta(self): ...
magicoder
python
You are tasked with implementing a pluralization function for different languages. The function should take into account the specific pluralization rules of each language and correctly pluralize a given word based on a numeric value. You are provided with a code snippet that demonstrates the usage of the pluralization...
```csharp public class Pluralizer { public string Pluralize(string languageCode, string[] arguments, decimal numericValue, int contextValue) { if (languageCode == "uk") { if (numericValue == 1) { return arguments[0]; // Singular form } ...
magicoder
csharp
You are tasked with creating a Python script that automates the signing of artifacts for the OpenSearch project. The script should take input arguments from the command line and sign the specified artifacts using the provided signing key. Your task is to implement the `sign_artifacts.py` script, which will be responsi...
```python # sign_artifacts.py import sys from sign_workflow.sign_args import SignArgs from sign_workflow.sign_artifacts import SignArtifacts def main(): # Parse command-line arguments sign_args = SignArgs() artifacts, signing_key = sign_args.parse_args(sys.argv[1:]) # Verify the existence of specifie...
magicoder
python
You are tasked with creating a Python function that simulates a simple web application testing scenario. The function should send HTTP requests to a web server and validate the responses based on the provided code snippet. You are given a Python code snippet that contains two test functions using the `pytest` framewor...
```python import requests def simulate_web_testing(base_url: str) -> bool: # Send a GET request to "/login/shib/login" with a specific header login_url = base_url + "/login/shib/login" headers = {"SHIBBOLETH_HEADER": "test"} response = requests.get(login_url, headers=headers) success = response.sta...
magicoder
python
You are given two arrays, `src` and `dst`, both of length `n`. The arrays represent a sequence of operations to be performed on a data structure. Each element in the arrays can be one of the following three types of operations: 1. `0`: Represents a "copy" operation, where the value at the current index is copied to th...
```python from typing import List def canTransform(src: List[int], dst: List[int]) -> bool: if len(src) != len(dst): return False n = len(src) src_sum = 0 dst_sum = 0 for i in range(n): if src[i] == 0: src_sum += 1 elif src[i] == 1: dst_sum ...
magicoder
python
You are working on a deployment script for a Django web application. The given code snippet is part of the deployment process and sets up various directory paths and configuration files. Your task is to write a function that takes the given environment variables and generates the final commands to be executed for setti...
```python def generate_setup_commands(REPO_DIR, CONF_PATH, SITE_NAME, HOME, APP_DIR): commands = [ f'echo "REPO_DIR={REPO_DIR}"', f'echo "CONF_PATH={CONF_PATH}"', f'echo "SITE_NAME={SITE_NAME}"', f'echo "SITE_DIR={REPO_DIR}/{SITE_NAME}"', f'echo "APP_DIR={APP_DIR}"', ...
magicoder
python
You are tasked with implementing a generic buffer type in Rust that can be used with different block sizes and buffer kinds. The provided code snippet includes module declarations, type aliases, and imports related to the buffer implementation. Your task is to create a generic Rust struct `Buffer<S>` that represents a...
```rust // Define the traits for block size and buffer kind trait BlockSizeUser { type BlockSize; } trait BufferKindUser { type BufferKind; } // Define the generic struct Buffer pub struct Buffer<S> where S: BlockSizeUser + BufferKindUser, { data: Vec<S::BufferKind>, } // Implement methods for the Bu...
magicoder
rust
You are working on a project that involves building and packaging a software application for a Linux distribution. As part of the build process, you need to automate the steps to build the application, copy the built executable to a specific directory, and then create a Debian package (.deb) for distribution. The provi...
```bash #!/bin/bash # Set the script to exit immediately if any command exits with a non-zero status set -xe # Build the application using stack stack build # Create the ppa/bin directory if it doesn't exist mkdir -p "$HOME/ppa/bin" # Copy the built executable to the ppa/bin directory cp -f .stack-work/dist/x86_64-...
magicoder
shell
You are tasked with implementing a custom error handling mechanism for a data processing application. The application needs to handle specific error conditions related to data length, such as invalid length, overflow, and underflow. To achieve this, you need to create custom error classes and ensure that they are appro...
```python class InvalidLengthError(Exception): pass class OverflowError(InvalidLengthError): pass class UnderflowError(InvalidLengthError): pass __all__ = ["InvalidLengthError", "OverflowError", "UnderflowError"] ``` In the solution, we define the custom error classes `InvalidLengthError`, `OverflowErro...
magicoder
python
You are tasked with implementing a simplified blockchain data structure and a proof-of-work algorithm. A blockchain is a distributed ledger that stores a growing list of records, called blocks, which are linked and secured using cryptography. Each block contains a cryptographic hash of the previous block, a timestamp, ...
```python import json import hashlib class Blockchain: def __init__(self): self.chain = [] def last_block(self): return self.chain[-1] @staticmethod def hash(block): block_string = json.dumps(block, sort_keys=True).encode() return hashlib.sha256(block_string).hexdigest...
magicoder
python
You are given a code snippet that initializes some variables and arrays. Your task is to complete the code by implementing a specific algorithm to calculate the number of ways to arrange black and white tiles in a row of length M, such that the number of arrangements equals or exceeds the TARGET value. The algorithm s...
```java long t = System.currentTimeMillis(); final int M = 50; final int TARGET = 1000000; int length = 0; // create array with totals long[] total = new long[M + 1]; // create array with blacks long[] blacks = new long[M + 1]; for (int i = 0; i <= M; i++) { total[i] = 1; blacks[i] = 1; } for (int i = 1; ...
magicoder
java
You are tasked with implementing a method to resize an image using a specific sampling factor. The method takes an input image and a sampling factor, and returns the resized image. You are given the following code snippet as a starting point: ```java int height = source.getHeight(); int scaledWidth = width / mSamplin...
```java public int[][] resizeImage(int[][] source, int mSampling) { int height = source.length; int width = source[0].length; int scaledWidth = width / mSampling; int scaledHeight = height / mSampling; int[][] resizedImage = new int[scaledHeight][scaledWidth]; for (int i = 0; i < scaledHeight; ...
magicoder
java
You are tasked with creating a SwiftUI view that displays a list of items and allows the user to select and deselect them. The selected items should be highlighted, and the user should be able to see the total count of selected items. You need to implement a custom SwiftUI view that fulfills these requirements. Your c...
```swift import SwiftUI struct SelectableListView: View { @State private var selectedItems: Set<String> = [] let items: [String] var body: some View { VStack { List(items, id: \.self) { item in HStack { Text(item) Spacer() ...
magicoder
swift
You are working on a script to automate the setup of a development environment. As part of this setup, you need to ensure that a specific directory is created and added to the system's PATH environment variable in both the `.bashrc` and `.zshrc` configuration files. The code snippet provided is a part of the script you...
```python from typing import List def update_shell_config(home_directory: str, shell_config_files: List[str]) -> None: import os # Check and create the directory if it does not exist bin_directory = os.path.join(home_directory, ".local/bin") if not os.path.exists(bin_directory): os.makedirs(bi...
magicoder
python
You are tasked with implementing a method `_daysFromToday` within a class that calculates the date a certain number of days from the current date. The method should take an integer `days` as input and return the date that is `days` days from the current date. You can assume that the input `days` will always be a non-ne...
```python import datetime class DateCalculator: def _daysFromToday(self, days): current_date = datetime.date.today() future_date = current_date + datetime.timedelta(days=days) return future_date ``` In the solution, the `_daysFromToday` method uses the `datetime` module to obtain the curre...
magicoder
python
You are working on a data analysis project for a scientific research team. The team has collected a large dataset of measurements from various experimental conditions and needs to perform data processing and analysis. One crucial aspect of the analysis involves mapping parameters and scales for different experimental c...
```python def perform_parameter_mapping(measurement_df, condition, sbml_model, condition_df): cur_measurement_df = measurements.get_rows_for_condition(measurement_df, condition) if 'PREEQUILIBRATION_CONDITION_ID' not in condition \ or not isinstance(condition['PREEQUILIBRATION_CONDITION_ID'], str) ...
magicoder
python
You are tasked with implementing a function for decoding and unflattening parameters in an inter-process communication (IPC) system. The provided code snippet contains part of the implementation for this task. Your goal is to complete the implementation of the `serverUnflattenDecode` function based on the given code sn...
```cpp bool IPCIntelPGParam::serverUnflattenDecode(void* pData, int dataSize, uintptr_t* client, int32_t* payloadCount, ia_binary_data** payloads) { // Check for null pointer in pData CheckError(!pData, false, "@%s, pData is nullptr", __func__); // Check if the s...
magicoder
cpp
You are tasked with implementing a simple memory management system for a hypothetical programming language. The system should support the allocation and deallocation of memory for both classes and structs. You are given a code snippet that demonstrates the creation of instances of classes and structs, as well as their ...
```cpp #include <iostream> #include <map> // Define a MemoryManager class to handle memory allocation and deallocation class MemoryManager { private: std::map<void*, size_t> memoryMap; // Map to store allocated memory addresses and their sizes public: // Allocate memory for an instance of a class or struct ...
magicoder
cpp
You are tasked with creating a program that extracts the license information from a given text. The license information is enclosed within a specific format and needs to be extracted and displayed. The license information is enclosed within a block comment, which starts with a line containing only "#" followed by the l...
```python import re def extract_license(text: str) -> str: match = re.search(r'#\n(.*?)\n#', text, re.DOTALL) if match: return match.group(1) else: return "No license found" ```
magicoder
python
You are tasked with creating a Python function that retrieves and processes file descriptions from a given directory. The function should take a directory path as input and return a dictionary containing file names as keys and their respective descriptions as values. The file descriptions are stored in separate text fi...
```python import os def get_file_description(directory_path): file_description_dict = {} for file in os.listdir(directory_path): if file.endswith('.txt') and not file.endswith('_description.txt'): description_file = file.replace('.txt', '_description.txt') description_path = os....
magicoder
python
You are tasked with implementing a class that manages annotations on a map. The class should handle adding and removing annotations based on changes in a collection. Your task is to write a method that adds new annotations to the map when the collection changes. You are given the following code snippet as a reference:...
```csharp public class AnnotationManager { public void AddAnnotationsOnCollectionChange(NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Add) { foreach (IBindingMapAnnotation item in e.NewItems) { Target.AddAnnotation(new...
magicoder
csharp
You are tasked with creating a custom operator for Apache Airflow, a popular platform for programmatically authoring, scheduling, and monitoring workflows. Your custom operator, named `SpellRunOperator`, will be responsible for executing a spell-checking task as part of an Airflow DAG (Directed Acyclic Graph). The `Sp...
```python from datetime import datetime, timedelta from airflow.models import BaseOperator from airflow.utils.decorators import apply_defaults from airflow.operators.bash_operator import BashOperator class SpellRunOperator(BaseOperator): @apply_defaults def __init__(self, task_id, bash_command, *args, **kwargs...
magicoder
python
You are tasked with implementing a custom judge protocol for a programming competition platform. The judge protocol is responsible for evaluating the correctness of submitted solutions to programming problems. The provided code snippet defines a class `JudgeProtocol` that inherits from `BaseJsonObject`, which is assume...
```python from abc import ABC, abstractmethod import json class JudgeProtocol(BaseJsonObject): def __init__(self): super().__init__() def receive_submission(self, submitted_solution, test_cases): """ Receives the submitted solution and its corresponding test cases. Args: ...
magicoder
python
You are given a list of Atom objects representing the coordinates of atoms in a molecular structure. Each Atom object has a symbol (element), coordinates, and units. Your task is to write a function that takes this list of Atom objects and returns the distance between the two closest atoms in the structure. An Atom ob...
```python import math class Atom: def __init__(self, symbol, coords, units): self.symbol = symbol self.coords = coords self.units = units def euclidean_distance(coord1, coord2): return math.sqrt((coord1[0] - coord2[0])**2 + (coord1[1] - coord2[1])**2 + (coord1[2] - coord2[2])**2) def ...
magicoder
python
You are tasked with creating a Python function that processes a list of transactions and calculates the total amount of money spent. Each transaction is represented as a dictionary with keys "amount" and "currency". The function should also allow for an optional parameter to specify the format in which the total amount...
```python def calculate_total_spent(transactions: list, format: str = None) -> str: total_spent = sum(transaction["amount"] for transaction in transactions) if format == "USD": return f"${total_spent:.2f}" elif format == "EUR": return f"{total_spent:.2f}€" elif format == "JPY": ...
magicoder
python
You are given a snippet of code that is part of a program to process a string of characters in a specific language. The code snippet contains some variable assignments, conditional checks, and a loop. Your task is to understand the code and answer a question related to its functionality. The code snippet is part of a ...
The specific condition being checked in the line `syll.asp = is_cons(string,i,c) == 2` is whether the function `is_cons` returns the value 2 when called with the arguments `string`, `i`, and `c`. The function `is_cons` likely checks if the character at index `i` in the string `string` is a consonant and returns a value...
magicoder
python
You are tasked with creating a script to automate the build and deployment process for a Rust project using Docker. The script should handle building the project with specific target architecture and then creating a Docker image and pushing it to a container registry. Your task is to write a shell script that accompli...
```bash #!/bin/bash # Step 1: Build the Rust project cargo build --release --target x86_64-unknown-linux-gnu # Step 2: Build the Docker image and push to the container registry docker build -t jarry6/jsa . docker push jarry6/jsa:latest ``` The provided shell script accomplishes the required tasks. It first builds th...
magicoder
shell
You are tasked with implementing a simplified version of a U-Net architecture for image segmentation. The U-Net consists of an encoder-decoder structure with skip connections, commonly used in biomedical image segmentation tasks. Your goal is to complete the implementation of the U-NetDecoderBlock class, which is respo...
```python import torch.nn as nn class UNetDecoderBlock(nn.Module): def __init__(self, in_channels: int, mid_channels: int, out_channels: int) -> None: super(UNetDecoderBlock, self).__init__() self.upconv = nn.ConvTranspose2d(in_channels, mid_channels, kernel_size=2, stride=2) self.conv1 = n...
magicoder
python
You are tasked with creating a Python class to manage redaction of sensitive information from documents. The class should provide methods to redact specific content based on certain criteria. Your task is to implement the `RedactionPage` class with a method `check_start_date_is` that redacts any content on the page tha...
```python from datetime import datetime class RedactionPage: def __init__(self, content: str): self.content = content def check_start_date_is(self, start_date: str): start_date_obj = datetime.strptime(start_date, '%d-%b-%Y %I:%M%p %Z') content_parts = self.content.split() redac...
magicoder
python
You are tasked with implementing a function that displays a success message with an optional status, success image, style, action, and completion closure. The function should also allow specifying closures to be executed when the user presses the Menu button or the Play/Pause button while the success message is display...
```swift public static func showSuccessWithStatus(_ status: String? = .none, andSuccessImage successImage: UIImage? = .none, andStyle style: tvProgressStyle? = .none, andAction action: (label: String, closure: ((Void) -> Void))? = .none, menuButtonDidPress: (() -> Void)? = .none, playButtonDidPress: (() -> Void)? = .no...
magicoder
swift
You are tasked with implementing a class that manages a collection of items and provides a method for bulk operations. Your task is to complete the implementation of the given class `CollectionManager` by adding the necessary methods. You are provided with the following code snippet as a starting point: ```php class ...
```php class CollectionManager { private $collection; private $bulk; public function __construct() { $this->collection = []; $this->bulk = []; } /** * Add an item to the collection * @param mixed $item The item to add */ public function add($item) { ...
magicoder
php
You are working on a signal processing project and need to calculate the root mean square (RMS) values for three different axes (x, y, z) of a signal at various frequency bands. The code snippet provided initializes arrays for storing the RMS values for each axis and frequency band. You are given the following informa...
```python import numpy as np import signal_processing_module as sp # Assuming the signal processing module is imported def calculate_rms_values(dir_path): file_list = sp.obtain_files(dir_path) f_band = sp.OneThird_octave(0.625 / 2**(1/3), 80 * 2**(1/3)) rms_x_array = np.zeros((len(f_band), len(file_list)...
magicoder
python
You are tasked with creating a Swift protocol that defines error handling for a networking library. The protocol, named `ErrorConverter`, includes an associated type `DomainError` and a static function `make` responsible for converting a specific library error type, `AphroditeError`, into the associated `DomainError`. ...
```swift // Define the networking library error type enum AphroditeError: Error { case connectionError case timeoutError case invalidResponse } // Define a domain-specific error type enum DomainError: Error { case networkError case serverError case dataError } // Implement the ErrorConverter p...
magicoder
swift
You are tasked with implementing a custom property decorator in Python that enforces specific constraints on the assigned value. The property decorator should be able to handle data validation and default value assignment. Your task is to create a `UserProperty` decorator that can be used to define properties for a `Us...
```python class UserProperty: def __init__(self, data_type, default, optional): self.data_type = data_type self.default = default self.optional = optional def __set_name__(self, owner, name): self.name = name def __set__(self, instance, value): if not isinstance(val...
magicoder
python
You are tasked with creating a script to convert a collection of audio files to WAV format using the `ffmpeg` command-line tool. The script should iterate through a specified search path, extract the file name from each audio file, and then use `ffmpeg` to convert the audio file to WAV format. The WAV files should be s...
```bash #!/bin/bash # Check if the correct number of arguments is provided if [ "$#" -ne 2 ]; then echo "Usage: $0 <search_path> <output_directory>" exit 1 fi searchPath="$1" outputDirectory="$2" # Iterate through each audio file in the search path for audioFile in "$searchPath"/*; do if [ -f "$audioFile" ]; t...
magicoder
shell
You are tasked with creating a custom Python class that manages skills for a role-playing game. The class should handle the initialization of skills, tokenizing skill names, and transforming skill data for reporting purposes. Your task is to implement the `SkillManager` class, which should have the following functiona...
```python from typing import List from .skill import SkillBase from .transforms import InitializeReportTransform, TokenizeTransform class SkillManager: def __init__(self): self.skills = [] def initialize_skills(self, skill_names: List[str]) -> None: self.skills = [SkillBase(name) for name in s...
magicoder
python
You are tasked with implementing a function that writes data to a file and saves it to an Amazon S3 bucket using multipart upload. The function should take the file path, data to be written, and upload arguments as input and return the number of bytes written to the file. The code snippet provided gives a glimpse of t...
```python import os import boto3 S3_EXPORT_DEFAULT_BUCKET = 'your_s3_bucket_name' UPLOAD_ARGS = {'Key': 'your_key_name'} def write_to_s3_file(file_path, data, upload_args): s3_save_path = os.path.join(S3_EXPORT_DEFAULT_BUCKET, file_path) write_count = 0 s3 = boto3.client('s3') with open(s3_save_path,...
magicoder
python
You are tasked with implementing a network request handling system in Swift. The provided code snippet is a part of a networking framework that supports various types of requests and response handling. Your task is to complete the implementation of the `request` method, which is responsible for making network requests ...
```swift func request(_ requestType: RequestType, path: String, cacheName: String?, parameterType: ParameterType?, parameters: Any?, parts: [FormDataPart]?, responseType: ResponseType, completion: @escaping (_ response: Any?, _ response: HTTPURLResponse, _ error: NSError?) -> Void) -> String { if let fakeRequests =...
magicoder
swift
You are tasked with implementing a function to determine whether a given country is completely surrounded by another country. A country is represented by a struct `Country` with the following fields: - `territories`: a vector of unique positive integers representing the territories within the country. - `border_color`:...
```rust fn is_completely_surrounded(country1: &Country, country2: &Country) -> bool { // Check if the border colors match if country1.border_color != country2.border_color { return false; } // Check if all territories of country1 are adjacent to territories of country2 for territory in &cou...
magicoder
rust
You are tasked with implementing a function that extracts a specific class from a TypeScript module and returns it as a named export. The module contains a code snippet similar to the following: ```typescript (<any>globalObject).BABYLON.GuiEditor = GUIEditor; // eslint-disable-next-line @typescript-eslint/naming-conve...
```typescript function extractClassAsNamedExport(moduleContent: string, className: string): string { const exportRegex = /export\s*\*\s*from\s*\".*\";/; const classRegex = new RegExp(`(<any>globalObject)\\.${className}\\s*=\\s*${className};`, 'g'); const modifiedContent = moduleContent.replace(classRegex, ...
magicoder
typescript
You are tasked with implementing a shell script that processes command-line arguments to set specific flags. The script should handle both short and long options, and it should support the accumulation of multiple flags into a single variable. Your task is to complete the shell script by adding the necessary code to h...
```bash declare flags="" while [ $# -ge 1 ]; do case "$1" in -z|--outOfOrder) flags="${flags} ${1}" shift 1 ;; -f|--force) flags="${flags} ${1}" shift 1 ;; -v|--verbose) flags="${flags} ${1}" shift 1 ;; -h|--help) flags="${flags} ${1}" ...
magicoder
shell
You are tasked with implementing a function that converts a given value to its HTML representation. The function should handle different types of input values and produce the corresponding HTML output. Write a function called `to_html` that takes a single argument `value` and returns its HTML representation. The funct...
```python def to_html(value): if isinstance(value, str): return f'<p>{value}</p>' elif isinstance(value, bool): return f'<strong>Yes</strong>' if value else f'<em>No</em>' elif isinstance(value, list): items = ''.join([f'<li>{item}</li>' for item in value]) return f'<ul>{item...
magicoder
python
You are tasked with creating a Java class that represents a video game. The game has different difficulty levels, which are represented by an enum called `Difficulty` with values `EASY`, `NORMAL`, and `HARD`. Your task is to create a `Game` class that has attributes for the game's title, genre, and difficulty level. Ad...
```java public class Game { private String title; private String genre; private Difficulty difficulty; public Game(String title, String genre, Difficulty difficulty) { this.title = title; this.genre = genre; this.difficulty = difficulty; } public String getTitle() { ...
magicoder
java
You are tasked with implementing a probability density function (PDF) for the Student's t-distribution in a database interface. The Student's t-distribution is a probability distribution that arises in the estimation of the mean of a normally distributed population when the sample size is small and the population stand...
```cpp /** * @brief Student's t probability density function: In-database interface */ AnyType students_t_pdf::run(AnyType &args) { double t = args[0].getAs<double>(); // Value at which to evaluate the PDF double df = args[1].getAs<double>(); // Degrees of freedom // Calculate the PDF using the formula ...
magicoder
cpp
You are tasked with implementing a custom HashMap in Rust that can store instances of a custom struct `HumanAddr`. The `HumanAddr` struct is defined as follows: ```rust #[derive(Serialize, Deserialize, Clone, Default, Debug, PartialEq, Eq, JsonSchema, Hash)] pub struct HumanAddr(pub String); ``` Your task is to imple...
```rust use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; // Custom HashMap struct pub struct CustomHashMap { data: Vec<Option<Vec<(HumanAddr, u64)>>>, size: usize, } impl CustomHashMap { // Create a new CustomHashMap with initial capacity pub fn new(capacity: usize) -> Sel...
magicoder
rust
You are tasked with implementing a middleware component for a web application. The middleware is responsible for controlling the flow of requests and responses. The provided code snippet is a part of the middleware implementation, and it shows a commented-out section that needs to be completed. Your task is to impleme...
To implement the missing functionality for the middleware, you can use the following code: ```csharp public class CustomMiddleware { private readonly RequestDelegate _next; public CustomMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { ...
magicoder
csharp
You are tasked with implementing a memory pool class in C++. A memory pool is a pre-allocated area of memory from which smaller chunks can be allocated and deallocated efficiently. Your task is to create a class `MemoryPool` that manages a pool of memory and provides methods for allocating and deallocating memory chunk...
```cpp #include <iostream> #include <cstring> class MemoryPool { private: char* memory; std::size_t totalPoolSize; bool* allocationMap; public: MemoryPool(std::size_t size) : totalPoolSize(size) { memory = new char[size]; allocationMap = new bool[size]; std::memset(allocationMa...
magicoder
cpp
You are given a Python code snippet that includes a function to check if a given number is prime. Your task is to complete the `is_prime` function and then use it to solve a specific problem. Complete the `is_prime` function to determine whether a given positive integer `x` is a prime number. A prime number is a natur...
```python import timeit import math def is_prime(x): if x == 2: return True if x == 1 or x % 2 == 0: return False for i in range(3, int(math.sqrt(x)) + 1, 2): if x % i == 0: return False return True def smallest_prime_replacement(n): if is_prime(n): retu...
magicoder
python
You are tasked with implementing a task scheduler for a mobile application. The scheduler should allow the application to schedule and execute tasks when the application transitions from the background to the active state. You need to design a class that manages the scheduling and execution of tasks when the applicatio...
```swift import UIKit class TaskScheduler { private var scheduledTasks: [(DispatchWorkItem, TimeInterval)] = [] private var isApplicationActive = true init() { NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForeground), name: UIApplication.willEnterForegroundN...
magicoder
swift
You are tasked with creating a custom settings class that securely maps attributes to values from a safe settings dictionary. The class should raise an AttributeError if an attribute is not found in the safe settings dictionary. Your task is to implement the missing `get_safe_settings()` function and complete the `Safe...
```python def get_safe_settings(): return {'USERNAME': 'admin', 'PASSWORD': 'secretpassword'} class SafeSettings(object): """ Map attributes to values in the safe settings dict """ def __init__(self): self._settings = get_safe_settings() def __getattr__(self, name): try: ...
magicoder
python
You are tasked with implementing a Swift class that manages a custom table view cell for a cryptocurrency wallet app. The cell contains various UI elements and properties related to cryptocurrency tokens. Your goal is to complete the implementation of the `CustomWalletCell` class by adding functionality to handle user ...
```swift import UIKit struct Token { let name: String let iconImage: UIImage let balance: Decimal } enum EditWalletType { case add case remove } typealias CurrencyId = String class CustomWalletCell: UITableViewCell { private let header = UILabel() private let subheader = UILabel() pr...
magicoder
swift
You are tasked with creating a script to automate the process of obtaining a signed SSH certificate from a Certificate Authority (CA) for secure access to a server. The script should handle the generation of a public key, sending the public key to the CA for signing, retrieving the signed certificate, and then using it...
```bash #!/bin/bash # Step 1: Generate and save the public key ssh-keygen -t rsa -b 2048 -f ./ssh/users_ca -N "" -C "CA Public Key" # Step 2: Send the public key to the CA and receive the signed certificate url="https://your-ca-url.com/sign" environment_public_key=$(cat ./ssh/users_ca.pub) signed_certificate=$(curl -...
magicoder
shell
You are tasked with implementing a Python class that manages retrievers for visual data. The class should handle the importing of necessary modules and provide methods for adding and retrieving retriever objects. Your task is to complete the implementation of the `Retrievers` class by adding the following methods: 1. ...
```python import logging class Retrievers(object): _visual_retriever = {} _retriever_object = {} np = None def __init__(self): try: from dvalib import indexer, retriever import numpy as np self.np = np except ImportError: logging.warning(...
magicoder
python
You are tasked with implementing a resampling algorithm for audio data. The resampling process involves converting audio samples from one sampling rate to another while preserving the audio quality. You are given a code snippet that involves resampling audio data and saving the resampled audio to a file. Your task is ...
```cpp #include <vector> #include <cmath> // Define the resampling function univector<fbase> resampleAudio(const univector<fbase>& audioData, int inputSamplingRate, int outputSamplingRate, double resamplingRatio, double resamplingPhase) { // Calculate the length of the resampled audio data size_t resampledLeng...
magicoder
cpp
You are tasked with implementing a memoization technique to optimize the computation of Fibonacci numbers. Memoization involves storing the results of expensive function calls and returning the cached result when the same inputs occur again. Your goal is to create a Python function that calculates the nth Fibonacci num...
```python import functools @functools.lru_cache(maxsize=None) def fib(n): if n <= 1: return n else: return fib(n-1) + fib(n-2) def compute_and_print_cache_info(): for x in range(16): fib(x) print(fib.cache_info()) compute_and_print_cache_info() ``` When the `compute_and_print...
magicoder
python
You are given a list of order IDs, which can be either strings or integers. Your task is to write a function that takes this list as input and returns a new list containing only the unique order IDs, preserving their original order of appearance. Write a function `get_unique_orders` that takes a list `order_id_list` a...
```python def get_unique_orders(order_id_list: list) -> list: unique_orders = [] seen = set() for order_id in order_id_list: if order_id not in seen: unique_orders.append(order_id) seen.add(order_id) return unique_orders ```
magicoder
python
You are tasked with implementing a Python class for a clustering algorithm. The class contains a method for setting up the algorithm, as well as methods for defining the input and output shapes and listing the required arguments. Your task is to complete the implementation of the class by writing the missing parts of t...
```python class ClusteringAlgorithm: def __init__(self, num_centers): self.num_centers = num_centers def infer_shape(self, in_shape): assert len(in_shape[0]) == 2 input_shape = in_shape[0] label_shape = (input_shape[0], self.num_centers) mu_shape = (self.num_centers, inp...
magicoder
python
You are tasked with implementing a utility function to parse and process callback configurations for a machine learning training framework. The function should handle the extraction of specific callback-related configuration parameters and instantiate corresponding callback objects based on the provided configuration. ...
```python def parse_callbacks(callback_config, trainer_config, thelper_utils): instantiated_callbacks = {} if "user_callback" in callback_config: user_callback_kwargs_keys = callback_config["user_callback"] user_callback_kwargs = thelper_utils.get_key_def(user_callback_kwargs_keys, trainer_...
magicoder
python
You are tasked with implementing a function to calculate the Levenshtein distance between two strings. The Levenshtein distance, also known as the edit distance, measures the minimum number of single-character edits (insertions, deletions, or substitutions) required to change one string into the other. Your task is to...
```python def levenshtein_distance(s1, s2): m, n = len(s1), len(s2) cost_matrix = [[0] * (n + 1) for _ in range(m + 1)] for i in range(m + 1): cost_matrix[i][0] = i for j in range(n + 1): cost_matrix[0][j] = j for i in range(1, m + 1): for j in range(1, n + 1): ...
magicoder
python
You are tasked with creating a script to automate the process of updating the SSH server configuration on a Linux system. The script should perform the following tasks: 1. Append the line "LoginGraceTime 60" to the file `/etc/ssh/sshd_config.new`. 2. Copy the contents of `/etc/ssh/sshd_config.new` to `/etc/ssh/sshd_co...
```bash #!/bin/bash # Append "LoginGraceTime 60" to sshd_config.new echo "LoginGraceTime 60" >> /etc/ssh/sshd_config.new # Check if sshd_config.new was created successfully if [ -e /etc/ssh/sshd_config.new ]; then # Copy sshd_config.new to sshd_config cp /etc/ssh/sshd_config.new /etc/ssh/sshd_config # Ch...
magicoder
shell
You are working on a web application that uses Python and the Flask framework. The application has a module called `core` which contains various controllers and domain services. The controllers handle the HTTP requests and responses, while the domain services contain the business logic of the application. Your task is ...
```python # core/controllers/acl_decorators.py from functools import wraps from flask import abort, request from core.domain import beam_job_services def access_control_required(permission): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): user_id = request.headers.get('...
magicoder
python
You are given a list of strings representing file paths. Each file path consists of a sequence of directories separated by slashes ("/"). Your task is to write a function that finds the longest common directory path among the file paths. If there is no common directory path, the function should return an empty string. ...
```python def longestCommonDirectoryPath(filePaths): if not filePaths: return "" paths = [path.split('/') for path in filePaths] min_len = min(len(path) for path in paths) common_path = [] for i in range(min_len): if all(path[i] == paths[0][i] for path in paths): common...
magicoder
python
You are working on a web application that uses dependency injection to manage its services. The code snippet provided is from the constructor of a class responsible for managing user sessions, redirection, blocks, assets, and session settings. The constructor takes in several interfaces and services as dependencies and...
```php <?php // Define the interfaces interface SessionInterface { // Define methods related to managing user sessions } interface RedirectionInterface { // Define methods related to URL redirection } // Define the services class BlocksService { // Provide functionality related to managing content blocks...
magicoder
php
You are tasked with creating a Python program to analyze and visualize temperature data using the matplotlib library. The program should read temperature data from a CSV file, perform a linear regression analysis, and then plot the original data points along with the linear regression line. Your task is to complete th...
```python # Plot the original data points and the linear regression line plt.plot(year, temp, 'r-', label='Original Data') plt.plot(year, fit_fn(year), 'b', label='Linear Regression') plt.xlabel('Year') plt.ylabel('Temperature') plt.title('Temperature Analysis') plt.legend() # Display the plot plt.show() ``` In the s...
magicoder
python
You are working on a project that involves managing a large collection of firearm data. Each firearm is represented by a string in the format "CUP_<manufacturer>_<model>_<caliber>_<barrel_length>_<attachment>". You need to write a function that can extract and organize this information from the given strings. Write a ...
```python def parseFirearmData(firearm_strings): firearm_data = {} for firearm in firearm_strings: parts = firearm.split('_') manufacturer = parts[1] model = parts[2] caliber = parts[3] barrel_length = parts[4] attachment = parts[5] if len(parts) > 5 else None ...
magicoder
python
You are tasked with implementing a TypeScript function that analyzes a list of class members and determines the static encapsulation type used within the class. The function signature is as follows: ```typescript import ts from 'typescript'; export declare function parseStaticEncapsulation(staticMembers: ts.ClassEleme...
```typescript import ts from 'typescript'; export function parseStaticEncapsulation(staticMembers: ts.ClassElement[]): "none" | "shadow" | "scoped" { const staticMemberNames = staticMembers.map(member => member.name.getText()); for (const member of staticMembers) { if (member.kind === ts.SyntaxKind.PropertyDe...
magicoder
typescript
You are tasked with implementing a lexer for a simple programming language. The lexer should be able to identify and tokenize different language constructs such as keywords, identifiers, and parentheses. Your task is to write a function that takes an input string and returns a list of tokens representing the lexical el...
```python import re class CommandNotFoundError(Exception): pass def lex(input_string): tokens = [] current_token = "" for char in input_string: if char in ('(', ')'): if current_token: tokens.append(current_token) current_token = "" token...
magicoder
python
You are tasked with implementing a custom normalization function in Python to handle both vectors and matrices. The function should be able to calculate different types of norms based on the input parameters. You are not allowed to use any external libraries or built-in functions for norm calculation. Write a Python f...
```python import math def custom_norm(input_data, norm_order): if isinstance(input_data[0], list): # Check if input_data is a matrix if norm_order == 1: return max(sum(abs(row[i]) for row in input_data) for i in range(len(input_data[0]))) elif norm_order == 2: # Not impleme...
magicoder
python
You are tasked with creating a Python function to facilitate flashing binary files onto a test device. The function should take the following parameters: - `mount_point`: The mount point of the test device. - `base_dir`: The base directory where the binary file is located. - `build_dir`: The directory where the binary ...
```python from pathlib import Path def flash_binary(mount_point, base_dir, build_dir, tag, force): # Step 1: Create the build directory if it does not exist build_dir.mkdir(exist_ok=True) # Step 2: Generate the binary file name bin_file_name = base_dir.name + ".bin" bin_file_path = build_dir / bin...
magicoder
python
You are working on a payment processing system that involves handling barcodes and URLs. Your task is to implement a function that sanitizes and validates the input data according to certain rules. The function should perform the following tasks: 1. If the `BARCODE` variable is truthy, it should be converted to 1; oth...
```python import warnings def process_payment_data(BARCODE, Amt, request, ReturnURL, NotifyURL): # Convert BARCODE to 1 if truthy, else set to 0 BARCODE = 1 if BARCODE else 0 # Check Amt and generate warning if BARCODE is truthy and Amt is not within the specified range if BARCODE and (Amt < 20 or Amt...
magicoder
python
You are working on a program to simulate an energy trading market. The program has access to various parameters related to energy trading, including the energy difference, energy market price, wanted energy, energy buy max price, energy buy starting price, energy buy price increment, and energy sell min price. Your t...
```python def max_profit_energy_trading(energy_difference, energy_market_price, wanted_energy, energy_buy_max_price, energy_buy_starting_price, energy_buy_price_increment, energy_sell_min_price) -> int: if wanted_energy <= 0: return 0 if energy_market_price <= energy_buy_starting_price: return ...
magicoder
python
You are tasked with implementing a function that processes an XML document to extract font information and create an asset for a game engine. The given code snippet is part of a larger system and provides some context for the task. The function `mark_progress` is used to check if the font information has already been p...
```cpp void processFontAsset(pugi::xml_document& m_doc, const std::string& m_name, const std::string& m_path, AssetManager& acc) { if (mark_progress(PRECOMPILED)) return; // Check if font information has been precompiled // Access the game engine's asset manager to add the font asset asset::AssetFont* af ...
magicoder
cpp
You are working on a project that involves implementing a cryptographic signature scheme using the Leighton-Micali One-Time Signature (LMOTS) scheme. The LMOTS scheme involves generating a signature by applying a hash function iteratively in a chain-like fashion. Your task is to write a function to generate a signature...
```rust use arrayvec::ArrayVec; fn generate_lmots_signature(message: &[u8], lmots_parameter: &LmotsParameter) -> Vec<ArrayVec<[u8; MAX_HASH_SIZE]>> { let mut signature_data: Vec<ArrayVec<[u8; MAX_HASH_SIZE]>> = Vec::new(); for _ in 0..lmots_parameter.get_hash_function_output_size() { signature_randomi...
magicoder
rust