query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a function that processes a computational graph and returns two dictionaries representing the nodes and edges of the graph.
The computational graph is represented using the following variables and data structures:
- `node`: A dictionary where the keys are unique identifiers for each no... | ```python
def process_graph(f_inputs):
node = {}
edge = {}
for i, input_ in enumerate(f_inputs, start=1):
node[i] = [input_.name, input_.input_shapes, input_.output_shapes]
creator_ids = [id(input_.creator) for input_ in f_inputs]
for creator_id, node_id in zip(creator_ids, node.keys())... | magicoder | python |
You are tasked with implementing a Spatial Channel-wise Squeeze and Excitation (SCSE) block in a deep learning framework. The SCSE block is a type of attention mechanism used to enhance the representational power of convolutional neural networks by adaptively recalibrating channel-wise feature responses. The block cons... | ```python
import torch
import torch.nn as nn
import torch.nn.functional as F
class SpatialAttention2d(nn.Module):
def __init__(self, in_channels):
super(SpatialAttention2d, self).__init__()
self.conv = nn.Conv2d(in_channels, 1, kernel_size=1, stride=1, padding=0)
def forward(self, x):
... | magicoder | python |
You are working on a script to manage data in a CouchDB database using cURL commands. The script includes commands to interact with different databases and perform operations such as creating, updating, and deleting documents. Your task is to write a function that simulates the execution of these cURL commands and retu... | ```python
import json
def simulate_curl_commands(base_url, curl_exec, json_files):
http_requests = []
for file_name, file_content in json_files.items():
if "design" in file_name:
http_requests.append(f"{curl_exec} -H 'Content-Type:application/json' -d @{file_name} -vX PUT '{base_url}/gb_me... | magicoder | python |
You are tasked with creating a Python program that calculates the average of a series of input numbers. The program should continuously prompt the user to enter numbers until they choose to stop. Once the user decides to stop entering numbers, the program should display the total count of numbers entered and the sum of... | ```python
total = 0
soma = 0
while True:
user_input = input("Enter a number (or 'stop' to finish): ")
if user_input.lower() == 'stop':
break
try:
valor = float(user_input)
total += 1
soma += valor
except ValueError:
print("Invalid input. Please enter a valid numb... | magicoder | python |
You are given a binary tree with the following structure:
```python
class Node:
def __init__(self, val, left=None, right=None, next=None):
self.val = val
self.left = left
self.right = right
self.next = next
```
The `next` pointer for each node is initially set to `None`. You need t... | ```python
class Node:
def __init__(self, val, left=None, right=None, next=None):
self.val = val
self.left = left
self.right = right
self.next = next
def connect(root: Node) -> None:
if not root:
return
if root.left:
root.left.next = root.right
if root.ri... | magicoder | python |
You are tasked with creating a secure user registration system for a university transportation service. The system should allow students to register their details, including name, year, department, bus number, bus route, email, and password. The registration data will be stored in a database using SQL.
Your task is to... | ```php
<?php
// Establish a connection to the MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "university_transportation";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check the connection
if ($conn->connect_error) {
die("Connection failed:... | magicoder | php |
You are tasked with simulating a simplified version of an Internet Relay Chat (IRC) system. In this scenario, you are required to implement a function that handles the process of a user joining a chat channel. The function should take the user's nickname, the list of available channels, and the client context as input.... | ```rust
fn handle_user_join(user: &str, chanlist: Vec<String>, client_ctx: &mut ClientContext) {
if user == *client_ctx.current_nickname() {
let join_delay = duration::ms(500);
let client_ref = client_ctx.as_ref().unwrap();
let channel_join_result = client_ref.send_join(&chanlist);
... | magicoder | rust |
You are tasked with implementing a function to check the header of a file. The header is considered valid if the first elements of the first two lines are of different lengths. If the header is invalid, an error message should be logged, and an exception should be raised.
You are given a code snippet that partially im... | ```python
def has_header(in_path):
"""Check if the input file has a header by examining the first two lines."""
with open(in_path, 'r') as file:
lines = [line.strip() for line in file.readlines()[:2]]
return len(lines) == 2 and len(lines[0]) != len(lines[1])
def log(message):
"""Log an erro... | magicoder | python |
You are tasked with creating a Makefile for a simple C program that uses the SDL2 library for graphics and image loading. The Makefile should compile the program using the GCC compiler and link it with the necessary SDL2 libraries. Your task is to write a Makefile that can compile the given C program and produce an exe... | ```make
CC = gcc
CFLAGS = -D__WINDOWS__ -I/mingw64/include/SDL2
LDFLAGS = -L/mingw64/lib/ -lSDL2 -lSDL2main -lSDL2_image -lm
all: $1
$1: $1.c
$(CC) $(CFLAGS) $1.c -o $1 $(LDFLAGS)
clean:
rm -f $1
```
In this Makefile solution:
- `CC` is defined as the GCC compiler
- `CFLAGS` contains the necessary compiler flags ... | magicoder | make |
You are tasked with creating a program that processes a CSV file containing time-stamped data and calculates the total time elapsed between each pair of consecutive timestamps. The CSV file contains two columns: the first column represents the timestamp in the format "YYYY-MM-DD HH:MM:SS" and the second column represen... | ```python
import csv
from datetime import datetime
# Function to calculate time difference in HH:MM:SS format
def calculate_time_difference(start_time, end_time):
time_format = "%Y-%m-%d %H:%M:%S"
start = datetime.strptime(start_time, time_format)
end = datetime.strptime(end_time, time_format)
time_dif... | magicoder | python |
You are working on a compiler for a new programming language called Futil. The Futil compiler translates Futil source code into an intermediate representation (IR) for further processing. As part of this process, you need to implement a function that transforms abstract syntax tree (AST) guard expressions into IR guard... | ```rust
fn build_guard(guard: GuardExpr, bd: &mut Builder) -> Result<Guard, FutilError> {
use GuardExpr::*;
let into_box_guard = |g: Box<GuardExpr>, bd: &mut Builder| -> Result<_, FutilError> {
Ok(Box::new(build_guard(*g, bd)?))
};
match guard {
None => Ok(Guard::True),
And(lef... | magicoder | rust |
You are tasked with implementing a theme-changing feature for a user interface. The `ChangeUiTheme` method takes an `ChangeUiThemeInput` object as input and is responsible for updating the UI theme based on the provided input. The `ChangeUiThemeInput` object contains the necessary information to determine the new theme... | ```csharp
public class UiThemeManager : IUiThemeManager
{
public async Task ChangeUiTheme(ChangeUiThemeInput input)
{
// Retrieve the selected theme name from the input
string selectedTheme = input.ThemeName;
// Apply the selected theme to the UI based on the theme name
switch (... | magicoder | csharp |
You are tasked with implementing a plugin system for a software application. The plugin system should allow for the dynamic loading and execution of plugin implementations. Each plugin implementation should adhere to a specific interface and provide a set of functionalities to the application.
Your task is to design a... | ```python
import importlib
from abc import ABC, abstractmethod
class PluginInterface(ABC):
@abstractmethod
def perform_action(self):
pass
class PluginSystem:
def __init__(self):
self.plugins = []
def register_plugin(self, plugin_module_name, plugin_class_name):
self.plugins.ap... | magicoder | python |
You are tasked with creating a custom annotation processor for a Java web framework. The framework uses annotations to define various aspects of HTTP request handling. Your goal is to implement a processor for a new custom annotation `@CustomEndpoint` that will be used to mark classes as endpoints for the web applicati... | ```java
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.Element;
import javax.lang.model.element.AnnotationMirror;
import java... | magicoder | java |
You are tasked with implementing a data processing function for a financial analysis system. The function takes a DataFrame containing financial data and performs specific operations to prepare the data for further analysis. The input DataFrame has columns "household_id", "asset_id", "t", "share", and "log_return". The... | ```python
import pandas as pd
def process_financial_data(input_df: pd.DataFrame) -> pd.DataFrame:
processed_df = (input_df
.groupby(["household_id", "asset_id"])
.agg({"share": "sum", "log_return": "mean"})
.reset_index()
.set_index(["... | magicoder | python |
You are tasked with creating a Django model for a user profile. The model should include fields for the user's ID, profile photo, bio, contact number, location, and a one-to-one relationship with the user's authentication model. Your task is to write the Django model code for the user profile, ensuring that the fields ... | ```python
from django.db import models
from django.conf import settings
import cloudinary.models
import phonenumber_field.modelfields
class Profile(models.Model):
id = models.AutoField(primary_key=True)
userPhoto = cloudinary.models.CloudinaryField(max_length=255, verbose_name='image')
bio = models.TextFie... | magicoder | python |
You are tasked with creating a custom logging system for a game mod. The game mod allows players to give gifts to non-player characters (NPCs) in the game, triggering custom dialogue reactions. Your goal is to implement a logging mechanism that captures any errors occurring during the handling of these custom gift reac... | ```csharp
public class GiftReactionLogger
{
public void LogError(string errorMessage, Exception exception)
{
// Implement the logging of the error message and exception details
ModMonitor.Log(errorMessage, LogLevel.Error);
ModMonitor.Log(exception.ToString());
}
}
public class GiftR... | magicoder | csharp |
You are given a list of integers representing the daily stock prices of a company. Your task is to write a function to calculate the maximum profit that can be obtained by buying and selling the stock on different days. However, you are only allowed to complete at most one transaction (i.e., buy one and sell one share ... | ```python
def maxProfit(prices):
if not prices or len(prices) == 1:
return 0
max_profit = 0
min_price = prices[0]
for price in prices:
if price < min_price:
min_price = price
else:
max_profit = max(max_profit, price - min_price)
return m... | magicoder | python |
You are tasked with creating a Python function that simulates a simple game of rock-paper-scissors. The function should take two arguments: the player's choice and the computer's choice. The function should then determine the winner based on the standard rules of rock-paper-scissors and return the result.
The standard... | ```python
def rock_paper_scissors(player_choice, computer_choice):
if player_choice == computer_choice:
return "It's a tie!"
elif (player_choice == 'rock' and computer_choice == 'scissors') or \
(player_choice == 'scissors' and computer_choice == 'paper') or \
(player_choice == 'paper'... | magicoder | python |
You are tasked with implementing a C++ program that involves two classes, `class_a` and `class_b`. The `class_a` has private data members `width` and `high`, a constructor, a destructor, and a member function `print_info()`. The `class_b` is not fully defined in the given code snippet. Your task is to complete the defi... | ```cpp
class class_a {
private:
int width, high;
public:
class_a(int _w, int _h) : width(_w), high(_h) {} // Constructor to initialize width and high
~class_a() {} // Destructor to release any allocated resources
void print_info(void) { // Member function to print width and high
std::cout << ... | magicoder | cpp |
You are given a list of strings, each representing a word. Your task is to write a function that justifies the text by evenly distributing spaces between the words to make each line of text in the justified format. The justified format means that the words in each line are aligned to both the left and right sides of th... | ```python
from typing import List
def justify_text(words: List[str], line_length: int) -> List[str]:
result = []
current_line = []
current_length = 0
for word in words:
if current_length + len(word) + len(current_line) <= line_length:
current_line.append(word)
current_l... | magicoder | python |
You are given a string containing a Chinese proverb and a comment in the form of a Python code snippet. Your task is to extract the Chinese proverb from the given string and print it in its original language.
The input string will consist of the following components:
1. A comment in the form of a Python code snippet, ... | ```python
import re
def extract_chinese_proverb(input_string: str) -> str:
chinese_proverb = re.search(r'[\u4e00-\u9fff]+', input_string).group()
return chinese_proverb
# Test the function with the given example
input_string = '''
print("Result:", result)
# 对影成三人。
'''
print(extract_chinese_proverb(input_strin... | magicoder | python |
You are tasked with creating a Rust function that manipulates file permissions based on the target operating system. The function should handle both Windows and Unix-like systems, setting the executable permissions for a given file path.
Your task is to implement the `set_executable` function, which takes a file path ... | ```rust
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
fn set_executable(path: &Path) {
#[cfg(target_family = "windows")]
{
// No action required for Windows
}
#[cfg(target_family = "unix")]
{
let metadata = fs::metadata(path).expect("Failed to get test run... | magicoder | rust |
You are tasked with implementing a macro system for a custom string matching library in Rust. The library aims to provide functionality for exact string matching and detecting false positives. The provided code snippet is a starting point for defining macros that will be used in the library.
Your task is to extend the... | ```rust
macro_rules! fallback_escaping {
// Define macro rule for exact match
($fa:expr, 128, ) => {
// Implement exact match logic here
println!("Exact match: {}", $fa);
};
// Define macro rule for false positive
($fa:expr, $val:expr, ) => {
// Implement false positive ... | magicoder | rust |
You are tasked with implementing a content delivery system that retrieves plurals data from an API and handles the storage of ETags. The system uses a completion handler to process the retrieved data and any potential errors. Your goal is to write a function that encapsulates this behavior.
You are given the following... | ```swift
func getPlurals(filePath: String, etag: String?, completion: @escaping ([PluralData]?, Error?) -> Void) {
contentDeliveryAPI.getPlurals(filePath: filePath, etag: etag, timestamp: nil, completion: { [weak self] (plurals, etag, error) in
guard let self = self else { return }
self.eTagStorage.... | magicoder | swift |
You are working on a software versioning system and need to create a function that extracts the version number from a given Python package name and version string. The version string follows the semantic versioning format (major.minor.patch), and the package name may contain alphanumeric characters and slashes.
Write ... | ```python
import re
def extract_version(package_name: str, version_string: str) -> str:
pattern = r"__version__ = '([\d\.]+-?\w*)'"
match = re.search(pattern, version_string)
if match:
return match.group(1)
else:
return "Version number not found"
``` | magicoder | python |
You are tasked with implementing a custom caching system using Java. The cache should have a maximum capacity and support two operations: `put` and `get`. The `put` operation adds a key-value pair to the cache, and if the cache is at its maximum capacity, it should evict the least recently used item before adding the n... | ```java
import java.util.HashMap;
import java.util.Map;
class LRUCache {
class Node {
int key;
int value;
Node prev;
Node next;
}
private void addNode(Node node) {
node.prev = head;
node.next = head.next;
head.next.prev = node;
head.next = n... | magicoder | java |
You are tasked with implementing a cave exploration algorithm. The caves are represented as a graph, and the goal is to find all possible paths from the "start" cave to other caves. Each cave can be connected to multiple other caves through tunnels.
You are given a `Cave` struct and a `Map` struct with the following m... | ```rust
impl Map {
fn enter(&self) -> Vec<Vec<Cave>> {
let mut paths = Vec::new();
if let Some(start) = self.caves.get("start") {
self.explore(&start, vec![start.clone()], &mut paths);
}
paths
}
fn explore(&self, cave: &Cave, mut current_path: Vec<Cave>, paths: &... | magicoder | rust |
You are tasked with creating a neural network model to classify images of handwritten digits. The dataset consists of grayscale images of size 28x28 pixels. Your goal is to implement a Python function that trains the neural network model using PyTorch and evaluates its performance on a test dataset.
You are provided w... | ```python
def train_func(model, loader, loss_func, optimizer, device):
# Set the model to training mode
model.train()
# Define the device for training
device = torch.device(device)
# Move the model to the specified device
model.to(device)
# Training the model
for epoch in range(num_ep... | magicoder | python |
You are tasked with creating a Python function that retrieves and processes auction data from the World of Warcraft (WoW) API. The function should take an API key and a realm name as input and return the average auction price for a specific item.
You are provided with the following code snippet for inspiration:
```pyt... | ```python
import requests
def get_average_auction_price(api_key: str, realm: str, item_id: int) -> float:
request_uri = f"https://eu.api.battle.net/wow/auction/data/{realm}?locale=en_US&apikey={api_key}"
response = requests.get(request_uri)
if response.status_code == 200:
auction_data = respon... | magicoder | python |
You are tasked with implementing a waypoint blocking system for a drone's flight control software. The drone is equipped with a MAV (Micro Air Vehicle) object that provides methods for controlling its movement. The code snippet provided demonstrates the usage of the MAV object to send waypoint blocking and run a circle... | ```python
class DroneController:
def __init__(self, mav_obj):
self.mav_obj = mav_obj
def send_waypoint_blocking(self, x, y, z, yaw, vel, acc, relative):
self.mav_obj.send_wp_block(x, y, z, yaw, vel, acc, relative)
def run_circle_tracker(self, Ax, Ay, T, num_repetitions):
self.mav_o... | magicoder | python |
You are tasked with implementing a Bayesian Neural Network (BNN) for a classification problem using PyTorch. A BNN is a type of neural network that incorporates uncertainty in its weights, making it suitable for tasks where uncertainty is a crucial factor, such as in medical diagnosis or financial predictions.
Your ta... | ```python
import torch
import torch.nn as nn
import pyro
import pyro.distributions as dist
from pyro.infer import SVI, Trace_ELBO
from pyro.optim import Adam
class BayesianNN(nn.Module):
def __init__(self, input_dim, hidden_dims, output_dim):
super(BayesianNN, self).__init__()
self.input_dim = inpu... | magicoder | python |
You are tasked with implementing a debounce function in JavaScript. The debounce function is a higher-order function that takes in a function and a delay time as parameters. It returns a new function that will only execute the original function if it has not been called again within the specified delay time. If the ori... | ```javascript
function set_debounce_counter(func, delay) {
let timeoutId;
return function() {
clearTimeout(timeoutId);
timeoutId = setTimeout(func, delay);
};
}
function $create(func, delay) {
return set_debounce_counter(func, delay);
}
``` | magicoder | javascript |
You are tasked with creating a Python function that retrieves and processes contest standings data from an online platform. The function should take the contest ID, a list of usernames, and a penalty value as input parameters. The contest standings data should be fetched and saved into a CSV file, including the usernam... | ```python
import conmato
import pandas as pd
def get_standings_to_csv(contest_id, usernames, penalty):
# Fetch contest standings data
standings_data = conmato.fetch_standings(contest_id)
# Filter standings data for the specified usernames
filtered_standings = standings_data[standings_data['username'].... | magicoder | python |
You are tasked with implementing a vote tracking system for a set of items. The system should allow users to vote on items, with each user being able to cast both positive and negative votes. Additionally, the system should be able to retrieve the scores and number of votes for each item.
You are given a code snippet ... | ```python
class Vote:
def __init__(self):
self.votes = {} # Dictionary to store votes for each item
def record_vote(self, item, user, vote_value):
if item not in self.votes:
self.votes[item] = {'score': 0, 'num_votes': 0}
self.votes[item]['score'] += vote_value
self... | magicoder | python |
You are tasked with implementing a custom resource management system for a software application. The system should allow for the efficient localization and management of various resources, such as labels, text, and images, within the application's user interface.
Your task is to design a class or set of classes that c... | ```python
class ResourceManager:
def __init__(self):
self.resources = {}
def load_resources(self, file_path):
# Load resources from the specified file (e.g., XML or JSON)
# Populate self.resources with the loaded data
pass
def add_resource(self, key, value):
# Add a... | magicoder | python |
You are tasked with creating a program that analyzes data from a fictional stock market. The data is represented as a series of stock prices over time. Your goal is to implement a function that calculates the maximum profit that can be obtained by buying and selling a single share of the stock at the right time.
You a... | ```typescript
function maxProfit(prices: number[]): number {
let maxProfit = 0;
let minPrice = Infinity;
for (let price of prices) {
if (price < minPrice) {
minPrice = price;
} else if (price - minPrice > maxProfit) {
maxProfit = price - minPrice;
}
}
... | magicoder | typescript |
You are tasked with implementing a function for Mel-frequency cepstral coefficients (MFCC) feature extraction. MFCC is a widely used technique in speech and audio processing for extracting features that represent the short-term power spectrum of a sound. The MFCC feature extraction process involves several steps, inclu... | ```python
import numpy as np
import scipy.fftpack as fft
from scipy.signal import get_window
def calculate_mfcc(audio_signal, sample_rate, num_mfcc_features):
# Step 1: Pre-emphasis
pre_emphasized_signal = np.append(audio_signal[0], audio_signal[1:] - 0.97 * audio_signal[:-1])
# Step 2: Framing
frame_... | magicoder | python |
You are tasked with implementing a simplified version of a state management system similar to Redux in TypeScript. You will need to create classes and interfaces to represent the core components of the system and ensure that they adhere to the specified requirements.
Your task is to define the following classes and in... | ```typescript
// Define the Action interface
interface Action {
type: string;
}
// Define the Reducer interface
interface Reducer<State, Action> {
(state: State, action: Action): State;
}
// Define the Observable interface
interface Observable<State> {
subscribe(observer: (state: State) => void): Unsubscribe;
}... | magicoder | typescript |
You are tasked with implementing a 2D Gaussian Mixture Model (GMM) using Python. A Gaussian Mixture Model is a probabilistic model that assumes all the data points are generated from a mixture of several Gaussian distributions with unknown parameters. Your task is to create a Python class that can fit a GMM to a given ... | ```python
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import multivariate_normal
class GaussianMixtureModel:
def __init__(self, n_components):
self.n_components = n_components
self.means = None
self.covariances = None
self.weights = None... | magicoder | python |
You are tasked with implementing a port factory that creates port products based on the input ports string. The port factory has two types of port products: SplitPort and HyphenPort. The input ports string can contain individual ports, port ranges separated by hyphens, or multiple ports separated by commas.
You need t... | ```java
public class PortFactory {
PortProduct portProduct = null;
public PortProduct create(String[] portsList, List<String> tempPorts, String ports) {
if (ports.contains(",")) {
portProduct = new SplitPort(portsList, ports);
} else if (ports.contains("-")) {
portProduc... | magicoder | java |
You are tasked with creating a Python program to decrypt data using RSA encryption. The program should read encrypted data from a file named "encrypted_data.bin" and use a private key from a file named "private.pem" to decrypt the data.
Your task is to complete the Python program by implementing the decryption process... | ```python
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
import binascii
# Step 1: Read the encrypted data from the file
with open("encrypted_data.bin", "rb") as file_in:
encrypted_data = file_in.read()
# Step 2: Import the private key from the file
private_key = RSA.import_key(open("privat... | magicoder | python |
You are tasked with implementing a Python decorator that caches the result of a function for a specified period of time. The decorator should store the function's return value in a cache and return the cached value if the function is called again with the same arguments within the specified time period. If the cache ha... | ```python
import time
def cache(expiry_time):
def decorator(fn):
cache_data = {}
def wrapper(*args, **kwargs):
key = (fn.__name__, args, frozenset(kwargs.items()))
if key in cache_data:
result, timestamp = cache_data[key]
if time.time() - tim... | magicoder | python |
You are tasked with implementing a function that processes a CSV file and performs specific operations based on the data it contains. The CSV file contains information about different styles of music and their associated countries. Each row in the CSV file represents a music style and its country. The function needs to... | ```python
def process_csv(headers, data):
music_styles_count = {}
country_music_styles = {}
for row in data:
style, country = row
# Count occurrences of each music style
if style in music_styles_count:
music_styles_count[style] += 1
else:
music_st... | magicoder | python |
You are tasked with creating a Python function that generates a map with a marker at a specified longitude and latitude. The function should also allow for adding text to the marker and setting a title for the map. You are provided with a code snippet that sets credentials for accessing a service and a function signatu... | ```python
import folium
def draw_map(lon, lat, text, titre='NO TITLE'):
# Create a map centered at the specified coordinates
map_obj = folium.Map(location=[lat, lon], zoom_start=12)
# Add a marker with the specified text at the given coordinates
folium.Marker([lat, lon], popup=text).add_to(map_obj)
... | magicoder | python |
You are tasked with implementing a function that checks whether a given string is a valid Java package name. A valid package name is a series of identifiers separated by periods, where each identifier must start with a letter and can be followed by any combination of letters, digits, or underscores. Additionally, the p... | ```java
public boolean isValidPackageName(String packageName) {
String[] identifiers = packageName.split("\\.");
for (String identifier : identifiers) {
if (!isValidIdentifier(identifier)) {
return false;
}
}
return true;
}
private boolean isValidIdentifier(String identifier... | magicoder | java |
You are tasked with implementing a function that checks whether a given string contains a specific pattern. The pattern is defined using a simple wildcard character '*' which can match any sequence of characters, including an empty sequence. The function should return true if the string matches the pattern, and false o... | ```swift
func matches(_ pattern: String, _ string: String) -> Bool {
let patternLength = pattern.count
let stringLength = string.count
var dp = Array(repeating: Array(repeating: false, count: stringLength + 1), count: patternLength + 1)
dp[0][0] = true
for i in 1...patternLength {
if patter... | magicoder | swift |
You are working on a script to manage a testbed configuration file called `testbed.sh`. The script is intended to extract a specific section of the file based on the IP address assigned to the `eth0` interface and then update the `testbed.sh` file with the extracted section. Your task is to write a script that automate... | ```bash
#!/bin/bash
# Get the IP address assigned to eth0 interface
MANAGMENT_IP=$( ip -4 addr show dev eth0 | grep -m 1 "inet " | awk '{print $2}' | cut -d "/" -f 1 )
# Extract the section containing "general" from testbed.sh and save it to tbs.sh
START_END=( $(grep -F general testbed.sh -n | cut -d ":" -f 1) )
sed ... | magicoder | shell |
You are given a code snippet that contains a nested class structure and a nested enum declaration. Your task is to write a program that can parse this code snippet and extract the class and enum names.
Write a function or method called `parseCode` that takes the code snippet as input and returns a list of class and en... | ```python
import re
def parseCode(code):
class_pattern = r'class\s+([A-Za-z0-9_]+)'
enum_pattern = r'enum\s+([A-Za-z0-9_]+)'
class_names = re.findall(class_pattern, code)
enum_names = re.findall(enum_pattern, code)
return class_names + enum_names
# Test the function with the given code snippet
c... | magicoder | python |
You are tasked with implementing a custom `take_until` method for a reader type in Rust. The `take_until` method should read from the reader until a specified delimiter is encountered, and then stop reading. Your task is to create a struct `TakeUntil` and implement the `AsyncRead` trait for it, allowing it to be used w... | ```rust
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::io::{AsyncRead, ReadBuf};
pub struct TakeUntil<R> {
reader: R,
delim: u8,
buffer: Vec<u8>,
done: bool,
}
impl<R: AsyncRead + Unpin> TakeUntil<R> {
pub fn new(reader: R, delim: u8) -> Self {
TakeUntil {
reader... | magicoder | rust |
You are tasked with creating a program to calculate the frequencies of musical notes in an octave. The frequencies of musical notes follow a specific pattern based on the equal temperament tuning system. In this system, the frequency of a note is calculated as a multiple of the frequency of the note A4 (440 Hz). The fr... | ```python
def calculate_frequency(note):
notes = {'A': 0, 'A#': 1, 'B': 2, 'C': 3, 'C#': 4, 'D': 5, 'D#': 6, 'E': 7, 'F': 8, 'F#': 9, 'G': 10, 'G#': 11}
if note.upper() in notes:
n = notes[note.upper()]
frequency = 2 ** (n / 12) * 440
return frequency
else:
return "Inval... | magicoder | python |
You are tasked with implementing a custom font name transformer in Python. The transformer should take the font name of a font as stored in user defaults and return the displayed font name of the font to show to the user. You are provided with a code snippet that sets up the foundation for the transformer using Objecti... | ```python
class FontNameToDisplayNameTransformer:
"""
Takes as input the fontName of a font as stored in user defaults,
returns the displayed font name of the font to show to the user.
"""
@classmethod
def transformedValueClass(cls):
return str
@classmethod
def allowsReverseTran... | magicoder | python |
You are tasked with implementing a custom permission class in a Django REST Framework (DRF) project. The custom permission class should restrict access to a specific view that removes a sport from the system. The permission class should only allow authenticated users to perform this action.
You are provided with the f... | To implement the custom permission class for restricting access to the view that removes a sport, follow these steps:
1. Create a new file named `permissions.py` in the Django app directory if it doesn't exist.
2. In the `permissions.py` file, define a custom permission class as follows:
```python
from rest_framewor... | magicoder | python |
You are tasked with creating a Python script that takes command-line arguments to encrypt a configuration file using AES encryption. The script should utilize the `argparse` module to handle the command-line arguments. The provided code snippet serves as a starting point for the script and includes the setup for handli... | ```python
import argparse
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
def encrypt_config(outfile, key, serial):
try:
with open('config_file.txt', 'rb') as file:
... | magicoder | python |
You are tasked with implementing a method in the `BoardChanger` class that will allow for the movement of a draught (a game piece) on a board represented by an array of squares. The `BoardChanger` class has the following properties:
- `squares`: An array of `Square` objects representing the board squares.
- `wDraughts`... | ```typescript
import { Draught } from './draught';
import { Square } from './square';
export class BoardChanger {
squares: Square[];
wDraughts: Draught[];
moveDraught(draughtId: string, newSquareId: string): void {
const selectedDraught = this.wDraughts.find(draught => draught.id === draughtId);
const n... | magicoder | typescript |
You are tasked with implementing a Python class that serves as a client for a synchronous dictionary API. The API client should be able to perform various dictionary-related operations, such as adding, retrieving, updating, and deleting key-value pairs. The client should use the `httpx` package for making HTTP requests... | ```python
import logging
import typing
import httpx
class DictionaryApiClient(BaseDictionaryApiClient):
def __init__(self, api_url: str):
super().__init__(api_url)
self.client = httpx.Client()
def add_entry(self, key: str, value: str) -> bool:
try:
response = self.client.po... | magicoder | python |
You are tasked with implementing a function to load a model from a file in a legacy OCR (Optical Character Recognition) engine. The legacy engine is encapsulated within a class named `tesseract`, and the function `LoadFromFile` is responsible for loading a model from a specified file path.
The function `LoadFromFile` ... | ```cpp
#ifndef DISABLED_LEGACY_ENGINE
static bool LoadFromFile(tesseract::ParamsModel &model, const char *lang, const char *full_path) {
tesseract::TFile fp;
if (!fp.Open(full_path, "rb")) {
// Failed to open the file for reading
return false;
}
// Assuming the model loading logic is encapsulated withi... | magicoder | cpp |
You are tasked with creating a program to solve a dice pairing problem. Given a set of dice with unique names and a number of pairs, your program should find all possible pairings of the dice such that each pair consists of two distinct dice names. Additionally, the program should enumerate all valid pairings.
You are... | ```python
from itertools import permutations
def generate_dice_pairings(dice_names, num_pairs):
dice_pairs = list(permutations(dice_names, 2))
pairings = []
for _ in range(num_pairs):
pairings.extend(dice_pairs)
return pairings
# Example usage
dice_names = ["A", "B", "C"]
num_pairs = 2
result ... | magicoder | python |
You are tasked with creating a script that checks for the existence of the `jps` executable in a Java environment. The script should first attempt to locate the `jps` executable in the system's default paths. If it is not found, the script should then check for the `jps` executable in the `bin` directory of the specifi... | ```bash
#!/bin/bash
# Check if jps executable exists in default paths
if command -v jps &> /dev/null; then
JPS_EXECUTABLE_BIN="jps"
else
# Check if JAVA_HOME is set
if [ -n "$JAVA_HOME" ] && [ -x "$JAVA_HOME/bin/jps" ]; then
JPS_EXECUTABLE_BIN="${JAVA_HOME}/bin/jps"
else
echo "jps execu... | magicoder | shell |
You are tasked with implementing a data cleaning algorithm for a sensor data processing system. The system has two methods for reading data: `_read_data` and `_read_dirty_data`. The `_read_data` method returns sensor data without any noise, while the `_read_dirty_data` method is intended to return sensor data with nois... | ```python
import random
class SensorDataProcessor:
def __init__(self, data):
self._data = data
def _read_data(self):
"""Get Sensor data without noise"""
return self._data
def _read_dirty_data(self, noise_range=(-0.1, 0.1)):
"""Get Sensor data with noise"""
noisy_da... | magicoder | python |
You are given a code snippet that represents the application of constraints to slave degrees of freedom (dofs) in a finite element analysis context. The code iterates over the rows of a relation matrix and calculates a modified constant vector based on the relation matrix and the values of master dofs. Your task is to ... | ```cpp
#include <vector>
std::vector<double> ApplyConstraint(const std::vector<std::vector<double>>& relationMatrix, const std::vector<double>& constantVector, const std::vector<double>& masterDofsValues) {
std::vector<double> modifiedConstantVector(constantVector.size(), 0.0);
for (size_t i = 0; i < relation... | magicoder | cpp |
You are working on a particle physics analysis project and need to implement a custom particle flow candidate selector using the Particle Flow Candidate (PFCandidate) objects. The provided code snippet is a part of the framework for this task. Your goal is to understand the code and create a custom PFCandidate selector... | ```cpp
#include "CommonTools/UtilAlgos/interface/ObjectSelectorStream.h"
#include "CommonTools/ParticleFlow/interface/IPCutPFCandidateSelectorDefinition"
// Custom PFCandidate selector class
class CustomPFCandidateSelector : public IPCutPFCandidateSelector {
public:
// Constructor
CustomPFCandidateSelector(con... | magicoder | cpp |
You are tasked with implementing a parser for RDF (Resource Description Framework) Turtle syntax, a widely used format for representing RDF data. The given code snippet defines a set of regular expressions for parsing specific components of Turtle syntax. Your goal is to utilize these regular expressions to build a par... | ```python
import re
def parseTurtle(input: str) -> dict:
components = {
"IRIREF": r"<([^\\x00-\\x20\<\>\\"\\{\\}\\|\\^`\\\\]|\\\\u[0-9A-Fa-f]{4}|\\\\U[0-9A-Fa-f]{8})*>",
"STRING_LITERAL_QUOTE": r"\"([^\\x22\\x5C\\x0A\\x0D]|\\t|\\b|\\n|\\r|\\f|\\\"|\\\\|\\\\u[0-9A-Fa-f]{4}|\\\\U[0-9A-Fa-f]{8})*\"",
... | magicoder | python |
You are tasked with creating a Python program to process email headers and organize emails into folders based on the sender's email address. The program should read a list of email headers and create a folder for each unique sender's email address. The email headers are represented as a list of dictionaries, where each... | ```python
def organize_emails(headers):
organized_emails = {}
for header in headers:
name = header.get("name")
value = header.get("value")
if name == 'From':
sender = value
if sender not in organized_emails:
organized_emails[sender] = [header]
... | magicoder | python |
You are tasked with implementing a function that will parse a given C++ namespace and extract all the nested namespaces and classes within it. The function should return a list of all the nested namespaces and classes found within the given namespace.
You are provided with a code snippet that represents a C++ namespac... | ```cpp
#include <iostream>
#include <vector>
#include <regex>
std::vector<std::string> extractNestedElements(const std::string& namespaceStr) {
std::vector<std::string> nestedElements;
// Regular expression to match nested namespaces and classes
std::regex nestedRegex("\\b" + namespaceStr + "::(\\w+)");
... | magicoder | cpp |
You are tasked with implementing a learning rate scheduler for a neural network training process. The learning rate scheduler is responsible for adjusting the learning rate during the training process to improve convergence and performance. The provided code snippet is a part of the learning rate scheduler implementati... | ```python
import warnings
class LearningRateScheduler:
def __init__(self, base_lr):
# Initialize the learning rate scheduler with the base learning rate
self.base_lr = base_lr
def adjust_learning_rate(self, epoch):
# Adjust the learning rate based on the training progress or other rele... | magicoder | python |
You are tasked with implementing a function that takes a string as input and returns the frequency of each character in the string as a dictionary. The function should ignore spaces and be case-insensitive, treating uppercase and lowercase letters as the same character.
The function signature is:
```python
def charact... | ```python
def character_frequency(input_string: str) -> dict:
# Remove spaces and convert the string to lowercase
input_string = input_string.replace(" ", "").lower()
# Initialize an empty dictionary to store character frequencies
frequency_dict = {}
# Iterate through the characters in the... | magicoder | python |
You are tasked with implementing a class for a humanoid robot's movement control system. The robot has various methods for controlling its movements, and you need to implement two specific methods: `spine_horizontal` and `feet_moving_towards_each_other`.
The `spine_horizontal` method is responsible for controlling the... | ```python
class RobotMovementControl:
def __init__(self):
# Initialize any necessary variables or state for the robot movement control
pass
def spine_horizontal(self, frameIndex):
"""
Adjusts the horizontal movement of the robot's spine based on the given frame index.
... | magicoder | python |
You are tasked with implementing a class for learning rate scheduling in a machine learning framework. The class should support two types of learning rate schedules: constant and linear decay with warmup. The class should be able to handle the initialization of the learning rate schedule based on the specified type and... | ```python
class ConstScheduleWithWarmup:
def __init__(self, lr, warmup):
self.lr = lr
self.warmup = warmup
def get_learning_rate(self, step):
if step < self.warmup:
return self.lr * (step / self.warmup)
else:
return self.lr
class LinearDecayWithWarmup:
... | magicoder | python |
You are tasked with creating a command-line tool that bundles and runs JavaScript tests using the following command-line arguments and options:
Command:
```
test-runner.sh <test_file> <source_file>
```
Options:
- `--no-minify`: Do not minify the test bundle.
- `-d <directory>`: Specify the output directory for the te... | ```bash
#!/bin/bash
# Parse command-line arguments
test_file=$1
source_file=$2
output_directory="./puretest/.dist/"
output_file="test-bundle.js"
minify=true
source_maps=true
# Process options
while [[ $# -gt 0 ]]; do
case "$1" in
--no-minify)
minify=false
shift
;;
... | magicoder | shell |
You are tasked with implementing a Python function that reads and processes data from a set of doctest files. Each doctest file contains a series of test cases, and your function should extract and execute these test cases, returning the results in a structured format.
You are provided with a code snippet that sets up... | ```python
import doctest
import os
def process_doctests(DOCFILES, globs):
results = []
for file_path in DOCFILES:
if os.path.exists(file_path):
with open(file_path, 'r') as file:
doctest_string = file.read()
test = doctest.DocTestParser().get_doctest(doctest_... | magicoder | python |
You are tasked with creating a script to automate the build process for a software project. The script should handle different operating systems and execute the necessary commands to build and install the project. The build process involves creating a directory, checking out a specific branch from a version control sys... | ```bash
#!/bin/bash
# Check the operating system type
if [[ "$OSTYPE" == "darwin"* ]]; then
# macOS specific commands
mkdir build
git checkout concat # temporary testing
../libhdfs3/bootstrap --prefix=$PREFIX --dependency=$PREFIX --enable-libc++
make
make install
else
# Linux specific comma... | magicoder | shell |
You are tasked with implementing a simple module builder framework in Swift. The framework should allow the creation of modules consisting of a view controller, a router, and a presenter. The provided code snippet is a starting point for the implementation. Your task is to complete the implementation of the module buil... | ```swift
import UIKit
// Implementation of FromViewController
class FromViewController: UIViewController {
// Implement the view controller as per the requirements
}
// Implementation of FromRouter
class FromRouter<ViewController: UIViewController> {
let viewController: ViewController
init(with viewContr... | magicoder | swift |
You are tasked with implementing a custom string manipulation function in C++. The function should take a string as input and split it into multiple parts based on a delimiter. Additionally, the function should count the number of parts created and store the individual parts in a vector.
Your task is to complete the i... | ```cpp
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
std::vector<std::string> parts;
int part_num = 0;
void splitString(const std::string& input, char delimiter) {
std::stringstream ss(input);
std::string part;
while (std::getline(ss, part, delimiter)) {
parts.push_bac... | magicoder | cpp |
You are tasked with implementing a function to calculate the total cost of a trade based on the given trade details. The trade details include the quantity of the base asset, the price of the quote asset, the side of the trade (buy or sell), and the quantity of the contract (if applicable). The total cost is calculated... | ```rust
enum TradeSide {
Buy,
Sell,
}
fn calculate_total_cost(quantity_base: f64, quantity_quote: f64, side: TradeSide) -> i64 {
let total_cost = match side {
TradeSide::Buy => (quantity_base * quantity_quote) as i64,
TradeSide::Sell => (quantity_quote * quantity_base) as i64,
};
to... | magicoder | rust |
You are tasked with implementing a class that handles the extraction of files from an archive. The given code snippet outlines the interface and private member variables of the class. Your task is to complete the implementation of the class by providing the necessary member functions and variables.
Your class, named `... | ```cpp
#include <iostream>
#include <string>
// Define the ISequentialOutStream interface
class ISequentialOutStream {
// Define the interface methods
};
// Define the IArchiveExtractCallback interface
class IArchiveExtractCallback {
public:
// Define the interface methods
virtual STDMETHOD( GetStream )( ... | magicoder | cpp |
You are tasked with implementing a reinforcement learning agent using a neural network for a simple game environment. The agent's neural network has been partially implemented using TensorFlow, and your task is to complete the implementation by defining the `restore` method. The `restore` method is responsible for rest... | ```python
def restore(self, sess, checkpoint_file):
saver = tf.train.Saver()
saver.restore(sess, checkpoint_file)
```
In the `restore` method, a `tf.train.Saver` object is created to handle the restoration of the model's weights. The `saver.restore` function is then used to restore the model's weights from the... | magicoder | python |
You are tasked with creating a Rust function that generates a transaction payload for a blockchain network. The function should take in various parameters and construct a transaction payload according to specific requirements.
You are provided with a code snippet that imports various modules and types from the `aptos_... | ```rust
use aptos_crypto::ed25519::Ed25519PublicKey;
use aptos_global_constants::{
APTOS_ROOT_KEY, MOVE_MODULES, OPERATOR_KEY, OWNER_KEY, TREASURY_COMPLIANCE_KEY,
};
use aptos_management::constants::{self, VALIDATOR_CONFIG, VALIDATOR_OPERATOR};
use aptos_secure_storage::{KVStorage, Namespaced};
use aptos_types::{
... | magicoder | rust |
You are tasked with implementing a payment processing system for a fictional e-commerce platform. The system should handle different types of payments, such as credit card, PayPal, and cryptocurrency. Each payment type has specific processing requirements and validation rules. Your task is to design and implement a fle... | ```java
public abstract class Payment {
protected double amount;
public Payment(double amount) {
this.amount = amount;
}
public abstract void processPayment();
public abstract boolean validatePayment();
}
public class CreditCardPayment extends Payment {
private String cardNumber;
... | magicoder | java |
You are tasked with implementing a C++ program that involves passing a variable by reference to a function and observing the changes made to the variable within the function. Your task is to predict the output of the program based on the given code snippet.
The provided code snippet is as follows:
```cpp
#include <io... | The correct option is A) Variable is: 5.
Explanation:
- In the `main` function, an integer variable `var` is declared.
- The `setValue` function is called with `var` as the argument. This function takes an integer reference as a parameter.
- Inside the `setValue` function, the user is prompted to input an integer, whi... | magicoder | cpp |
You are tasked with creating a Python program that simulates a simple banking system. The program should allow users to create accounts, log in, deposit money, withdraw money, and view their balance. To achieve this, you will need to implement the Account and Bank classes, as well as a simple user interface.
Your task... | ```python
class Account:
def __init__(self, account_number, balance):
self.account_number = account_number
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if self.balance >= amount:
self.balance -= amount
... | magicoder | python |
You are tasked with implementing a custom attention mechanism for a sequence-to-sequence model using TensorFlow. The attention mechanism will be used to improve the model's ability to focus on specific parts of the input sequence when generating the output sequence.
Your task is to complete the implementation of the ... | ```python
import tensorflow as tf
class BahdanauAttention(tf.keras.layers.Layer):
def __init__(self, units):
super(BahdanauAttention, self).__init__()
self.W1 = tf.keras.layers.Dense(units)
self.W2 = tf.keras.layers.Dense(units)
self.V = tf.keras.layers.Dense(1)
def call(self, ... | magicoder | python |
You are tasked with implementing a text processing function that cleans up HTML content. The function should take a string of HTML content as input and perform the following operations in sequence:
1. Replace all `</p>` tags with a newline character `\n`.
2. Replace all `<br>` or `<br/>` tags with a newline character ... | ```python
import re
def clean_html(html: str) -> str:
html = html.replace('</p>', '\n')
html = re.sub('<br\s*/?>', '\n', html)
html = re.sub('<.*?>', ' ', html)
html = re.sub(' +', ' ', html)
html = '\n'.join([x.strip() for x in html.splitlines()])
return html.strip()
``` | magicoder | python |
You are tasked with creating a Python module that manages versioning for a software project. Your module should include a function to retrieve the current version number. The version number should follow the semantic versioning format, which consists of three non-negative integers separated by periods (e.g., 1.2.3). Ad... | ```python
class VersionManager:
def __init__(self):
self.version = [1, 0, 0]
def get_version(self):
return '.'.join(map(str, self.version))
def increment_major(self):
self.version[0] += 1
self.version[1] = 0
self.version[2] = 0
def increment_minor(self):
... | magicoder | python |
You are tasked with creating a Python decorator that logs the entry and exit of a function. Your decorator should print a message when the function is entered and exited, along with the function name and its arguments. You should also ensure that the original function's return value is preserved.
Create a decorator ca... | ```python
def entry_exit(func):
def wrapper(*args, **kwargs):
print(f"Entering {func.__name__} with arguments {args}")
result = func(*args, **kwargs)
print(f"Exiting {func.__name__} with return value {result}")
return result
return wrapper
@entry_exit
def myFunction(x, y):
r... | magicoder | python |
You are tasked with implementing a stack data structure in Python. A stack is a Last-In-First-Out (LIFO) data structure where elements are added and removed from the same end, known as the top. You need to implement the `Stack` class with the following functionalities:
- `push(x)`: Add an element `x` to the top of the ... | ```python
class Stack:
def __init__(self, max_size):
self.s = []
self.max_size = max_size
def __repr__(self):
return str(self.s)
def push(self, x):
if len(self.s) < self.max_size:
self.s.append(x)
else: raise StackOverflowError("Stack is full")
... | magicoder | python |
You are tasked with implementing a custom memory management system for a virtual machine (VM). The VM has a global object that provides access to the VM's memory and other resources. The provided code snippet initializes a reference to the VM using the global object.
Your task is to design a class that manages memory ... | ```cpp
#include <iostream>
#include <unordered_map>
#include <vector>
class MemoryManager {
private:
VM& vm;
std::unordered_map<void*, size_t> allocatedBlocks;
std::vector<std::pair<void*, size_t>> freeBlocks;
public:
MemoryManager(VM& globalObjectVM) : vm(globalObjectVM) {}
void* allocateMemory(... | magicoder | cpp |
You are tasked with implementing a logging system for a pizza delivery service. The system should utilize the provided code snippet as a starting point and extend it to incorporate additional functionality.
Your task is to create a Java class that manages logging for pizza orders. The class should include the followin... | ```java
import java.util.logging.Logger;
import java.util.ArrayList;
import java.util.List;
public class PizzaOrderLogger {
private static final long serialVersionUID = -5296361038666702228L;
private final static Logger LOGGER = Logger.getLogger("PIZZA-ORDERS");
private List<String> orders;
public Piz... | magicoder | java |
You are tasked with implementing a function to rotate an image by a specified angle. The function takes in an image represented as a 2D NumPy array of shape (ngrid, ngrid) and an optional keyword argument "ROTATION" which specifies the angle of rotation in degrees. If the "ROTATION" keyword argument is not provided, th... | ```python
import numpy as np
def rotate_image(image, **kwargs):
ngrid = image.shape[0]
if "ROTATION" in kwargs:
angle = kwargs["ROTATION"]
angle_rad = angle * np.pi/180.
else:
angle = 0.0
angle_rad = 0.0
# Calculate the center of the image
center = (ngrid-1) / 2.0
... | magicoder | python |
You are tasked with implementing a video dataset loader for a machine learning project. The dataset consists of video clips, each accompanied by audio and a corresponding class label. Your goal is to create a Python class that loads and preprocesses the video data for training a deep learning model. The class should in... | ```python
import torch
class VideoDatasetLoader:
def __init__(self, file_path):
self.file_path = file_path
# Initialize other necessary variables
def load_video(self):
# Load video data from file_path and return as a tensor
video_data = torch.load(self.file_path) # Example: us... | magicoder | python |
You are given the definition of a binary tree node and a class with two methods, `height` and `diameterOfBinaryTree`, to calculate the height and diameter of a binary tree. The `height` method takes a binary tree node as input and returns the height of the tree rooted at the given node. The `diameterOfBinaryTree` metho... | ```python
class BinaryTree:
def diameterOfBinaryTree(self, root: BinaryTreeNode) -> int:
def height_and_diameter(node):
if not node:
return 0, 0
left_height, left_diameter = height_and_diameter(node.left)
right_height, right_diameter = height_and_diameter(... | magicoder | python |
You are tasked with implementing a Python class that represents a multi-component data structure. The class should have the following functionalities:
1. Initialize the data and position attributes. If the position is not provided as a list, it should default to a list with the same length as the components.
2. Implem... | ```python
class MultiComponentData:
def __init__(self, data, components, pos=None):
self.data = data
self.components = components
if pos is not None and not isinstance(pos, list):
pos = [pos for _ in self.components]
self.pos = pos
def __str__(self):
s = ''
... | magicoder | python |
You are given a Python code snippet that prints the public keys of a card and a door. Your task is to write a program that calculates the encryption key based on these public keys.
The code snippet provided is as follows:
```python
print('--------------------------')
print('Card public key: %d' % cardPublicKey)
print... | ```python
def transform_subject_number(subject_number, loop_size):
value = 1
for _ in range(loop_size):
value *= subject_number
value %= 20201227 # Prime number used in the encryption algorithm
return value
def find_loop_size(public_key):
subject_number = 7
value = 1
loop_size ... | magicoder | python |
You are tasked with creating a function that generates a project descriptor for a given project using Swift. The function takes in a `Project` object and a `GraphTraversing` object as parameters and is expected to return a `ProjectDescriptor`. The function also logs a message using a `logger` object. Additionally, the ... | ```swift
func generate(project: Project, graphTraverser: GraphTraversing) -> Result<ProjectDescriptor, Error> {
do {
logger.notice("Generating project \(project.name)")
let selfRef = XCWorkspaceDataFileRef(location: .`self`(""))
let selfRefFile = XCWorkspaceDataElement.file(selfRef)
... | magicoder | swift |
You are tasked with implementing a Python class for a Todo item in a backend system. The Todo item should have a unique identifier represented by a value object called `TodoId`. The `TodoId` is a string that uniquely identifies each Todo item.
Your task is to create a Python class called `Todo` that has the following ... | ```python
class TodoId:
def __init__(self, todo_id: str):
self._id = todo_id
@property
def id(self):
return self._id
class Todo:
def __init__(self, id: TodoId, title: str, completed: bool):
self._id = id
self.title = title
self.completed = completed
@proper... | magicoder | python |
You are tasked with implementing a Python function that takes in a list of function names and executes them in a specific order. The functions are defined in a given module, and the order of execution is determined by their dependencies. Each function may have dependencies on other functions, and these dependencies mus... | ```python
def execute_functions_in_order(module, function_order):
executed_functions = set()
def execute_function(func_name):
if func_name in executed_functions:
return
if func_name not in dir(module):
return None
func = getattr(module, func_name)
depende... | magicoder | python |
You are tasked with creating a class hierarchy for a web application firewall (WAF) rule statement in a TypeScript-based infrastructure as code (IaC) project. The WAF rule statement should support complex matching conditions for HTTP requests. Your task is to design and implement the class hierarchy for the WAF rule st... | ```typescript
// Your TypeScript interface and proxy class implementation for the field to match all query arguments within the XSS match statement
interface IWafv2WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchAllQueryArguments {
// Define the interface f... | magicoder | typescript |
You are tasked with implementing a function that splits a list of words into sublists based on the length of the words. The function should take a list of words as input and return a dictionary where the keys are the lengths of the words and the values are lists of words with the corresponding length.
Write a function... | ```python
def split_by_length(wordlist):
result = {}
for word in wordlist:
word_length = len(word)
if word_length in result:
result[word_length].append(word)
else:
result[word_length] = [word]
return result
```
The `split_by_length` function iterates through t... | magicoder | python |
You are tasked with implementing a Python function that performs 2D interpolation on a given set of data points. The function should take in three parameters: `X`, `Y`, and `Z`, representing the x-coordinates, y-coordinates, and corresponding z-values of the data points. Additionally, the function should accept a `fact... | ```python
import numpy as np
from scipy.interpolate import griddata
def interpolate_2d(X, Y, Z, factor):
# Flatten the input arrays
X_f, Y_f, Z_f = X.flatten(), Y.flatten(), Z.flatten()
# Scale the x-coordinates and y-coordinates
x_inter = scale(X, factor=factor).reshape(1, -1)
y_inter = scale... | magicoder | python |
You are tasked with implementing a unit test for a `Fast` class using the `unittest` framework in Python. The provided code snippet shows a part of the test setup where the `setUp` method is being overridden to initialize a `Fast` object for testing. Your task is to complete the unit test by adding test methods to veri... | ```python
import unittest
class Fast:
def __init__(self):
self.data = []
def add_data(self, item):
self.data.append(item)
def get_data(self):
return self.data
class TestFastClass(unittest.TestCase):
def setUp(self):
super().setUp()
self.detector = Fast()
... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.