query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with automating the versioning and deployment process for a web application. Your goal is to create a script that extracts the version number from the `package.json` file, updates the version number in specific files, installs dependencies, builds the application, and then copies the built files to a ser... | ```bash
#!/bin/bash
# Check if version argument is provided
if [ -z "$1" ]; then
echo "Usage: $0 <version>"
exit 1
fi
# Extract version from package.json
VERSION=$(cat package.json | grep '"version":' | awk 'NR==1{print $2}' | awk -F'"' '{print $2}')
# Update version in CMakeLists.txt files
sed -i "s/CPACK_PACKA... | magicoder | shell |
You are tasked with implementing a function to validate whether a given matrix aligns with a specified slice membership pattern. The slice membership pattern is represented by a 2D array, and the function should return True if the matrix matches the pattern, and False otherwise.
The function signature is:
```python
de... | ```python
from typing import List
import numpy as np
def validate_slice_membership(matrix: List[List[int]], slice_pattern: List[List[int]]) -> bool:
slice_matrix = np.array(slice_pattern * (len(matrix) // len(slice_pattern)))
return np.allclose(slice_matrix, np.array(matrix))
```
The `validate_slice_membership... | magicoder | python |
You are tasked with implementing a function that subtracts a given value from a balance and returns the result. The function should also handle error cases where the full amount was not subtracted.
You are given the following code snippet as a reference:
```rust
let sub: TokenAmount = std::cmp::min(&available, req).cl... | ```rust
use std::cmp::Ordering;
struct TokenAmount(i32); // Assuming TokenAmount is a custom type representing a token amount
impl TokenAmount {
fn is_positive(&self) -> bool {
self.0 > 0
}
}
struct BalanceManager {
// Assuming the BalanceManager has an add method to modify the balance
fn add... | magicoder | rust |
You are given a function `get_edge_bin(array)` that takes in an array of integers or booleans and returns a list of tuples representing the start and end indices of consecutive edges in the array. An edge is defined as a transition from 0 to 1 for integer arrays or from False to True for boolean arrays. The function us... | ```python
def get_edge_bin_standard(array):
edges = []
start = None
for i in range(len(array)):
if i == 0 and array[i]:
start = i
elif array[i] and not array[i-1]:
start = i
elif not array[i] and array[i-1]:
edges.append((start, i))
if array[-1... | magicoder | python |
You are given a code snippet that involves processing a collection of passports. Your task is to create a program that validates the passports based on certain criteria and counts the number of valid passports.
The passports are represented as a collection of key-value pairs, where each key-value pair corresponds to a... | ```rust
fn is_valid_passport(passport: &str) -> bool {
let fields: Vec<&str> = passport.split_whitespace().collect();
let mut field_count = 0;
for field in fields {
let key_value: Vec<&str> = field.split(':').collect();
if key_value.len() == 2 {
let key = key_value[0];
... | magicoder | rust |
You are tasked with implementing a Python function that analyzes the entropy of a given file and generates a plot of the entropy distribution. Entropy is a measure of the amount of uncertainty or disorder in a set of data. The function should take two input parameters: `input_file` (the file to be analyzed) and `output... | ```python
import os
import math
import matplotlib.pyplot as plt
def calculate_entropy(data: bytes) -> float:
"""Calculate the entropy of a given byte string."""
entropy = 0
length = len(data)
for byte in range(256):
frequency = data.count(byte)
if frequency != 0:
probability... | magicoder | python |
You are tasked with implementing a custom error type for parsing string literals in Rust. The error type, `StringLiteralParseError`, should encompass different parsing errors that may occur during the processing of string literals. Your goal is to define the error type and its associated variants, and then implement th... | ```rust
use std::error;
use std::fmt;
// Define the custom error type for parsing string literals
#[derive(Debug)]
enum StringLiteralParseError {
InvalidUtf8Parse(Box<dyn error::Error + 'static>),
// Define additional variants for other parsing errors
// Example: InvalidEscapeSequence,
// Inva... | magicoder | rust |
You are tasked with implementing a Python decorator that enhances the functionality of a service discovery system. The service discovery system is responsible for managing and providing information about available services in a distributed environment. The provided code snippet demonstrates the application of a decorat... | ```python
def base_decorator(func):
def wrapper(*args, **kwargs):
# Define the new backend
new_backend = "mock_backend"
# Add the new backend to the list of service discovery backends
modified_backends = func() + [new_backend]
# Return the modified function
... | magicoder | python |
You are tasked with creating a command-line tool to manage iOS simulators for testing and development purposes. The tool should allow users to perform various operations such as listing available simulators, creating new ones, deleting existing ones, and launching specific simulators.
Your task is to implement a simpl... | ```java
import java.util.HashMap;
import java.util.Map;
public class Simctl {
private static Map<String, String> simulators = new HashMap<>();
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: Simctl <command> [options]");
return;
... | magicoder | java |
You are tasked with implementing a Python plugin loader that can load and reload plugins based on a given set of dependencies. The plugin loader should be able to handle dependencies, reload modules, and fetch specific plugins.
Your task is to implement the `PluginLoader` class with the following methods:
1. `loaddeps... | ```python
import importlib
class PluginLoader:
def __init__(self):
self.loaded_modules = {}
def loaddeps(self, modname, force, showerror, loaded):
if modname in loaded:
return loaded
loaded.append(modname)
module = self.getmodule(modname)
if module:
... | magicoder | python |
You are tasked with creating a Python function that interacts with Amazon Web Services (AWS) Transcribe service to transcribe an audio file stored in an S3 bucket. The function should take the AWS Transcribe client, the name of the uploaded file, and the locale as input parameters. It should then initiate a transcripti... | ```python
import boto3
import os
import time
AWS_UPLOAD_BUCKET_URL = "s3://your-bucket-name/" # Replace with your S3 bucket URL
def transcribe_storage_uri(client, uploaded_file, locale):
# must be unique (required by aws api)
job_name = time.ctime().replace(" ", "-").replace(":", "-")
storage_uri = os.p... | magicoder | python |
You are tasked with creating a program to analyze a collection of text documents and generate a report on the frequency of words in each document. To accomplish this, you will need to perform the following steps:
1. Read the text data from multiple files in a specified directory.
2. Tokenize the text data to extract i... | ```python
import os
import csv
import glob
import numpy as np
import pandas as pd
import nltk
import string
import re
from numpy import genfromtxt
def read_text_files(directory):
text_data = []
for file in glob.glob(os.path.join(directory, '*.txt')):
with open(file, 'r', encoding='utf-8') as f:
... | magicoder | python |
You are given a 2D grid representing a Voronoi diagram, where each cell in the grid belongs to a specific zone. The goal is to write a function to label the connected components within each zone.
Write a function `labelComponents(grid: List[List[int]]) -> List[List[int]]` that takes in a 2D grid of integers representi... | ```python
from typing import List
from collections import deque
def labelComponents(grid: List[List[int]]) -> List[List[int]]:
def is_valid_move(x, y):
return 0 <= x < len(grid) and 0 <= y < len(grid[0])
def bfs(x, y, label):
queue = deque([(x, y)])
while queue:
curr_x, cur... | magicoder | python |
You are tasked with implementing a function to find a resource file within a given directory structure. The function should take a directory path and a file name as input and return the full path to the file if it exists, or an empty string if the file is not found. The directory structure is represented as a tree, whe... | ```cpp
#include <iostream>
#include <vector>
#include <string>
struct Node {
std::string name;
std::vector<Node> children;
};
class Directory {
public:
Directory(const std::string& name) : name(name) {}
std::string find_resource_file(const std::string& file_name) const {
return find_resource_... | magicoder | cpp |
You are tasked with implementing a firmware manager class in Swift. The firmware manager is responsible for handling firmware updates for a device. The firmware manager interacts with a backend service to download and manage firmware updates. Your task is to implement the `FirmwareManager` class and its associated meth... | ```swift
// Define the FirmwareInfo struct to represent firmware information
struct FirmwareInfo {
let version: String
// Add any other relevant properties
}
// Define the FirmwareManager class
class FirmwareManager {
var firmwares: [FirmwareInfo] = []
func downloadFirmware(firmwareInfo: FirmwareI... | magicoder | swift |
You are tasked with creating a Python function that simulates a simple database management system. The function should be able to create a database, retrieve the database instance, and close the database when necessary. Your task is to implement the `DatabaseManager` class with the following methods:
1. `create_databa... | ```python
import sheraf
class DatabaseManager:
_database_instance = None
@classmethod
def create_database(cls):
if cls._database_instance is None:
cls._database_instance = sheraf.Database()
return cls._database_instance
@classmethod
def get_database(cls):
if cl... | magicoder | python |
You are working as a DevOps engineer at a software company. Your team is responsible for automating the build and packaging process for a new software project. As part of this process, you need to write a script that automates the import of a GPG key, builds a binary, and creates a Debian package. Your task is to write... | ```bash
#!/bin/bash
# Import GPG key
gpg --import /tmp/key.asc
# Copy source files
cp -r /src/* .
# Fetch dependencies
go get -t
# Build binary
go build -o /artifacts/gemnasium
# Create Debian package
dpkg-buildpackage -tc -k689FC23B -p/bin/gpg_wrapper.sh
# Move package files to artifacts directory
mv ../gemnasiu... | magicoder | shell |
You are tasked with implementing a program to perform singular value decomposition (SVD) on a given set of movie ratings. Singular value decomposition is a technique used in linear algebra and matrix factorization, often applied in recommendation systems and data compression. The goal is to decompose the original matri... | ```python
import numpy as np
import logging
# Sample movieRatings matrix (replace with actual data)
movieRatings = np.array([[3, 1, 2], [4, 3, 4], [3, 2, 5]])
# Perform SVD using numpy
U, singularValues, V = np.linalg.svd(movieRatings)
# Log U values and V values
logging.info("U values: %s", U)
logging.info("V value... | magicoder | python |
You are tasked with developing a command-line interface (CLI) for a machine learning model training and testing system. The CLI should allow users to specify various settings and parameters for the model, such as the type of classification (binary or multi-class), the classifier to be used, the time interval for testin... | ```python
from typing import List, Dict, Union, Tuple
import argparse
def parse_command_line_args(args: List[str]) -> Dict[str, Union[str, Tuple[str, str], int]]:
parser = argparse.ArgumentParser(description='Machine Learning Model CLI')
parser.add_argument('--classification-type', help='Whether to perform bin... | magicoder | python |
You are tasked with implementing a Python class that manages namespaces and type variables. The class should provide methods to check for errors and to find a specific name within the namespaces.
You are given a partial code snippet for the class:
```python
class TypeVariable:
def __init__(self, name, namespaces,... | ```python
class TypeVariable:
def __init__(self, name, namespaces, messages, parent):
self.name = name
self.namespaces = namespaces
self.__messages = messages
self.parent = parent
def is_error(self):
return len(self.__messages) > 0
def find_name(self, name):
... | magicoder | python |
You are tasked with creating a script to manage a server process. The script should set resource limits, start the server process, and redirect its output to a log file. Your task is to write a Python script that accomplishes these tasks.
Your Python script should perform the following actions:
1. Set the maximum numb... | ```python
import subprocess
python_ver = "python3" # Replace with the desired Python version
# Set the maximum number of open file descriptors
subprocess.run(["ulimit", "-n", "512000"])
# Start the server process and redirect output to a log file
subprocess.run([python_ver, "server.py"], stdout=open("ssserver.log",... | magicoder | python |
You are tasked with implementing a function that constructs a SQL query based on a given base SQL statement and a list of filters. The function should take the base SQL statement and a list of filter conditions as input and return the final SQL query with the applied filters.
The function signature is as follows:
```p... | ```python
from typing import List
from psycopg2 import sql
def construct_filtered_sql(base_sql: str, filters: List[str]) -> str:
filters_sql = [sql.SQL(filter) for filter in filters]
if len(filters_sql) > 0:
final_sql = sql.SQL('{0} WHERE {1}').format(sql.SQL(base_sql), sql.SQL(' AND ').join(filters_sq... | magicoder | python |
You are given a list of integers representing the scores of a game. Your task is to write a function that calculates the average score of the game, excluding the highest and lowest scores.
Write a function `calculateAverage` that takes in a list of integers and returns the average score, rounded to the nearest integer... | ```cpp
#include <vector>
#include <algorithm>
#include <numeric>
#include <cmath>
int calculateAverage(std::vector<int> scores) {
if (scores.size() <= 2) {
return 0; // Handle edge case where there are less than 2 scores
}
// Sort the scores in ascending order
std::sort(scores.begin(), scores.... | magicoder | cpp |
You are tasked with implementing a custom transformer class for feature engineering in a machine learning pipeline. The class, named `CustomTransformer`, is designed to perform a specific transformation on input data.
The `CustomTransformer` class has the following attributes and methods:
Attributes:
- `variables`: A... | The `transform` method in the `CustomTransformer` class is completed as follows:
```python
def transform(self, X):
X = X.copy()
for variable in self.variables:
X[variable] = X[self.related_variable] - X[variable]
return X
```
This solution correctly implements the transformation logic by subtracti... | magicoder | python |
You are tasked with implementing a custom exception class in C++ to handle situations where a particular feature or functionality is not yet implemented. Your task is to create a class `NotImplementedException` that inherits from the standard `std::exception` class and includes additional functionality to store the nam... | ```cpp
#include <exception>
#include <string>
#include <sstream>
class NotImplementedException : public std::exception {
private:
std::string functionName;
int errorCode;
std::string message;
public:
NotImplementedException(const std::string& funcName)
: functionName(funcName), errorCode(0), m... | magicoder | cpp |
You are tasked with implementing a custom iterator for a class `FunctionGroup` that represents a group of function overloads. The class has a private member `mOverloads` of type `std::vector<Function>` to store the function overloads. Your goal is to create an iterator that allows iterating over the function overloads ... | ```cpp
class FunctionGroup {
private:
std::vector<Function> mOverloads;
public:
class overloads_iterator {
private:
std::vector<Function>::iterator iter;
public:
overloads_iterator(std::vector<Function>::iterator it) : iter(it) {}
overloads_iterator& operator++() {
... | magicoder | cpp |
You are tasked with implementing a Python program to efficiently generate prime numbers using the Sieve of Eratosthenes algorithm. The Sieve of Eratosthenes is an ancient algorithm for finding all prime numbers up to a specified integer. The algorithm works by iteratively marking the multiples of each prime number star... | ```python
# sieve_module.py
cdef extern from "stdbool.h":
bint __is_prime(int n)
cdef int __is_prime(int n):
cdef int i
if n <= 1:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
def sieve_of_eratosthenes(int limit):
cdef i... | magicoder | python |
You are tasked with creating a Python package version checker. Your program should take in a package name and a version number, and then determine if the provided version number is the latest version available for the given package. You can assume that the package versions follow the semantic versioning format (major.m... | ```python
import requests
def is_latest_version(package_name, version_number):
# Fetch the latest version of the package from PyPI
response = requests.get(f'https://pypi.org/pypi/{package_name}/json')
if response.status_code == 200:
latest_version = response.json()['info']['version']
return... | magicoder | python |
You are tasked with creating a Python function that processes a video stream to detect a specific color range and highlight it in the output. The function should take a video stream as input and return the processed video stream with the specified color range highlighted.
You are provided with the following code snipp... | ```python
import cv2
import numpy as np
def highlight_color_range(video_stream):
cap = cv2.VideoCapture(video_stream)
while True:
_, frame = cap.read()
if frame is None:
break # Break the loop if no frame is captured
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
lowe... | magicoder | python |
You are tasked with implementing a function that simulates a simple data storage system for a mobile application. The function should save data when the application is about to terminate and retrieve the saved data when the application is launched again. You are provided with a code snippet that represents the point in... | ```swift
import Foundation
class DataStorage {
private let fileName = "savedData.txt"
func saveData(data: String) {
do {
let fileURL = try FileManager.default
.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
.appendi... | magicoder | swift |
You are tasked with implementing a function that converts a given SVG path string into an array of commands. Each command in the array should be represented as an object containing the command type and its corresponding parameters.
The SVG path string will consist of a sequence of commands, where each command is repre... | ```javascript
function parseSVGPath(pathString) {
const commands = pathString.match(/[A-Za-z][^A-Za-z]*/g);
const parsedCommands = commands.map(command => {
const [type, ...params] = command.trim().split(/\s+|,/);
return {
command: type,
parameters: params.map(param => parseFloat(param))
};
... | magicoder | javascript |
You are tasked with implementing a function that compares two dictionaries and returns a new dictionary containing the key-value pairs that are common to both input dictionaries. Additionally, you need to handle the case where the values associated with the common keys are also equal.
Write a function `find_shared_it... | ```python
def find_shared_items(dict1, dict2):
shared_items = {k: dict1[k] for k in dict1 if k in dict2 and dict1[k] == dict2[k]}
return shared_items
```
The `find_shared_items` function iterates through the keys of `dict1` and checks if the key is present in `dict2` and if the associated values are equal. If ... | magicoder | python |
You are given an array `nums` containing only 0, 1, and 2. Write a function to sort the array in-place in linear time complexity and constant space complexity without using any sorting algorithms.
For example, given the input array `nums = [2,0,2,1,1,0]`, after sorting, the array should be modified to `nums = [0,0,1,1... | ```python
def sortColors(nums):
zero, two = 0, 0
for value in nums:
if not value:
nums[zero] = 0
zero += 1
elif value == 2:
two += 1
for i in range(zero, len(nums)-two):
nums[i] = 1
for i in range(len(nums)-two, len(nums)):
nu... | magicoder | python |
You are tasked with implementing a dependency resolution algorithm for a software application. The application is composed of modules, each with its own dependencies and initialization logic. The provided code snippet is a part of the application framework and includes a method to retrieve the dependencies of a module ... | ```cpp
#include <vector>
#include <unordered_map>
#include <queue>
std::vector<ModuleId> resolveInitializationOrder(const std::vector<Module>& modules) {
std::unordered_map<ModuleId, std::vector<ModuleId>> dependencyMap;
std::unordered_map<ModuleId, int> dependencyCount;
for (const auto& module : modules)... | magicoder | cpp |
You are tasked with implementing a Python class to manage student information. The class should have methods to set and get the student's name, ID, gender, birthstone, age, and grade. Additionally, the class should keep track of the total number of students created. You need to implement the class and its methods based... | ```python
class Student:
studentCounter = 0 # Class variable to keep track of the total number of students
def __init__(self, name, studentID, gender, birthstone, age, grade):
self.name = name
self.studentID = studentID
self.gender = gender
self.birthstone = birthstone
... | magicoder | python |
You are tasked with implementing a Python function that simulates the behavior of a simple heat transfer system using the finite difference method. The system consists of a one-dimensional rod with a given initial temperature distribution. The goal is to evolve the temperature distribution over time according to the he... | ```python
import numpy as np
import matplotlib.pyplot as plt
def explicit_finite_difference(T, dx, dt, alpha):
T_next = np.copy(T)
for i in range(1, len(T) - 1):
T_next[i] = T[i] + alpha * (T[i+1] - 2*T[i] + T[i-1])
return T_next
def run_solvers_and_plot(solvers, rhs, T, dt, title=None, filename=N... | magicoder | python |
You are tasked with creating a Python decorator that retries a function a specified number of times with a delay between each attempt. The decorator should be able to handle any function, along with its arguments and keyword arguments. Your task is to implement the `retry` decorator function that takes the number of tr... | ```python
import time
import functools
def retry(tries, delay):
def decorator_retry(func):
@functools.wraps(func)
def wrapper_retry(*args, **kwargs):
for _ in range(tries):
try:
return func(*args, **kwargs)
except Exception as e:
... | magicoder | python |
You are tasked with implementing a parser for a simplified version of the SyGuS input language, which is used for specifying syntax-guided synthesis problems. The given code snippet is a part of the Python implementation of the parser. The parser is responsible for parsing sort expressions in the SyGuS input language.
... | ```python
def sortStar(self):
sorts = []
while self.hasNextSort():
sorts.append(self.getTypedRuleContext(SygusParser.SortExprContext, 0))
if self.hasNextSort():
self.match(' ')
return sorts
```
In the solution, the `sortStar` method iterates through the input string, parsing each... | magicoder | python |
You are given a rectangular grid of size n x n, where n is a positive integer. The grid is divided into cells, and each cell is identified by its row and column indices. The top-left cell has coordinates (1, 1), and the bottom-right cell has coordinates (n, n).
You are also given two integers, h and w, where 1 ≤ h ≤ n... | ```python
def count_subgrids(n, h, w):
return (n - h + 1) * (n - w + 1)
```
The solution function `count_subgrids` takes in the integers n, h, and w as input and returns the number of subgrids with the specified height and width. The formula `(n - h + 1) * (n - w + 1)` efficiently calculates the number of subgrids... | magicoder | python |
You are tasked with implementing a function to set the flash voltage for an ESP (Embedded Systems Processor) using the provided code snippet as a reference. The function `set_flash_voltage` takes three parameters: `esp` (the ESP object), `efuses` (a dictionary containing the efuse values), and `args` (additional argume... | ```python
def set_flash_voltage(esp, efuses, args):
def _get_efuse(efuses, efuse_name):
if efuse_name in efuses:
return efuses[efuse_name]
else:
raise ValueError(f"EFUSE {efuse_name} not found")
sdio_force = _get_efuse(efuses, "XPD_SDIO_FORCE")
sdio_tieh = _get_efuse... | magicoder | python |
You are given a list of flight routes with their respective costs. Each route is represented as a tuple in the format (source, destination, cost). Your task is to write a function that finds the cheapest itinerary for a given trip.
Write a function `find_cheapest_itinerary(flights, start, end)` that takes in the follo... | ```python
import heapq
def find_cheapest_itinerary(flights, start, end):
graph = {}
for source, dest, cost in flights:
if source not in graph:
graph[source] = []
graph[source].append((dest, cost))
heap = [(0, start, [])]
while heap:
total_cost, curr, path = heapq.he... | magicoder | python |
You are working on a deep learning project and are tasked with implementing a sequence of operations for processing input data. The operations include adding elements to a sequence, generating noise, performing convolution, applying normalization, and activating the output. Your task is to write a function that takes i... | ```python
from typing import List
def construct_sequence(seq, tmp, fill_noise, inp, conv, GenNoise, conv_num, pad, normalization, act) -> List:
seq.append(tmp)
if fill_noise:
seq.append(GenNoise(inp))
seq.append(conv(inp, conv_num, 3, pad=pad))
seq.append(normalization(conv_num))
seq.append... | magicoder | python |
You are tasked with creating a Python function that processes a given text file and returns the frequency of each word in the file. The function should ignore punctuation and be case-insensitive. Additionally, the function should return the word frequencies in descending order based on their occurrence count.
Create a... | ```python
def word_frequency(file_path):
word_freq = {}
with open(file_path, 'r') as file:
text = file.read().lower()
words = ''.join([c if c.isalnum() or c.isspace() else ' ' for c in text]).split()
for word in words:
word_freq[word] = word_freq.get(word, 0) + 1
sorted_w... | magicoder | python |
You are tasked with implementing a C++ template meta-programming problem that involves understanding and manipulating type traits and function call expressions.
You are given the following code snippet as a starting point for your problem:
```cpp
typedef typename meta::as_logical<sA0>::type result_type;
BOOST_SIMD_FU... | ```cpp
// Solution for meta::as_logical metafunction
template <typename T>
struct meta {
using as_logical = T; // Default case, returns the same type
};
template <typename T>
struct meta<T*> {
using as_logical = bool; // Specialization for pointer types, returns bool
};
// Solution for BOOST_SIMD_FUNCTOR_CALL m... | magicoder | cpp |
You are tasked with creating a program that reads a file containing a software license and extracts the name and email of the copyright holder. The license file is in the format specified by the code snippet below:
```
/*
* MIT License
*
* Copyright (c) 2020 John Doe <john.doe@example.com>
*
* Permission is hereb... | ```python
import re
def extractCopyrightHolder(file_path):
with open(file_path, 'r') as file:
content = file.read()
match = re.search(r'Copyright \(c\) \d{4} (.+?) <(.+?)>', content)
if match:
return match.group(1), match.group(2)
return None # Handle case when no match is ... | magicoder | python |
You are tasked with implementing a macro in Rust that simulates the behavior of a function call using the provided `ffi_dispatch` macro. The `ffi_dispatch` macro takes a handle, a function name, and any number of arguments, and then calls the corresponding function on the handle with the provided arguments.
Your task ... | ```rust
#[macro_export]
macro_rules! ffi_dispatch(
($handle: ident, $func: ident, $($arg: expr),*) => (
($handle.$func)($($arg),*)
)
);
#[macro_export]
macro_rules! call_function {
($handle: ident, $func: ident, $($arg: expr),*) => {
ffi_dispatch!($handle, $func, $($arg),*);
};
}
struc... | magicoder | rust |
You are tasked with implementing a class that manages a hash vector and a list of neighbors in a peer-to-peer network. The class has the following attributes and behaviors:
Attributes:
- `hashid`: a hexadecimal string representing the hash ID of the node.
- `vectorlength`: an integer representing the length of the has... | ```python
class PeerNode:
def __init__(self, hashid, vectorlength, homeip, max_neighbors):
self.hashid = hashid
self.vectorlength = vectorlength
self.max_neighbors = max_neighbors
self.inth = int(self.hashid, 16)
self.hashvector = [0] * vectorlength
self.neighbors = [... | magicoder | python |
You are tasked with implementing a function that fetches data from a RabbitMQ server using a set of parameters. The function should handle loading indicators, token-based authentication, and customizable headers. Your goal is to complete the implementation of the `fetchData` function by filling in the missing parts bas... | ```typescript
function fetchData<T>(
url: string,
config: RabbitFetchParams = { method: "GET" }
): Promise<T> {
const responseType: ResponseType = config.responseType ?? "json";
try {
!config.suppressLoading && emitLoadingInc();
const token = localStorage.getItem("token");
let headers: { [key: str... | magicoder | typescript |
You are tasked with creating a Python class that implements a similarity encoder for a given dataset. The similarity encoder is a type of neural network architecture used for encoding similarity information between data points. Your task is to implement the `SimilarityEncoder` class, which will utilize various utility ... | ```python
import numpy as np
from .simec import SimilarityEncoder, masked_mse, masked_binary_crossentropy, LastLayerReg
from .utils import center_K
class SimilarityEncoder:
def __init__(self, input_dim, output_dim, hyperparameters):
self.input_dim = input_dim
self.output_dim = output_dim
se... | magicoder | python |
You are tasked with implementing a configuration method for a Composable object in Swift. The method `configure` takes in an `Item` struct and a collection of `Spotable` objects to configure the child Composable. Additionally, the method also accepts an optional collection of `CompositeSpot` objects. Your goal is to im... | ```swift
class Composable {
func configure(_ item: inout Item, spots: [Spotable], compositeSpots: [CompositeSpot]?) {
for spot in spots {
spot.spot()
}
if let compositeSpots = compositeSpots {
let sortedCompositeSpots = compositeSpots.sorted { $0.priority < $... | magicoder | swift |
You are tasked with implementing a function that takes a reference to a string slice and returns a new `String` containing the same content as the input slice. However, the function should not simply clone the input slice; instead, it should create a new `String` object and copy the content of the slice into it. You ar... | ```rust
fn copy_string_slice(input: &str) -> String {
let new_string = input.to_string();
new_string
}
```
The `to_string` method is used to create a new `String` object from the given string slice. This method allocates memory on the heap and copies the content of the slice into the newly allocated memory, ef... | magicoder | rust |
You are tasked with implementing a CUDA kernel that performs element-wise addition of two arrays and stores the result in a third array. The CUDA kernel should be designed to handle arrays of arbitrary size and should utilize the CUDA API for memory management and error handling.
You are provided with the following co... | ```cpp
#include <cuda/api/array.hpp>
#include <cuda/api/error.hpp>
#include <cuda_runtime.h>
namespace cuda {
__global__ void addArrays(const float* a, const float* b, float* result, size_t size) {
size_t index = blockIdx.x * blockDim.x + threadIdx.x;
if (index < size) {
result[index] =... | magicoder | cpp |
You are working as a software developer for an e-commerce company that uses Laravel, a popular PHP framework, for its backend operations. Your task is to create a command-line interface (CLI) command using Laravel's Artisan console to facilitate the creation of new orders in the system. The command should accept input ... | To implement the `create:order` Artisan command in Laravel, you can follow the steps outlined below:
1. Create the Artisan command using the `make:command` Artisan command:
```bash
php artisan make:command CreateOrder
```
2. Open the generated `CreateOrder.php` file within the `app/Console/Commands` directory and def... | magicoder | shell |
You are given an array of integers `arr`. Your task is to write a function that returns an array `vector` where each element at index `i` represents the nearest smaller element to the right of `arr[i]`. If there is no smaller element to the right of `arr[i]`, the value at index `i` in `vector` should be -1.
For exampl... | ```python
def nearest_smaller_to_right(arr):
stack = []
vector = []
for i in range(len(arr)-1, -1, -1):
while len(stack) > 0 and stack[-1] >= arr[i]:
stack.pop()
if len(stack) == 0:
vector.append(-1)
else:
vector.append(stack[-1])
stack.app... | magicoder | python |
You are given a string containing a series of comma-separated integers. Your task is to write a function to find the maximum sum of a contiguous subarray within the string. For example, given the input string "1,-3,2,1,-1", the contiguous subarray with the largest sum is "2,1", and the maximum sum is 3.
Write a functi... | ```python
def maxSubarraySum(arr: str) -> int:
nums = list(map(int, arr.split(','))) # Convert the input string to a list of integers
max_sum = current_sum = nums[0] # Initialize max_sum and current_sum with the first element of the list
for num in nums[1:]: # Iterate through the list starting from the ... | magicoder | python |
You are working on a web application that displays user information in a table format. The code snippet provided is a part of the HTML template used to generate the table rows. The snippet uses JavaScript template literals to dynamically insert user information into the table cells.
Your task is to write a function th... | ```javascript
function generateUserTableRows(users) {
let htmlCode = '';
users.forEach(user => {
htmlCode += `
<tr>
<td class="pt-3"><span class="fa fa-user mr-1"></span> ${user.firstname} ${user.lastname}</td>
<td class="pt-3">${user.contact}</td>
<td class="... | magicoder | javascript |
You are tasked with implementing a time formatting function for a mobile application. The function should take the current context and a given hour and minute as input and return the formatted time as a string. The formatting should consider whether the device is set to a 24-hour or 12-hour time format.
You are provid... | ```java
import android.content.Context;
import android.text.format.DateFormat;
public abstract class TimePrintHelper {
public static String getTime(Context context, int hour, int minute){
if(DateFormat.is24HourFormat(context)){
return ((hour<10)?"0"+hour:""+hour)+" : "+((minute<10)?"0"+minute:"... | magicoder | java |
You are tasked with creating a program that processes a series of binary expressions and performs specific operations based on the given keywords and operands. Each binary expression consists of an object, a keyword, an operand (which can be an object, number, string, or boolean), and a modifier (which can be a number ... | ```python
def processBinaryExpression(obj, keyword, operand, modifier):
if keyword == 'setvariable':
obj.variable = operand
return f"Variable set to {operand} for {obj}"
elif keyword == 'setvectordir':
obj.set_direction_vector(operand)
return f"Direction vector set for {obj}"
... | magicoder | python |
You are tasked with implementing a function to simulate event injection and handling in a graphics rendering system. The system consists of a session for rendering, a renderer, and a set of input events. The goal is to ensure that the system correctly handles injected events and updates its state accordingly.
You are ... | ```cpp
#include <iostream>
#include <vector>
// Define the structure for input events
struct InputEvent {
int compositorId;
// Other event data
};
// Define the container to hold received input events
std::vector<InputEvent> received_input_events;
// Function to inject a fresh event into the rendering sessio... | magicoder | cpp |
You are tasked with creating a Django REST framework API for managing ingredients in a recipe application. Your goal is to implement a view that retrieves all ingredients from the database and serializes them using the `IngredientSerializer`. Additionally, you need to write tests to ensure that the API endpoint returns... | ```python
# views.py
from rest_framework import generics
from rest_framework import status
from rest_framework.response import Response
from .models import Ingredient
from .serializers import IngredientSerializer
class IngredientListAPIView(generics.ListAPIView):
queryset = Ingredient.objects.all().order_by('-name... | magicoder | python |
You are working on a data preprocessing task for a machine learning project. You have been given a dataset consisting of two parts: a training set and a validation set. Your task is to write a Python function that takes the training and validation datasets as input and performs the following operations:
1. Save the tra... | ```python
import pandas as pd
def preprocess_data(train, valid, folder):
train_file = open(folder + "/train2id.txt", "w")
train.to_csv(train_file, header=None, index=None, sep=" ", mode='a')
train_file.close()
valid_file = open(folder + "/valid2id.txt", "w")
valid_file.write("%d\n" % (valid.shape[... | magicoder | python |
You are tasked with implementing a command-line tool for image processing that includes an argument parser. The tool should support the option to specify the upsampler for alpha channels and the file extension for the output images.
Your task is to complete the implementation of the argument parser by adding the neces... | ```python
import argparse
def main():
parser = argparse.ArgumentParser(description='Image processing tool')
parser.add_argument(
'--upsampler',
type=str,
default='realesrgan',
choices=['realesrgan', 'bicubic'],
help='The upsampler for the alpha channels. Options: realesr... | magicoder | python |
You are tasked with creating a Python function that analyzes the performance of different machine learning models using various optimization methods and default parameters. Your function will take in three input lists: `models_to_use`, `methods_to_use`, and `sensible_defaults`. The function will iterate through these l... | ```python
import time
import utils
def analyze_model_performance(models_to_use, methods_to_use, sensible_defaults):
timings = []
observations = # provide the dataset for training
temp = # provide the target variable for training
for m in models_to_use:
for optimizer_method in methods_to_us... | magicoder | python |
You are tasked with implementing a database management system for a company's inventory. The system should allow for the creation, updating, and deletion of product records. To achieve this, you need to create a Python class that interacts with a database using SQLAlchemy.
Your task is to implement a `ProductManager` ... | ```python
from sqlalchemy import create_engine, Column, Integer, String, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class Product(Base):
__tablename__ = 'products'
id = Column(Integer, primary_key=True)
product_id = Colum... | magicoder | python |
You are tasked with creating a function that validates a user's input for a fax number. The input is expected to be in the format of a standard fax number, which consists of an optional country code, followed by the area code and the fax number itself. The function should return true if the input is in the correct form... | ```javascript
function validateFaxNumber(input) {
if (input.trim() === '') {
return false; // Input should not be empty
}
// Regular expression to match the fax number format
const faxRegex = /^(\+\d+)?(\(\d+\))?[ -]?\d{3,}([ -]?\d{4,})$/;
return faxRegex.test(input);
}
// Test cases
console.log(valida... | magicoder | javascript |
You are tasked with creating a program to identify common elements between two arrays. Given two arrays of integers, you need to write a function to find the common elements between them and return the result as a new array.
Write a function `findCommonElements` that takes in two arrays of integers as input and return... | ```python
def findCommonElements(arr1, arr2):
common_elements = []
set1 = set(arr1)
set2 = set(arr2)
for num in set1:
if num in set2:
common_elements.append(num)
return common_elements
```
The `findCommonElements` function first converts both input arrays into sets to take adv... | magicoder | python |
You are tasked with creating a Python class that manages the configuration of data types and their properties for a data processing application. The class should allow for the definition and retrieval of data type configurations, including primitive types and their corresponding item types, as well as the ability to ma... | ```python
import logging
logger = logging.getLogger(__name__)
class DataTypeConfig:
def __init__(self):
self.configurations = {}
def add_type_config(self, type_name, item_type, required):
self.configurations[type_name] = {
'item_type': item_type,
'required': required
... | magicoder | python |
You are tasked with implementing a custom SentenceStateGate class in Python. The SentenceStateGate class is responsible for creating gates used in natural language processing tasks, such as sentiment analysis or language modeling. Each gate takes a hidden state and an input, and produces an output based on specific ope... | ```python
import numpy as np
class HiddenGate:
def __init__(self, hidden_size, input_size, nonlinearity):
self.hidden_size = hidden_size
self.input_size = input_size
self.nonlinearity = nonlinearity
def forward(self, input_data):
# Perform operations using the specified nonline... | magicoder | python |
You are tasked with implementing a custom exception hierarchy in C++. Your goal is to create a set of exception classes that inherit from `std::exception` and `boost::exception`. The `std::exception` class is a base class for all standard C++ exceptions, while `boost::exception` is a class template that allows adding a... | ```cpp
#include <exception>
#include <boost/exception/exception.hpp>
class my_exception : public std::exception
{
// Custom implementation for my_exception
};
class my_exception2 : public std::exception, public boost::exception
{
// Custom implementation for my_exception2
};
```
In the solution, we define two... | magicoder | cpp |
You are tasked with implementing a class for managing units in a measurement system. The class should allow for the addition of base and derived units, as well as the ability to append a specified number of units to a given unit. Your task is to complete the implementation of the `MeasurementSystem` class by adding the... | ```python
class MeasurementSystem:
def __init__(self):
self.baseUnits = []
self.derivedUnits = {}
def add_base_unit(self, unit_name):
# Add the specified base unit to the measurement system
if unit_name not in self.baseUnits:
self.baseUnits.append(unit_name)
def... | magicoder | python |
You are tasked with implementing a class that can parse and interact with Ethereum contract ABIs (Application Binary Interface). An ABI is a JSON representation of a contract's interface, including its functions, inputs, and outputs. Your goal is to create a class `Abi` that can handle the parsing and interaction with ... | ```typescript
interface AbiFunction {
name: string;
inputs: Array<{ name: string; type: string }>;
outputs: Array<{ name: string; type: string }>;
}
class Abi {
private abi: AbiFunction[];
constructor(abi: AbiFunction[]) {
this.abi = abi;
}
parseFunction(funcName: string): { inputs: Array<{ name: s... | magicoder | typescript |
You are tasked with implementing a plugin system for a software application. The application allows users to extend its functionality by creating and integrating plugins. Each plugin can modify the application's behavior, add new features, or customize existing ones. The application provides a plugin interface with the... | ```typescript
class Plugin implements PluginInterface {
plugins?: Array<Plugin>;
schema: object;
variants: object;
prng?: (prng: any) => object;
constructor(schema: object, variants: object, prng?: (prng: any) => object) {
this.schema = schema;
this.variants = variants;
this... | magicoder | typescript |
You are given a 2D array `input` of size `n x m`. Each cell of the array contains an integer value. Your task is to write a function or method that determines if there exists a cell in the array that is greater than or equal to all the elements in its row and less than or equal to all the elements in its column.
The f... | ```python
from typing import List
def find_special_cell(input: List[List[int]]) -> bool:
for i in range(len(input)):
for j in range(len(input[0])):
cur = input[i][j]
if all(cur >= input[i][n] for n in range(len(input[i]))) and all(cur <= input[n][j] for n in range(len(input))):
... | magicoder | python |
You are tasked with implementing a Python function that interacts with a financial transactions API. The function is responsible for constructing a POST request to retrieve transactions based on specified parameters. The code snippet provided is a part of the function and demonstrates the handling of optional parameter... | ```python
class TransactionManager:
def __init__(self, client):
self.client = client
def get_transactions(self, account_ids=None, count=None, offset=None):
options = {}
if account_ids is not None:
options['account_ids'] = account_ids
if count is not None:
... | magicoder | python |
You are tasked with creating a Python function that processes a list of GitHub repository information and returns a filtered list based on specific criteria. Each repository is represented as a dictionary with the following keys: "reponame" (the name of the repository), "filename" (the name of the file), and "gh_stars"... | ```python
from typing import List, Dict, Union
def filter_repositories(repositories: List[Dict[str, Union[str, int]]], keyword: str, min_stars: int) -> List[Dict[str, Union[str, int]]]:
filtered_repositories = []
for repo in repositories:
if keyword in repo["reponame"] or keyword in repo["filename"]:
... | magicoder | python |
You are given a list of points in the 2D plane, each represented by a pair of integers (x, y). Your task is to write a function that finds the area of the largest rectangle that can be formed from these points, with sides parallel to the x and y axes. If there isn't any rectangle that can be formed, the function should... | ```python
from typing import List, Tuple
def largest_rectangle_area(points: List[Tuple[int, int]]) -> int:
max_area = 0
point_set = set(points)
for i in range(len(points)):
for j in range(i + 1, len(points)):
if points[i][0] != points[j][0] and points[i][1] != points[j][1]:
... | magicoder | python |
You are tasked with creating a parallel processing function for performing groupby and apply operations on a given dataframe. The function should allow the user to specify the number of processes to use for parallelization. The goal is to optimize the performance of the groupby/apply operation by leveraging parallel pr... | ```python
import pandas as pd
import dask.dataframe as dd
import dill
from multiprocessing import Pool, cpu_count
def apply_func(args):
group, func, data = args
return group, data.groupby(group).apply(func)
def parallel_groupby_apply(dataframe, columns, func, n_processes=None):
if n_processes is None:
... | magicoder | python |
You are tasked with implementing a 3D convolutional neural network (CNN) architecture for a computer vision project. The provided code snippet is a part of the network definition using PyTorch. Your task is to understand the given code and complete the network architecture by adding the remaining layers.
The `convbn_3... | ```python
self.conv2 = convbn_3d(inplanes*2, inplanes*2, kernel_size=3, stride=1, pad=1)
self.conv3 = nn.Sequential(convbn_3d(inplanes*2, inplanes*2, kernel_size=3, stride=2, pad=1),
nn.ReLU(inplace=True))
self.conv4 = nn.Sequential(convbn_3d(inplanes*2, inplanes*2, kernel_size=3, stride=1,... | magicoder | python |
You are tasked with implementing a function that registers datasets for evaluation in a computer vision project. The function should take in a list of dataset names, their corresponding directories, and their split types, and register them for evaluation. Additionally, the function should set the evaluator type for eac... | ```python
import os
from detectron2.data import MetadataCatalog
def register_datasets(dataset_info, root_directory):
SPLITS = dataset_info
for name, dirname, split in SPLITS:
year = 2007 if "2007" in name else 2012
register_pascal_voc(name, os.path.join(root_directory, dirname), split, year)
... | magicoder | python |
You are tasked with implementing a function that validates the structure of a given configuration object. The configuration object is represented as a nested data structure, and you need to ensure that it adheres to a specific format. The format consists of a list with a specific type and a member structure. The type c... | ```javascript
function validateConfigObject(config) {
if (config.type === "list" || config.type === "map") {
if (config.member && typeof config.member === "object") {
if (config.type === "list") {
return validateConfigObject(config.member);
} else if (config.type === "map") {
return (
... | magicoder | javascript |
You are tasked with implementing a Python function that encodes a sequence of symbols using a custom model. The custom model is provided as a Rust function, and your task is to call this function from Python and process the output.
The Rust function `encode_iid_custom_model` takes the following parameters:
- `py`: A P... | ```python
import ctypes
from cffi import FFI
# Load the Rust library
ffi = FFI()
lib = ffi.dlopen("./libcustom_model.so") # Replace with the actual path to the Rust library
# Define the Rust function signature
ffi.cdef("""
void encode_iid_custom_model(void* py, int* symbols, int num_symbols, int** compressed);
"... | magicoder | python |
You are working on a graph slicing algorithm that involves finding a slice at a particular step in the process. The algorithm involves scaling and has a complexity of O(n*(Slicer(n)+Ordering(n))) where n is the number of nodes in the graph. Additionally, the algorithm has a greedy complexity of O(2n^2). You need to imp... | ```python
def find_slice_at_step(ordering, graph, p_bunch):
"""
Parameters:
ordering: list - A list representing the ordering of nodes in the graph
graph: dict - A dictionary representing the graph structure
p_bunch: int - An integer representing the step in the process
Returns:
graph: dict... | magicoder | python |
You are tasked with implementing a URL redirection system for a web application. The system should take a requested URL and redirect it to a specific endpoint with additional parameters. Your task is to write a function that takes a URL and a parameter, and returns a new URL with the parameter appended as a query strin... | ```python
def add_query_param_to_url(url, param_name, param_value):
if '?' in url:
return f"{url}&{param_name}={param_value}"
else:
return f"{url}?{param_name}={param_value}"
```
The `add_query_param_to_url` function first checks if the original URL contains any existing query parameters. If it... | magicoder | python |
You are tasked with creating a Python program to manage a simple inventory system using the tkinter library for the graphical user interface (GUI). The program should allow users to input the number of items, update the inventory, and display the inventory in a tree view.
Your task is to implement a class `InventoryMa... | ```python
import tkinter
from tkinter import ttk
class InventoryManager:
def __init__(self):
self.root = tkinter.Tk()
self.courier = {'font': ('Courier', 12)}
def create_gui(self):
top_frame = tkinter.Frame(self.root)
top_frame.pack()
self.number_of_item_entry = tkinte... | magicoder | python |
You are tasked with creating a program that simulates a simplified version of a Leiningen build tool. Leiningen is a popular build automation tool for Clojure projects, used to manage dependencies, run tests, and build artifacts. Your program should be able to handle adding dependencies, running tests, and building art... | ```python
class LeiningenSimulator:
def __init__(self):
self.dependencies = {}
def add_dependency(self, artifact_id, version):
self.dependencies[artifact_id] = version
def run_tests(self):
# Simulate running tests
print("Running tests...")
def build_artifact(self):
... | magicoder | python |
You are tasked with implementing a class that applies a series of transformations to a given dataset. The class, `TransformDataset`, takes in a dataset and a set of transformations, and ensures that the transformations are valid before applying them.
The `TransformDataset` class has the following requirements:
- It sh... | ```python
class TransformDataset:
def __init__(self, dataset, transforms):
super(TransformDataset, self).__init__()
if not (isinstance(transforms, dict) or callable(transforms)):
raise AssertionError('expected a dict of transforms or a function')
if isinstance(transforms, dict):... | magicoder | python |
You are tasked with implementing a function to process account loading in a banking system. The function receives a list of lookup tables, each containing a certain number of accounts. The goal is to ensure that at least one account is loaded from each lookup table and to track the total number of loaded accounts.
You... | ```rust
#[derive(Debug, PartialEq)]
enum SanitizeError {
InvalidValue,
}
fn process_accounts(num_table_loaded_accounts: Vec<u32>) -> Result<u32, SanitizeError> {
let mut num_loaded_accounts: u32 = 0;
for &accounts in &num_table_loaded_accounts {
if accounts == 0 {
return Err(SanitizeEr... | magicoder | rust |
You are tasked with creating a program that simulates a simplified version of a code generator tool used in a Laravel application. The tool is responsible for generating migration and model files based on a set of directives provided in a configuration file. The directives specify the structure and relationships of the... | ```php
<?php
class DirectiveProcessor
{
public function processDirectives($configFile)
{
$config = json_decode(file_get_contents($configFile), true);
foreach ($config['directives'] as $directive) {
if ($directive['type'] === 'migration') {
$this->generateMig... | magicoder | php |
You are tasked with implementing a Python class that generates a table of contents for a document. The provided code snippet is a simplified version of a `TableOfContents` class, which is a subclass of `NoOptionsNoContentsItem`. The `TableOfContents` class has an `options` attribute that holds a sequence of strings rep... | ```python
def generate_toc(self, sections: Sequence[str]) -> str:
"""
Generates the table of contents based on the provided sections.
Args:
- sections: A sequence of strings representing the sections of the document.
Returns:
A formatted string representing the table of contents with appropria... | magicoder | python |
You are working on a game state management system for a two-player game. The game state is represented by a set of properties and their values. The code snippet provided is a part of the game state management logic. The `state` object is used to access and modify the game state.
The code snippet performs the following... | ```python
import math
def manage_game_state(state):
p1_hand = state.get_value(propname='_placed', fkey='player-1_hand', scope='private', column='unknown')
p2_hand = state.get_value(propname='_placed', fkey='player-2_hand', scope='private', column='unknown')
player = state.get_value(key='$player')
... | magicoder | python |
You are tasked with implementing a simple banking system using Python. The system should support the creation of bank accounts, deposits, withdrawals, and transfers between accounts. Each bank account should have a unique account number, and the system should be able to handle multiple accounts.
Your task is to implem... | ```python
from multipledispatch import dispatch
from copy import deepcopy
import abc
class BankAccount:
def __init__(self, account_number, name, initial_balance):
self.account_number = account_number
self.name = name
self.balance = initial_balance
class Bank(abc.ABC):
def __init__(self... | magicoder | python |
You are tasked with creating a Python program that simulates a simple terminal management system using the Tornado web framework. The program will handle WebSocket connections for terminal sessions and serve static files using Tornado's web application features.
Your task is to implement a class `TerminalManager` that... | ```python
import tornado.web
import tornado.websocket
import tornado_xstatic
class TerminalManager:
def __init__(self):
self.terminals = {}
def create_terminal(self, session_id):
if session_id not in self.terminals:
self.terminals[session_id] = TerminalSession(session_id)
def ... | magicoder | python |
You are tasked with implementing a Snake game using object-oriented programming in Python. The game will involve creating a Snake class with various methods to control the snake's movement and growth. Your task is to implement the `add_body_block` method within the Snake class.
The `add_body_block` method should add a... | ```python
class Snake:
def __init__(self, initial_x, initial_y, initial_direction):
self.__body = [{'x': initial_x, 'y': initial_y}]
self.__directions = [initial_direction]
def add_body_block(self):
# Last block parameters
x, y = self.__body[-1]['x'], self.__body[-1]['y']
... | magicoder | python |
You are tasked with creating a Python decorator function that generates different permutations of a given input test class. The decorator function should take the input test class and return a new test class with all possible permutations of the original test class's methods. Each permutation should be a distinct test ... | ```python
import itertools
import unittest
def permutation_decorator(test_class):
class PermutationTestClass(unittest.TestCase):
pass
methods = [method for method in dir(test_class) if method.startswith('test_')]
for permutation in itertools.permutations(methods):
def generate_test(permut... | magicoder | python |
You are tasked with creating a routing configuration for a web application using Angular. The application has a layout component with a specific layout style, and it needs to load a module for managing movies. Your task is to define the routing configuration for the movies module, ensuring that it is lazy-loaded and re... | ```typescript
{
path: '',
component: LayoutComponent,
data: {
layout: 'classy'
},
resolve: {
initialData: InitialDataResolver
},
children: [
// Movies
{
path: 'movies',
loadChildren: () => import('app/modules/movies/movies.module').then... | magicoder | typescript |
You are given a list of chemical reactions in the form of "X A => Y B", where X and Y are the quantities of chemical A and B produced, respectively. Each reaction specifies the quantities of input chemicals required to produce a certain quantity of output chemicals. Additionally, you are given the quantity of a specifi... | ```python
from typing import List
def calculateORE(reactions: List[str], fuelQuantity: int) -> int:
reaction_map = {}
for reaction in reactions:
inputs, output = reaction.split(" => ")
input_chemicals = inputs.split(", ")
quantity, chemical = output.split(" ")
reaction_map[chemi... | magicoder | python |
You are tasked with implementing a secret sharing scheme using Shamir's Secret Sharing algorithm. Shamir's Secret Sharing is a method for distributing a secret amongst a group of participants, where each participant is given a share of the secret, but only a subset of the shares is sufficient to reconstruct the secret.... | ```python
from typing import List, Tuple
from sympy import mod_inverse
from functools import reduce
class Shamir:
@staticmethod
def split_secret(secret: int, num_shares: int, threshold: int) -> List[Tuple[int, int]]:
shares = []
coefficients = [secret] + [randint(1, 100) for _ in range(threshol... | magicoder | python |
You are tasked with implementing a Java class that manages access tokens for a User-Managed Access (UMA) system. The class should handle token generation, signing, and encryption based on the provided interfaces and properties.
Your task is to create a class named `UMATokenManager` that implements the following interf... | ```java
package org.apereo.cas.uma;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.services.ServicesManager;
import org.apereo.cas.support.oauth.web.response.accesstoken.OAuth20TokenGenerator;
import org.apereo.cas.ticket.IdTokenGeneratorService;
import org.apereo.cas.ticket.OAut... | magicoder | java |
You are tasked with simulating a traffic intersection using an agent-based modeling framework. The intersection consists of four arms, each with a traffic light and a set of agents representing vehicles. The agents move through the intersection based on the state of the traffic lights and their unique identifiers. Each... | ```python
class TrafficIntersection:
def __init__(self, schedule):
self.schedule = schedule
self.count_left = 0
self.count_right = 0
def update_counts(self):
self.count_left = 0
self.count_right = 0
for agent in self.schedule.agents:
if agent.agent_ty... | magicoder | python |
You are tasked with creating a Python function that processes a list of dependencies and operations related to database migrations. Your function should analyze the dependencies and operations to determine the correct order in which the operations should be executed, considering the dependencies between them.
You are ... | ```python
class CircularDependencyError(Exception):
pass
def resolve_migration_order(dependencies, operations):
graph = {dep[1]: dep[0] for dep in dependencies}
visited = set()
result = []
def dfs(operation):
if operation in visited:
raise CircularDependencyError("Circular depe... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.