query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a real-time data visualization system for physiological signals. The system receives data at a sampling frequency of 250 Hz and is required to display the most recent 3 seconds of data. Additionally, a notch filter at 60 Hz needs to be applied to the data before visualization. Your task... | ```python
import numpy as np
import scipy.signal
def updater():
global data, plots, colors
fs = 250 # Hz
disp_sec = 3 # Seconds to display
t_data = np.array(data[-(fs * disp_sec + 100):]).T # transpose data
# Notch Filter at 60 Hz
nyquist = 0.5 * fs
freq = 60.0
Q = 30.0 # Quality ... | magicoder | python |
You are tasked with creating a Python function that simulates the behavior of a simple command-line interface (CLI) tool for managing software releases. The CLI tool has three main functions: `test_release()`, `release()`, and `install_python_version()`. The `test_release()` function checks if the release process is su... | ```python
# cli.py
import subprocess
def test_release():
# Simulate the behavior of the test_release function
# Return 0 to indicate a successful release test
return 0
def release():
# Call subprocess.run with appropriate arguments
# For example, to run a command 'release_command' in the current d... | magicoder | python |
You are tasked with implementing a data structure to manage Relative Distinguished Names (RDNs) in a public key infrastructure (PKI) system. An RDN is a component of a Distinguished Name (DN) in X.500 directory services, typically used in X.509 certificates. Each RDN is a set of attribute value assertions (AVAs) that u... | ```rust
use std::cmp::Ordering;
use std::convert::TryInto;
// Define a struct for Attribute Type And Value (AVA)
#[derive(Debug, PartialEq, Eq)]
struct AttributeTypeAndValue {
attribute_type: String,
attribute_value: String,
}
impl AttributeTypeAndValue {
fn new(attribute_type: &str, attribute_value: &str... | magicoder | rust |
You are tasked with implementing a price adjustment system for a financial trading platform. The system should allow for different types of price adjustments based on predefined options. Each option corresponds to a specific price adjustment rule.
You are given a snippet of code that defines some of the available pric... | ```python
class PriceAdjustmentSystem:
def __init__(self):
self.base_price = 0
self.adjusted_prices = {}
def set_base_price(self, price):
self.base_price = price
def apply_price_adjustment(self, option):
if option == 69:
self.adjusted_prices[option] = self.base_... | magicoder | python |
You are given a set of instructions that represent movements in a 2D space. The movements are represented by a series of commands, each of which can be one of four directions: "N" (north), "S" (south), "E" (east), or "W" (west). Each command also includes a positive integer representing the distance to move in that dir... | ```rust
// Define the struct Position to represent the current position and direction
struct Position {
horizontal: i32,
vertical: i32,
aim: i32,
}
// Define the enum Move to represent the possible movements
enum Move {
North(i32),
South(i32),
East(i32),
West(i32),
}
// Implement the proce... | magicoder | rust |
You are tasked with implementing a custom widget for the Qtile window manager in Python. The widget will display information related to an IMAP email account. The widget should inherit from the `base.ThreadPoolText` class provided by the `libqtile.widget` module. This class allows for asynchronous updates to the widget... | ```python
from libqtile.log_utils import logger
from libqtile.widget import base
import imaplib
import email
class ImapWidget(base.ThreadPoolText):
def __init__(self, **config):
super().__init__("", **config)
self.add_callbacks({
'Button1': self.on_click
})
def fetch_email_... | magicoder | python |
You are tasked with implementing a simplified version of a messaging system using Python. Your goal is to create a class that manages users and allows sending messages to specific users. The provided code snippet includes a method for sending messages to users and the beginning of a class for managing Line users.
Your... | ```python
from linebot import LineBotApi
class LineUsers:
def __init__(self, channel_access_token):
self.line_bot_api = LineBotApi(channel_access_token)
self.registered_users = {}
def register_user(self, user_id):
self.registered_users[user_id] = True
def send_message(self, user_i... | magicoder | python |
You are tasked with creating a Python program that retrieves information about the most starred repositories on GitHub and stores this data in a PostgreSQL database. The program should handle potential errors and log relevant information using the Python `logging` module.
Your program should perform the following step... | ```python
import requests
import psycopg2
import logging
import json
# Set up logging
logging.basicConfig(filename='github_repos.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# Fetch most starred repositories from GitHub API
try:
response = requests.get('https://api.github.com/sear... | magicoder | python |
You are tasked with implementing a session management system for an API server. The system should support logging, tracking active sessions, and categorizing sessions based on their type. You are provided with a code snippet that declares the necessary data structures for this system:
```java
private Logger logger;
pr... | ```java
import java.util.*;
public class APISessionManager {
private Logger logger;
private Set<APISession> sessions;
private Map<String, List<APISession>> chatTakers;
private Map<String, List<APISession>> snitchTakers;
public APISessionManager() {
logger = new Logger(); // Initialize the ... | magicoder | java |
You are tasked with implementing a game management system for a mobile game. The system needs to handle the transition between different scenes and perform specific actions during these transitions. The provided code snippet is from the script responsible for transitioning from the gameplay scene to the menu scene. The... | ```csharp
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameManagement : MonoBehaviour
{
private float adDuration = 5.0f; // Duration of the advertisement in seconds
// Function to display an advertisement before transitioning to the menu scene
public void PlayAd()
{
// Co... | magicoder | csharp |
You are tasked with creating a program that simulates a simple CSS parser. Your program should be able to parse a given CSS code snippet and extract the properties and values for each CSS rule.
You are given a CSS code snippet as a string. Each CSS rule is represented by a set of properties and values enclosed within ... | ```javascript
function parseCSS(cssSnippet) {
const rules = cssSnippet.split(';').map(rule => rule.trim());
const parsedCSS = {};
let currentSelector = '';
for (let rule of rules) {
if (rule.includes('{')) {
currentSelector = rule.split('{')[0].trim();
parsedCSS[currentSelector] = {};
} e... | magicoder | javascript |
You are tasked with creating a program that can extract and display the names of individuals mentioned in a series of print statements. The names are embedded within the strings and are surrounded by various characters. Your program should be able to identify and extract these names, then display them in a standardized... | ```python
import re
def extract_names(input_strings):
names = []
pattern = r'["\']([^"\']+)["\']| --\(([^)]+)\) =([^=]+)'
for string in input_strings:
matches = re.findall(pattern, string)
for match in matches:
names.extend([name.strip() for name in match if name])
... | magicoder | python |
You are tasked with implementing a recursive algorithm for analyzing data. The algorithm operates on a data structure `algo_data` which contains a field `level` representing the current level of recursion. The algorithm decrements the `level` by 1 and then checks if it has reached a specific `max_level`. If the `max_le... | ```python
class Algorithm:
def __init__(self, algo_data, max_level):
self.algo_data = algo_data
self.max_level = max_level
def analyze(self):
if self.algo_data.level == self.max_level:
return self.analyze_data()
else:
self.algo_data.level -= 1
... | magicoder | python |
You are tasked with creating a program that can parse and analyze the source code of a given project to extract information about its open-source license. The program should be able to identify the license type and provide a link to the full text of the license.
Your task is to implement a function or method that take... | ```python
import re
def extract_license_info(source_code: str) -> dict:
license_info = {}
# Regular expression pattern to match license information in comments
pattern = r'(?<=开源协议:)([\w-]+)(?:\s*\(.*\))?\s*((http[s]?:\/\/[^\s\)]+))'
match = re.search(pattern, source_code)
if match:
licen... | magicoder | python |
You are tasked with implementing a custom neural network architecture for 1D signal processing. The architecture involves creating a series of blocks, each consisting of a downsampling convolutional layer followed by a ResNet-like structure with growing dilation rates. Your goal is to write a function that constructs t... | ```python
import torch.nn as nn
class Resnet1D(nn.Module):
def __init__(self, channels, res_depth, m_conv, dilation_growth_rate):
super(Resnet1D, self).__init__()
self.res_layers = nn.ModuleList()
for i in range(res_depth):
dilation = 2 ** (i % dilation_growth_rate)
... | magicoder | python |
You are given a snippet of HTML code representing a portion of a web page. Your task is to write a program that extracts all the phone numbers present in the HTML code and prints them in a standardized format.
The HTML code snippet is as follows:
```
alt="#" />+7123569847</a></li>
... | ```python
import re
def extract_phone_numbers(html_code):
phone_numbers = re.findall(r'\+\d+', html_code) # Extract phone numbers prefixed with '+'
standardized_numbers = [re.sub(r'\D', '', number) for number in phone_numbers] # Remove non-numeric characters
return standardized_numbers
html_snippet = ""... | magicoder | python |
You are given a JSON object representing a system's status. The object contains nested key-value pairs, and you need to write a function to calculate the total count of all numeric values in the object.
You are to implement a function `calculateTotal` that takes a JSON object as input and returns the total count of al... | ```javascript
function calculateTotal(obj) {
let total = 0;
function traverse(obj) {
for (let key in obj) {
if (typeof obj[key] === 'object') {
traverse(obj[key]);
} else if (typeof obj[key] === 'number') {
total += obj[key];
}
}
}
traverse(obj);
return total;
}
//... | magicoder | javascript |
You are given a 2D grid of integers representing elevation points. Each cell in the grid represents the elevation at that point. Your task is to implement a function `lowPoints(grid)` that yields the coordinates of all the points in the grid that are lower than all their neighboring points (up, down, left, right).
The... | ```python
def lowPoints(grid):
M, N = len(grid), len(grid[0])
for y, row in enumerate(grid):
for x, n in enumerate(row):
right = grid[y][x + 1] if x != N - 1 else 9
up = grid[y - 1][x] if y != 0 else 9
left = grid[y][x - 1] if x != 0 else 9
down = grid[y +... | magicoder | python |
You are tasked with implementing a logging middleware for a Node.js web application. The provided code snippet demonstrates the configuration and usage of the logging middleware using the `logger` function. The middleware is conditionally configured based on the presence of the `DEBUG` environment variable and the avai... | ```javascript
function configureApp(app) {
const loggerOptions = {};
if (!process.env.DEBUG) {
loggerOptions.meta = false;
if (typeof global.it === "function") {
loggerOptions.level = "http";
}
}
app.use(logger(loggerOptions));
const routes = [];
routes.push(new AuthRoutes(app));
rou... | magicoder | javascript |
You are tasked with implementing a Python function that processes a list of smiles strings and their corresponding molecule IDs. The function should take the list of smiles and molecule IDs as input and return a dictionary where the keys are the molecule IDs and the values are the corresponding smiles strings.
The inp... | ```python
from typing import List, Dict
def process_smiles_list(smiles_list: List[str]) -> Dict[str, str]:
smiles_dict = {}
for entry in smiles_list:
smiles, mol_id = entry.split("|")
smiles_dict[mol_id] = smiles
return smiles_dict
```
The `process_smiles_list` function iterates through th... | magicoder | python |
You are working on a Minecraft modding project and need to create block states for various types of sloped and steep dash panels. The code snippet provided is a part of the process to define block states for these panels. Each block state is associated with a specific model and orientation. Your task is to write a func... | ```java
import java.util.List;
import java.util.Map;
public class BlockStateGenerator {
public Map<String, JState> generateBlockStates(Map<String, JState> slopedDashPanel, Map<String, JState> steepDashPanel, List<Direction> horizontalDirs) {
JState slopedBlockState = new JState().add(slopedDashPanel);
... | magicoder | java |
You are tasked with implementing a Python class that simulates a vehicle's dynamics. The class should have the following functionalities:
- Accept a time step and a vehicle dynamics function as input during initialization.
- Return the result of the vehicle dynamics function when called with appropriate arguments.
- Pr... | ```python
class VehicleSimulator:
def __init__(self, time_step, veh_dyn):
# Initialize the class with the given time step and vehicle dynamics function
self.time_step = time_step
self.veh_dyn = veh_dyn
def simulate(self, *args, **kwargs):
# Call the vehicle dynamics function wit... | magicoder | python |
You are tasked with creating a Django migration to alter a specific field in a model. The model represents a user profile, and the field to be altered is the "age" field. The goal is to change the data type of the "age" field from an IntegerField to a CharField to accommodate additional information such as "unknown" or... | ```python
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('redacted', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='userprofile', # Replace 'userprofile' with the actual model name
name='age',
... | magicoder | python |
You are tasked with simulating the evolution of a game board based on a specific set of rules. The game board is represented as a 4x4 grid, and each cell can contain either a 0 or a positive integer power of 2. The evolution of the board follows the rules of the popular game "2048".
The rules for the evolution of the... | ```python
import numpy as np
def evolve_board(board):
# Helper function to perform merging and sliding in a single row or column
def merge_and_slide(row):
# Remove zeros from the row
row = row[row != 0]
# Merge adjacent cells with the same value
for i in range(len(row) - 1):
... | magicoder | python |
You are tasked with creating a function that converts a given time from the 24-hour clock format to the Farsi (Persian) numeral system. The Farsi numeral system uses a different set of symbols to represent numbers compared to the standard Arabic numerals. Your task is to implement the conversion function and handle the... | ```php
function convertToPersianNumeral($timeString, $transnumber) {
$timeComponents = explode(":", $timeString);
$hour = intval($timeComponents[0]);
$minute = intval($timeComponents[1]);
if ($transnumber == 1) {
$farsiHour = Convertnumber2farsi($hour);
$farsiMinute = Convertnumber2fars... | magicoder | php |
You are tasked with creating a Python function that simulates a simplified version control system. Your function should implement the basic functionality of adding, committing, and locking files within a repository.
You are given a code snippet that demonstrates the usage of the version control system's commands. The ... | ```python
class VersionControl:
def __init__(self):
self.files = {} # Dictionary to store file status (added, committed, locked)
def add_file(self, file_name):
if file_name not in self.files:
self.files[file_name] = {'status': 'added', 'locked_by': None}
def commit(self, messa... | magicoder | python |
You are tasked with implementing a module system for a web application. The application has a file structure where each module is contained in its own file. The code snippet provided is an example of how modules are imported in the application.
Your task is to create a function that takes a module name as input and re... | ```javascript
const modules = {
'Article': 'export const title = "Sample Article";\nexport const author = "John Doe";'
// Other module contents can be added here
};
function getModuleContent(moduleName) {
if (modules[moduleName]) {
return modules[moduleName];
} else {
return "Module not found";
}
}
... | magicoder | javascript |
You are tasked with implementing a class that manages an in-memory backing store with dirty tracking of changes. The class should allow for setting and getting values, as well as registering callbacks to be invoked when a value changes.
You are provided with the following code snippet as a starting point:
```typescri... | ```typescript
export class InMemoryBackingStore implements BackingStore {
private store: Map<string, storeEntry>;
private callbacks: Map<string, subscriptionCallback[]>;
private returnOnlyChangedValues: boolean;
constructor(returnOnlyChangedValues: boolean = true) {
this.store = new Map();
... | magicoder | typescript |
You are tasked with creating a Python function that validates and processes incoming HTTP requests using Django's `RequestFactory`. The function should take a message in MessagePack format as input, validate it, and then create a POST request using the `RequestFactory`. If the message is valid, the function should retu... | ```python
from django.test import RequestFactory
from django.http import HttpResponse
import msgpack
def process_message_pack_request(data: str) -> Union[str, HttpResponse]:
try:
# Attempt to decode the message pack data
decoded_data = msgpack.unpackb(data, raw=False)
# If decoding... | magicoder | python |
You are given an array of integers and an integer representing the number of rotations to perform on the array. Your task is to implement a function to rotate the array to the right by the given number of positions.
You need to implement the following function:
```java
public static void arrayRotate(int[] arr, int n,... | ```java
public static void arrayRotate(int[] arr, int n, int shift) {
shift = shift % n; // Normalize shift to be within the range of array length
reverse(arr, 0, n - 1); // Reverse the entire array
reverse(arr, 0, shift - 1); // Reverse the first 'shift' elements
reverse(arr, shift, n - 1); // Reverse... | magicoder | java |
You are tasked with implementing a multi-threaded server that processes incoming network requests. The server is designed to handle multiple client connections concurrently using a specified number of threads. Your goal is to create a program that simulates this server behavior and ensures that the threads are managed ... | ```cpp
#include <iostream>
#include <thread>
#include <chrono>
#include <vector>
#include <mutex>
#include <condition_variable>
class Server {
public:
static const int THREAD_COUNT = 5; // Number of threads in the thread pool
std::vector<std::thread> thread_pool;
std::mutex mtx;
std::condition_variable... | magicoder | cpp |
You are tasked with implementing a function to retrieve the last location bounds from a database using Combine framework in Swift. The function should return a publisher that emits the location bounds or an error.
You are given a code snippet that initializes an SQL query to retrieve the last location bounds from a ta... | ```swift
import Combine
struct LocationBounds {
// Define the structure of LocationBounds
}
struct LastLocationTable {
static let tableName = "LastLocation" // Define the table name
}
class LocationService {
private let database: Database // Assume the existence of a Database class
init(database: Da... | magicoder | swift |
You are tasked with creating a simple transaction management system using Rust. The system should consist of two modules: `storage` and `transaction`. The `storage` module will handle the storage of transaction data, while the `transaction` module will provide functionality for creating and processing transactions.
Yo... | ```rust
// storage.rs
pub struct Storage {
transactions: Vec<Transaction>,
}
impl Storage {
pub fn new() -> Self {
Storage {
transactions: Vec::new(),
}
}
pub fn store_transaction(&mut self, transaction: Transaction) {
self.transactions.push(transaction);
}
}
/... | magicoder | rust |
You are tasked with implementing a dependency resolution algorithm for a package manager. The package manager maintains a set of packages that need to be fetched, along with their dependencies. Your goal is to fetch all the required packages while ensuring that each package is fetched only once.
You are given a code s... | ```rust
// Solution for the dependency resolution algorithm
let mut deps_to_fetch: Vec<PackageId> = /* initialize with package IDs */;
let mut fetched_packages: HashSet<PackageId> = HashSet::new();
while let Some(id) = deps_to_fetch.pop() {
if !fetched_packages.insert(id) {
// Handle the case when the pack... | magicoder | rust |
You are given a code snippet from a Java program that appears to be adding integer values to a list named `args` based on the case of a switch statement. Your task is to write a program that simulates the behavior of this code snippet and determines the final contents of the `args` list.
The code snippet provided is p... | To simulate the behavior of the switch statement and determine the final contents of the `args` list, we can create a Java program that replicates the provided code snippet. Here's a sample Java program to achieve this:
```java
import java.util.ArrayList;
import java.util.List;
public class ArgsListSimulation {
p... | magicoder | java |
You are given a text file containing lines of data representing the velocities of objects in a 2D space. Each line consists of a string of characters, and the velocities are encoded within specific positions of the string. The velocities are represented as 12-character substrings, with the first 11 characters represent... | ```python
def calculate_average_velocities(file_path):
total_vx = 0
total_vy = 0
line_count = 0
with open(file_path, 'r') as file:
for line in file:
vx_encoded = line[67:78]
vy_encoded = line[78:89]
vx = float(vx_encoded) / 1e6
vy = float(vy_enco... | magicoder | python |
You are working on a script to automate the copying of files from a Jenkins job workspace to a local directory. The script snippet provided is part of this automation process. The script is written in a Bash shell.
The script starts by extracting the atomic job name from the environment variable `JOB_NAME` using the `... | ```bash
# Bash function to derive the PACKAGE name from the JOB_NAME
derive_package_name() {
local ATOMIC_JOB_NAME
local PACKAGE
ATOMIC_JOB_NAME=$(echo "$1" | cut -d / -f 1) # Extract atomic job name
PACKAGE=${ATOMIC_JOB_NAME%-source*} # Derive PACKAGE name
echo "$PACKAGE" # Return the PACKAGE ... | magicoder | shell |
You are given a list of non-negative integers representing the heights of a set of buildings. You are also given a maximum jump length `k`. Your task is to find the minimum number of hops required to reach the end of the buildings list, where each hop can cover at most `k` buildings. If it's not possible to reach the e... | ```rust
fn min_hops_to_end(buildings: &[usize], k: usize) -> isize {
let n = buildings.len();
let mut dp = vec![std::usize::MAX; n];
dp[0] = 0;
for i in 1..n {
for j in 0..i {
if i - j <= k {
dp[i] = dp[i].min(dp[j] + 1);
}
}
}
if dp[n - ... | magicoder | rust |
You are working as a DevOps engineer for a company that uses Docker for containerization. Your team is responsible for managing Docker Swarm clusters and deploying various services using Docker stacks. One of the critical tasks is to monitor the status of services running in the Docker Swarm cluster. You need to create... | ```python
import subprocess
def get_docker_stack_status(node_name, stack_name):
command = f'docker-machine ssh {node_name} "docker stack ps {stack_name}"'
output = subprocess.check_output(command, shell=True, text=True)
status_dict = {}
lines = output.strip().split('\n')[1:] # Skip the header line
... | magicoder | python |
You are tasked with creating a Python decorator that restricts access to certain functions based on the user's role. The decorator should only allow users with administrative privileges to execute the decorated functions. You are provided with a basic code snippet that demonstrates the structure of the decorator.
Your... | ```python
from functools import wraps
from flask import abort
class User:
def __init__(self, role):
self.role = role
def is_admin(self):
return self.role == 'admin'
# Example current_user object
current_user = User('admin')
def admin_required(func):
@wraps(func)
def decorated_functio... | magicoder | python |
You are tasked with implementing a training scheduler for a machine learning model. The training process involves iterating over a specified number of epochs and adjusting the learning rate based on certain conditions. The code snippet provided gives some insight into the logic for determining the number of valid batch... | ```python
def training_scheduler(batches_to_valid, valid_gen, train_gen, scheduler, epochs):
valid_batches = max(1, int(batches_to_valid * len(valid_gen) / len(train_gen)))
if 'ReduceLROnPlateau' in str(type(scheduler)):
step_scheduler_after_val = True
else:
step_scheduler_after_val = False
... | magicoder | python |
You are tasked with implementing a file decompression algorithm using the Huffman coding technique. Huffman coding is a widely used method for lossless data compression. In this problem, you are given a Python code snippet that calls a method `decompress` on an object `h`. The `decompress` method takes a single argumen... | ```python
import json
import heapq
import os
class HuffmanDecoder:
def __init__(self, encoded_file_path: str, codebook_path: str):
self.encoded_file_path = encoded_file_path
self.codebook_path = codebook_path
self.codebook = self.load_codebook()
def load_codebook(self):
with op... | magicoder | python |
You are working on a project that involves implementing a neural network using TensorFlow. As part of this project, you need to create a function that manipulates input data and performs certain operations based on the TensorFlow library. The function `digit` takes several parameters and performs operations on the inpu... | ```python
import tensorflow as tf
def digit(x, filters, length, iters=3, scope=None):
if tf.__version__ > '2':
filters0 = int(x.shape[1])
length0 = int(x.shape[2])
else:
filters0 = x.shape[1].value
length0 = x.shape[2].value
# fully-connected weights between capsules: [1152... | magicoder | python |
You are tasked with implementing a method to remove the "Remember Me" cookie associated with a user's authentication in a web application. The method `removeRememberMeWithWholeAuthn` takes three parameters: `realmName` (the name of the authentication realm), `request` (the HTTP request object), and `httpResponse` (the ... | ```java
public void removeRememberMeWithWholeAuthn(String realmName, HttpServletRequest request, HttpServletResponse httpResponse) {
try {
Optional<RememberMeCookie> unityRememberMeCookie = getRememberMeUnityCookie(request, realmName);
if (unityRememberMeCookie.isPresent()) {
RememberMeC... | magicoder | java |
You are given a code snippet that reads an image in grayscale using OpenCV and applies Prewitt edge detection kernels to the image. Your task is to implement a function that applies the Prewitt edge detection algorithm to an input grayscale image.
The Prewitt edge detection algorithm uses two 3x3 convolution kernels t... | ```python
import cv2
import numpy as np
from typing import Tuple
def prewitt_edge_detection(image: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
prewitt_kernel_v = np.array([
[-1, -1, -1],
[0, 0, 0],
[1, 1, 1],
])
prewitt_kernel_h = np.array([
[-1, 0, 1],
[-1, 0, 1]... | magicoder | python |
You are tasked with implementing a function to resolve project dependencies in a software development environment. The function should take a project name and a list of already resolved dependencies as input and return a dependency tree for the given project.
You are provided with a code snippet that initializes a var... | ```python
class DependencyNode:
def __init__(self, name):
self.name = name
self.children = []
def recursively_resolve_dependencies(project_name, resolved_dependencies):
# Simulated dependency resolution for demonstration purposes
dependency_tree = {
"A": ["B", "C"],
"B": ["D... | magicoder | python |
You are working on a structural analysis software and need to implement a function to define and integrate beam sections. The software uses the OpenSeesPy library for structural analysis. The code snippet provided demonstrates the usage of various functions to define and integrate beam sections.
Your task is to implem... | ```python
def generate_beam_section_commands(integration_type: str, section_id: int, integration_id: int, np: str) -> str:
commands = f"ops.beamIntegration(\"{integration_type}\", {section_id}, {integration_id}, {np})\n"
commands += "ops.section(\"Fiber\", 2)\n"
commands += "ops.patch(\"quad\", 2, 1, 10, -1... | magicoder | python |
You are tasked with implementing a function that processes a data structure in a Rust program. The function is responsible for creating a new entity within a scene, given a set of parameters. Your task is to complete the implementation of the `create` function, ensuring that it correctly handles the provided inputs and... | ```rust
fn create(context: &Context, scene: &mut Scene, place: Option<&TypeVariable>, value: &Value, index: &ValueIndex, fields: &HashMap<Identifier, (ValueIndex, Span)>) {
// Check if the place is specified and create the entity accordingly
match place {
Some(p) => {
scene.create_entity(Som... | magicoder | rust |
You are tasked with implementing a function to separate a given string into segments based on specified opening and closing boundaries. The boundaries are represented by pairs of strings. If the opening boundary is encountered, the function should start a new segment, and if the closing boundary is encountered, the fun... | ```python
from typing import List, Tuple
def separate(content: str, boundaries: Tuple[str, str]) -> List[str]:
opening, closing = boundaries
segments = []
current_segment = ""
balance = 0
for char in content:
if char == opening:
balance += 1
if balance > 1:
... | magicoder | python |
You are working on a project that involves interacting with a MaaS (Metal as a Service) API to manage nodes in a data center. The provided code snippet is a method within a Python class that is responsible for retrieving a list of nodes and their status from the MaaS API. The method uses an HTTP GET request to the 'v1.... | ```python
class MaaSClient:
def __init__(self, session):
self.session = session
def get_nodes(self):
"""Get list of nodes in MaaS and their status."""
endpoint = 'v1.0/nodes'
resp = self.session.get(endpoint)
self._check_response(resp)
return resp.json()
def... | magicoder | python |
You are tasked with implementing a method to find the maximum value in each row of a given matrix. The matrix is represented by a custom `Matrix` class, and the method should return a list of the maximum values found in each row.
The `Matrix` class has the following relevant methods:
- `int getRowSize()`: Returns the ... | ```java
public List<Number> findMaxValuesPerRow(Matrix matrix) {
List<Number> maxValues = new ArrayList<>();
int rowSize = matrix.getRowSize();
int columnSize = matrix.getColumnSize();
for (int i = 0; i < rowSize; i++) {
Number max = matrix.getValue(i, 0); // Initialize max with the first valu... | magicoder | java |
You are tasked with creating a Python script to automate the process of zipping a directory while excluding specific files or directories. Your script should take the following inputs:
- `source_dir`: The path to the directory that needs to be zipped.
- `output_zip`: The name of the output zip file.
- `exclusions`: A l... | ```python
import os
import zipfile
import fnmatch
def zip_directory(source_dir, output_zip, exclusions):
try:
with zipfile.ZipFile(output_zip, 'w', zipfile.ZIP_DEFLATED) as zipf:
for root, dirs, files in os.walk(source_dir):
for file in files:
file_path = os.... | magicoder | python |
You are tasked with creating a Python function that determines whether a given positive integer is divisible by all the numbers in a specified range. Your function should take three parameters: `num` (the positive integer to be checked), `start` (the starting number of the range), and `end` (the ending number of the ra... | ```python
def is_divisible_by_all(num, start, end):
for i in range(start, end + 1):
if num % i != 0:
return False
return True
```
The `is_divisible_by_all` function iterates through the specified range from `start` to `end` (inclusive) and checks if the given number `num` is divisible by ea... | magicoder | python |
You are tasked with creating a program that processes a list of function and type allowlists and generates a Rust source file based on the provided input. The input consists of a series of command-line arguments, each specifying an allowlist for functions or types, dynamic loading requirements, and the source and desti... | ```rust
use std::env;
use std::fs;
use regex::Regex;
fn main() {
let args: Vec<String> = env::args().collect();
let mut allowlist_function_pattern = String::new();
let mut allowlist_type_pattern = String::new();
let mut dynamic_loading_module = String::new();
let mut dynamic_link_require_all = fal... | magicoder | rust |
You are tasked with implementing a media management system for a cannabis dispensary. The system should allow users to upload, retrieve, and manage various types of media, such as images, videos, and audio files, related to cannabis products and events. The media management system should also support tagging and catego... | ```python
class MediaItem:
def __init__(self, file_path, title, description, tags, category):
self.file_path = file_path
self.title = title
self.description = description
self.tags = tags
self.category = category
class MediaManagementSystem:
def __init__(self):
s... | magicoder | python |
You are tasked with implementing a function to calculate the contrast ratio between the text color of an HTML element and its background color. The contrast ratio is a measure of the difference in luminance or color that makes the text easily readable against the background. The WCAG (Web Content Accessibility Guidelin... | ```typescript
public static getContrastWithBackground(
element: HTMLElement,
colorAttributeName: keyof CSSStyleDeclaration = 'color',
backgroundElement: HTMLElement = element
): number {
const getRGBValue = (color: string): number => {
const trimmedColor = color.trim();
if (trimmedColor.... | magicoder | typescript |
You are tasked with creating a Python decorator that measures the execution time of a function using Celery, a distributed task queue. The code snippet provided imports the Celery application instance from the `approot.celery` module. Your task is to implement the `measure_execution_time` decorator that utilizes Celery... | ```python
from celery import shared_task
from datetime import datetime
from approot.models import ExecutionTime # Assuming a model for storing execution times
def measure_execution_time(celery_app):
@shared_task(bind=True)
def measure_execution_time_task(self, function_name, start_time, end_time):
exe... | magicoder | python |
You are tasked with implementing a function to upload pixel data to a GPU texture. The function should take in pixel data and store it in the GPU's video memory (VRAM). You are provided with a code snippet that includes a method `size_px` which returns the width and height of the pixel data.
Your task is to implement ... | ```rust
use std::error::Error;
pub struct Texture {
w: u32,
h: u32,
// Other texture data members
}
impl Texture {
pub fn size_px(&self) -> [u32; 2] {
[self.w, self.h]
}
pub fn upload_pixels(&self, pixels: &[u8], width: u32, height: u32) -> Result<(), Box<dyn Error>> {
// Simu... | magicoder | rust |
You are tasked with implementing a custom thread pool in Rust. A thread pool is a collection of worker threads that are used to execute tasks concurrently. The pool has a fixed number of worker threads and a queue to hold incoming tasks. When a task is submitted to the pool, it is enqueued, and a worker thread picks it... | ```rust
// The solution provided in the problem description is a comprehensive and correct implementation of a custom thread pool in Rust. It includes the `ThreadPool` struct with the `new` and `execute` methods, as well as the `Worker` struct and associated implementations.
// The `ThreadPool` struct uses the `crossb... | magicoder | rust |
You are tasked with implementing a function that generates and organizes basis blocks for a quantum mechanics simulation. The basis blocks are generated based on certain parameters and constraints. The function takes in three input parameters: `Nfs`, `kblocks`, and `pblocks`, which are lists of integers representing di... | ```python
import numpy as np
from itertools import product
def generate_basis_blocks(Nfs, kblocks, pblocks):
L = len(Nfs) # Assuming L is the length of Nfs
t = np.array([(i+1)%L for i in range(L)])
p = np.array([L-i-1 for i in range(L)])
gen_blocks = {}
basis_blocks = {}
for Nf, kblo... | magicoder | python |
You are given the definition of a ListNode class and a method mergeTwoLists1 that takes in two sorted linked lists, l1 and l2, and returns a new sorted linked list that contains all the elements of l1 and l2. The ListNode class is defined as follows:
```java
class ListNode {
int val;
ListNode next;
ListNod... | ```java
public ListNode mergeTwoLists1(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
if (l1.val < l2.val) {
l1.next = mergeTwoLists1(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists1(l1, l2.next);
... | magicoder | java |
You are tasked with implementing a class that simulates a paper casting machine. The machine takes in a roll of paper and produces individual sheets of paper of a specified length. Your task is to implement the `paperCast` class with the following specifications:
- The `paperCast` class should have a constructor that ... | ```java
public class paperCast {
private String paperRoll;
public paperCast(String paperRoll) {
this.paperRoll = paperRoll;
}
public String produceSheet(int sheetLength) {
if (paperRoll.length() < sheetLength) {
return "Not enough paper left!";
} else {
... | magicoder | java |
You are tasked with implementing a custom memory management system for a programming language that supports object-oriented programming. The system should include a garbage collector to automatically deallocate memory for objects that are no longer in use. To achieve this, you need to design a simple mark-and-sweep gar... | ```python
def mark_and_sweep(objects):
# Marking Phase
def mark_reachable(obj):
if obj['marked']:
return
obj['marked'] = True
for reference in obj.get('references', []):
mark_reachable(reference)
# Mark all reachable objects starting from the root set
for... | magicoder | python |
You are tasked with creating a program to manage orders at a fast-food restaurant. The program should use arrays to store information about the menu items and process customer orders. Each menu item has a name, price, and availability. The program should allow customers to place orders, calculate the total cost of the ... | ```c
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#define MAX_ITEMS 5
typedef struct {
char name[50];
float price;
bool available;
} MenuItem;
MenuItem menu[MAX_ITEMS] = {
{"Burger", 5.99, true},
{"Fries", 2.49, true},
{"Soda", 1.50, true},
{"Salad", 4.99, true},
{"Ice ... | magicoder | c |
You are tasked with creating a Python script that automates the process of uploading a Python package to the Python Package Index (PyPI) using the `twine` package. The `twine` package is a utility for interacting with PyPI and is commonly used to upload Python packages to the repository. Your script should handle the b... | ```python
import subprocess
# Step 1: Build the distribution wheel using setuptools
build_process = subprocess.run(['python', 'setup.py', 'bdist_wheel'], capture_output=True, text=True)
if build_process.returncode == 0:
print("Distribution wheel built successfully.")
else:
print("Error occurred during the bui... | magicoder | python |
You are tasked with implementing a secure communication protocol using Rust. Your goal is to create a function that establishes a secure connection between two endpoints using a Diffie-Hellman key exchange and encrypts the communication using the derived shared secret.
You are provided with a partial code snippet that... | ```rust
use crypto::diffie_hellman;
use crypto::aes;
struct SecretConnection {
shared_secret: [u8; 32],
encryptor: fn(message: &str, shared_secret: &[u8; 32]) -> Vec<u8>,
decryptor: fn(encrypted_message: &[u8], shared_secret: &[u8; 32]) -> String,
}
impl SecretConnection {
fn new(remote_public_key: &[... | magicoder | rust |
You are tasked with implementing a timestamp validation function that checks if a given timestamp is valid. A valid timestamp should adhere to the format "YYYY-MM-DD HH:MM:SS", where:
- YYYY represents the year in four digits (e.g., 2022).
- MM represents the month in two digits (e.g., 01 for January, 12 for December).... | ```python
import re
def validateTimestamp(timestamp: str) -> bool:
pattern = r'^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]) (0\d|1\d|2[0-3]):([0-5]\d):([0-5]\d)$'
if re.match(pattern, timestamp):
return True
else:
return False
```
The `validateTimestamp` function uses a regular expression ... | magicoder | python |
You are tasked with implementing a function that processes a list of commands and updates a dictionary based on the given rules. Each command is a string that consists of two parts separated by the keyword " if ". The first part represents an assignment to a variable, and the second part represents a condition that mus... | ```python
def process_commands(commands):
dictionary = {}
for command in commands:
assignment, condition = command.split(" if ")
var, value = assignment.split(" = ")
condition_var, comparison, condition_value = condition.split()
if condition_var in dictionary:
condi... | magicoder | python |
You are tasked with creating a Python function that securely connects to a remote server using the provided credentials and retrieves specific information. The function should take in the user's credentials and the URL of the server, and then use these to establish a secure connection and fetch the required data.
You ... | ```python
import requests
def fetch_data(user_name: str, password: str, url: str) -> str:
# Create a session to persist the connection
session = requests.Session()
# Set the authentication credentials
session.auth = (user_name, password)
# Make a secure GET request to the server's API end... | magicoder | python |
You are tasked with creating a script to recursively change the permissions of all files within a directory and its subdirectories. The script should take a list of directory paths as input and then apply the permission change to all files within each directory.
Your script should accept a list of directory paths as i... | ```bash
#!/bin/bash
# Check if input directories are provided
if [ $# -eq 0 ]; then
echo "Usage: $0 dir1 dir2 dir3 ..."
exit 1
fi
# Iterate through each input directory
for dir in "$@"; do
# Check if the directory exists
if [ -d "$dir" ]; then
# Change permissions of all files within the directory and its... | magicoder | shell |
You are working on a deployment script for a command-line tool called "ls-x" written in Go. The script is responsible for setting up the necessary configuration and adding the tool to the user's shell resource file. Your task is to write a Bash script that automates this setup process.
Write a Bash script named "setup... | ```bash
#!/bin/bash
# Create directory if it doesn't exist
mkdir -p "$HOME/.config/lsx"
# Copy lsx.sh to the created directory
cp "script/lsx.sh" "$HOME/.config/lsx/lsx.sh"
# Build ls-x and place the executable in $GOPATH/bin
go build -o "$GOPATH/bin/ls-x"
# Check if build was successful
if [ $? -eq 0 ]; then
ech... | magicoder | shell |
You are working on a TypeScript project that involves generating an enhanced map based on various input parameters. The `generateEnhanceMap` function takes in a source file and several arrays of model mappings, relation models, models, input types, and output types. Your task is to implement the logic for the `generate... | ```typescript
export declare function generateEnhanceMap(
sourceFile: SourceFile,
modelMappings: DMMF.ModelMapping[],
relationModels: DMMF.RelationModel[],
models: DMMF.Model[],
inputs: DMMF.InputType[],
outputs: DMMF.OutputType[]
): void {
// Your implementation logic goes here
// Process the input par... | magicoder | typescript |
You are working on a simulation model to predict the spread of a contagious disease within a population. The code snippet provided initializes arrays to store the number of individuals in various states related to the disease. The arrays `dead`, `recovered`, `infected`, and `proven` are all initialized as arrays of zer... | ```python
import numpy as np
def simulate_disease_spread(dead, recovered, infected, proven, num_time_steps):
data_len = len(dead)
for _ in range(num_time_steps):
for i in range(data_len):
if proven[i] == 1: # Skip individuals who have been proven infected
continue
... | magicoder | python |
You are tasked with creating a program that analyzes CSS code to identify and count the number of unique CSS properties used in a given stylesheet. Each CSS property is defined by a line that follows the format `property: value;`. The program should ignore any leading whitespace and consider only the property name, dis... | ```javascript
function countUniqueCSSProperties(cssCode) {
const properties = new Set();
const lines = cssCode.split('\n');
for (let line of lines) {
const property = line.trim().split(':')[0];
properties.add(property);
}
return properties.size;
}
// Test the function
const cssCode = `
font-weight: ... | magicoder | javascript |
You are tasked with implementing a negotiation mechanism for a fast factory simulator. The simulator is designed to handle storage as an array and temporary transactions. Your goal is to create a custom negotiator using the `AspirationNegotiator` class from the `my_mechanism` module. The negotiator should be able to ha... | ```python
from negmas.common import NamedObject
from negmas.events import Notification
from negmas.outcomes import Issue, Outcome
from negmas.utilities import UtilityValue, normalize
from negmas.helpers import get_class
from negmas.common import FastFactorySimulator, storage_as_array, temporary_transaction
from negmas.... | magicoder | python |
You are tasked with implementing a program that can parse and extract information from a specific type of file. The file format consists of a series of records, each containing multiple fields. Each field is represented by a key-value pair, where the key and value are separated by a colon. The records are separated by ... | ```python
def parse_file_contents(file_contents):
records = file_contents.strip().split('\n\n') # Split the file contents into individual records
result = []
for record in records:
fields = record.split('\n') # Split each record into individual fields
record_dict = {}
for field in ... | magicoder | python |
You are tasked with implementing a class to manage a file format called RMF (Rich Molecular Format). The RMF file format is used to store molecular structures and associated data. Your task is to create a class that can handle the creation of RMF files and manage the addition of frames and nodes within the file.
You a... | ```cpp
#include <iostream>
#include <string>
#include <vector>
#include <RMF.h> // Assuming the RMF library is included
class RMFFileHandler {
public:
RMF::FileHandle createRMFFile(const std::string& filename) {
return RMF::create_rmf_file(filename);
}
void addFrame(RMF::FileHandle& fileHandle, c... | magicoder | cpp |
You are tasked with creating a Python module that manages global variables and provides initialization functionality. Your task is to implement the `init_globals` function, which should return a list of strings containing global variable assignments. Additionally, you need to ensure that the module cannot be directly c... | ```python
import os
def _getBasepath():
# Define the logic to obtain the base path
pass
def init_globals():
basepath = _getBasepath()
imports_path = os.path.join(basepath, 'import')
return [
'@var _id="sys" basepath="{}" imports="{}"'.format(basepath, imports_path),
]
if __name__ == '... | magicoder | python |
You are tasked with implementing a thread-safe data structure called `ConcurrentStack<T>`. The stack should support the standard push and pop operations, but with the added requirement of being thread-safe to allow concurrent access from multiple threads without causing data corruption or race conditions.
Your task is... | ```csharp
public class ConcurrentStack<T>
{
private volatile Node<T> _head;
public void Push(T obj)
{
Node<T> newNode = new Node<T>(obj);
while (true)
{
Node<T> oldHead = _head;
newNode.Next = oldHead;
if (Interlocked.CompareExchange(ref _head, ne... | magicoder | csharp |
You are tasked with creating a program to process text data and generate vocabulary counts using the GloVe word embedding tool. GloVe (Global Vectors for Word Representation) is an unsupervised learning algorithm for obtaining vector representations for words. The given code snippet is a part of a larger program that p... | ```python
from typing import List
from pathlib import Path
import subprocess
def generate_vocabulary_counts(input_files: List[str], min_count: int, verbose: bool, output_path: str) -> None:
output_path = Path(output_path)
output_path.mkdir(parents=True, exist_ok=True) # Create the output directory if it does ... | magicoder | python |
You are tasked with creating a reinforcement learning environment for a simple game. The game involves a player navigating a grid-based world, aiming to reach a goal while avoiding obstacles. To accomplish this, you need to implement a Python class that represents the game environment and allows an agent to interact wi... | ```python
import numpy as np
from microtbs_rl.algorithms.common.agent import AgentLearner
from microtbs_rl.algorithms.common.loops import run_policy_loop
class GridWorldEnvironment:
def __init__(self, grid):
self.grid = np.array(grid)
self.initial_state = np.where(self.grid == 0)
self.agent... | magicoder | python |
You are tasked with implementing a function that parses a given HTML class attribute and returns a list of the column sizes specified in the attribute. The class attribute follows the Bootstrap grid system format, where the column sizes are defined for different screen sizes.
The class attribute format is as follows:
... | ```python
from typing import List, Tuple
def parseColumnSizes(class_attribute: str) -> List[Tuple[str, int]]:
column_sizes = []
classes = class_attribute.split()
for class_name in classes:
if class_name.startswith('col-'):
parts = class_name.split('-')
screen_size = parts[1]... | magicoder | python |
You are tasked with creating a Python function that simulates a volume driver's initialization process for a storage system. The function should handle the connection between a host and a storage volume, and raise a specific exception if the connection cannot be established.
You are given a code snippet that initializ... | ```python
class VolumeDriverException(Exception):
pass
class YourVolumeDriver:
def initialize_connection(self, volume, connector):
# Simulate connection initialization process
volume_id = volume['provider_location']
host_name = connector['host']
wwpns = connector['wwpns']
... | magicoder | python |
You are tasked with implementing a function that processes test configurations and draws the results of an experiment. The function `experiment_drawing.draw_results(ibs, testres)` is provided for drawing the results of the experiment. Additionally, a commented-out function `get_cmdline_testres()` is given, which seems ... | ```python
import main_helpers
import experiment_drawing
def process_and_draw_test_results(test_cfg_name_list):
ibs, qaids, daids = main_helpers.testdata_expanded_aids(verbose=False)
testres = run_test_configurations(ibs, qaids, daids, test_cfg_name_list)
experiment_drawing.draw_results(ibs, testres)
re... | magicoder | python |
You are tasked with creating a Python program that simulates a simple email management system. Your program should include the following functionalities:
1. Send an email to multiple recipients with both plain text and HTML content.
2. Generate a URL for a given view in a Django web application.
Your program should u... | ```python
from django.core.mail import EmailMultiAlternatives
from django.core.urlresolvers import reverse
from django.conf import settings
def send_email_with_url(subject, from_email, to_emails, plain_text_content, html_content, view_name, url_args):
# Send email with plain text and HTML content
msg = EmailMu... | magicoder | python |
You are tasked with implementing a function that performs scatter update on a given tensor. Scatter update is an operation that updates the elements of a tensor at specified indices with new values. The function takes three inputs: `indices` (a tensor of type int32), `updates` (a tensor of type float16, float32, int32)... | ```python
import akg
def scatter_update(indices, updates, shape):
# Create an output tensor of the specified shape filled with zeros
output = akg.tvm.compute(shape, lambda *i: akg.tvm.const(0, dtype=updates.dtype), name='output')
# Update the elements of the output tensor at the specified indices with the... | magicoder | python |
You are tasked with creating a custom class for managing podcast episodes in a mobile app. The class should include properties for the episode's details and a progress view for tracking the episode's playback progress. Additionally, the class should handle updating the user interface elements based on the episode's inf... | ```swift
import UIKit
import SDWebImage
class PodcastEpisode {
var progress: Float = 0 {
didSet {
progressView.progressTintColor = .primaryColor
// Update progress view with new progress
updateProgressView()
}
}
var episode: Episode! {
didSet... | magicoder | swift |
You are tasked with writing a program to process a string containing file paths and extract the unique directory names from the paths. Each file path is enclosed in double quotes and separated by a plus sign. The file paths are absolute paths to directories and end with the "/Headers" directory.
Write a function or me... | ```python
import re
def extract_directory_names(input_string):
paths = re.findall(r'"(.*?/Headers)"', input_string)
unique_directories = list(set(paths))
return unique_directories
input_string = (
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/sensors/sensors.framework/Headers\""+... | magicoder | python |
You are given a list of strings representing numbers in English words. The list contains numbers from 1 to 9999. Your task is to write a function that takes a number as input and returns its English word representation.
For example, given the following code snippet:
```
ones = ['','one','two','three','four','five','si... | ```python
def numberToWords(num: int) -> str:
ones = ['','one','two','three','four','five','six','seven','eight','nine']
tens = ['','ten','twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety']
hundreds = ['','one hundred','two hundred','three hundred','four hundred','five hundred','six hundr... | magicoder | python |
You are tasked with implementing a custom data structure to store and manage test results. The `TestResultList` class is designed to represent a list of test results, and it includes various annotations and methods for data management. Your goal is to complete the implementation of this class by adding necessary fields... | ```java
import lombok.ToString;
import java.util.ArrayList;
import java.util.List;
/**
* Model of the test result list.
*/
@Schema(
description = "The test result list model."
)
@Getter
@ToString
@EqualsAndHashCode
public class TestResultList {
private List<Integer> testResults;
public TestResultList() {... | magicoder | java |
You are tasked with creating a Python function that parses command-line arguments for a reinforcement learning agent training and running program. The function should take a list of strings as input and return a tuple containing an optional string and a non-optional string. The function should also have a decorator `@r... | ```python
from typing import List, Optional, Tuple, Union
from argparse import ArgumentParser
def run(
args: List[str] = None
) -> Union[None, Tuple[Optional[str], str]]:
"""
Run RLAI.
:param args: Arguments.
:return: Return value of specified function.
"""
parser = ArgumentParser(add_... | magicoder | python |
You are tasked with implementing a class method that calculates the total number of tokens in an image generation model. The model has a decoder with a specified number of resolutions, and the method should take into account the dimensions of the image and a scaling factor. The method should return the total number of ... | ```python
class ImageModel:
def calculate_total_tokens(self, model, e_dim, n_toks, width, height, scale):
f = 2 ** (model.decoder.num_resolutions - 1)
self.e_dim = e_dim
self.n_toks = n_toks
width *= scale
height *= scale
total_tokens = (width // f) * (height // f) ... | magicoder | python |
You are tasked with creating a Python class that models a team within an organization. The class should have attributes for the team name, a unique key, a manager (who is also a member of the team), and a list of other teams that this team communicates with.
Your task is to implement the `Team` class with the specifie... | ```python
from peewee import Model, CharField, IntegerField, ForeignKeyField, ManyToManyField
class Team(Model):
name = CharField(max_length=50, primary_key=True, description="The TEAM name (and PK)")
key = IntegerField()
manager = ForeignKeyField("self", related_name="team_members", null=True)
talks_t... | magicoder | python |
You are tasked with creating a secure password hashing function using Python. Your function should take a plaintext password as input and return a securely hashed version of the password. To achieve this, you will need to utilize the `hashlib` library for hashing and the `base64` library for encoding the hashed passwor... | ```python
import uuid
import base64
import hashlib
def secure_hash_password(plaintext_password: str) -> str:
# Generate a unique salt
salt = str(uuid.uuid4())
# Combine the plaintext password with the salt
combined_password = plaintext_password + salt
# Hash the combined password and salt using S... | magicoder | python |
You are tasked with creating a class to solve a specific challenge. The challenge involves finding the sum of all prime numbers below a given limit. Your task is to implement the `Challenge10` class and the `solveChallenge10` function to solve this challenge.
The `Challenge10` class should have the following propertie... | ```cpp
#include <vector>
#include <cmath>
namespace challenges {
class Challenge10 {
public:
using Type_t = unsigned long long;
Challenge10(unsigned long long limit) : limit(limit) {}
Type_t solve() {
std::vector<bool> sieve(limit, true);
sieve[0] = sieve[1] =... | magicoder | cpp |
You are tasked with implementing a macro expansion system for a simplified version of the C preprocessor. The system should be able to handle the expansion of macros with or without parameters.
A macro definition can take two forms:
1. Simple macro without parameters:
```c
#define MACRO_NAME replacement_text
```
2. Ma... | ```c
#include <iostream>
#include <string>
#include <unordered_map>
#include <sstream>
std::unordered_map<std::string, std::string> macroDefinitions;
// Function to expand a single macro
std::string expandMacro(const std::string& macroName, const std::string& args) {
std::string replacementText = macroDefinitions... | magicoder | c |
You are tasked with implementing a Python decorator that tracks the number of times a decorated function is called. The decorator should be applied to various methods within a class, and the class itself should be decorated to enable the tracking functionality. The decorator should maintain a count of how many times ea... | ```python
# Define the track_calls decorator
def track_calls(func):
def wrapper(*args, **kwargs):
wrapper.call_count += 1 # Increment the call count
return func(*args, **kwargs)
wrapper.call_count = 0 # Initialize the call count
return wrapper
# Define the enable_tracking decorator
def en... | magicoder | python |
You are tasked with creating a script to automate the setup of Datadog monitoring in a PHP environment. The script should modify an INI configuration file to include specific settings related to Datadog monitoring. Your task is to implement a function that processes the given code snippet and determines the changes mad... | ```python
def process_datadog_setup_code(code_snippet):
ini_file = "path/to/ini/file.ini" # Replace with actual INI file path
changes = []
for line in code_snippet.split('\n'):
if line.startswith('assert_file_not_contains'):
config = line.split(' ')[-1][1:-1] # Extract the configurati... | magicoder | python |
You are working on a web application that allows users to participate in quizzes. The application has certain configurations that determine the behavior of the quiz system. Two of these configurations are defined in the code snippet provided:
1. `ALLOW_MULTIPLE_ANSWER`: A boolean variable that determines whether playe... | ```python
def quiz_system_behavior(allow_multiple_answer, zoom_level):
if allow_multiple_answer:
behavior_message = "Players can provide multiple answers to the same question"
else:
behavior_message = "Players can only provide a single answer to each question"
return f"If multiple answers a... | magicoder | python |
You are tasked with simulating the recovery from a page fault on a RISC-V processor. In this problem, you will need to implement a class that handles the recovery process and verify its functionality through a series of test cases.
Your task is to create a Python class that extends the functionality of a base class `P... | ```python
from riscv.ModifierUtils import PageFaultModifier
class MainSequence(PageFaultSequence):
def __init__(self, gen_thread, name=None):
super().__init__(gen_thread, name)
self._mInstrList = (
"JAL##RISCV",
"JALR##RISCV",
"LD##RISCV",
"SD##RISCV"... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.