query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with designing a system for managing and applying rules to a network service. The system is responsible for creating rule objects based on configuration data and applying commands to these rules. Your goal is to implement a class that can handle the creation and application of rules based on the provided... | ```cpp
#include <memory>
#include <stdexcept>
#include <vector>
// Define the interface for the rule
class IRule {
public:
virtual void applyCommands() = 0;
// Add any other necessary methods or members
};
// Define the configuration data structure
struct ConfigData {
struct Rule {
std::string nam... | magicoder | cpp |
You are tasked with implementing a Python function that evaluates the performance of an image autoencoder model. An autoencoder is a type of artificial neural network used to learn efficient representations of data, typically for the purpose of dimensionality reduction. The given code snippet is part of a larger progra... | ```python
import torch
def calculate_reconstruction_error(original_images, reconstructed_images):
"""
Calculate the average pixel-wise reconstruction error between original and reconstructed images.
Args:
original_images (torch.Tensor): Tensor containing original images.
reconstructed_images (torc... | magicoder | python |
You are tasked with implementing a concurrent mark stack draining algorithm using the given template class `OopClosureClass`. The goal is to apply the given closure to all fields of objects on the mark stack until the stack is empty. The `par_pop_arr` function is provided for concurrent popping of elements from an arra... | ```cpp
template<class OopClosureClass>
bool drain_mark_stack(oop* ptr_arr, int max, int* n, Object* bm, bool yield_after) {
while (*n > 0) {
oop obj;
if (par_pop_arr(ptr_arr, max, &obj)) {
if (bm != nullptr && !bm->is_marked(obj)) {
// Object is not marked, skip processin... | magicoder | cpp |
You are given a list of integers representing a sequence of numbers. Your task is to write a function that returns the majority element in the list. A majority element is an element that appears more than ⌊n/2⌋ times, where n is the length of the list.
For example, given the list [3, 3, 4, 2, 4, 4, 2, 4, 4], the major... | ```python
from typing import List
def majority_element(nums: List[int]) -> int:
count = 0
candidate = None
for num in nums:
if count == 0:
candidate = num
count = 1
elif num == candidate:
count += 1
else:
count -= 1
return candid... | magicoder | python |
You are tasked with implementing a function that calculates the distance between two points on the Earth's surface given their latitude and longitude coordinates. The Haversine formula is commonly used to perform this calculation. The formula is as follows:
\[ a = \sin^2\left(\frac{\Delta\text{lat}}{2}\right) + \cos(\... | ```swift
func calculateDistance(lat1: Double, lon1: Double, lat2: Double, lon2: Double) -> Double {
let R = 6371.0 // Earth's radius in kilometers
let lat1Rad = lat1 * .pi / 180.0
let lon1Rad = lon1 * .pi / 180.0
let lat2Rad = lat2 * .pi / 180.0
let lon2Rad = lon2 * .pi / 180.0
let dLat = l... | magicoder | swift |
You are tasked with creating a script to automate the process of updating the bash completion file for Docker Compose. The script should download the latest bash completion file from the Docker Compose GitHub repository and then move it to the appropriate location for bash completion on a Linux system.
Your task is to... | ```bash
#!/bin/bash
# Retrieve the version number of the installed Docker Compose
compose_version=$(docker-compose version --short)
# Download the corresponding bash completion file from the Docker Compose GitHub repository
wget https://raw.githubusercontent.com/docker/compose/${compose_version}/contrib/completion/ba... | magicoder | shell |
You are working on a machine learning project and need to optimize hyperparameters for two different models: Random Forest and XGBoost. The hyperparameters and their potential values are given in the code snippet below. Additionally, the class weight for both models is set to 'balanced'. Your task is to write a functio... | ```python
from itertools import product
def generate_hyperparameter_combinations(hyperparameters):
combinations = []
for model, params in hyperparameters.items():
keys = list(params.keys())
values = [params[key] for key in keys]
for combination in product(*values):
combinati... | magicoder | python |
You are tasked with creating a Laravel API endpoint that returns a paginated list of images using the Fractal library for transformation. The API should accept a request with a cursor parameter to implement cursor-based pagination. You will need to use the `Illuminate\Http\Request` class to handle the incoming request ... | ```php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use League\Fractal\Pagination\Cursor;
use App\Transformers\ImageTransformer;
use App\Models\Image;
use League\Fractal\Serializer\ArraySerializer;
use League\Fractal\Manager;
use League\Fractal\Resource\Collection;
class ImageController extends... | magicoder | php |
You are working on a computer vision project and need to implement a function to calculate the transformation matrix for converting 3D coordinates to 2D image coordinates. The transformation involves camera calibration parameters and the 3D coordinates of a point in the world coordinate system. You are given the follow... | ```python
import numpy as np
def calculate_transformation_matrix(x, y, x_cam, y_cam, cam_x, cam_y):
ones = np.ones_like(x)
A = np.vstack([x, y, ones]).T
b = np.vstack([x_cam, y_cam, ones]).T
T, _, _, _ = np.linalg.lstsq(A, b, rcond=None)
return T.T
```
The `calculate_transformation_matrix` functio... | magicoder | python |
You are working on a project to analyze data from a space telescope. The project involves using the `astropy` library to handle astronomical units and quantities. You need to write a Python function to calculate the total observation time based on the field of view offset bins and the observation time for individual ev... | ```python
import astropy.units as u
def calculate_total_observation_time(fov_offset_bins, t_obs):
total_observation_time = fov_offset_bins.size * t_obs
return total_observation_time.to(u.s) # Ensure the output has the correct units (seconds)
# Example usage
fov_offset_bins = 10 * u.deg # Example field of vi... | magicoder | python |
You are tasked with creating a Python class that manages activity areas and their status. The class should have a method to delete an activity area based on the provided ID. The method should only allow deletion if the requesting user is an admin and the activity area with the given ID exists and is currently active. I... | The `ActivityManager` class is implemented with the `delete` method that checks the user's admin status and the existence of the activity area with the given ID. If the conditions are met, the method updates the status of the activity area and returns the appropriate response. If the conditions are not met, it returns ... | magicoder | python |
You are given a Python code snippet that processes a 2D array of image data and writes the flattened image data along with an output value to a file. Your task is to understand the code and implement a function to achieve the same functionality using a different approach.
You need to write a Python function that takes... | ```python
import numpy as np
def process_and_write(rows):
with open("processed_data.txt", "w") as f:
for row in rows:
img_as_list = row.inrow.flatten().tolist() # Flatten the 2D input image data
img_data_str = ','.join(map(str, img_as_list)) # Convert the flattened image data to a... | magicoder | python |
You are tasked with implementing a Discord bot feature that manages user experience points (XP) based on certain conditions. The provided code snippet is a part of the bot's logic for processing XP-related actions. The relevant variables and their meanings are as follows:
- `isAdmin`: a boolean indicating whether the a... | ```python
# Check Bet
if isAdmin and adminUnlim:
approve = True
decrement = False
elif reserveXP > 0:
approve = True
decrement = False
elif author.top_role.name >= minRole: # Assuming author's top role name is compared with minRole
approve = True
decrement = True
else:
approve = False
d... | magicoder | python |
You are tasked with creating a command-line utility to visualize the data flow through a pipeline. The utility should provide options to display the average data transfer speed, limit the data transfer rate, display only the byte count without a progress bar, operate in quiet mode, and specify the data size flowing thr... | ```python
import sys
import time
import argparse
def visualize_data_flow(args):
if args.q:
return # Quiet mode, no output
if args.b:
print(f"Byte count: {args.s}")
elif args.a:
# Calculate and display average data transfer speed
start_time = time.time()
# Simulate ... | magicoder | python |
You are tasked with implementing a function that processes a list of code snippets. Each code snippet is represented as a string and may contain various programming constructs. The function should analyze each code snippet and perform specific operations based on the content of the snippet. The operations include count... | ```python
from typing import List, Dict, Union
def process(code: List[str]) -> List[Dict[str, Union[str, int]]]:
keyword_list = ["if", "else", "for", "while", "def", "return", "in"]
output = []
for snippet in code:
snippet_info = {
"snippet": snippet,
"keyword_counts": ... | magicoder | python |
You are tasked with simulating a simple command-line interface for a device using Python. The device communicates with the computer through a serial port, and you need to send a series of AT commands to retrieve information and perform actions. Each command is followed by a 1-second delay before sending the next comman... | ```python
import time
from typing import List
def send_commands(commands: List[str]) -> List[str]:
responses = []
for command in commands:
time.sleep(1)
response = f'Response to {command}'
responses.append(response)
return responses
```
The `send_commands` function iterates through... | magicoder | python |
You are tasked with creating a program to compress a set of text files using a custom compression tool. The compression process involves removing newline characters from the original text files and then using a custom compression tool to create compressed binary files.
Your program should take a directory containing t... | ```bash
#!/bin/bash
compress_files() {
input_dir=$1
for file in $(ls $input_dir); do
echo -ne "Compressing $file\r"
# Remove newlines
cat "$input_dir/$file" | tr -d '\n' > "build/$file"
# Compress
mzx_compress "build/$file" "build/$(echo $file | sed 's/txt/bin/')"
done
}
# Example usage
comp... | magicoder | shell |
You are tasked with implementing a function that processes test cases and their associated tests in a testing framework. The function takes in a result tuple and populates an event object with the appropriate test cases and tests. The result tuple contains four elements: parent, obj, name, and index. The function needs... | ```python
import unittest
def process_test_result(result, event):
parent, obj, name, index = result
if isinstance(obj, type) and issubclass(obj, unittest.TestCase):
event.extraTests.append(self._loadTestsFromTestCase(event, obj))
elif (isinstance(parent, type) and
issubclass(parent, unitt... | magicoder | python |
You are tasked with creating a program that simulates a simple command line interface for a version control system. The program should support basic commands such as `push`, `pull`, `commit`, and `status`. Additionally, the program should handle end-to-end integration testing using a testing framework.
Your task is to... | ```python
def execute_command(command):
if command == "push":
print("Simulating pushing changes to a remote repository")
elif command == "pull":
print("Simulating pulling changes from a remote repository")
elif command == "commit":
print("Simulating committing changes to the local re... | magicoder | python |
You are tasked with creating a Java method that generates a SQL WHERE clause for a DELETE operation in a database. The method should take in the table column name and the value to be matched, and then construct the WHERE clause and its corresponding arguments for the DELETE operation.
Write a method `generateDeleteWhe... | ```java
public class DatabaseHelper {
public String[] generateDeleteWhereClause(String columnName, Object value) {
String whereClause = columnName + " = ?"; // Constructing the WHERE clause
String[] whereArgs = {String.valueOf(value)}; // Converting value to String and creating arguments array
... | magicoder | java |
You are working on a data synchronization module for a mobile application. The code snippet provided is part of a data synchronization algorithm that compares the data on the local device with the data from a server to identify new, updated, and deleted objects. Your task is to implement a function that takes the exist... | ```swift
func identifyChanges(allObjects: [Any], realmPrimaryKey: String, sourceModels: [SourceModel], server: Server) -> (deletedIDs: Set<String>, newIDs: Set<String>) {
let existingIDs = Set(allObjects.compactMap { $0[realmPrimaryKey] as? String })
let incomingIDs = Set(sourceModels.map {
UM.primaryKe... | magicoder | swift |
You are working on a large-scale TypeScript project with a complex directory structure. The project contains multiple modules, each with its own DTO (Data Transfer Object) file. The DTO files are located in deeply nested directories, making it challenging to import them directly. To simplify the import process, you wan... | ```typescript
import * as path from 'path';
async function importAllDto(basePath: string): Promise<{ [key: string]: any }> {
const moduleDirs = await fs.promises.readdir(path.join(basePath, 'src', 'modules'));
const dtoImports = {};
for (const moduleDir of moduleDirs) {
const dtoPath = path.join(basePath, '... | magicoder | typescript |
You are tasked with implementing a simple routing system for a web server using Node.js and Express. The provided code snippet is a part of a larger application that manages client data. The `ClientsRoutes` module is responsible for handling client-related HTTP requests. The snippet shows the deletion route for a clien... | ```javascript
// Assuming the existence of an Express application instance
const express = require('express');
const app = express();
// Simulated client data storage
let clients = [
{ id: 1, name: 'Client A' },
{ id: 2, name: 'Client B' },
{ id: 3, name: 'Client C' }
];
// Implementation of the deleteClient.ha... | magicoder | javascript |
You are tasked with implementing a speech recognition system for a virtual assistant. The system should be able to recognize and execute specific commands embedded within a continuous stream of speech input. The commands are represented as strings and are associated with specific actions to be performed by the virtual ... | ```cpp
#include <iostream>
#include <vector>
#include <string>
class VirtualAssistant {
public:
void startAutoSpeech(const std::vector<std::vector<std::string>>& commands, int minCommandLength, int maxCommandLength, int minConfidenceLevel, bool enableNoiseCancellation, bool enableContinuousRecognition) {
/... | magicoder | cpp |
You are given a list of integers representing the scores of a game. The game has a special rule for scoring where the score of each player is the sum of their best three scores. Write a function `calculateTotalScore` to calculate the total score for each player based on this rule.
The function should take in a list of... | ```swift
func calculateTotalScore(_ scores: [Int]) -> Int {
let sortedScores = scores.sorted(by: >) // Sort the scores in descending order
var totalScore = 0
for i in 0..<min(3, sortedScores.count) { // Iterate through the first three scores or all available scores if less than 3
totalScore += sorte... | magicoder | swift |
You are tasked with implementing a simple game engine for a tile-based game. The game engine is responsible for managing the game state, updating the game world, and rendering the game to the screen. The game world is represented as a grid of tiles, and the engine needs to handle player input, collision detection, and ... | ```python
class GameEngine:
def __init__(self, tileset):
self.tileset = tileset
# Initialize game state, player position, etc.
def update(self):
# Update game state based on player input and game logic
pass
def render(self):
# Render the game world to the screen
... | magicoder | python |
You are tasked with implementing a Python class that processes live timing data from a file and provides methods to extract specific information. The class should handle writing data to the file and then reading and processing the live timing data.
You are provided with a code snippet that writes data to a file using ... | ```python
class LiveTimingData:
def __init__(self, filename):
self.filename = filename
def write(self, data):
with open(self.filename, 'a') as fobj:
fobj.write(data)
def get_latest_data(self):
with open(self.filename, 'r') as fobj:
lines = fobj.readlines()
... | magicoder | python |
You are tasked with implementing a function to flatten hierarchical data and produce a list with parent references and path segments. The input data is in the form of a hierarchical tree, and the output should be a flattened list of items with additional properties.
You are given the following code snippet as a starti... | ```typescript
export interface IHierarchyItem {
id: string;
name: string;
children?: IHierarchyItem[];
}
export interface IFlatItem {
id: string;
parentId: string;
path: string;
// Additional properties based on the output of addPropsInput function
}
export const flattenItems = (parentId: string, pathLi... | magicoder | typescript |
You are tasked with implementing a custom serialization mechanism for a specific message type in a robotics framework. The framework provides a template class `PublisherImpl` that is responsible for publishing messages of a given type. The provided code snippet is a part of the implementation of the `publish` method fo... | ```cpp
#include <roswasm/roswasm.h>
#include <roswasm/publisher.h>
#include <roscpp_json_serialize/serialize.h>
// Define the CustomMessage type
struct CustomMessage {
int id;
std::string data;
// Add any other fields as needed
};
// Custom serialization function for CustomMessage
std::string custom_seria... | magicoder | cpp |
You are tasked with implementing a function that retrieves JSON data from a remote source and returns it as a `Data` object. The function should handle potential errors by throwing an appropriate error type. You are provided with a partial code snippet for the function:
```swift
public func jsonData() throws -> Data {... | ```swift
import Foundation
enum JSONError: Error {
case networkError
case dataError
}
public func jsonData() throws -> Data {
guard let url = URL(string: "https://example.com/api/data") else {
throw JSONError.networkError
}
do {
let jsonData = try Data(contentsOf: url)
... | magicoder | swift |
You are tasked with creating a Python decorator that logs the execution time of a function and prints the result to the console. The decorator should be able to handle functions with any number of arguments and keyword arguments. Your task is to implement the `@log_execution_time` decorator and apply it to the `add_num... | ```python
import time
def log_execution_time(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
execution_time = end_time - start_time
print(f"Function '{func.__name__}' executed in {execution_time:.6f} seconds... | magicoder | python |
You are tasked with creating a script to automate the processing of data chunks using Slurm job array in a high-performance computing (HPC) environment. The script should be designed to handle a specific number of data chunks and execute a processing task for each chunk in parallel.
Your script should utilize Slurm di... | ```bash
#!/bin/bash
#SBATCH --mail-type=ALL
#SBATCH --array=1-71
echo "processing chunk $SLURM_ARRAY_TASK_ID ..."
# Add your data processing command here using $SLURM_ARRAY_TASK_ID as needed
```
In the solution, the script begins with the shebang line to indicate that it is a Bash script. It then includes Slurm direc... | magicoder | shell |
You are tasked with creating a Python class that simulates a simplified version of a vectorized environment for reinforcement learning. The class should be able to handle multiple environments running in parallel, allowing for efficient batched operations. Your task is to implement the `SubprocVecEnv` class, which will... | ```python
import numpy as np
from multiprocessing import Process, Pipe
class SubprocVecEnv:
def __init__(self, env_fns):
self.num_envs = len(env_fns)
self.remotes, self.work_remotes = zip(*[Pipe() for _ in range(self.num_envs)])
self.ps = [Process(target=self.worker, args=(work_remote, remo... | magicoder | python |
You are working on a bioinformatics project and need to develop a program to analyze DNA sequences. You have been given a code snippet that involves the use of classes and functions to process DNA patterns and calculate overlap lengths. Your task is to understand the given code and create a Python class that can perfor... | ```python
import numpy
class DNAAnalyzer:
def __init__(self, dna_strand):
self.dna_strand = dna_strand
def calculate_overlap(self, other):
max_overlap = 0
for i in range(1, min(len(self.dna_strand), len(other.dna_strand))):
if (self.dna_strand[-i:] == other.dna_strand[:i]).... | magicoder | python |
You are tasked with creating a script that dynamically generates a Makefile for a given set of test files. The script should take a list of test file names as input and produce a Makefile that includes rules for compiling and running each test file. Each test rule should echo "ok" to the console when executed.
Write a... | ```bash
#!/bin/bash
# Check if the number of arguments is at least 1
if [ "$#" -lt 1 ]; then
echo "Usage: generate_makefile.sh <test_file1> <test_file2> ..."
exit 1
fi
# Create the Makefile
cat <<EOF > "${BATS_TMPDIR}/make/Makefile"
## Auto-generated Makefile
test: $@
@ echo "ok"
$@:
@ echo "ok"
EOF
```
When ... | magicoder | shell |
You are tasked with creating a URL routing system for a web application framework. The framework uses Django, a popular Python web framework, and the code snippet provided represents a part of the URL configuration for the application.
The code snippet shows a series of URL patterns defined using the `path` function. ... | ```python
from typing import List, Tuple, Dict, Callable
def extract_url_mappings(url_patterns: List[Tuple[str, Callable, str]]) -> Dict[str, Callable]:
url_mappings = {}
for pattern, view_function, url_name in url_patterns:
url_mappings[url_name] = view_function
return url_mappings
# Test the fun... | magicoder | python |
You are tasked with creating a PHP function that calculates the average value of a specific field from a MySQL database table. The function will take in the database connection, table name, and field name as parameters, and return the average value of the specified field.
You are provided with the following code snipp... | ```php
function calculateAverage($connection, $tableName, $fieldName) {
$query = "SELECT AVG($fieldName) AS average FROM $tableName";
$result = mysqli_query($connection, $query);
if ($result) {
$row = mysqli_fetch_assoc($result);
return $row['average'];
} else {
return "Erro... | magicoder | php |
You are tasked with implementing a genetic algorithm for optimizing a population of individuals. The genetic algorithm is represented by the following code snippet:
```python
for gen in n._allGenerations:
print 'Generation: ',i
for j in range(len(gen[1])):
print gen[1].keys()[j],gen[1].values()[j]
... | ```python
def genetic_algorithm_stats(generations, population_size, elitism_proportion, mutation_probability, mutation_std_deviation):
stats_str = ""
for i, gen in enumerate(generations):
stats_str += f"Generation: {i}\n"
for key, value in gen.items():
stats_str += f"{key}: {value}\n... | magicoder | python |
You are tasked with simulating the motion of a particle in one dimension using the Euler-Maruyama method. The Euler-Maruyama method is a numerical technique for solving stochastic differential equations. In this problem, you will implement a simplified version of the simulation using a given code snippet as a reference... | ```cpp
#include <iostream>
#include <random>
#include <map>
// Function to generate a random number from a normal distribution with mean 0 and standard deviation 1
double generateRandomNumber(std::default_random_engine& engine) {
std::normal_distribution<double> distribution(0.0, 1.0);
return distribution(engi... | magicoder | cpp |
You are tasked with implementing a transaction builder module for a cryptocurrency system. The provided code snippet includes a reference to a default transaction builder module, which is responsible for constructing valid transactions within the cryptocurrency network. Your goal is to create a new transaction builder ... | ```rust
// transaction_builder.rs
use crypto_library::CryptoKey;
use transaction::{Transaction, TransactionInput, TransactionOutput};
pub struct TransactionBuilder {
inputs: Vec<TransactionInput>,
outputs: Vec<TransactionOutput>,
fee: u64,
}
impl TransactionBuilder {
pub fn new() -> Self {
Tr... | magicoder | rust |
You are tasked with implementing a Python class that serializes a Deterministic Finite Automaton (DFA) into a string representation. The DFA is represented by a set of states, alphabet, transition function, initial state, and set of accepting states. The string representation should follow a specific format to represen... | ```python
class LexerDFASerializer(DFASerializer):
def __init__(self, dfa:DFA):
super().__init__(dfa, None)
def getEdgeLabel(self, i:int):
transition = self.dfa.transitions[i]
return f"{transition.inputSymbol} => {transition.targetState}"
def serialize(self):
serialized_df... | magicoder | python |
You are tasked with implementing a simple server-state management system in Rust. The `State` struct is responsible for maintaining connections to clients, storing a password, and managing a memory-mapped file. Your goal is to implement a method for the `State` struct that allows clients to update the server state by p... | ```rust
fn main() {
// Create a new State instance
let mut state = State {
connections: HashMap::new(),
password: Some("secure_password".to_string()),
file: File::create("state.json").unwrap(),
mmap: None,
len: 0,
size: 0,
};
// Update the state with the ... | magicoder | rust |
You are tasked with implementing a generic `AuthEndpoint` class that provides a common interface for various authentication endpoints. The `AuthEndpoint` class should support different types of authentication methods such as username/password, token-based, or any other custom authentication mechanism. Your task is to d... | ```python
from abc import ABC, abstractmethod
class AuthEndpoint(ABC):
def __init__(self):
self.credentials = None
def set_credentials(self, credentials):
self.credentials = credentials
def get_credentials(self):
return self.credentials
@abstractmethod
def authenticate(se... | magicoder | python |
You are tasked with creating a program that processes data from a PDF file using a custom PDF viewer library. The library provides a PdfTController class for interacting with PDF files. The PdfTController class has a method called extractTextFromPage(int pageNum) that takes a page number as input and returns the text c... | ```java
import viewer.VC.PdfTController;
public class PdfTextProcessor {
public static void main(String[] args) {
try {
PdfTController pdfController = new PdfTController(); // Create an instance of PdfTController
int page1 = 1;
int page3 = 3;
String textFrom... | magicoder | java |
You are tasked with creating a program to manage and store information about gems found in various areas of a fantasy world. The program should be able to serialize this information and save it to a file for future retrieval. Your task is to implement a class structure and methods to achieve this functionality.
You ar... | ```csharp
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
class Gem
{
public string Name { get; set; }
public int Count { get; set; }
}
class Area
{
public string Name { get; set; }
public List<Gem> Gems { get; set; ... | magicoder | csharp |
You are tasked with creating a program that simulates a simple banking system. The system should allow users to create accounts, deposit money, withdraw money, and check their balance. Each account should have a unique account number, and the system should be able to handle multiple accounts.
Your task is to implement... | ```csharp
using System;
using System.Collections.Generic;
public class BankAccount
{
public int AccountNumber { get; }
public string AccountHolderName { get; }
public float CurrentBalance { get; private set; }
public BankAccount(int accountNumber, string accountHolderName, float initialBalance)
{
... | magicoder | csharp |
You are tasked with implementing a service for managing offers in an e-commerce platform. The provided code snippet is a part of an Angular component that handles the editing of an offer. The `onEdit` method is called when a user submits an edited offer, triggering an update request to the server. Upon successful updat... | ```typescript
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class OfferService {
private apiUrl = 'https://example.com/api/offers'; // Replace with actual API endpoint
constructor(priva... | magicoder | typescript |
You are tasked with implementing a custom logging system for a job processing framework. The framework provides an interface `JobLogger` for logging job-related information and a utility class `CatPrinter` for printing log messages. Your goal is to create a class that implements both `JobLogger` and `CatPrinter` and en... | ```java
import java.util.ArrayList;
import java.util.List;
public class CustomLogger implements JobLogger, CatPrinter {
private List<String> loggedMessages = new ArrayList<>();
@Override
public void log(String message) {
loggedMessages.add(message);
}
@Override
public void d(String ta... | magicoder | java |
You are tasked with creating a Python program to manage a movie database using Flask and Flask-RESTPlus. Your program should include a movie serializer to handle the serialization of movie data. The movie serializer should have fields for status, data, and message.
Your task is to implement a function that takes a mov... | ```python
from flask_restplus import fields, Namespace
# Define the Flask-RESTPlus namespace
movie_ns = Namespace('movie', description='Movie operations')
# Define the movie model
movie = movie_ns.model('Movie', {
'title': fields.String(required=True, description='The title of the movie'),
'year': fields.Inte... | magicoder | python |
You are tasked with creating a Python function that calculates the modular exponentiation of a given base, exponent, and modulus. Modular exponentiation is a type of exponentiation performed over a modulus, which is particularly useful in cryptography and number theory. Your function should take three integer inputs: `... | ```python
def modular_exponentiation(base: int, exponent: int, modulus: int) -> int:
result = 1
base = base % modulus # Reduce base to a smaller value to optimize computation
while exponent > 0:
if exponent % 2 == 1:
result = (result * base) % modulus
exponent = exponent >> 1 #... | magicoder | python |
You are tasked with implementing a function to check if advertising tracking is enabled on an iOS device, while adhering to Apple's policy. You are given a code snippet that attempts to perform this check using Objective-C selectors. Your task is to create a Swift function that achieves the same functionality using Swi... | ```swift
// Swift function to check if advertising tracking is enabled
func isAdvertisingTrackingEnabled(manager: ASIdentifierManager) -> Bool {
if #available(iOS 14, *) {
return manager.advertisingTrackingEnabled
} else {
return manager.isAdvertisingTrackingEnabled
}
}
```
In the solution,... | magicoder | swift |
You are given a 2D list representing a tic-tac-toe board. Each cell in the list can contain either 'X', 'O', or an empty space. Your task is to write a function that determines the winner of the game, if any. The winner is the player who has three of their marks in a horizontal, vertical, or diagonal row.
Create a fun... | ```python
def tic_tac_toe_winner(board):
# Check rows and columns
for i in range(3):
if board[i][0] == board[i][1] == board[i][2] and board[i][0] != ' ':
return board[i][0]
if board[0][i] == board[1][i] == board[2][i] and board[0][i] != ' ':
return board[0][i]
# Chec... | magicoder | python |
You are tasked with creating a Python function that loads environment variables from a .env file if it exists, and if not, sets default values. The function should take two optional parameters: `filepath` and `filename`. If `filepath` is provided, it should be used as the path to the .env file. If not, the function sho... | ```python
import os
import pathlib
def load_env_variables(filepath=None, filename=None):
dotenv_path = filepath or os.getenv('DOTENV_PATH', None)
if dotenv_path is None:
ROOT_DIR = pathlib.Path(os.path.abspath(__file__)).parents[3]
dotenv_file = filename or os.getenv('DOTENV_FILE', ".env")
... | magicoder | python |
You are tasked with creating a program to manage members of a club. Each member has a name, a list of roles within the club, and an image path for their profile picture. Your task is to implement a method that filters the members based on their roles and returns a list of members who have a specific role.
You are give... | ```swift
class Member {
let name: String
let roles: [String]
let imagePath: String
init(name: String, roles: [String], imagePath: String) {
self.name = name
self.roles = roles
self.imagePath = imagePath
}
}
class ClubManager {
func filterMembersByRole(members: [Memb... | magicoder | swift |
You are tasked with implementing a Python class that manages a shared resource among multiple instances. The class should enforce a specific usage pattern and raise an exception if the resource is accessed incorrectly.
You need to implement the `SharedResource` class with the following requirements:
- The class should... | ```python
class SharedResource:
def __init__(self, opt, shared=None):
if opt == 'self_chat':
raise RuntimeError('-t self_chat is a dummy helper, and not meant to be used directly.')
else:
self.shared = shared
```
The `SharedResource` class is implemented with an `__init__` m... | magicoder | python |
You are tasked with creating a PHP class that represents a course in an educational system. The course class should have methods to enroll a user, add a post, and retrieve all posts associated with the course. Additionally, the class should have a property to store the course name and a relationship with the User and P... | The provided solution completes the Course class by adding the necessary methods and relationships. The `enrollUser` method allows a user to be enrolled in the course by establishing a many-to-many relationship between the Course and User classes. The `addPost` method creates a new post associated with the course, and ... | magicoder | php |
You are working on a database migration for a transportation management system. The migration script is responsible for creating a new table to store transportation records. The snippet provided is a part of the migration script written in Laravel's Eloquent ORM syntax.
The snippet includes the following operations:
1... | ```php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTransportationRecordsTable extends Migration
{
public function up()
{
Schema::create('transportation_records', function (Blueprint $table) {
$tab... | magicoder | php |
You are tasked with automating the build process for a multi-platform library using xcodebuild. The library, named BananaLib, needs to be built for various platforms including iOS, macOS, watchOS, and tvOS. The provided code snippet demonstrates the build commands for different platforms using xcodebuild.
Your task is... | ```bash
#!/bin/bash
# Clean and archive BananaLib for iOS
xcodebuild clean archive -project BananaLib.xcodeproj -scheme "BananaLib" -sdk iphoneos -archivePath "${archiveDir}/iOS" $settings
# Store dSYMs for iOS
cp -R "${archiveDir}/iOS/BananaLib.xcarchive/dSYMs" "$DSYM_FOLDER/iOS"
# Clean and archive BananaLib for iO... | magicoder | shell |
You are tasked with implementing a function that takes an array of integers as input and returns the maximum sum of a subarray within the input array. A subarray is defined as a contiguous segment of the input array. Your task is to write a function `maxSubarraySum` that efficiently computes the maximum sum of a subarr... | To solve this problem, we can use Kadane's algorithm, which efficiently computes the maximum sum of a subarray within an array. The algorithm involves iterating through the array and keeping track of the maximum sum ending at each position. We initialize two variables, `maxSum` and `currentSum`, to track the maximum su... | magicoder | javascript |
You are tasked with implementing a migration script for a Django application. The script needs to add a new field to two different models in the application's database. The models are `JobExecution` and `JobTypeRevision`, and the new field to be added is `docker_image` of type `TextField` with a `null` option set to `T... | ```python
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('job', '0044_jobtypetag_job_type'),
]
operations = [
migrations.AddField(
model_name='jobexecution',
name='docker_image',
field=models.TextField(... | magicoder | python |
You are tasked with creating a SwiftUI app that visualizes equipotential lines in a 2D space. Equipotential lines are imaginary lines that connect points with the same electric potential. In this problem, you will implement a function to calculate and draw equipotential lines based on a given electric potential functio... | ```swift
typealias Point = (x: Double, y: Double)
typealias LineSegment = (start: Point, end: Point)
func calculateEquipotentialLines(electricPotentialFunction: ElectricPotentialFunction, xRange: ClosedRange<Double>, yRange: ClosedRange<Double>, step: Double) -> [LineSegment] {
var equipotentialLines: [LineSegment... | magicoder | swift |
You are tasked with implementing a custom error handling system for an iOS application. The provided code snippet is a part of the APIError.swift file in the SaberIOSGitHubRepoViewer project. Your task is to create a custom error type that can be used to represent various API-related errors in the application.
Your cu... | ```swift
// APIError.swift
// SaberIOSGitHubRepoViewer
//
// Created by Andrew Pleshkov on 13/04/2019.
enum APIError: Error {
case networkError
case invalidResponse
case apiError(message: String)
}
extension APIError {
static func mapError(_ error: Error) -> APIError {
if let apiError = error ... | magicoder | swift |
You are tasked with designing a user management system for a web application. The system should allow for the delegation of group administration, assignment of moderators for forums, and management of user preferences. To achieve this, you need to implement a class-based solution that provides the necessary functionali... | ```python
class UserManagementSystem:
def __init__(self):
self.group_admins = {} # Dictionary to store group administrators
self.forum_moderators = {} # Dictionary to store forum moderators
self.user_preferences = {} # Dictionary to store user preferences
def delegate_administration(... | magicoder | python |
You are tasked with creating a custom integration for Home Assistant, a popular open-source home automation platform. Your integration will handle the authentication process for a hypothetical smart home device. The device requires the user to provide their email and password to establish a connection with Home Assista... | ```python
from homeassistant.config_entries import ConfigFlow
from homeassistant.const import CONF_EMAIL, CONF_PASSWORD
from homeassistant.data_entry_flow import (
AbortFlow,
FlowHandler,
Result,
StepForm,
StepAbort,
)
class CustomDeviceConfigFlow(ConfigFlow):
async def async_step_user(self, us... | magicoder | python |
You are tasked with implementing a message handling system for a network application. The given code snippet is a partial implementation of a message type called "Destroy_MessageType" and its corresponding event "Destroy_Message". Your task is to complete the implementation of the "Destroy_MessageType" class and provid... | ```java
public class Destroy_MessageType extends MessageType {
public Destroy_MessageType() {
super("destroy_", (short) 22);
}
public Event instantiate(final byte val34) {
return new Destroy_Message(this, val34);
}
}
public class Destroy_Message extends Event implements java.io.Seriali... | magicoder | java |
You are tasked with implementing a custom neural network architecture using PyTorch for a specific classification task. The network should consist of multiple layers and utilize various activation functions and optimization techniques. Additionally, you need to preprocess the input data and evaluate the model's perform... | ```python
import numpy as np
import os
import glob
from random import shuffle
import torch
from torch import nn, optim
import torch.nn.functional as F
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
# Data Preprocessing
data_dir = 'path_to_dataset_directory'
file_paths = glob.glob(... | magicoder | python |
You are given a string `s` consisting of lowercase English letters. Your task is to write a function `longest_substring_length(s: str) -> int` that returns the length of the longest substring without repeating characters.
For example, given the input string "abcabcbb", the longest substring without repeating character... | ```python
def longest_substring_length(s: str) -> int:
if not s:
return 0
max_length = 0
start = 0
char_index_map = {}
for end in range(len(s)):
if s[end] in char_index_map and char_index_map[s[end]] >= start:
start = char_index_map[s[end]] + 1
char_index_map[s[e... | magicoder | python |
You are tasked with implementing a custom input accessory view for a form input field in a mobile application. The input accessory view should be displayed above the keyboard and provide additional functionality or controls for the user to interact with while entering data into the form field.
Your task is to create a... | ```swift
import UIKit
class CustomInputAccessoryView: UIView {
// Additional functionality or controls specific to the form input field can be added here
/// Returns the custom input accessory view if it is defined or calls super if not.
override var inputAccessoryView: UIView? {
if let customInpu... | magicoder | swift |
You are tasked with creating a Python function that calculates the total weight of edges in a given graph that are greater than a specified threshold. The graph is represented using the NetworkX library.
You are given the following function signature to implement:
```python
def calculate_total_weight_above_threshold(G... | ```python
import networkx as nx
def calculate_total_weight_above_threshold(G, pos, threshold):
total_weight = 0
for u, v, data in G.edges(data=True):
if 'weight' in data and data['weight'] > threshold:
total_weight += data['weight']
return total_weight
```
In the solution, we iterate t... | magicoder | python |
You are tasked with creating a Python program that simulates a simplified version of a video streaming service. The program will utilize asyncio and Kafka to publish video frame details to a server. Your task is to implement the missing parts of the code to achieve this functionality.
You are provided with a partial c... | ```python
import asyncio
import jsonpickle
import traceback
from nats.aio.client import Client as NATS
async def initiate(loop):
"""
Producer will publish to Kafka Server a video file given as a system arg.
Otherwise it will default by streaming webcam feed.
"""
nc = NATS()
try:
await ... | magicoder | python |
You are tasked with implementing a packet routing system for a network. The system should be able to handle different types of packets and route them to their respective destinations. Each packet has a unique identifier and a payload. The system should support adding, removing, and routing packets based on their type.
... | ```python
class Packet:
def __init__(self, identifier, payload):
self.identifier = identifier
self.payload = payload
def route(self, destination):
print(f"Routing packet {self.identifier} to {destination}")
def remove(self):
print(f"Removing packet {self.identifier} from th... | magicoder | python |
You are tasked with creating a program that analyzes the distribution of stars for GitHub repositories within a specified range. The program should take in a range of stars (e.g., 1-10) and output the number of repositories that fall within that range.
Write a function or method `countRepositories` that takes two para... | ```python
def countRepositories(stars, star_range):
min_stars, max_stars = map(int, star_range.split('-'))
count = 0
for star in stars:
if min_stars <= star <= max_stars:
count += 1
return count
``` | magicoder | python |
You are tasked with creating a Python script that reads environment variables from a Docker-compose file and assigns default values to them if they are not present. The script should check for the presence of specific environment variables and use default values if they are not set.
The script should perform the foll... | ```python
import os
# Define a list of environment variables and their default values
env_variables = {
"DB_HOST": "localhost",
"DB_PORT": "5432",
"DB_USER": "admin",
"DB_PASSWORD": "password123",
"SECRET_KEY": "mysecretkey"
}
# Check if each environment variable is present and assign default valu... | magicoder | python |
You are tasked with creating a web application feature that provides autocomplete functionality for selecting a car model. The application is built using the ASP.NET MVC framework. The provided code snippet is a part of the view file for this feature. The model used for the autocomplete functionality is `MVCSampleBrows... | Server-side Code (C#):
```csharp
// Controller action to retrieve car model data
public JsonResult GetCarModels(string term)
{
// Replace this with actual data retrieval from the data source
var carModels = new List<string> { "Toyota", "Honda", "Ford", "Chevrolet" };
var filteredModels = carModels.Where(mo... | magicoder | csharp |
You are tasked with creating a function that can parse and manipulate URIs (Uniform Resource Identifiers). A URI is a string of characters used to identify a resource on the internet. The function should be able to handle various components of a URI, such as the scheme, host, path, query parameters, and fragment.
Writ... | ```python
import urllib.parse
def parseURI(uri):
parsed_uri = urllib.parse.urlparse(uri)
query_params = urllib.parse.parse_qs(parsed_uri.query)
uri_components = {
"scheme": parsed_uri.scheme,
"host": parsed_uri.netloc,
"path": parsed_uri.path,
"query": dict(query_params... | magicoder | python |
You are tasked with implementing a firewall management system for a cloud infrastructure. The system will allow users to create and check the existence of firewall rules for different instances and hostnames. You are provided with a code snippet that includes a function for creating a firewall rule and another function... | ```python
class FirewallManager:
def create_firewall_rule(self, instance_id, hostname, gateway_port, service_port):
# Implement the logic to create a firewall rule using the provided code snippet
# For demonstration purposes, a placeholder print statement is used
print(f"Creating firewall ru... | magicoder | python |
You are tasked with implementing a command-line interface (CLI) for managing player accounts in a gaming platform. The provided code snippet is a part of the CLI setup using the `argparse` module in Python. Your task is to extend this CLI by adding a new command and its associated arguments.
Extend the CLI with a comm... | ```python
subparser = player_account_subparsers.add_parser('reset-player-password', help='Reset a player password')
subparser.add_argument('--username', type=str, required=True, help='The cognito username of the account to target')
add_common_args(subparser)
subparser.set_defaults(func=pa_service_api.command_reset_play... | magicoder | python |
You are working on a data processing script for analyzing polar coordinate data. The script takes in angle data and corresponding weights, and then calculates a weighted histogram based on the angle data. However, there is a bug in the script that needs to be fixed.
The relevant part of the script is as follows:
```p... | The bug in the script is that the `weight` list is being used to calculate the weighted histogram without ensuring that it has the same number of elements as the `theta` list. To fix this, we need to ensure that the `weight` list has the same number of elements as the `theta` list before calculating the weighted histog... | magicoder | python |
You are tasked with implementing a custom memory allocator in Rust. Your goal is to create a simple memory allocator that allocates memory using a first-fit strategy. The allocator should be able to allocate and deallocate memory blocks of varying sizes.
You are provided with a skeleton code that defines a custom allo... | ```rust
use std::alloc::{GlobalAlloc, System, Layout};
struct MyAllocator;
unsafe impl GlobalAlloc for MyAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
let size = layout.size();
let align = layout.align();
let ptr = System.alloc(layout);
if ptr.is_null() {
... | magicoder | rust |
You are tasked with implementing an asynchronous file reading function in Python. Your function should open a file in binary mode, read its contents asynchronously, and then close the file. Additionally, you need to write a test case using the `pytest` framework to verify the functionality of your asynchronous file rea... | ```python
import pytest
from pathlib import Path
import asyncio
async def open_async(file_path: str, mode: str) -> bytes:
async with open(file_path, mode) as f:
data = await f.read()
return data
@pytest.mark.asyncio
async def test_read(testdatafile, testdata):
file_path = Path(str(testdatafile))
... | magicoder | python |
You are tasked with implementing the shell sort algorithm to sort a given list of integers in ascending order. Shell sort is a highly efficient sorting algorithm that is a variation of insertion sort. The algorithm starts by sorting pairs of elements far apart from each other, then progressively reducing the gap betwee... | ```python
def shell_sort(alist):
n = len(alist)
gap = n // 2
while gap > 0:
for i in range(gap, n):
temp = alist[i]
j = i
while j >= gap and alist[j - gap] > temp:
alist[j] = alist[j - gap]
j -= gap
alist[j] = temp
... | magicoder | python |
You are tasked with creating a program to manage a database of geographical coordinates. The program should retrieve entries from a database, and if any of the entries lack coordinates, it should fetch the missing coordinates from an external service. You are provided with a code snippet that demonstrates the retrieval... | ```csharp
public async Task<List<Entry>> GetAllEntriesAsync(DatabaseClient client, Builder noCoordinatesBuilder)
{
List<Entry> entriesWithoutCoordinates = await client.GetEntriesWithoutCoordinatesAsync(); // Retrieve entries without coordinates from the database
List<Task<EntryWithCoordinates>> coordinateTasks... | magicoder | csharp |
You are tasked with creating a function that processes and displays daily expenses in a web application. The given code snippet is part of a Laravel application and is responsible for fetching and displaying expenses for a specific day.
You need to implement a function that takes a date as input and retrieves all the ... | ```php
/**
* Retrieve and display daily expenses
*
* @param string $day The date for which expenses need to be retrieved (format: 'Y-m-d')
* @return \Illuminate\View\View The view containing the expenses for the given day
*/
function displayDailyExpenses($day) {
// Assuming the 'EndExpense' model is properly d... | magicoder | php |
You are tasked with implementing a file hashing function using the SHA-384 algorithm in Swift. The SHA-384 algorithm is a cryptographic hash function that produces a 384-bit (48-byte) hash value. You are provided with a code snippet that sets up the context for the SHA-384 algorithm and then calls a function `hashOfFil... | ```swift
import Foundation
import CommonCrypto
func hashOfFile(atPath filePath: String, with context: CCHmacContext) -> Data? {
guard let fileData = FileManager.default.contents(atPath: filePath) else {
return nil // Unable to read file data
}
var hash = [UInt8](repeating: 0, count: Int(context.di... | magicoder | swift |
You are tasked with creating a Python function that simulates a card game called "素数大富豪" (Sosu Daifugo), a Japanese variant of the popular card game "President". The game involves a deck of cards, and players take turns playing cards according to specific rules.
Your task is to implement the `play_sosu_daifugo` functi... | ```python
def play_sosu_daifugo(players, initial_deck):
player_hands = [sorted(initial_deck[i::players]) for i in range(players)]
current_player = initial_deck.index(3) % players
current_play = None
pass_count = 0
while any(player_hands):
if current_play is None:
current_play = ... | magicoder | python |
You are tasked with implementing a function that processes training data for a machine learning model. The function takes several input arrays representing training and validation data, as well as various configuration parameters. Your goal is to complete the implementation of the `train` function by adding the necessa... | ```python
def train(X_train_s, X_train_s_n, y_train_s, X_val_s, y_val_s, X_val_t, y_val_t, X_t, X_t_n, Y_t, norm, args, source_target=None):
import logging
logging.basicConfig(handlers=[logging.FileHandler(filename="./log_{}_flops.txt".format(str(args.mode)), encoding='utf-8', mode='a+')],format="%(asctime... | magicoder | python |
You are tasked with creating a Python decorator that logs the execution time of a function and also logs the arguments and return value of the function. Your decorator should be able to handle both synchronous and asynchronous functions.
Your decorator should have the following features:
1. It should be able to handle... | ```python
import time
import asyncio
import functools
def log_execution(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
execution_time = time.time() - start_time
print(f"Function '{func.__name__}' executed in {e... | magicoder | python |
You are tasked with implementing a function that adds a value to a specific variable within a TypeScript file. You are given a test case and a partial code snippet from a testing framework. Your task is to write a function that can locate the specified TypeScript file, find the variable, and add the given value to it.
... | ```typescript
import * as fs from 'fs';
function addValueToVariable(fileName: string, componentName: string, variableName: string, value: number): void {
const filePath = `path/to/${fileName}`; // Replace with the actual file path
const fileContent = fs.readFileSync(filePath, 'utf8');
const componentRegex = new ... | magicoder | typescript |
You are tasked with creating a Python function that compares two YAML files and checks if their contents are equivalent. The function should take two file paths as input and return a boolean value indicating whether the YAML contents are the same. You are provided with a code snippet that includes a test case using the... | ```python
import yaml
def compare_yaml_files(file1, file2):
try:
with open(file1, "r") as file1_stream, open(file2, "r") as file2_stream:
yaml1 = yaml.safe_load(file1_stream)
yaml2 = yaml.safe_load(file2_stream)
return yaml1 == yaml2
except FileNotFoundError:
... | magicoder | python |
You are given an array of non-negative integers representing the amount of money of each house. The houses are arranged in a circle, meaning the first house is adjacent to the last house. You are not allowed to rob adjacent houses. The goal is to determine the maximum amount of money you can rob without alerting the po... | ```python
def rob(nums):
if not nums:
return 0
if len(nums) == 1:
return nums[0]
# Helper function to calculate the maximum amount that can be robbed in a range
def rob_range(start, end):
max_rob = 0
prev_rob = 0
for i in range(start, end):
prev_rob, ... | magicoder | python |
You are tasked with simulating a game controller's behavior based on a given set of rules and conditions. The controller communicates with a web interface and a serial port to manage the game state and send messages. Your goal is to implement the logic for updating the game state and sending messages based on specific ... | ```python
# Define the Gamestate enum
class Gamestate:
GAMEOVER = "GAMEOVER"
# Add other game states as needed
# Define the send_message function
def send_message(ser, message, debug_shared):
# Implementation of send_message function
# Define the Message class with create_controller_strikeout and create_c... | magicoder | python |
You are tasked with implementing a Python function that calculates scalar summaries for a given list of numerical values. The scalar summaries to be calculated are the mean, median, mode, range, and standard deviation. The function should take a list of numerical values as input and return a dictionary containing these... | ```python
from typing import List, Dict, Union
import statistics
def calculate_scalar_summaries(values: List[float]) -> Dict[str, Union[float, List[float]]]:
summaries = {}
# Calculate mean
mean = sum(values) / len(values)
summaries['mean'] = mean
# Calculate median
median = statistic... | magicoder | python |
You are tasked with implementing a custom `for_each` function that iterates over two single-pass ranges and applies a given function to each pair of elements from the ranges. The function signature is as follows:
```cpp
template<class SinglePassRange1, class SinglePassRange2, class Fn2>
inline Fn2 for_each(SinglePassR... | ```cpp
#include <iostream>
#include <vector>
namespace boost {
// Define SinglePassRangeConcept and range_detail::for_each_impl here
// ...
template<class SinglePassRange1, class SinglePassRange2, class Fn2>
inline Fn2 for_each(SinglePassRange1& rng1, const SinglePassRange2& rng2, Fn2 fn)
{
... | magicoder | cpp |
You are working on a project that involves manipulating views in a macOS application. You have a class that inherits from NSView, and you need to implement a method to transfer subviews from one NSView to another. The method should take the following parameters:
1. `oldView`: The original NSView from which subviews wil... | ```swift
extension NSView {
func transferSubviews(from oldView: NSView, to newView: NSView) {
guard oldView !== newView else { return } // If oldView and newView are the same, do nothing
// If newView is a subview of oldView, remove it from oldView
if newView.isDescendant(of: oldVie... | magicoder | swift |
You are tasked with implementing a performance monitoring system for a deep learning model training process. The system should display progress updates and record validation accuracy metrics during the training process. You are given a code snippet that partially implements this functionality using Python and PyTorch's... | ```python
def update_performance_metrics(i, print_freq, progress, writer, top1, top5, epoch, val_loader):
if i % print_freq == 0:
progress.display(i)
writer.add_scalar('val_acc_1', top1.avg, epoch * len(val_loader) + i)
writer.add_scalar('val_acc_5', top5.avg, epoch * len(val_loader) + i)
... | magicoder | python |
You are tasked with implementing a simplified Scheme interpreter in Python. Scheme is a functional programming language that uses prefix notation for expressions. The given code snippet is part of the interpreter's `evaluate` method, which handles different types of Scheme expressions.
Your task is to implement the `e... | ```python
class Scheme:
@classmethod
def evaluate(cls, token, environment):
if isinstance(token, int) or isinstance(token, float):
return token
elif isinstance(token, str):
return environment.find(token)[token]
elif token[0] is cls.__symbol('quote'):
(... | magicoder | python |
You are tasked with creating a Rust function that processes command-line arguments and constructs a vector of string references from the raw C-style string pointers passed as arguments. Your task is to complete the implementation of the `parse_args` function, which takes in the raw C-style string pointers and the numbe... | ```rust
use std::os::raw::c_char;
use std::ffi::CStr;
use std::slice;
fn parse_args(argv: *const *const c_char, argc: usize) -> Vec<&str> {
unsafe {
let args_raw = slice::from_raw_parts(argv, argc);
args_raw
.iter()
.map(|&arg| {
CStr::from_ptr(arg)
... | magicoder | rust |
You are tasked with implementing a Python function that processes a string containing key-value pairs in a specific format and returns a dictionary with the extracted key-value pairs.
You are given a string `inpStr` in the following format:
- The string contains key-value pairs enclosed in square brackets, separated b... | ```python
import re
def extract_key_value_pairs(inpStr: str) -> dict:
key_value_pairs = re.findall(r'\[(.+?)]=\[(.+?)]', inpStr)
return dict(key_value_pairs)
```
The `extract_key_value_pairs` function uses the `re.findall` method to extract key-value pairs from the input string `inpStr` based on the specified... | magicoder | python |
You are tasked with creating a Python function that interacts with a web API to retrieve and process JSON data. The function should handle potential exceptions and log any errors that occur. Below is a skeleton of the function with some missing parts:
```python
import logging
import aiohttp
async def fetch_and_proces... | ```python
import logging
import aiohttp
async def fetch_and_process_data(url: str, payload: dict) -> dict:
logger = logging.getLogger(__name__)
try:
async with aiohttp.ClientSession() as session:
async with session.post(url, json=payload) as response:
response_json = await r... | magicoder | python |
You are tasked with implementing a class that represents a system for tracking and managing various metrics. The interface `HasMetrics` is provided, which requires implementing a method `metrics()` that returns a list of `Metric` objects. Each `Metric` object contains a name and a value.
Your task is to create a class... | ```java
import java.util.ArrayList;
import java.util.List;
public class MetricsSystem implements HasMetrics {
private List<Metric> metricList;
public MetricsSystem() {
this.metricList = new ArrayList<>();
}
public void addMetric(String name, double value) {
Metric newMetric = new Metr... | magicoder | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.