query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a Python class that combines the functionality of two existing classes. The first class, `pl`, represents a power law model, while the second class, `sfpl`, represents a scale factor power law model. Your goal is to create a new class, `CombinedModel`, that inherits from both `pl` and `... | ```python
import numpy as np
class pl:
default_extra_params = True
default_p = [1]
param_names = ['param1']
default_mappers = [1, 2, 3]
class sfpl:
default_extra_params = True
default_p = [2]
param_names = ['param2']
default_mappers = [4, 5, 6]
class CombinedModel(pl, sfpl):
def _... | magicoder | python |
You are working on a machine learning project that involves sparsifying neural network models to reduce their memory footprint and computational complexity. As part of this project, you need to implement a custom sparsity method using the `FakeSparsity` utility from the `sparsifier` module. The `FakeSparsity` utility p... | ```python
def apply_fake_sparsity(model, sparsity_level):
"""
Apply FakeSparsity method to sparsify the neural network model.
Args:
- model: The neural network model to be sparsified.
- sparsity_level: A float representing the desired sparsity level (proportion of weights to be zeroed out).
Re... | magicoder | python |
You are tasked with creating a Python function that interacts with a PostgreSQL database to perform a search operation based on a user-provided query. The function should connect to the database, execute a search query, and return the results. Your task is to complete the Python function `search_books(query)`.
The fun... | ```python
import os
import psycopg2
def search_books(query):
if query == "" or query is None:
return []
param_str_search = "%" + query + "%"
DATABASE_URL = os.environ.get('DATABASE_URL')
con = psycopg2.connect(DATABASE_URL)
cur = con.cursor()
search_query = "SELECT * FROM books WHERE... | magicoder | python |
You are tasked with implementing a function to manage user and group privileges in a Unix-like operating system. The function `drop_privilege` takes two parameters: `user` (a string representing the username) and `group` (a string representing the group name). The function should drop the group privilege first and then... | ```rust
use nix::unistd::{Group, User};
use anyhow::{Result, Context};
pub fn drop_privilege(user: &str, group: &str) -> Result<()> {
// Retrieve the group ID corresponding to the provided group name
let group = Group::from_name(group)?
.with_context(|| format!("group is not found: {}", group))?;
/... | magicoder | rust |
You are tasked with creating a Python class that processes and tags words within a given sentence. The class should have the following functionalities:
1. Initialize a tag dictionary with word-tag pairs based on a given frequency threshold and ambiguity threshold.
2. Parse a sentence into a list of word-tag tuples.
Y... | ```python
class TagProcessor:
def __init__(self, freq_thresh, ambiguity_thresh):
self.tag_dict = {}
self.freq_thresh = freq_thresh
self.ambiguity_thresh = ambiguity_thresh
def add_word_tag_pair(self, word, tag, mode, n):
if n >= self.freq_thresh and (mode / n) >= self.ambiguity_... | magicoder | python |
You are tasked with implementing a data processing system for a monitoring application. The system receives data in the form of key-value pairs, where the keys represent different attributes of the monitored entities. Your task is to design a data structure and associated methods to efficiently store and retrieve these... | To efficiently store and retrieve the key-value pairs, we can use a HashMap data structure in most programming languages. The key-value pairs can be stored where the key is the attribute name and the value is the associated data.
Here's a sample implementation in Java:
```java
import java.util.HashMap;
public class ... | magicoder | java |
You are tasked with creating a script to automate the process of checking the status of a healthcare dataset using the Google Cloud Healthcare API. The script should take in the project location, dataset name, and store name as input parameters and then use the `gcloud` command-line tool to describe the dataset.
Write... | ```bash
#!/bin/bash
# Check if the required arguments are provided
if [ "$#" -ne 3 ]; then
echo "Usage: $0 <project> <location> <dataset>"
exit 1
fi
# Capture the input arguments
project="$1"
location="$2"
dataset="$3"
# Use gcloud command to describe the healthcare dataset
gcloud alpha healthcare datasets descr... | magicoder | shell |
You are working on a machine learning project and are using PyTorch for building and training neural networks. You have encountered a situation where you need to understand the concept of gradient tracking and detaching in PyTorch.
In PyTorch, when you perform operations on tensors, the framework automatically tracks ... | The concept of gradient tracking in PyTorch refers to the framework's ability to automatically track operations on tensors to compute gradients for backpropagation during training. When a tensor is created with `requires_grad=True`, any operations performed on it are tracked, and gradients can be computed with respect ... | magicoder | python |
You are tasked with implementing a custom view class in Swift that manages a summary table view and a close button. The custom view should handle the layout and interaction of these subviews.
Your task is to create a `SummaryView` class that subclasses `UIView` and includes the following requirements:
- It should have... | ```swift
import UIKit
protocol SummaryViewDelegate: AnyObject {
func closeButtonTapped()
}
class SummaryView: UIView {
weak var delegate: SummaryViewDelegate?
let summaryTableView: UITableView = {
let tableView = UITableView()
// Configure table view properties
return tableView
... | magicoder | swift |
You are tasked with implementing a function that processes date and time information based on the given code snippet. The code snippet is part of a larger program that handles different types of datetime representations. Your task is to create a function that takes a buffer of bytes representing a datetime string and r... | ```rust
use chrono::{DateTime, NaiveDateTime, Utc};
fn process_datetime(buf: &[u8]) -> Option<DateTime<Utc>> {
if buf.is_empty() {
return None; // Empty buffer, unsupported format
}
let datetime_str = match std::str::from_utf8(buf) {
Ok(s) => s,
Err(_) => return None, // Invalid UT... | magicoder | rust |
You are tasked with implementing a simple command pattern in C++. The command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time. The code snippet provided is a simplified version of a command pattern implement... | ```cpp
#include <iostream>
#include <vector>
// Command interface
class Command {
public:
virtual void Execute() = 0;
};
// Concrete command classes
class ConcreteCommand1 : public Command {
public:
void Execute() override {
std::cout << "Executing ConcreteCommand1" << std::endl;
}
};
class Concr... | magicoder | cpp |
You are tasked with creating a function that parses a given set of Laravel routes and extracts the route names and corresponding controller actions. The routes are defined using the `Route::get` and `Route::resource` methods. The function should return a dictionary where the keys are the route names and the values are ... | ```python
import re
def parse_laravel_routes(routes):
route_dict = {}
route_pattern = r"Route::(?:get|resource)\(['\"]([^'\"]+)['\"],\s*['\"]([^'\"]+)['\"]\)"
matches = re.findall(route_pattern, routes)
for match in matches:
route_name = match[1] + '.' + match[0] if match[0] != 'index' els... | magicoder | python |
You are tasked with implementing a Python function that processes a list of dictionaries representing coworking spaces. Each dictionary contains information about a coworking space, with keys representing different attributes such as space name, description, value, label, and URL. However, the keys in the dictionaries ... | ```python
from typing import List, Dict, Union
def standardize_coworkspace_data(data: List[Dict[str, Union[str, int]]]) -> List[Dict[str, Union[str, int]]]:
standardized_data = []
keys_to_standardize = ['pk', 'space_name', 'cs_description', 'value', 'label', 'coworkspace_url']
for entry in data:
... | magicoder | python |
You are tasked with creating a function that handles errors in a Node.js application. The function should take in a callback function and return a new function that wraps the original callback function with error handling. If the original callback function throws an error, the wrapper function should respond with a JSO... | ```javascript
function wrapWithErrorHandling(callback) {
return (req, res) => {
try {
const result = callback(req, res);
res.json(result);
} catch (err) {
res.status(500).json({ message: err.message });
}
};
}
```
The `wrapWithErrorHandling` function takes in a `callback` function and... | magicoder | javascript |
You are tasked with implementing a class for a game's minimap feature. The class, named `Minimap`, should have a method `update` that takes in the position and angle of the game's board and updates the minimap accordingly.
The `Minimap` class has the following attributes:
- `boardPosition`: A 2D vector representing th... | ```cpp
#include <iostream>
class Vector2 {
public:
double x, y;
Vector2(double x, double y) : x(x), y(y) {}
void shrink(double factorX, double factorY) {
x /= factorX;
y /= factorY;
}
};
class Minimap {
private:
Vector2 boardPosition;
double scaleFactor;
public:
Minimap(... | magicoder | cpp |
You are tasked with creating a Python function to simulate a simple reinforcement learning environment. The environment consists of a game with a finite number of episodes, and the goal is to calculate the average reward obtained over a specified number of episodes. The function should take into account the policy used... | ```python
import numpy as np
def calculate_average_reward(env, policy, num_episodes):
episode_rewards = [play_policy(env, policy) for _ in range(num_episodes)]
average_reward = np.mean(episode_rewards)
return average_reward
```
The `calculate_average_reward` function takes the environment `env`, a policy ... | magicoder | python |
You are tasked with creating a Python class that represents a matrix and provides various operations on it. The matrix will be represented as a 2D list of integers. Your class should support the following operations:
1. Initializing a matrix with a given number of rows and columns.
2. Setting a specific cell in the ma... | ```python
class Matrix:
def __init__(self, num_rows, num_cols):
self.matrix = [[0 for _ in range(num_cols)] for _ in range(num_rows)]
self.num_rows = num_rows
self.num_cols = num_cols
def set_value(self, row, col, value):
if 0 <= row < self.num_rows and 0 <= col < self.num_cols:... | magicoder | python |
You are tasked with creating a Django view function that displays building information based on the user's permissions. The view function should only be accessible to authenticated users and should render different content based on whether the user is an admin or not.
Your task is to complete the `buildinginfos_displa... | ```python
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext
from django.shortcuts import render
from webapps.buildinginfos.models import BuildingInfo
from _utils.device_list_utils import get_device_list_and_co... | magicoder | python |
You are tasked with implementing a utility function to calculate the factorial of a given non-negative integer using recursion in Java.
Write a Java method `calculateFactorial` that takes an integer `n` as input and returns the factorial of `n`. The factorial of a non-negative integer `n`, denoted as `n!`, is the prod... | ```java
public class FactorialCalculator {
public static long calculateFactorial(int n) {
if (n < 0) {
throw new IllegalArgumentException("Input should be a non-negative integer");
}
if (n == 0 || n == 1) {
return 1; // Base case: 0! and 1! are both 1
} else {... | magicoder | java |
You are tasked with implementing a data loader for a specific file format used in genomics called BEDPE (Browser Extensible Data Paired-End). The BEDPE format is commonly used to represent paired-end genomic alignments and structural variations. The given code snippet provides a starting point for implementing the data... | ```python
from typing import List, Tuple
def read_bedpe(file_name: str) -> List[Tuple[str, int, int, str, int, int, str]]:
bedpe_data = []
with open(file_name, 'r') as file:
for line in file:
if not line.startswith('#'): # Skip comment lines if present
fields = line.strip()... | magicoder | python |
You are tasked with creating a web application that processes and displays billing information based on user input. The provided code snippet is a part of the HTML form used in the application. The form contains hidden and input fields, as well as a button for processing the data. The PHP code is used to populate some ... | ```php
function generateBillingInfo($bln, $thn)
{
$monthName = date("F", mktime(0, 0, 0, $bln, 1));
$billingDetails = "Billing information for " . $monthName . " " . $thn; // Replace with actual billing calculation logic
return array(
"month" => $monthName,
"year" => $thn,
"billing_... | magicoder | php |
You are tasked with implementing a custom data structure in Swift to represent a stack that supports push, pop, and getMin operations, all of which should be performed in constant time. Additionally, the getMin operation should return the minimum value in the stack at any given time.
You need to create a Swift class n... | ```swift
class MinStack {
private var stack: [(val: Int, minVal: Int)] = []
func push(val: Int) {
if stack.isEmpty {
stack.append((val, val))
} else {
let minVal = min(val, getMin())
stack.append((val, minVal))
}
}
func pop() {
if !st... | magicoder | swift |
You are given a list of strings representing various operations to be performed on a stack. Each operation can be one of the following:
1. "push n": Push the integer n onto the stack.
2. "pop": Pop the top element from the stack.
3. "inc i v": Add v to each of the first i elements of the stack.
Your task is to impleme... | ```python
from typing import List
def performOperations(operations: List[str]) -> List[int]:
stack = []
for op in operations:
if op.startswith("push"):
_, num = op.split()
stack.append(int(num))
elif op == "pop":
stack.pop()
elif op.startswith("inc"):... | magicoder | python |
You are tasked with creating a test suite for a directory management application. The application allows users to create, delete, and navigate through directories. Your task is to implement a test case to ensure that the directory creation functionality works as expected.
You are provided with a `DirectoryManager` cla... | ```swift
import XCTest
class DirectoryManager {
var directories: Set<String> = []
func createDirectory(_ name: String) {
directories.insert(name)
}
func deleteDirectory(_ name: String) {
directories.remove(name)
}
func directoryExists(_ name: String) -> Bool {
return ... | magicoder | swift |
You are tasked with implementing a network packet capture program using the Rust programming language. Your program should utilize the `pcap` crate to capture network packets from a specified device. The code snippet provided below demonstrates the setup of the packet capture process.
Your task is to complete the prog... | ```rust
use pcap::{Capture, Device, Error};
fn main() {
// Find and select a network device
let device = Device::lookup().unwrap().next().expect("no device available");
println!("Using device {}", device.name);
// Setup Capture
let mut cap = Capture::from_device(device)
.unwrap()
.... | magicoder | rust |
You are tasked with creating a Python module for counting the number of API calls made by a program. Your module should be able to track and display the APIs that have been called during the program's execution. You need to implement the `apicount` module and its associated classes and methods to achieve this functiona... | ```python
# apicount.py
class funcnode:
def __init__(self):
self.api_calls = []
def track_api_call(self, api_name):
self.api_calls.append(api_name)
def showapis(self):
if self.api_calls:
print("APIs called during program execution:")
for api in self.api_cal... | magicoder | python |
You are tasked with creating a custom logging system for a software application. The system should utilize the Apache Commons Logging library to handle logging operations. Your task is to implement a class that encapsulates the logging functionality using the Apache Commons Logging API.
You need to create a Java class... | ```java
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class CustomLogger {
private Log logger;
public CustomLogger(String className) {
this.logger = LogFactory.getLog(className);
}
public void debug(String message) {
logger.debug(message);... | magicoder | java |
You are tasked with creating a program that simulates a simple file system navigation and manipulation tool. Your program should implement a subset of commands similar to those found in a Unix shell.
Your program should support the following commands:
- `pushd <directory>`: Pushes the current directory onto the direct... | ```python
class FileSystemNavigator:
def __init__(self):
self.directory_stack = []
self.enabled_directories = set()
def process_command(self, command):
parts = command.split()
if parts[0] == "pushd":
self.push_directory(parts[1])
elif parts[0] == "popd":
... | magicoder | python |
You are working on a bioinformatics project and need to implement a function to decode sources of ligands from a given set of arguments. The function `decode_sources` takes three parameters: `sargs` (a list of strings representing arguments), `ps` (an object containing information about ligands and groups), and `grid` ... | ```python
from KSFD import find_duplicates, KSFDException
def decode_sources(sargs, ps, grid):
try:
ligands = ps.groups.ligands()
nligands = ps.nligands
sources = [0.0] * (nligands + 1)
keys = [arg.split('=', maxsplit=1)[0] for arg in sargs]
dups = find_duplicates(keys)
... | magicoder | python |
You are working on a bioinformatics project and have a list of file names representing variant call format (VCF) files from a genetic sequencing experiment. The file names follow a specific pattern, where `${pre}` represents a placeholder for a prefix. The files contain information about single nucleotide variants (SNV... | ```python
def categorize_files(file_names):
counts = {"SNV": {}, "indel": {}}
for file_name in file_names:
parts = file_name.split("-")
file_type = "SNV" if "snv" in parts[1] else "indel"
region = parts[-1].split(".")[0]
if region not in counts[file_type]:
counts[fi... | magicoder | python |
You are tasked with implementing a priority queue data structure using C++. The priority queue should support the addition of elements with varying priorities and provide a method to remove the element with the highest priority.
The priority queue is implemented using a map where the key is the priority and the value ... | ```cpp
#include <map>
#include <string>
// Element class representing an element in the priority queue
class Element {
public:
Element(const std::string& id, int priority) : id_(id), priority_(priority) {}
const std::string& GetId() const { return id_; }
int GetPriority() const { return priority_; }
priv... | magicoder | cpp |
You are tasked with creating a program to manage and control various coprocessors in a gaming console. The gaming console has multiple coprocessors, each with its own set of functionalities and capabilities. The coprocessors are represented by different classes, each providing specific features and operations. Your tas... | ```cpp
#include <iostream>
#include <memory>
#include <map>
#include <stdexcept>
#include "sfc/coprocessor/cx4/cx4.hpp"
#include "sfc/coprocessor/dsp1/dsp1.hpp"
#include "sfc/coprocessor/dsp2/dsp2.hpp"
#include "sfc/coprocessor/dsp4/dsp4.hpp"
#include "sfc/coprocessor/st0010/st0010.hpp"
// Define a map to store coproc... | magicoder | cpp |
You are tasked with implementing a simple event handling system in JavaScript. The provided code snippet demonstrates the usage of an event handling library called `evn`. The `evn` library provides a method `deactivate()` to deactivate event handling. Additionally, there is a standard `window.dispatchEvent(event)` call... | ```javascript
class EventHandler {
constructor() {
this.active = true;
this.flags = {};
}
activate() {
this.active = true;
}
deactivate() {
this.active = false;
}
dispatchEvent(event) {
if (this.active) {
// Handle the event
// For example: trigger associated callbacks o... | magicoder | javascript |
You are tasked with implementing a function that will parse a given TypeScript file and extract all the imported components from it. The TypeScript file will contain import statements for various components, and your function should return a list of all the imported components.
You are given the following code snippet... | ```typescript
import * as ts from 'typescript';
import * as fs from 'fs';
function extractImportedComponents(filePath: string): string[] {
const fileContent = fs.readFileSync(filePath, 'utf8');
const sourceFile = ts.createSourceFile(filePath, fileContent, ts.ScriptTarget.Latest, true);
const importedComponents:... | magicoder | typescript |
You are tasked with creating a PHP script that organizes and processes various types of user transactions from a database. The script should retrieve and process data from the given models and perform specific operations based on the transaction type. The models represent different types of user activities and transact... | ```php
function processTransaction($transactionType) {
switch ($transactionType) {
case "BookLog":
// Retrieve and display the details of the book log entries
$bookLogs = BookLog::all();
// Display $bookLogs details
break;
case "Card":
// R... | magicoder | php |
You are tasked with creating a script to automate the setup of AWS CloudTrail for multiple regions. The script should check if a CloudTrail is already set up for a specific region and account, and if not, it should create a new CloudTrail with a specified naming convention.
The script should use the AWS CLI and the `j... | ```bash
#!/bin/bash
# Define variables
profile="your_aws_profile"
accountId="your_aws_account_id"
trailname="your_trail_name"
trailbucket="your_s3_bucket_name"
regions=("us-east-1" "us-west-2" "eu-west-1") # Add all required regions
# Function to set up CloudTrail for a region
setup_trail() {
aws --profile $profil... | magicoder | shell |
You are tasked with implementing a method to update a series collection based on user input. The `SeriesCollection` property represents a collection of data series, and the `UpdateAllOnClick` method is called when a user clicks a button to update all the series in the collection. Your task is to write the logic inside ... | ```csharp
private void UpdateAllOnClick(object sender, RoutedEventArgs e)
{
foreach (var series in SeriesCollection)
{
if (series.Name.StartsWith("A"))
{
for (int i = 0; i < series.DataPoints.Count; i++)
{
series.DataPoints[i] *= 2;
}
}... | magicoder | csharp |
You are tasked with implementing a custom conversion service for a Neo4j database using Java. The conversion service will be responsible for converting entities to and from their corresponding graph representations. Your task is to create a class that extends the `org.springframework.core.convert.converter.Converter` i... | ```java
import org.springframework.core.convert.converter.Converter;
import java.util.HashMap;
import java.util.Map;
public class EntityToHashMapConverter<Entity> implements Converter<Entity, HashMap<String, Object>> {
@Override
public HashMap<String, Object> convert(Entity entity) {
HashMap<String, O... | magicoder | java |
You are tasked with creating a Python function that processes notification settings for users within a specific legislative district. The function will take in an email object and retrieve the users who have daily batch sample notifications enabled and are staff members within the same organization as the email. It wil... | ```python
def process_notification_settings(email):
# Retrieve users with daily batch sample notifications enabled and who are staff members within the same organization
users = User.objects.filter(
notificationsetting__daily_batch_sample=True,
organization_id=email.organization_id,
is_s... | magicoder | python |
You are tasked with creating a custom implementation of a generic repository interface in Java. Your goal is to extend the functionality of the JpaRepository interface provided by the Spring Data JPA framework. The JpaRepository interface is a part of the Spring Data JPA library and provides methods for performing CRUD... | ```java
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
public interface AuthorityRepository extends JpaRepository<Authority, String> {
// Custom method for retrieving authorities based on a specific criterion
List<Auth... | magicoder | java |
You are given a tuple `times` containing the names of football teams in a specific league. Your task is to write a Python function that performs the following operations:
A) Return a list of the first five teams in alphabetical order.
B) Determine the position of the team "Chapecoense" in the league table.
Write a fu... | ```python
def league_operations(times):
# A) Return a list of the first five teams in alphabetical order
first_five_alphabetical = sorted(times)[:5]
# B) Determine the position of the team "Chapecoense" in the league table
chapecoense_position = times.index('Chapecoense') + 1
return (first_five_al... | magicoder | python |
You are tasked with creating a Python function that simulates a simple task scheduling system. The function should take in a list of tasks, each represented by a dictionary containing task details such as task name, duration, and resource requirements. The function should then schedule these tasks based on their resour... | ```python
import heapq
def schedule_tasks(tasks):
tasks.sort(key=lambda x: (-int(x["resource"][:-2]), x["duration"])) # Sort tasks by resource (descending) and duration (ascending)
schedule = []
resource_heap = [] # Heap to track available resources
for task in tasks:
duration, resource = ta... | magicoder | python |
You are tasked with creating a command-line tool that processes artifact commands. The tool should accept a list of commands separated by "+" as a parameter and validate each command against a predefined list of available commands. If any of the commands are invalid, an error should be raised. Your task is to implement... | ```python
import argparse
available_commands = ["show", "package", "verify", "upload", "download", "install"]
def parse_command_parameter(argument_value):
command_list = argument_value.split("+")
for command in command_list:
if command not in available_commands:
raise argparse.ArgumentType... | magicoder | python |
You are tasked with creating a Python function that generates a migration file for a Django application. In Django, migrations are used to propagate changes you make to your models (adding a field, deleting a model, etc.) into your database schema. The code snippet provided is a partial representation of a migration fi... | ```python
def generate_migration_file(model_name, fields):
migration_template = f'''
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('relations', '0001_initial'),
]
operations = [
migrations.CreateModel(
... | magicoder | python |
You are given a code snippet that represents a partial implementation of a function to generate unique permutations of a given set of integers. Your task is to complete the implementation of the `permuteUniqueHelper` function to generate all unique permutations of the input integers and return the results.
The `permut... | ```cpp
#include <vector>
#include <algorithm>
class Solution {
public:
std::vector<std::vector<int>> permuteUnique(std::vector<int>& nums) {
std::vector<std::vector<int>> results;
std::sort(nums.begin(), nums.end());
permuteUniqueHelper(results, nums, 0);
return results;
}
priva... | magicoder | cpp |
You are tasked with implementing a simple dependency injection framework in C#. The framework should allow the registration of services and their dependencies, and provide a way to resolve these dependencies when needed.
Your task is to complete the implementation of the `ServicesInjector` class that implements the `I... | ```csharp
// Test the ServicesInjector class
public interface ILogger
{
void Log(string message);
}
public class ConsoleLogger : ILogger
{
public void Log(string message)
{
Console.WriteLine(message);
}
}
public interface IService
{
void Serve();
}
public class Service : IService
{
pr... | magicoder | csharp |
You are tasked with implementing a program that simulates a simple text-based adventure game. The game will involve navigating through different rooms, encountering obstacles, and making decisions that affect the outcome of the game.
Your task is to implement a class `Room` that represents a room in the game. Each roo... | ```csharp
using System;
using System.Collections.Generic;
class Room
{
public string Description { get; set; }
public Dictionary<string, Room> Exits { get; } = new Dictionary<string, Room>();
public List<string> Items { get; } = new List<string>();
public void AddExit(string direction, Room room)
... | magicoder | csharp |
You are given a string containing multiple code snippets in Python. Each code snippet is enclosed within triple quotes (`"""..."""`). Your task is to write a function that extracts and returns all the code snippets from the given string.
Write a function `extract_code_snippets(input_string: str) -> List[str]` that tak... | ```python
from typing import List
def extract_code_snippets(input_string: str) -> List[str]:
snippets = []
start_index = 0
while True:
start_index = input_string.find('"""', start_index)
if start_index == -1:
break
end_index = input_string.find('"""', start_index + 3)
... | magicoder | python |
You are working on a natural language processing (NLP) project and need to implement a topic modeling algorithm using Latent Dirichlet Allocation (LDA). LDA is a generative statistical model that allows sets of observations to be explained by unobserved groups that explain why some parts of the data are similar. In thi... | ```python
import nltk
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.decomposition import LatentDirichletAllocation
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
import string
# Sample text data
documents = [
... | magicoder | python |
You are tasked with creating a program that analyzes the distribution of Python package metadata tags. The metadata is represented as a list of strings, where each string represents a tag. Each tag has a specific format, such as "Programming Language :: Python :: 3" or "Topic :: Software Development :: Libraries". Your... | ```python
from typing import List, Dict
def analyze_tags(tags: List[str]) -> Dict[str, int]:
tag_counts = {}
for tag in tags:
group = tag.split('::')[0].strip()
tag_counts[group] = tag_counts.get(group, 0) + 1
return tag_counts
# Test the function with the given example
tags = [
'Progr... | magicoder | python |
You are tasked with creating a simple application monitoring system. The system should be able to detect when an application is stopping and perform a series of cleanup tasks. Your goal is to implement a class that encapsulates this monitoring functionality.
You are provided with a code snippet that represents a part ... | ```csharp
using System;
using System.Threading;
using System.Threading.Tasks;
public class ApplicationMonitor
{
private readonly CancellationTokenSource _cancellationTokenSource;
public ApplicationMonitor()
{
_cancellationTokenSource = new CancellationTokenSource();
}
public bool IsApplic... | magicoder | csharp |
You are tasked with creating a TypeScript function that interacts with a database and handles potential errors using a wrapper function. The function `insert` takes a `payload` of type `User` and returns a `Promise` of type `ReturnFunc`. The `insert` function attempts to insert the `payload` into a database using a rep... | ```typescript
interface User {
// Define the properties of the User interface
}
interface ReturnFunc {
message: string;
data?: any;
}
// Wrapper function for successful data
const wrapperData = (data: any): ReturnFunc => {
return { message: 'Success', data };
};
// Wrapper function for error
const wrapperErr... | magicoder | typescript |
You are tasked with implementing a generic dispatcher class in Python that can handle different types of dictionaries and dispatch them to corresponding functions based on their types. The dispatcher class should be able to register functions for specific dictionary types and then dispatch incoming dictionaries to the ... | ```python
from typing import Type, Dict, Any, Callable
class Dispatcher:
def __init__(self):
self._dispatch_table: Dict[Type, Callable] = {}
def register(self, type_: Type, func: Callable):
self._dispatch_table[type_] = func
def dispatch(self, data: Dict[Any, Any]):
data_type = ty... | magicoder | python |
You are tasked with implementing a function that reorders words in a given sentence based on specific rules. The function takes in a sentence and a question word as input and rearranges the words in the sentence according to the following rules:
1. If the question word is "what" and the sentence starts with a verb mat... | ```python
def reorder_sentence(sentence: str, question_word: str) -> str:
qwords = sentence.split()
qqword = question_word.lower()
qverb = [word for word in qwords if word[0].lower() == qqword[0]]
a = qwords[0]
if qqword == 'what' and qverb and qwords[0].startswith(str(qverb[0])):
out =... | magicoder | python |
You are tasked with creating a Python function that calculates the area between two given curves. The curves are represented by two lists of y-values, and the area is to be calculated within a specified range of x-values. You should use the `matplotlib` library to visualize the curves and the area between them.
Write ... | ```python
import matplotlib.pyplot as plt
def calculate_area_between_curves(x, y1, y2, xmin, xmax):
plt.plot(x, y1)
plt.plot(x, y2)
plt.fill_between(x, y1, y2, alpha=0.2)
plt.axis([xmin, xmax, min(min(y1), min(y2)), max(max(y1), max(y2))])
plt.ylabel(r"$\bar{r}(\delta / k)$")
plt.xlabel(r"$\del... | magicoder | python |
You are tasked with implementing a function that converts a nested object into a multidimensional array in PHP. The function should handle both associative arrays and objects, and recursively convert any nested objects or arrays into arrays. You are given a partial code snippet as a starting point:
```php
class Object... | ```php
class ObjectConverter {
public function objectToArray($obj) {
if (is_array($obj)) {
$array = [];
foreach ($obj as $key => $value) {
if (is_array($value) || is_object($value)) {
$array[$key] = $this->objectToArray($value);
} e... | magicoder | php |
You are tasked with implementing a simple encryption and decryption program using the AWSCrypto library in Swift. The AWSCrypto library provides cryptographic functionalities for encrypting and decrypting data.
Your task is to create a Swift program that takes a plaintext message as input, encrypts it using the AWSCry... | ```swift
import AWSCrypto
func encryptAndDecryptMessage(plaintext: String) -> Bool {
do {
// Encrypt the plaintext message
let key = SymmetricKey(size: .bits256)
let encryptedData = try AES.GCM.seal(plaintext.data(using: .utf8)!, using: key).combined
// Decrypt the encrypted messag... | magicoder | swift |
You are tasked with creating a program that processes a list of server configuration options and generates a command-line string based on the provided options. Each option is represented as a key-value pair, and the command-line string should be constructed by concatenating the keys and values in a specific format.
Yo... | ```python
from typing import List, Tuple
def generateCommandLine(options: List[Tuple[str, str]]) -> str:
command_line = " ".join(f"-Dplay.server.https.{key}={value}" for key, value in options)
return command_line
```
The `generateCommandLine` function takes a list of tuples representing server configuration o... | magicoder | python |
You are tasked with creating a Python class that simulates a simple plugin system. Your task is to implement the `Plugin` class with a method `do_start` that will be called to start the plugin. The `do_start` method should be overridden by subclasses to perform specific plugin start routines. Additionally, the `do_star... | ```python
class Plugin:
def do_start(self) -> None:
"""
Perform the actual plugin start routine. This method should usually be overwritten by subclasses.
"""
class CustomPlugin(Plugin):
def do_start(self) -> None:
"""
Perform the start routine for the custom plugin.
... | magicoder | python |
You are tasked with implementing a Python class method that handles responses and errors in a state machine. The method is responsible for processing response messages, updating the state, and handling errors. Your task is to complete the implementation of the method `handle_response` in the `StateMachine` class.
The ... | ```python
class StateMachine:
def __init__(self, initial_state_id):
self.state_id = initial_state_id
self.states = []
def handle_response(self, response, err1, err2):
msgs = "\n\n".join(
msg
for msg in (response.msg, response.val["res_msg"], response.status.msg)
... | magicoder | python |
You are tasked with implementing a dependency resolution algorithm. Given a map of dependencies and a map of dependency counters, your goal is to update the dependency counters and identify dependencies that have been resolved.
You are provided with the following code snippet as a starting point:
```rust
if let Some(... | ```rust
use std::collections::HashMap;
fn resolve_dependency(
dependencies_map: &mut HashMap<char, Vec<char>>,
dependencies_counter_map: &mut HashMap<char, i32>,
c: char,
vec: &mut Vec<char>,
) {
if let Some(list) = dependencies_map.get_mut(&c) {
for x in list {
if let Some(coun... | magicoder | rust |
You are tasked with implementing a constraint graph data structure for a computational geometry library. The constraint graph represents a set of points and constraints between them. Each constraint is represented as an edge in the graph. The given code snippet is part of the implementation and contains a method to che... | ```rust
use std::collections::HashSet;
struct Point {
// Define the Point struct with appropriate fields
}
struct Edge {
// Define the Edge struct with appropriate fields and methods
}
struct ConstraintGraph {
edges: HashSet<Edge>,
}
impl ConstraintGraph {
fn insert_constraint(&mut self, point1: Poi... | magicoder | rust |
You are working on a project that involves using a custom library called `vdb` for managing metadata entities. The `vdb` library provides a class called `Entity` which represents a metadata entity in the system. Your task is to create a program that utilizes the `Entity` class to manage a collection of metadata entitie... | ```java
import vdb.metacat.Entity;
import java.util.ArrayList;
import java.util.List;
public class MetadataManager {
private List<Entity> entityCollection;
public MetadataManager() {
entityCollection = new ArrayList<>();
}
public void addEntity(Entity entity) {
entityCollection.add(en... | magicoder | java |
You are tasked with implementing a password generator function in C#. The function should take in two parameters: an integer `length` representing the length of the password to be generated, and a boolean `includeSpecialChars` indicating whether the password should include special characters.
The password generator fu... | ```csharp
using System;
using System.Text;
public class PasswordGenerator
{
private const string UppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private const string LowercaseLetters = "abcdefghijklmnopqrstuvwxyz";
private const string Digits = "0123456789";
private const string SpecialChars = "!@#$%^... | magicoder | csharp |
You are tasked with creating a program to process and combine data related to different types of coins. The data is stored in a nested dictionary structure and needs to be aggregated based on certain criteria. Your task is to write a function that takes the coin data as input and returns the combined data in a specific... | ```python
import collections
def combine_coindata(coindata_cmb):
combined_coindata = collections.defaultdict(list)
for coin_data in coindata_cmb["data"]:
for attribute, value in coin_data.items():
combined_coindata[attribute].append(value)
return dict(combined_coindata)
```
The `combine... | magicoder | python |
You are tasked with implementing a function to calculate the Intersection over Union (IoU) for a batch of bounding boxes. The input to the function is a tensor representing the bounding boxes in the format [batch, box, ...], where each box is represented by its top-left coordinates (x, y) and its width and height. The ... | ```python
import torch
class iou(torch.nn.Module):
def __init__(self):
super(iou, self).__init__()
def forward(self, pred_boxes, gt_boxes):
# Calculate the coordinates of the intersection rectangle
x1 = torch.max(pred_boxes[:, :, 0], gt_boxes[:, :, 0])
y1 = torch.max(pred_boxes... | magicoder | python |
You are tasked with implementing a class for a paraboloid geometry in a ray tracing library. The paraboloid is defined as a surface of revolution, and the class should provide methods for intersection testing, calculating the normal at a given point, checking if a point is inside the paraboloid, and computing the dista... | ```cpp
#include <cmath>
#include "ray_tracing_library.hpp" // Include the ray tracing library
class GC_paraboloid : public GeometryBase {
public:
// Method to determine if a given ray intersects with the paraboloid
virtual bool intersect(const Ray& ray, Intersection& intersection) const override {
// ... | magicoder | cpp |
You are tasked with creating a function to calculate the minimum number of wins required for a team to achieve a certain level of success in a sports tournament. The success level is determined by a given threshold value `n`. The team's win and loss records are represented by variables `w` and `l` respectively. The fun... | ```python
def myfrac(a, b):
return a / b
def minimumWinsRequired(n):
w, l = 999, 1
while True:
f = myfrac(2 * w - l, 2000)
if pow(1 + 2 * f, w) * pow(1 - f, l) >= n:
return w
w, l = w - 1, l + 1
```
The `minimumWinsRequired` function iterates through different win and lo... | magicoder | python |
You are given a list of coin denominations and a target amount. Your task is to write a function to find the minimum number of coins needed to make up that amount. If it is not possible to make up the amount using the given denominations, return -1.
Write a function `minCoins(coins, amount)` where:
- `coins` is a list... | ```python
def minCoins(coins, amount):
dp = [float('inf')] * (amount + 1)
dp[0] = 0 # Base case: 0 coins needed to make 0 amount
for i in range(1, amount + 1):
for coin in coins:
if i >= coin and dp[i - coin] != float('inf'):
dp[i] = min(dp[i], dp[i - coin] + 1)
re... | magicoder | python |
You are tasked with implementing a numerical integration algorithm to calculate the total cost of a system over a given time period. The system is represented by a set of time-dependent parameters and a running cost function. The provided code snippet demonstrates a simple numerical integration process using a time par... | ```python
import numpy as np
def numerical_integration(time_partition, running_cost, **kwargs):
ITest = 0.0
for t0, tf in pairwise(time_partition):
ITest += integrate(running_cost, [t0, tf], **kwargs)
return ITest
```
The `numerical_integration` function takes the time partition, running cost funct... | magicoder | python |
You are tasked with creating a recommendation system for a movie database. The system should take into account user preferences and movie attributes to suggest relevant movies. To achieve this, you need to implement a collaborative filtering algorithm using the cosine similarity measure.
You are given a dataset contai... | ```python
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
def recommend_movies(user_ratings, movie_attributes):
# Convert user ratings to a vector
user_vector = np.array([rating for movie, rating in user_ratings.items()])
# Convert movie attributes to a matrix
attribute_matri... | magicoder | python |
You are tasked with implementing a Python function that calculates the numerically stable log probabilities for a mixture distribution. The function takes in a components distribution and a mixture distribution, and it should return the numerically stable log probabilities for the mixture distribution.
The input compo... | ```python
import torch
class MixtureDistribution:
def __init__(self, components_distribution, mixture_distribution):
self.components_distribution = components_distribution
self.mixture_distribution = mixture_distribution
def calculate_log_prob(self, value):
log_prob_components = self.c... | magicoder | python |
You are given a code snippet that initializes a list called `sieve` with a single element set to `False`. This code is part of an implementation of the Sieve of Eratosthenes, an ancient algorithm for finding all prime numbers up to a specified integer. Your task is to complete the implementation of the Sieve of Eratost... | ```python
def sieve_of_eratosthenes(n):
sieve = [True] * (n + 1)
sieve[0:2] = [False, False] # 0 and 1 are not prime
p = 2
while p * p <= n:
if sieve[p]:
for i in range(p * p, n + 1, p):
sieve[i] = False
p += 1
primes = [i for i in range(2, n + 1) if si... | magicoder | python |
You are tasked with creating a Python function that initializes a classifier for a data visualization tool. The function takes several input parameters and is responsible for setting up the classifier based on the provided inputs. Your goal is to implement the `initialize_classifier` function according to the given spe... | ```python
def initialize_classifier(
viewer: Viewer,
label_layer: "napari.layers.Labels",
label_layer_config={"label": "Label Layer:"},
feature_path_config={"label": "Feature Path:", "filter": "*.csv"},
classifier_name_config={"label": "Classifier Name:"},
feature_selection_config={
"cho... | magicoder | python |
You are tasked with implementing a Python class that represents a configuration for a software application. The configuration consists of a set of key-value pairs, where the keys are strings and the values can be of various types such as strings, integers, floats, or lists. Additionally, the configuration can have chil... | ```python
class Config:
def __init__(self, data, child_configs=None):
self.data = data
self.child_configs = child_configs if child_configs else []
def get_value(self, key):
if key in self.data:
return self.data[key]
for child_config in self.child_configs:
... | magicoder | python |
You are tasked with implementing a Python class that manages different types of runners for a remote sensing application. The runners are responsible for executing processing jobs on different computing environments. Your task is to create a class called `RunnerManager` that can add, remove, and execute different types... | ```python
class RunnerManager:
def __init__(self):
self.runners = {}
def add_runner(self, runner_type, runner_instance):
self.runners[runner_type] = runner_instance
def remove_runner(self, runner_type):
if runner_type in self.runners:
del self.runners[runner_type]
... | magicoder | python |
You are tasked with implementing a class that represents a set of sliders for a user interface. The class should provide functionality for creating, accessing, and manipulating the sliders.
You are given the following code snippet as a starting point:
```cpp
class SliderSet {
private:
Slider* mFeedbackSlider;
... | ```cpp
#include <iostream>
#include <unordered_map>
class Slider {
private:
std::string mName;
double mValue;
public:
Slider(const std::string& name) : mName(name), mValue(0.0) {}
const std::string& getName() const {
return mName;
}
double getValue() const {
return mValue;
... | magicoder | cpp |
You are tasked with implementing a function to calculate the Julian day number corresponding to a given fixed date. The Julian day number is a continuous count of days since the beginning of the Julian period, which started on January 1, 4713 BCE. The fixed date is represented as an integer, where 0 corresponds to Nove... | ```python
def jd_from_fixed(date):
"""Return the Julian day number corresponding to fixed date 'rd'."""
return date + 1721424
```
The solution involves adding a constant value of 1721424 to the given fixed date to obtain the corresponding Julian day number. This constant value aligns with the offset between th... | magicoder | python |
You are given a list of integers representing the heights of a series of walls. Each integer in the list represents the height of a wall at a specific position. Your task is to find the maximum amount of water that can be trapped between the walls. The water is trapped if there are higher walls on both sides of a wall.... | ```python
from typing import List
def max_trapped_water(heights: List[int]) -> int:
n = len(heights)
left_max = [0] * n
right_max = [0] * n
water_trapped = 0
left_max[0] = heights[0]
for i in range(1, n):
left_max[i] = max(left_max[i-1], heights[i])
right_max[n-1] = heights[n-1]
... | magicoder | python |
You are tasked with implementing a memory management system for a custom programming language. The system should track memory usage and handle memory allocation and deallocation.
You are provided with the following code snippet as a starting point:
```cpp
if (void* ptr = malloc(size)) {
CURRENT_MEMORY_USAGE += si... | ```cpp
#include <iostream>
#include <stdexcept>
// Define a custom memory management class
class CustomMemoryManager {
private:
static std::size_t CURRENT_MEMORY_USAGE;
public:
static void* allocate(std::size_t size) {
void* ptr = customAllocationStrategy(size);
if (ptr) {
CURRENT_... | magicoder | cpp |
You are working on a Django project that includes multiple apps. Each app has its own configuration class that inherits from `AppConfig`. The configuration class is responsible for providing metadata about the app, such as its name and any app-specific configurations.
Your task is to create a function that takes a lis... | ```python
import re
def extract_app_config_info(file_paths):
app_config_info = {}
for path in file_paths:
match = re.search(r'([^/]+)\/apps.py<gh_stars>(\d+)', path)
if match:
app_name = match.group(1)
num_stars = int(match.group(2))
file_name = "apps.py"
... | magicoder | python |
You are tasked with implementing a function that will parse and extract data from an HTML file. The function should take in the HTML content as a string and return a list of all the classes present in the "div" elements within the file.
Function Signature:
```python
def extract_div_classes(html_content: str) -> List[... | ```python
from bs4 import BeautifulSoup
from typing import List
def extract_div_classes(html_content: str) -> List[str]:
classes = []
soup = BeautifulSoup(html_content, 'html.parser')
div_elements = soup.find_all('div')
for div in div_elements:
class_attr = div.get('class')
if class_att... | magicoder | python |
You are tasked with creating a dynamic form builder for a web application. The form builder should generate HTML form elements based on the provided configuration. The configuration is an array of objects, each representing a form field. Each form field object contains properties such as name, class, options, dependenc... | ```javascript
function generateFormElements(config) {
let formHtml = '';
config.forEach(field => {
if (field.name) {
if (field.options) {
formHtml += `<select name="${field.name}" class="${field.class}">`;
field.options.forEach(option => {
formHtml += `<option value="${option.va... | magicoder | javascript |
You are tasked with creating a load balancer for a distributed system. The load balancer will be responsible for distributing incoming client connections across a list of available hosts. The load balancer should randomly select a host from the list and attempt to establish a connection. If the connection attempt fails... | ```cpp
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
class Client {
public:
void createConnection(const std::string& host) {
// Simulate connection attempt
if (rand() % 2 == 0) {
// Successful connection
std::cout << "Connected to " << host << std... | magicoder | cpp |
You are tasked with implementing a function to aggregate fit results using weighted average. The function takes in three parameters:
1. `rnd`: an integer representing the round number.
2. `results`: a list of tuples, where each tuple contains a `ClientProxy` object and a `FitRes` object.
3. `failures`: a list of except... | ```python
from typing import List, Tuple, Optional
from some_module import ClientProxy, FitRes, Weights
class FitAggregator:
def __init__(self, min_completion_rate_fit: float):
self.min_completion_rate_fit = min_completion_rate_fit
def aggregate_fit_results(
self,
rnd: int,
res... | magicoder | python |
You are tasked with implementing a file system traversal algorithm using a stack. The file system is represented as a tree structure, where each node can be either a directory containing subdirectories and resources, or a resource itself. The algorithm should traverse the file system in a depth-first manner, returning ... | ```rust
fn main() {
// Example usage
let file_system = DirOrResource::Dir {
name: "root".to_string(),
iter: vec![
DirOrResource::Dir {
name: "dir1".to_string(),
iter: vec![
DirOrResource::Resource(1),
DirOrResour... | magicoder | rust |
You are tasked with implementing a garbage collection algorithm for a programming language runtime. The garbage collector (GC) has three main collection methods: `minor_collection`, `collect`, and `stepwise_major_collection`. The GC also has a method called `pinned_obj_in_stackroot` which checks for pinned objects in t... | ```python
class GarbageCollector:
def __init__(self):
# Initialize garbage collector
def pinned_obj_in_stackroot(self, collection_method):
# Check for pinned objects in the stack root during the collection process
# Implementation logic goes here
def minor_collection(self):
... | magicoder | python |
You are tasked with creating a PHP function that interacts with a cloud service API to retrieve and process data. The cloud service API is accessed using the `communication` function provided by the WeEngine System framework. Your function should retrieve a specific type of data from the cloud service and perform a spe... | ```php
<?php
/**
* [WeEngine System] Copyright (c) 2014 W7.CC.
*/
defined('IN_IA') or exit('Access Denied');
load()->model('cloud');
load()->func('communication');
function processCloudData($dataType) {
if ($dataType === 'users') {
// Retrieve user data from the cloud service
$userData = communi... | magicoder | php |
You are tasked with implementing a data structure to store and display information about agents in a security system. The provided code snippet is part of a larger program that creates cells containing specific information about an agent. Each cell is initialized with a string value derived from the agent's creation ti... | ```python
from prettytable import PrettyTable
class Agent:
def __init__(self, created_at, last_seen_at, identity_public_key_base64):
self.created_at = created_at
self.last_seen_at = last_seen_at
self.identity_public_key_base64 = identity_public_key_base64
def display_agent_info(self):
... | magicoder | python |
You are tasked with creating a simple interactive game interface for two players. The game interface consists of a screen where messages are displayed for each player, and they can manipulate their respective messages using keyboard inputs. The game logic is implemented in Python using the Pygame library.
The provided... | ```python
import pygame
from pygame.locals import *
# Initialize Pygame
pygame.init()
# Define screen dimensions
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
# Create the game screen
screen_object = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# Define the font for rendering text
font_object = pygame.font.Font(... | magicoder | python |
You are tasked with implementing a method to retrieve authentication session information in a web application. The provided code snippet is from an `AuthenticationSessionService` class, which is responsible for managing user authentication sessions. The class has a constructor that takes three dependencies: `IHttpConte... | ```csharp
public async Task<AuthenticationSessionInfo> GetSessionInfoAsync()
{
// Retrieve the current HTTP context
var httpContext = _httpContextAccessor.HttpContext;
if (httpContext != null)
{
// Extract the token from the HTTP context using the ITokenAnalyzer
var token = _tokenAnalyz... | magicoder | csharp |
You are tasked with implementing a custom error handling system for a software application. The system should support categorizing errors into different types and providing meaningful error messages for each error code. Each error code is associated with a unique error message, and the error codes are structured in a h... | ```python
def get_error_message(error_code: int) -> str:
error_messages = {
31522: 'Positive keyword not loaded (UniquenessError)',
31531: 'Negative keyword not loaded (TypeError)',
31532: 'Negative keyword not loaded (UniquenessError)',
40000: 'Unknown error'
}
return e... | magicoder | python |
You are tasked with implementing a message-sending system for a messaging platform similar to DingTalk. The system should be able to send messages to specific users or groups using the provided API. Your task is to complete the implementation of the `send` method in the `MessageSender` class, which is responsible for s... | ```java
import java.util.HashMap;
import java.util.Map;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.OutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class MessageSender {
private Properties properties;
public MessageSender(Properties properties) ... | magicoder | java |
You are given a string representing a message that has been encoded using a specific rule. The rule states that each word in the message should be converted to camel case, where each word (except the first one) starts with a capital letter and there are no spaces between words. However, the message you received has bee... | ```python
def decode_camelcase(encoded_message):
words = encoded_message.split()
decoded_message = words[0] + ''.join(word.capitalize() for word in words[1:])
return decoded_message
```
The `decode_camelcase` function splits the input `encoded_message` into individual words and then reconstructs the origin... | magicoder | python |
You are tasked with implementing a memory allocation system for a custom class in C++. The goal is to create a memory allocation function that allocates memory without calling the constructor of the class. This is a common requirement in scenarios where memory needs to be allocated for placement new operations or custo... | ```cpp
#include <iostream>
class MemoryAllocator {
public:
virtual void* Allocate() = 0;
};
class CustomAllocator : public MemoryAllocator {
public:
void* Allocate() override {
// Allocate memory without calling the constructor
void* memory = ::operator new(sizeof(CustomAllocator));
re... | magicoder | cpp |
You are working on a file management system that involves removing specific files from multiple directories. The code snippet provided is a part of a shell script that removes files matching a certain pattern from the directories `dev/osd0/current` and `dev/osd2/current`. The `rm` command is used to delete files, and t... | ```python
import os
def remove_files(directory: str, file_pattern: str) -> None:
for root, _, files in os.walk(directory):
for file in files:
if file.startswith(file_pattern):
file_path = os.path.join(root, file)
os.remove(file_path)
```
The `remove_files` funct... | magicoder | python |
You are tasked with implementing a simple command-line tool to manage a list of tasks. The tool should support adding new tasks, listing all tasks, and marking tasks as completed. The tool should also handle the "restart" command, which clears all tasks from the list.
You are provided with a code snippet that represen... | ```python
class TaskManager:
def __init__(self):
self.tasks = []
def add_task(self, description):
self.tasks.append({"description": description, "completed": False})
print(f"Task added: {description}")
def list_tasks(self):
for i, task in enumerate(self.tasks, start=1):
... | magicoder | python |
You are tasked with implementing a Python class for image manipulation. The class should inherit from two parent classes, `wx.Image` and `公用方法` (which translates to "common methods" in English). Additionally, the class should have a method `设置宽度高度` (which translates to "set width height" in English) that takes in the w... | ```python
import wx.lib.agw.floatspin as floatspin
from .wxControl import *
class 图片操作(wx.Image, 公用方法):
def 设置宽度高度(self, width, height, quality=0):
# Implement the logic to modify the image's dimensions and quality
# Example implementation:
self.Rescale(width, height) # Modify the image d... | magicoder | python |
You are tasked with implementing a TagChartPresenter class that is responsible for presenting data in a chart format. The presenter interacts with various services and a view to display the data. Your goal is to create the TagChartPresenter class and ensure that it is properly configured to work with the provided servi... | ```swift
class TagChartPresenter {
var settings: Settings?
var calibrationService: CalibrationService?
var view: View?
var measurementService: MeasurementsService?
// Additional methods and logic can be implemented here as per the requirements
init() {
// Initialization code ca... | magicoder | swift |
You are working for a cloud computing company called SauerCloud, which provides various services through the AWS platform. Your task is to create a Python script that automates the deletion of AWS EC2 key pairs for different users. The key pairs are named in a specific format: "SauerCloud-mission4-keypair-Evilcorp-Evil... | ```python
import subprocess
def delete_ec2_key_pair(user_profile: str, user_id: str, key_pair_name: str) -> None:
aws_command = f'aws --profile "{user_profile}" ec2 delete-key-pair --key-name "{key_pair_name}"'
try:
subprocess.run(aws_command, shell=True, check=True)
print(f"Key pair '{key_pair... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.