query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a Java class that represents a date in a specific format and provides functionality to manipulate and display the date. The class should be named `DayDate` and should adhere to the following requirements:
1. The class should have a static block that sets the default time zone to UTC fo... | ```java
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;
public class DayDate {
private static final SimpleDateFormat dayDateFormat = new SimpleDateFormat("yyyy-MM-dd");
static {
dayDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
}
private long time... | magicoder | java |
You are tasked with creating a program to analyze and visualize the total times of athletes in a race. The program should take in the total times of each athlete and plot a line graph to display their performance. Additionally, the program should set the plot size, y-axis limits, title, and x-axis ticks based on the ra... | ```python
import numpy as np
import matplotlib.pyplot as plt
def plot_athlete_times(total_times, names, colors, gender_name, length, title_names, nr_laps, size):
for i in range(len(total_times)):
athlete_times = total_times[i, total_times[i, :] > 0]
plt.plot(athlete_times, color=colors[i], label=na... | magicoder | python |
You are tasked with creating a Python program that simulates a simple banking system. The program should allow users to create accounts, deposit funds, withdraw funds, and check their balance. Each account should have a unique account number, and the program should support multiple accounts.
Your task is to implement ... | ```python
from typing import Dict, Union
class Bank:
def __init__(self):
self.accounts: Dict[int, Dict[str, Union[str, float]]] = {}
def create_account(self, name: str, initial_balance: float) -> int:
account_number = len(self.accounts) + 1
self.accounts[account_number] = {'name': name... | magicoder | python |
You are tasked with implementing a caching mechanism for network responses in a Swift application. The provided code snippet includes a declaration of a variable `data` of type `Data?`, which is intended to store the response data from a network request. Additionally, there is a commented-out declaration of `response` ... | ```swift
import Foundation
// Define a protocol for the cached item to ensure consistency in handling successful responses and errors
protocol CachedItem {
var timestamp: Date { get }
}
// Define a struct to represent a successful network response
struct SuccessCachedItem: CachedItem {
let data: Data
let ... | magicoder | swift |
You are tasked with implementing a reinforcement learning algorithm using the Proximal Policy Optimization (PPO) method. PPO is a popular policy gradient method that aims to optimize the policy function in reinforcement learning. In this problem, you will be focusing on implementing the PPO algorithm for a simple envir... | ```python
import numpy as np
class PPOAgent:
def __init__(
self,
capacity: int,
beta: float = 0.5,
stack_size: int = 1,
n_step: int = 1,
gamma: float = 0.9,
):
self.capacity = capacity
self.beta = beta
self.stack_size = stack_size
... | magicoder | python |
You are tasked with creating a Python function that processes a list of integers and returns the sum of all even numbers in the list. However, there's a catch - the function must utilize asynchronous programming using the `asyncio` library and the `uvloop` event loop policy.
Your task is to implement the `async` funct... | ```python
import uvloop
import asyncio
from typing import List
async def async_sum_even_numbers(numbers: List[int]) -> int:
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
async def sum_even():
total = 0
for num in numbers:
if num % 2 == 0:
total += num
... | magicoder | python |
You are tasked with implementing a simple HTTP request parser in Java. Your goal is to create a class that can parse a given HTTP request string and extract the method, request URI, and HTTP version from it.
You are provided with a partial code snippet that includes a test case for the HTTP request parser. The `HttpRe... | ```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
class HttpRequest {
private String method;
private String requestURI;
private String httpVersion;
public HttpRequest(String method, String requestURI, String httpVersion) {
... | magicoder | java |
You are tasked with creating a Rust program to manage triggers in a collection within a NoSQL database. The program should utilize the provided code snippet as a starting point and extend it to handle error scenarios and improve the trigger management functionality.
Your task is to implement a function that retrieves ... | ```rust
use std::pin::Pin;
use futures::stream::StreamExt;
use azure_sdk_cosmos::prelude::*;
async fn manage_triggers(collection_client: &CollectionClient) {
let mut last_session_token: Option<ConsistencyLevel> = None;
let ret = ConsistencyLevel::Strong;
let stream = collection_client
.list_trigge... | magicoder | rust |
You are tasked with implementing a file hashing function in Python. The function should take a filename and a block size as input, read the file in blocks of the specified size, and calculate the hash of the file content using the SHA-256 algorithm. However, the current implementation has a TODO comment suggesting the ... | ```python
import hashlib
def calculate_file_hash(filename, block_size):
hash = hashlib.sha256() # Use a more precise argument type for hash.
with open(filename, "rb") as f:
for block in iter(lambda: f.read(block_size), b""):
hash.update(block)
return hash.hexdigest()
# Test the functi... | magicoder | python |
You are tasked with implementing a priority queue data structure using Python. A priority queue is an abstract data type similar to a regular queue or stack, but where each element has a "priority" associated with it. In this problem, you will create a class `PriorityQueue` with the following methods:
1. `__init__(sel... | ```python
from typing import Any
class PriorityQueue:
def __init__(self):
self.queue = []
def insert(self, item: Any, priority: float) -> None:
self.queue.append((item, priority))
self.queue.sort(key=lambda x: x[1], reverse=True)
def pop_highest_priority(self) -> Any:
if s... | magicoder | python |
You are tasked with creating a Python framework for registering callbacks and evaluators. The framework should allow users to register callbacks and evaluators using decorators and provide a way to retrieve the registered callbacks and evaluators.
Your task is to implement the `CallbackFramework` class, which should h... | ```python
class CallbackFramework:
FRAMEWORK_CALLBACKS = {}
FRAMEWORK_EVALUATORS = {}
@classmethod
def register_callback(cls, name):
def decorator(callback_cls):
cls.FRAMEWORK_CALLBACKS[name] = callback_cls
return callback_cls
return decorator
@classmethod
... | magicoder | python |
You are tasked with creating a custom form control for a content management system (CMS) that allows users to select a URL shortener and set a publish date and time for their content. The form control should be implemented in C# using ASP.NET.
Your task is to create a custom ASP.NET user control that includes the foll... | ```csharp
// CustomFormControls.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="CustomFormControls.ascx.cs" Inherits="YourNamespace.CustomFormControls" %>
<%@ Register TagPrefix="uc" TagName="AvailableUrlShortenerSelector" Src="~/CMSModules/SocialMarketing/FormControls/AvailableUrlShortenerSelector.as... | magicoder | csharp |
You are tasked with implementing a custom view for an image preview in a C# WPF application. The view is defined within the `AngelNode.View` namespace and is associated with the XAML file `ImagePreviewView.xaml`. Your goal is to create a user control that allows users to preview images with additional interactive featu... | ```csharp
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace AngelNode.View
{
public partial class ImagePreviewView : UserControl
{
private double _scale = 1.0;
private Point _o... | magicoder | csharp |
You are tasked with creating a Node.js program that simulates a simplified Minecraft server startup process. Your program should read a configuration file, initialize a server with the provided settings, and load internal plugins. You are given a code snippet as inspiration:
```javascript
let configuration = await con... | ```javascript
// Simulated configuration retrieval function
async function config() {
return {
spout: {
motd: "Welcome to the server!",
port: 25565,
maxplayers: 20
}
};
}
// Simulated SpoutServer class with create method
class SpoutServer {
static create(... | magicoder | javascript |
You are tasked with implementing a Python class that generates unique case objects for a legal expungement service. The provided code snippet is the beginning of a `CaseFactory` class, which is responsible for creating instances of the `Case` class. The `create` method of the `CaseFactory` class takes an optional `info... | ```python
class CaseFactory:
total_cases_created = 0
@staticmethod
def create(info=["<NAME>", "1990"]):
name, birth_year = info
case_id = CaseFactory.total_cases_created # Unique identifier for the case
CaseFactory.total_cases_created += 1 # Increment the total cases created
... | magicoder | python |
You are tasked with understanding and explaining the concept of ownership and borrowing in Rust. Consider the following code snippet:
```rust
fn main() {
// Uncomment the following lines one by one and observe the behavior
// println!("{}", s); // This will print `hello, world!'
// let x = 5;
// let ... | The code snippet provided demonstrates the concepts of ownership and borrowing in Rust. Let's analyze each uncommented line to understand the behavior:
1. `println!("{}", s); // This will print `hello, world!'`
- This line will result in a compilation error because the variable `s` is not declared or initialized in... | magicoder | python |
You are tasked with implementing a class that manages tasks and their due dates. The class should have a method to calculate the due date for a task based on its submission time and the turnaround time. The submission time is the date and time when the task is submitted, and the turnaround time is the number of working... | ```php
<?php
class TaskManager
{
private $tasks = [];
public function submitTask($submissionTime, $turnaroundTime)
{
$this->tasks[] = ['submissionTime' => $submissionTime, 'turnaroundTime' => $turnaroundTime];
}
public function getDueDate($taskId)
{
$task = $this->tasks[$taskI... | magicoder | php |
You are tasked with creating a Python function that processes financial data from a cryptocurrency exchange. The function should take in a list of dictionaries, each representing a trade, and return the average trade volume for a given cryptocurrency pair within a specified time range.
The input to the function will b... | ```python
from datetime import datetime
def average_trade_volume(trades, start_time, end_time) -> float:
total_volume = 0
trade_count = 0
for trade in trades:
if start_time <= trade["timestamp"] <= end_time:
total_volume += trade["volume"]
trade_count += 1
if trade_cou... | magicoder | python |
You are working on a project that involves offline graph processing. The project includes several modules for generating node skeletons, offline cost calculation, main offline callback, and graph pruning. Each module is implemented in a separate file within the `graph_ltpl` package. Your task is to create a Python scri... | ```python
import graph_ltpl.offline_graph.src.gen_node_skeleton as gen_node_skeleton
import graph_ltpl.offline_graph.src.gen_offline_cost as gen_offline_cost
import graph_ltpl.offline_graph.src.main_offline_callback as main_offline_callback
import graph_ltpl.offline_graph.src.prune_graph as prune_graph
try:
# Call... | magicoder | python |
You are tasked with creating a command-line tool to parse and execute a series of commands specified in a string. Each command is separated by a semicolon, and some commands may include variables denoted by a dollar sign followed by an uppercase alphanumeric identifier. Your task is to implement a function that takes t... | ```python
import re
def parse_commands(command_string):
commands = re.split(r';(?=\$)', command_string) # Split commands at semicolons followed by a variable
parsed_commands = []
current_variable = None
for command in commands:
if command.startswith('$'):
current_variable = comman... | magicoder | python |
You are tasked with creating a script to automate the setup of SSH key-based authentication for remote servers using tmux and a command-prompt interface. Your script should prompt the user for the hostname of the remote server and then execute a shell script to establish the SSH connection using the provided hostname a... | ```bash
#!/bin/bash
# Prompt the user for the hostname of the remote server
read -p "Enter the hostname of the remote server: " hostname
# Validate the hostname input
if [ -z "$hostname" ]; then
echo "Error: Hostname cannot be empty."
exit 1
fi
# Execute the shell script to establish the SSH connection
ssh_scrip... | magicoder | shell |
You are tasked with implementing a UNetEncoderBlock class in Python for a convolutional neural network architecture. The UNetEncoderBlock is a building block used in the encoder part of the UNet architecture, which is commonly used for image segmentation tasks.
The UNetEncoderBlock class should have the following spec... | ```python
from typing import List
import torch.nn as nn
class UNetEncoderBlock(nn.Module):
# conv->conv->pooling
def __init__(self, in_channels: int, out_channels: int, with_bn: bool):
super(UNetEncoderBlock, self).__init__()
self.with_bn = with_bn
if with_bn:
self.conv1 = ... | magicoder | python |
You are tasked with implementing a Python class method that takes a variable number of arguments and keyword arguments and performs a specific operation based on the input. The method should be able to handle various data types and execute the operation accordingly.
You are given the following code snippet as a starti... | ```python
class Calculator:
def execute(self, *args, **kwargs):
if not args:
return 0
elif len(args) == 1:
return args[0] ** 2
else:
operation = kwargs.get('operation')
if operation == 'product':
result = 1
for a... | magicoder | python |
You are tasked with implementing a class for handling 3D rotations using the SO(3) representation. The SO(3) class provides methods for setting the rotation using Euler angles and computing the logarithm of the rotation matrix.
You need to implement the following methods in the SO3 class:
1. `set_euler`: This method t... | ```python
import numpy as np
class SO3:
def __init__(self):
self.rotation_matrix = np.eye(3)
def set_euler(self, euler_angles):
phi, theta, psi = euler_angles
c1, s1 = np.cos(phi), np.sin(phi)
c2, s2 = np.cos(theta), np.sin(theta)
c3, s3 = np.cos(psi), np.sin(psi)
... | magicoder | python |
You are tasked with implementing a class method that manages the generation of checkpoints for a machine learning model. The provided code snippet is from a Python class method that checks if a checkpoint should be generated based on a specified interval. If the condition is met, it calls the `save_checkpoint` method w... | ```python
class ModelCheckpointManager:
def __init__(self, config, generation):
self.config = config
self.generation = generation
def should_generate_checkpoint(self):
if self.config.checkpoint_gen_interval is not None and self.generation % self.config.checkpoint_gen_interval == 0:
... | magicoder | python |
You are tasked with implementing a custom plugin for logging HTTP request and response bodies in a Rust web server. The provided code snippet is a starting point for the plugin implementation. The `BodyLogger` struct is intended to be the plugin that logs the HTTP request and response bodies. Your task is to complete t... | ```rust
// Define the BodyLogger struct
pub struct BodyLogger {}
// Implement the Plugin trait for the BodyLogger
impl Plugin for BodyLogger {
fn name(&self) -> &'static str {
"BodyLogger"
}
}
// Implement the HttpPlugin trait for the BodyLogger
impl HttpPlugin for BodyLogger {
fn start(&self, _co... | magicoder | rust |
You are tasked with implementing a class to manage a batch of experiences in a reinforcement learning setting. The class should support adding individual experiences and extracting states, actions, and rewards from the batch. An experience consists of a state, an action, a reward, and an optional last state. The last s... | ```python
class ExperienceBatch:
def __init__(self):
self.states = []
self.actions = []
self.rewards = []
def add_experience(self, state, action, reward, last_state=None):
self.states.append(state)
self.actions.append(action)
self.rewards.append(reward)
i... | magicoder | python |
You are tasked with implementing a Python function that handles instrument-specific wrappers for data retrieval from a space physics data system. The function is meant to be called indirectly through instrument-specific wrappers, such as `pyspedas.erg.mgf()` and `pyspedas.erg.hep()`. The function takes several optional... | ```python
def retrieve_data(no_update=False, uname=None, passwd=None, time_clip=False, version=None):
"""
This function is not meant to be called directly; please see the instrument specific wrappers:
pyspedas.erg.mgf()
pyspedas.erg.hep()
"""
# Perform data retrieval operations based on ... | magicoder | python |
You are tasked with implementing a dependency resolution algorithm for a software configuration system. The system uses a combination of schemas and dependencies to define the structure of configurations. Each schema can have a name and a flag indicating whether it is required. Dependencies can be nested and are associ... | ```python
from collections import deque
def resolve_dependencies(subject):
queue = deque([(subject.configuration.schema, [], None)])
while queue:
schema, tokens, dependency = queue.popleft()
if dependency:
structure = dependency.construct_schema(name=dependency.token)
... | magicoder | python |
You are tasked with implementing a sensor grid router system that can efficiently route data from multiple sensors to a central processing unit. The sensor grid router is represented by the `SensorGridRouter` class, which provides methods for adding sensors, routing data, and retrieving sensor information.
The `Sensor... | ```cpp
#include <unordered_map>
#include <vector>
class Sensor {
public:
int x, y;
int data;
Sensor(int x, int y) : x(x), y(y), data(0) {}
};
class SensorGridRouter {
private:
std::unordered_map<int, Sensor> sensors;
public:
void addSensor(int sensorId, int x, int y) {
sensors[sensorId] ... | magicoder | cpp |
You are tasked with creating a release verification tool for Apache Mesos, an open-source distributed systems kernel. Your tool will need to fetch and verify the release artifacts for a given release tag.
You are provided with a code snippet that contains placeholders for various URLs and variables related to the rele... | ```python
import urllib.request
import hashlib
import gnupg
def verifyRelease(tag):
TAG = tag
SVN_DEV_REPO = "https://svn.apache.org/repos/asf/mesos"
TARBALL = "mesos-" + TAG + ".tar.gz"
KEYS_URL = "https://dist.apache.org/repos/dist/release/mesos/KEYS"
# Construct the URL for the commit associate... | magicoder | python |
You are tasked with creating a PHP program that utilizes the RakePlus library to extract keywords from a given text. RakePlus is a library that performs keyword extraction using the RAKE (Rapid Automatic Keyword Extraction) algorithm. The RakePlus library is already included via the autoload.php file.
Your program sho... | ```php
// Pour exécuter cet exemple à partir de la ligne de commande
// $ cd examples
// $ php fr_FR_example.php "Quelques exemples de texte dont j'aimerais extraire des mots-clés."
require '../vendor/autoload.php';
use DonatelloZa\RakePlus\RakePlus;
if ($argc < 2) {
echo "Spécifiez le texte que vous souhaitez a... | magicoder | php |
You are tasked with implementing an efficient algorithm to calculate the nth number in the Fibonacci sequence. 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 sequence goes as follows: 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on.
Wr... | ```python
def fibonacci_iterative(n):
if n <= 0:
return 0
elif n == 1:
return 1
a, b = 0, 1
for _ in range(2, n + 1):
a, b = b, a + b
return b
```
The `fibonacci_iterative` function efficiently calculates the nth number in the Fibonacci sequence using an iterative approach... | magicoder | python |
You are tasked with implementing a simple ledger system for tracking transactions associated with user accounts. The system consists of two classes: `User` and `Ledger`. The `User` class represents a user account and has a one-to-many relationship with the `Ledger` class, which represents individual transactions. The `... | ```python
class Ledger(Base):
__tablename__ = 'ledger'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('user.id'))
amount = Column(Float)
date = Column(DateTime)
description = Column(String)
def __repr__(self):
return "<Ledger(amount={}, date={}, descript... | magicoder | python |
You are tasked with implementing a custom data structure that supports key-value pairs and efficient retrieval of values based on a given context. The data structure should allow for the storage of multiple values for a single key, and it should support the retrieval of values based on a specified context.
You are giv... | ```python
class CustomDataStructure:
def __init__(self):
self.data = {}
def add_value(self, key, value, context):
if key not in self.data:
self.data[key] = {}
if context not in self.data[key]:
self.data[key][context] = []
self.data[key][context].append(va... | magicoder | python |
You are tasked with implementing a file system visitor pattern in PHP. The file system consists of files and directories, and the visitor pattern allows you to perform operations on these elements without modifying their structure.
You need to create the necessary interfaces and classes to implement the visitor patter... | ```php
// Define the FileInterface representing the file in the file system
interface FileInterface
{
public function accept(VisitorInterface $visitor): void;
}
// Define the VisitorInterface with methods for visiting files and directories
interface VisitorInterface
{
public function visitFile(File $file): voi... | magicoder | php |
You are tasked with implementing a simple routing system for a web application using PHP. Your goal is to create a route for handling user login requests. The provided code snippet demonstrates the registration of a POST route for the "/login" endpoint, which is associated with the "login" method of the "UserController... | ```php
class UserController {
public function login() {
// Retrieve POST data
$username = $_POST['username'];
$password = $_POST['password'];
// Perform user authentication (example logic)
if ($username === 'example_user' && $password === 'example_password') {
//... | magicoder | php |
You are working on a bioinformatics project and need to automate the processing of DNA sequencing data. One of the tasks involves using the `trim_galore` and `bwa mem` tools to perform quality trimming and alignment of paired-end reads. You have a directory containing multiple FASTQ files named with a common prefix fol... | ```python
import os
def generate_commands(file_path, out_path, sample, reference):
out_path = out_path + r'/' # Ensure out_path ends with a '/'
if not os.path.isdir(out_path):
os.makedirs(out_path) # Create the output directory if it does not exist
commands = []
for file in os.listdir(file_p... | magicoder | python |
You are tasked with implementing a file reading function that reads a specified number of bytes from a file into a buffer. The function should handle potential errors, such as buffer overflow, and provide a way to handle these errors gracefully.
Write a function `read_file_into_buffer` that takes the following paramet... | ```rust
use std::fs::File;
use std::io::{Read, Result};
fn read_file_into_buffer(file_path: &str, buffer: &mut [u8], bytes_to_read: usize) -> Result<usize> {
let mut file = File::open(file_path)?;
let bytes_read = file.read(&mut buffer[..bytes_to_read])?;
if bytes_read < bytes_to_read {
return Err(... | magicoder | rust |
You are tasked with implementing a music composition application that involves creating measures of musical notes. Each measure is represented by the `Measure` class, which implements the `IEnumerable<Note>` interface and the `IMeasureCollection` interface. The `Measure` class contains a list of notes and a constructor... | ```csharp
using System;
using System.Collections;
using System.Collections.Generic;
namespace Music
{
public class Measure : IEnumerable<Note>, IMeasureCollection
{
private List<Note> Notes { get; set; }
public Measure(List<Note> notes)
{
Notes = notes;
}
p... | magicoder | csharp |
You are tasked with implementing a method to retrieve the centroid of a cluster in a K-means clustering algorithm. The K-means algorithm is a popular unsupervised machine learning technique used for clustering data points into K clusters. The centroid of a cluster is the mean position of all the data points in that clu... | ```csharp
public KCentroid<TScalar, TKernel> GetKCentroid(int index)
{
if (!(0 <= index && index < this.NumberOfCenters))
throw new ArgumentOutOfRangeException();
// Retrieve the data points belonging to the cluster at the given index
List<DataPoint> clusterDataPoints = GetClusterDataPoints(index);... | magicoder | csharp |
You are tasked with creating a Python function that processes storage shares using an API. The function should add a new storage share if it does not already exist. You are given a code snippet that includes logging statements and a partial implementation of the `addStorageShare` function. Your task is to complete the ... | ```python
import logging
def addStorageShare(anvilRest, sharePath):
logging.info("add storage share '{}'".format(sharePath))
shareNames = anvilRest.getSharenames()
for share in shareNames:
logging.info("existing share: {}".format(share))
if share.path == sharePath:
logging.info(... | magicoder | python |
You are tasked with implementing a custom memory management system for a specific data structure. The data structure is a doubly linked list, and the memory management system should handle the allocation and deallocation of memory for the nodes in the list. The provided code snippet is a part of the memory deallocation... | ```cpp
#include <iostream>
namespace D3 {
// Define the structure for the doubly linked list node
struct Node {
int data;
Node* prev;
Node* next;
};
// Define the custom allocator class for memory management
class CustomAllocator {
public:
// Allocate memory for a new node in the doubly li... | magicoder | cpp |
You are tasked with implementing a function to process a hierarchical data structure represented by the `HierItem` enum. The enum has several variants, and your function needs to handle each variant appropriately. The `HierItem` enum is defined as follows:
```rust
enum HierItem {
Root,
Folder(String),
File... | ```rust
fn process_hierarchical_data(data: Vec<HierItem>) -> Result<(), &'static str> {
for item in data {
match item {
HierItem::Root => println!("Processing root item"),
HierItem::Folder(name) => println!("Processing folder: {}", name),
HierItem::File(name) => println!(... | magicoder | rust |
You are given a Python function that takes in a list of integers and returns the maximum sum of a contiguous subarray within the input list. Your task is to implement the function `max_subarray_sum` to achieve this.
The function signature is:
```python
def max_subarray_sum(nums: List[int]) -> int:
pass
```
Your f... | ```python
from typing import List
def max_subarray_sum(nums: List[int]) -> int:
max_sum = float('-inf')
current_sum = 0
for num in nums:
current_sum = max(num, current_sum + num)
max_sum = max(max_sum, current_sum)
return max_sum
```
The solution defines the function `max_sub... | magicoder | python |
You are given two sorted linked lists, `head1` and `head2`, representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. You need to return a new sorted linked list representing the sum of the two integers.
Each linked list's length is at most 100, an... | To solve this problem, we can use a dummy node to keep track of the result. We iterate through both input linked lists, adding their values along with any carry from the previous addition. We then update the carry and create a new node with the sum's least significant digit. Finally, we move to the next nodes in the in... | magicoder | python |
You are tasked with implementing a memory allocation system for a virtualization platform. The system manages the allocation status of virtual resources and assigns them to specific virtual processors. The code snippet provided defines two member variables within a struct representing a virtual resource.
The `m_alloca... | ```cpp
#include <mutex>
#include <unordered_map>
enum class AllocatedStatusT { UNALLOCATED, ALLOCATED };
struct VirtualResource {
AllocatedStatusT m_allocated;
bsl::SafeU16 m_assigned_vpid;
std::mutex resourceMutex;
};
class MemoryAllocationSystem {
private:
std::unordered_map<resource_id_type, Virtu... | magicoder | cpp |
You are given a Swift code snippet that includes a unit test class for animation functionality. Your task is to complete the implementation of a custom animation class that supports various animation operations. The animation class should be able to animate the position, scale, and opacity of a view. You need to implem... | ```swift
import XCTest
class CustomAnimation {
var view: UIView
var duration: TimeInterval
init(view: UIView, duration: TimeInterval) {
self.view = view
self.duration = duration
}
func animatePosition(to newPosition: CGPoint, completion: @escaping () -> Void) {
UIV... | magicoder | swift |
You are tasked with creating a command-line tool to process data using the Julia programming language. The tool takes various command-line arguments to specify the input data, processing parameters, and output locations. Your task is to implement a parser for the command-line arguments and extract the relevant informat... | ```julia
using ArgParse
function process_command_line_arguments(args)
parser = ArgParse.ArgumentParser()
ArgParse.add_arg!(parser, "--matfile"; help="Input data file", required=true)
ArgParse.add_arg!(parser, "--exName"; help="Output location and file name", required=true)
ArgParse.add_arg!(parser, "--... | magicoder | julia |
You are tasked with creating a program that processes data from a file called "myouji". The "myouji" file contains a list of last names, each on a separate line. Your program needs to read the contents of the "myouji" file, process the last names, and then perform specific operations based on the data.
Your task is t... | ```python
def read_last_names_from_file(file_name):
try:
with open(file_name, 'r') as file:
last_names = file.readlines()
return [name.strip() for name in last_names]
except FileNotFoundError:
print(f"File '{file_name}' not found.")
return []
def count_last_name_... | magicoder | python |
You are tasked with implementing a function to calculate the confidence intervals for a set of parameters based on their standard deviations and the covariance matrix. The function should take in the standard deviations, covariance matrix, and the number of parameters, and return the confidence intervals for each param... | ```python
import numpy as np
from scipy.stats import norm
def calculate_confidence_intervals(std, covmat, nparam):
z_score = norm.ppf(0.975) # For a 95% confidence level (two-tailed test)
intervals = np.zeros((nparam, 2))
for i in range(nparam):
std_dev = std[i]
parameter_value = 0 # Rep... | magicoder | python |
You are tasked with implementing a data structure that supports the `pick` operation, which returns an integer from a given range, excluding a set of blacklisted integers. You need to design a solution to efficiently pick a random integer from the range `[0, n)` while avoiding the blacklisted integers.
You are given a... | To solve this problem, we can use a mapping approach to efficiently handle the blacklisted integers. We can map the blacklisted integers to the available non-blacklisted integers in the range `[0, n)`.
Here's the Python implementation of the `Solution` class:
```python
import random
class Solution:
def __init__(... | magicoder | python |
You are tasked with implementing a function to train a machine learning model using mini-batch gradient descent. The function should take in the input data `x` and target values `y`, and train the model for a specified number of epochs with a given mini-batch size. The loss of the final epoch should be returned as the ... | ```python
import numpy as np
def train(x, y, epochs, batch_size):
num_data = len(y)
final_loss = 0
for epoch in range(epochs):
# Shuffle the data for each epoch
indices = np.random.permutation(num_data)
x_shuffled = x[indices]
y_shuffled = y[indices]
total_loss = 0... | magicoder | python |
You are working on a natural language processing (NLP) project and have been tasked with preprocessing a dataset and feeding it into a model for training. The code snippet provided is a part of the preprocessing and model input preparation process. Your task is to complete the missing part of the code to ensure that th... | ```python
outputs = model(finalInput)
```
In the missing part of the code, the `finalInput`, which represents the preprocessed dataset, is directly passed to the `model()` function to obtain the outputs. This ensures that the model is properly fed with the preprocessed dataset for training or inference. | magicoder | python |
You are tasked with implementing a custom error type and a function to parse a string into a specific data type. The custom error type should represent two distinct error cases: "InvalidFormat" for when the input string cannot be parsed into the desired data type, and "OutOfRange" for when the parsed value is outside a... | ```rust
use std::fmt;
use std::result;
// Define a custom error type
#[derive(Debug, PartialEq)]
enum CustomError {
InvalidFormat,
OutOfRange,
}
// Implement the Display trait for the custom error type
impl fmt::Display for CustomError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match... | magicoder | rust |
You are given a string representing a mathematical expression. The expression contains only non-negative integers, the four basic arithmetic operators (+, -, *, /), and parentheses. Your task is to write a function to evaluate the given mathematical expression and return the result.
Your function should consider the o... | ```python
def evaluate_math_expression(expression: str) -> int:
stack = []
num = 0
sign = '+'
for i in range(len(expression)):
if expression[i].isdigit():
num = num * 10 + int(expression[i])
if (not expression[i].isdigit() and expression[i] != ' ') or i == len(expression) - 1... | magicoder | python |
You are working on a deployment script for a web application. The script is located at `~/dev/www/dystroy/deploy.sh`. The script is responsible for deploying the latest version of the web application to a production server. However, the script currently lacks the functionality to handle versioning and rollback in case ... | ```bash
#!/bin/bash
# Function to create a backup of the current production version
create_backup() {
timestamp=$(date +"%Y%m%d%H%M%S")
backup_dir="/path/to/production/backups/$timestamp"
mkdir -p $backup_dir
cp -r /path/to/production/current_version $backup_dir
echo "Backup created at $backup_dir"
}
# Func... | magicoder | shell |
You are tasked with creating a Discord bot command that interacts with an API and performs statistical analysis on user input. The bot command is named `best` and is designed to work within a Discord server. The command takes variable arguments passed by users and is subject to a check function `is_disabled` to ensure ... | ```python
import discord
from discord.ext import commands
import statistics
bot = commands.Bot(command_prefix='!')
# Check function to ensure the command is not disabled
def is_disabled(ctx):
# Implement the logic to check if the command is disabled
return False # Replace with actual logic
# Function to han... | magicoder | python |
You are tasked with implementing a function that loads a machine learning model and its weights based on the given mode and configurations. The function `load_model_and_weights` takes three parameters: `mode` (a string representing the mode of operation), `cmdcfg` (command line configurations), and `appcfg` (applicatio... | ```python
def load_model_and_weights(mode, cmdcfg, appcfg):
# TODO: check for WEIGHTS_PATH in all cases - training or prediction
# TODO: check for Annotation files in case of training
if mode == "training":
# Check for annotation files
if "annotation_files" in cmdcfg:
annotation... | magicoder | python |
You are tasked with implementing a function to calculate the digest of a block header in a blockchain system. The block header contains the following fields:
- `time_stamp`: A timestamp indicating when the block was created, represented as a `DateTime` in UTC.
- `tx_list`: A list of transactions included in the block.
... | ```rust
use chrono::{DateTime, Utc};
use sha2::{Digest, Sha256};
use ethereum_types::H256;
pub type BlockHeight = u64;
pub type BlockTxList = Vec<Transaction>;
pub struct Transaction {
// transaction fields
}
pub fn block_header_to_digest(
height: BlockHeight,
prev_blk_hash: H256,
time_stamp: DateTim... | magicoder | rust |
You are tasked with creating a Python function that processes a list of test cases and evaluates each test case using a custom evaluation function. The function should then assert that the evaluated value meets a specific condition using the `assertRaises` context manager from the `unittest` module.
Your task is to im... | ```python
from typing import List, Dict, Union, Callable
import ast
import unittest
def process_test_cases(test_cases: List[Dict[str, Union[str, bool]]], evaluation_function: Callable) -> None:
class TestEvaluation(unittest.TestCase):
pass
for idx, test in enumerate(test_cases):
value_to_evalu... | magicoder | python |
You are tasked with creating a Python unit test for a function that converts NumPy data types to schema field details. The function `details_from_numpy_dtype` takes a NumPy data type as input and returns details about the field, such as its name, data type, and other relevant information. Your goal is to write a unit t... | ```python
import unittest
from mock import Mock
from records_mover.records.schema.field.numpy import details_from_numpy_dtype
class TestDetailsFromNumpyDtype(unittest.TestCase):
def test_details_from_numpy_dtype_int(self):
mock_dtype = Mock()
mock_dtype.kind = 'i'
field_details = details_fr... | magicoder | python |
You are tasked with implementing a class that enforces a frequency constraint on a given operation. The class should allow the operation to be executed only if a certain amount of time has passed since the last execution. Your task is to implement the `FrequencyConstraint` class with the following specifications:
- Th... | ```python
import time
class FrequencyConstraint:
def __init__(self, frequency_constraint):
self._frequency_constraint = frequency_constraint
self._last_execution_time = 0
def can_execute(self):
current_time = time.time()
if current_time - self._last_execution_time >= self._freq... | magicoder | python |
You are tasked with creating a file storage logging system for a DAMS (Digital Asset Management System) client. The system should log information about uploaded files, including the subject ID, source file, and request URL. However, the system should also handle potential errors, such as IOExceptions, and ensure that t... | ```java
public void logFileStorage(DAMSClient damsClient, UploadTask uploadTask, FileWriter fileStoreLog) throws IOException {
try {
fileStoreLog.write(DAMSClient.stripID(uploadTask.getSubjectId()) + "\t"
+ uploadTask.getSourceFile() + "\t"
+ damsClient.getRequestURL() + "\n"... | magicoder | java |
You are tasked with creating a Python function that simulates a simple file system. Your function should be able to create, delete, and display files and directories within the file system. Additionally, it should be able to navigate through the file system and display the current working directory.
Your task is to im... | ```python
import os
def file_system(commands):
current_dir = "/"
outputs = []
for command in commands:
if command.startswith("create_file"):
file_name = command.split()[1]
open(current_dir + file_name, 'w').close()
elif command.startswith("create_dir"):
d... | magicoder | python |
You are tasked with creating a Python function that processes a given text file and removes all the comments from it. Comments in the file are marked by the # character, and any text following this character on a line should be considered a comment and removed.
Write a function `remove_comments(file_path: str) -> str`... | ```python
def remove_comments(file_path: str) -> str:
with open(file_path, 'r') as file:
lines = file.readlines()
result = ''
for line in lines:
if '#' in line:
line = line[:line.index('#')]
result += line
return result
``` | magicoder | python |
You are tasked with creating a program that analyzes Swift code to identify and count the occurrences of specific Swift declaration attribute kinds within a given source file. Swift declaration attributes are annotations that can be applied to declarations in Swift code, such as `@discardableResult`, `@objc`, `@availab... | ```swift
import Foundation
func countSwiftDeclarationAttributes(in sourceFile: String) -> [String: Int] {
var attributeCounts: [String: Int] = [:]
guard let fileContent = try? String(contentsOfFile: sourceFile) else {
print("Error: Unable to read the file.")
return attributeCounts
}
l... | magicoder | swift |
You are tasked with creating a Python decorator that records the execution of a function and its arguments. The decorator should be able to store the function name, arguments, and return value in a log file for later analysis. Your task is to implement the `@record_only()` decorator and apply it to the `test_policy_ins... | ```python
import functools
def record_only():
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
with open('function_log.txt', 'a') as log_file:
log_file.write(f"Function: {func.__name__}\n")
... | magicoder | python |
You are working on a software system that handles various types of commands and their corresponding reply data. The given code snippet is part of a larger system and contains two functions: `get_command_full` and `get_reply_data`. The `get_command_full` function takes a command name as input and returns the full detail... | ```python
_instruction_fields_key = {
"Command Type": 0, # Index for the command type in command_full list
"Reply Data": 1 # Index for the reply data in command_full list
}
# Example command_full list containing details of commands
command_full = [
["Command1", "ReplyData1"],
["Command2", "ReplyData2... | magicoder | python |
You are given a snippet of code that processes a file containing labeled features. The code reads the file line by line, splits each line into words, and appends the first word as a label and the remaining words as features to separate lists. Additionally, it extracts indexes from another file and maps them to integers... | ```python
from typing import List, Tuple, Dict
def process_features(labels: List[int], features: List[Tuple[int, List[str]]]) -> Dict[int, List[List[str]]]:
result = {}
for label, feature in zip(labels, features):
if label in result:
result[label].append(feature[1])
else:
... | magicoder | python |
You are tasked with implementing a function to build a dataset for training word embeddings using TensorFlow. The function should take a list of words and a vocabulary size as input and return the processed data, word counts, dictionary, and reverse dictionary.
The `build_dataset` function should process the input lis... | ```python
import collections
import numpy as np
def build_dataset(words, vocabulary_size):
count = [['UNK', -1]]
count.extend(collections.Counter(words).most_common(vocabulary_size - 1))
dictionary = dict()
for word, _ in count:
dictionary[word] = len(dictionary)
data = list()
unk_count... | magicoder | python |
You are tasked with simulating a simplified cryptocurrency exchange polling system using Python's asyncio library. The code snippet provided demonstrates an asynchronous process that fetches ticker data for specified cryptocurrency pairs and prints the symbol and ticker information. Your goal is to extend this code to ... | ```python
import asyncio
async def fetch_ticker_data(pairs):
ticker_data = {}
for pair in pairs:
try:
await asyncio.sleep(kraken.rateLimit / 1000) # Handle rate limiting
# Simulate fetching ticker data for the pair (replace with actual API call)
ticker_data[pair] = ... | magicoder | python |
You are tasked with implementing a class to represent an organizational structure. The class should be able to store the name of an employee and their subordinates. Each employee can have multiple subordinates, forming a hierarchical structure. Your task is to implement the `Employee` class with the following requireme... | ```python
class Employee:
def __init__(self, name):
self.name = name
self.subordinates = []
def add_subordinate(self, subordinate):
if isinstance(subordinate, Employee):
self.subordinates.append(subordinate)
else:
raise ValueError("Subordinate must be an ... | magicoder | python |
You are tasked with implementing a function to process audio channels based on the given configuration parameters. The function should handle the following parameters:
- `num_channels`: A positive integer representing the number of channels to be selected from the audio file. If this parameter is not specified, all ch... | ```python
def process_audio_channels(num_channels: int = None, convert_to_mono: bool = False) -> str:
# Assume audio data processing logic here
if num_channels is not None and num_channels < 1:
raise ValueError("num_channels should be a positive integer")
if convert_to_mono and num_channels == 1:
... | magicoder | python |
You are working on a Django project that involves creating a GraphQL API for analyzing files. The provided code snippet is a part of the GraphQL schema definition using graphene library in Django. The code defines a DjangoObjectType for Analysis, which has a field "files" that returns a list of NotebookType. Additional... | ```python
from .file import FileType, FileUploadType, NotebookType
class FileUpload(models.Model):
file_name = models.CharField(max_length=100)
file_type = models.CharField(max_length=50)
analysis = models.ForeignKey(Analysis, on_delete=models.CASCADE)
class FileUploadType(DjangoObjectType):
class Met... | magicoder | python |
You are tasked with implementing a function to manipulate a buffer chain data structure. The buffer chain consists of a series of buffers, each containing a contiguous block of data. The goal is to write a chunk of data to the buffer chain and then verify the correctness of the operation.
You are given the following i... | ```cpp
// Write a chunk of 'B' straddling all three buffers.
memset(buf.get(), 'B', kSecondCopy);
ASSERT_EQ(ZX_OK, mem_out.copy_array_to_user(buf.get(), kSecondCopy));
ASSERT_EQ(ZX_OK, bc->Append(mem_in, kSecondCopy));
// Verify it.
iter = bc->buffers()->begin();
for (size_t i = kOffset; i < BufferChain::kContig; ++i)... | magicoder | cpp |
You are tasked with creating a bash script to toggle the state of a microphone input on a Linux system using PulseAudio. The script should take two optional flags: `-t` to toggle the microphone state and `-s` to display the current source ID of the microphone. The script should enforce that only one of these flags is s... | ```bash
#!/bin/bash
# Function to display usage instructions
usage() {
echo "Usage: $0 [-t] [-s]"
exit 1
}
# Initialize flags
t_flag=0
s_flag=0
# Parse command line options
while getopts "ts" opt; do
case $opt in
t) t_flag=1 ;;
s) s_flag=1 ;;
*) usage ;;
esac
done
# Check tha... | magicoder | shell |
You are given a list of utility projects and a list of projects present in an input file. Each utility project has a weight associated with it, and the goal is to calculate the weight of each utility project based on its dependencies and the maximum distance allowed for dependencies. The weight of a utility project is ... | ```python
from typing import List
class Utility:
def __init__(self, name: str, dependencies: List[str], weight: int):
self.name = name
self.dependencies = dependencies
self.weight = weight
class Project:
def __init__(self, name: str, dependencies: List[str]):
self.name = name
... | magicoder | python |
You are tasked with implementing a custom error type in Swift for a service quotas management system. The system needs to handle various error scenarios, and you are required to define a specific error type for the case of encountering too many tags associated with a resource.
Your task is to create a custom error typ... | ```swift
// Custom error type for service quotas management system
enum ServiceQuotasErrorType: Error {
case tooManyTagsException
}
// Equatable conformance for ServiceQuotasErrorType
extension ServiceQuotasErrorType: Equatable {
static func == (lhs: ServiceQuotasErrorType, rhs: ServiceQuotasErrorType) -> Bool... | magicoder | swift |
You are tasked with creating a simple game to help users learn the names of U.S. states. The game will display an image of a map of the U.S. with the state names omitted. The user will then click on the map to guess the name of a state. When the user correctly guesses a state, the name of the state will be revealed on ... | ```python
import turtle
# Define a function to get the coordinates of the mouse click
def get_mouse_click_coor(x, y):
# Implement the logic to check if the click is within the boundaries of a state
# If the click is within a state, reveal the name of the state on the map
pass # Placeholder for the actual ... | magicoder | python |
You are tasked with implementing a simple messaging system using Combine framework in Swift. The system consists of a `MessageService` class that allows sending and receiving messages. The `MessageService` class has the following structure:
```swift
import Combine
class MessageService {
enum Event {
case ... | ```swift
func send(message: String) -> Publishers.Promise<Void, Error> {
let promise = Publishers.Promise<Void, Error> { promise in
// Simulate sending message asynchronously
DispatchQueue.global().async {
// Simulate successful sending of message
let success = true // Replac... | magicoder | swift |
You are tasked with implementing a simple Pub/Sub system using Python. The system should support the following operations: creating a new topic, listing all existing topics, and publishing a message to a specific topic.
You are given the following code snippet as a starting point:
```python
class PubSub:
def __in... | ```python
class PubSub:
def __init__(self):
self.topics = {}
def create_topic(self, topic_name):
if topic_name not in self.topics:
self.topics[topic_name] = []
print(f"Topic '{topic_name}' created successfully.")
else:
print(f"Topic '{topic_name}' alr... | magicoder | python |
You are tasked with creating a Python function that interacts with an API to download and upload comic images. The function should take in a comic ID and a token, and then use these parameters to download the comic image from a specific URL, upload it to a server, and save the comic details. The code snippet provided g... | ```python
import requests
from typing import Tuple
def process_comic(token: str, comic_id: int) -> Tuple[int, int]:
# Step 1: Download the comic image
comic_url = f"https://xkcd.com/{comic_id}/info.0.json"
response = requests.get(comic_url)
comic = response.json()
image_url = comic["img"]
respo... | magicoder | python |
You are tasked with creating a command-line tool that simulates a simple file versioning system. Your program should accept commands to manage and retrieve different versions of files. The commands your program should support are as follows:
1. `create <file_name>`: This command creates a new file with the given name ... | ```python
class FileVersioningSystem:
def __init__(self):
self.files = {}
def create(self, file_name):
self.files[file_name] = [""]
def append(self, file_name, content):
self.files[file_name].append(content)
def revert(self, file_name, version_number):
self.fil... | magicoder | python |
You are tasked with implementing a custom iterator in Rust that iterates over a forward iterable collection. The provided code snippet includes a partial definition of a `ForwardIterator` struct, which is intended to iterate over a forward iterable collection using a reference to an index type `I`. Your task is to comp... | ```rust
pub trait ForwardIterableIndex {
// Define the required methods for the ForwardIterableIndex trait
// For example:
// fn get_element(&self, index: u64) -> Option<&Element>;
}
pub struct ForwardIterator<'a, I>
where
I: ForwardIterableIndex,
{
index: &'a I,
i: u64,
}
impl<'a, I> ForwardI... | magicoder | rust |
You are given a list of lists representing a grid of buttons. Each inner list represents a row of buttons, and each element in the inner list represents a button. The value of each button can be either 0 or 1. You need to write a function that returns the number of adjacent pairs of buttons that have the same value, wh... | ```python
from typing import List
def count_adjacent_pairs(grid: List[List[int]]) -> int:
count = 0
rows = len(grid)
cols = len(grid[0])
for i in range(rows):
for j in range(cols):
if j < cols - 1 and grid[i][j] == grid[i][j + 1]:
count += 1
if i < rows ... | magicoder | python |
You are tasked with implementing a Python class that parses import statements from a given input line. The class should be able to identify and extract the module name and the imported item from the input line.
You are provided with a code snippet that contains a method `parse` within a Python class. The `parse` metho... | ```python
import re
class ImportLine:
def __init__(self, module_name, item_name):
self.module_name = module_name
self.item_name = item_name
class ImportParser:
def parse(self, line):
matches = re.match('^from[ ]+([^ ]+) import ([^ ]+)$', line)
if matches is None:
r... | magicoder | python |
You are working on a healthcare application that involves evaluating home visit actions for antenatal care. The application has a class `BaseAncHomeVisitAction` with various methods for evaluating different aspects of the home visit. One of the methods is `evaluateSubTitle()` which returns a formatted message for couns... | ```java
public class BaseAncHomeVisitAction {
private boolean childSafetyCounselling;
private Payload payload;
// Constructor and other methods are not shown for brevity
public String evaluateSubTitle() {
return MessageFormat.format("Counselled mother for child safety : {0}", childSafetyCounse... | magicoder | java |
You are tasked with creating a program that analyzes file data and generates a report containing information about file extensions and their corresponding file names and sizes. The program should read input data from a file, process it, and then write the report to a new file.
The input data consists of lines in the f... | ```csharp
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Program
{
static void Main()
{
Dictionary<string, Dictionary<string, decimal>> extFullNameSize = new Dictionary<string, Dictionary<string, decimal>>();
// Read input data from a file
str... | magicoder | csharp |
You are tasked with creating a web form that dynamically generates radio buttons based on a given configuration. The configuration is stored in an associative array `$config`, where each key-value pair represents a configuration item and its corresponding value. The form should display a radio button for each configura... | ```php
function generateConfigForm($config) {
$formHtml = '<form>';
foreach ($config as $config_item => $config_value) {
$formHtml .= '<tr>';
$formHtml .= '<td><strong>' . $config_item . '</strong></td>';
$formHtml .= '<td>';
$formHtml .= '<input type="radio" id="' . $config_item... | magicoder | php |
You are tasked with testing a Python web application using the `unittest` framework. The application includes a method `test_getAddedPictureExpires` that needs to be tested. The method is responsible for checking the expiration of added pictures in the server's information. Additionally, the test involves setting a spe... | ```python
import unittest
import datetime
import pytz
import json
class TestPictureExpires(unittest.TestCase):
def test_getAddedPictureExpires(self):
# Assuming the existence of testClient, appObj, and serverInfoWithoutAnyPictures
# Call the method to add a picture to the server
self.test_g... | magicoder | python |
You are tasked with implementing a function to calculate the transformed bounding box of a document within a canvas. The function will take in the canvas transformation and the size of the document, and it should return the transformed bounding box.
You are given the following code snippet as a starting point:
```cpp... | ```cpp
#include <QTransform>
#include <QRect>
QRect calculateTransformedBoundingBox(const QTransform& fromCanvas, const QSize& documentSize) {
QRect canvasRect = fromCanvas.mapRect(QRect(QPoint(), documentSize));
return canvasRect;
}
```
The `calculateTransformedBoundingBox` function takes in the `fromCanvas`... | magicoder | cpp |
You are tasked with implementing a class to represent a lattice structure and its associated methods. The lattice is a grid-like structure with rows and columns, and each cell in the lattice has a set of neighboring cells based on a specified distance metric. Your task is to implement the `Lattice` class with the follo... | ```python
from itertools import combinations, compress
class Lattice:
def __init__(self, n_rows, n_cols, distance_metric):
self.n_rows = n_rows
self.n_cols = n_cols
self.distance_metric = distance_metric
def euclidean_distance(self, x, y):
return ((x[0] - y[0])**2 + (x[1] - y[1... | magicoder | python |
You are tasked with implementing a simple elevator control system in Python. The elevator system should be able to handle requests to move the elevator up or down, and should also be able to report the current floor it is on. Additionally, the system should raise a custom exception if the elevator is already on the top... | ```python
class ElevadorJahNoUltimoAndarException(Exception):
pass
class Elevator:
def __init__(self, total_floors):
self.total_floors = total_floors
self.current_floor = 0
def move_up(self):
if self.current_floor == self.total_floors:
raise ElevadorJahNoUltimoAndarExce... | magicoder | python |
You are tasked with implementing a decorator system for composing audio effects in Python. The provided code snippet outlines the beginning of this system, with a decorator `effect` and an empty dictionary `EFFECTS` to store the composed effects.
The `effect` decorator is used to declare composable effects. When a fun... | ```python
"""Effect decorator for Noisemaker Composer Presets"""
EFFECTS = {}
def effect(func):
"""Function decorator for declaring composable effects."""
EFFECTS[func.__name__] = func
return func
def compose_effects(signal, *effect_names):
"""Compose and apply effects to the input signal."""
c... | magicoder | python |
You are tasked with implementing a data source plugin system in Python. The goal is to create a framework that allows for the definition of different data sources through plugins. Each plugin should be able to provide data from a specific source, such as a database, web service, or file.
Your task is to complete the i... | ```python
from dataclasses import dataclass
@dataclass
class DataSourcePlugin:
"""数据源插件,定义不同的数据源"""
name: str
description: str
def connect(self):
"""Establishes a connection to the data source."""
raise NotImplementedError("connect method must be implemented in a subclass")
def fe... | magicoder | python |
You are tasked with creating a Java program to simulate a simplified version of a scientific experiment using the concept of oscillations. The program will take input data and perform calculations to simulate the behavior of a system undergoing oscillations.
The input data consists of a string representing the dimensi... | ```java
public class ChimeraService {
public void init(InputData data) {
// Initialization logic for the simulation
}
}
public class InputData {
private String dimensions;
private int amplitude;
public InputData(String dimensions, int amplitude) {
this.dimensions = dimensions;
... | magicoder | java |
You are tasked with implementing a Python function to display images using the `imshow` function. The `imshow` function takes in various parameters to display images with different configurations. Your task is to create a function that can handle different input configurations and display the images accordingly.
You a... | ```python
import cv2
def display_images(*images, mode=None, window_title=None, title=None, padding=None):
if not images:
print("No images to display")
return
if isinstance(mode, str):
modes = [mode] * len(images)
elif isinstance(mode, list):
modes = mode
else:
m... | magicoder | python |
You are tasked with creating a Python function that sets up a self-assignable role feature for a Discord bot. The function `setupAddSelfrole` takes in five parameters: `plugin` (representing the Discord bot plugin), `ctx` (representing the context of the command), `name` (a string representing the name of the role), `r... | ```python
import discord
async def setupAddSelfrole(plugin, ctx, name, role, roles):
role_id = role.id
guild = ctx.guild
role_exists = discord.utils.get(guild.roles, name=name)
if not role_exists:
new_role = await guild.create_role(name=name)
roles.append(new_role)
else:
ro... | magicoder | python |
You are tasked with implementing a function that parses different types of errors into a specific error type for interpretation in the frontend. The function should handle various error types and transform them into a custom error type called `ExposureSubmissionError`. If the incoming error cannot be parsed to the expe... | ```swift
class ExposureSubmissionService {
func parseError(_ error: Error) -> ExposureSubmissionError {
if let enError = error as? ENError {
switch enError {
// Handle specific ENError cases and return corresponding ExposureSubmissionError
}
} else if let expo... | magicoder | swift |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.