query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a simple application framework for managing screens. The framework should allow for the creation of multiple screens and the ability to switch between them. Each screen should have a unique identifier and be able to display its content.
You are provided with a basic `Screen` class that... | ```cpp
#include <iostream>
#include <unordered_map>
class Screen {
public:
Screen(int id) : id(id) {}
virtual void display() = 0;
int getId() const { return id; }
private:
int id;
};
class App {
public:
void addScreen(Screen* screen) {
screens[screen->getId()] = screen;
}
void rem... | magicoder | cpp |
You are tasked with creating a Python class for a simple neural network model and implementing a training loop using PyTorch. Your task is to complete the implementation of the `train` method in the given `NeuralNetwork` class. The `train` method takes a dataset of input-output pairs and trains the neural network using... | ```python
def train(self, epochs):
for epoch in range(epochs):
for batch in self.train_loader:
inputs, labels = batch[0], batch[1]
self.optimizer.zero_grad(set_to_none=True) # Zero the gradients
outputs = self.model(inputs) # Forward pass
... | magicoder | python |
You are tasked with creating a Python script that parses a given module source file and extracts information about the extensions to be built. The script should identify the extension modules and their respective details from the provided module source file.
Write a Python function `extract_extensions_info(module_src)... | ```python
import ast
def extract_extensions_info(module_src):
with open(module_src, 'r') as file:
source_code = file.read()
# Parse the source code to extract information about the extensions
tree = ast.parse(source_code)
extensions_info = {}
# Find the build function and extract the setu... | magicoder | python |
You are tasked with implementing a class that reads XML data from an input stream and provides methods for parsing and extracting information from the XML content. Your task is to create a Java class named `XmlParser` that includes the following functionalities:
1. A constructor that takes an `InputStream` as a parame... | ```java
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;
import java.io.InputStream;
import java.u... | magicoder | java |
You are tasked with creating a Python function that calculates guess parameters for a given model based on input data. The model is related to medical imaging and requires the estimation of certain parameters. You are provided with a code snippet that tests the output of the function for a specific set of input data an... | ```python
import numpy as np
import pandas as pd
def get_guess_params(model_type, data_frame, key_uptakes, key_pressures):
if model_type == "mdr":
guess_params = {}
# Perform calculations to estimate guess parameters for the "mdr" model
# ...
return guess_params
else:
ra... | magicoder | python |
You are tasked with implementing a simplified version of a task execution system in Rust. The system is designed to execute tasks asynchronously and handle their status updates. Your goal is to implement the `TaskExecutor` struct and its associated methods to manage the execution of tasks and handle their status update... | ```rust
use std::sync::Arc;
use tokio::sync::Mutex;
use anyhow::Result;
struct TaskHeader {
// Define the fields of the task header
}
struct HeaderSliceStatusWatch {
// Define the fields and methods for monitoring header slice status
}
struct TaskExecutor {
header_slices: Vec<TaskHeader>,
sentry: Arc... | magicoder | rust |
You are tasked with implementing a class hierarchy for a simple database query system. The system consists of a `Query` class and several subclasses representing different types of query operations. Each subclass represents a specific type of query operation, such as filtering, sorting, or field selection.
The provide... | ```python
class Query:
def __init__(self):
pass
def children_like(self, cls):
# Get all the subclasses of Query
subclasses = self._get_subclasses(Query)
# Filter the subclasses that match the specified class cls
result = [subclass for subclass in subclasses if issubclass... | magicoder | python |
You are tasked with creating a function that extracts all the HTML classes from a given HTML code snippet and returns them as a list. The HTML code snippet will be provided as a string. Each HTML class is defined within the `class` attribute of an HTML tag and is separated by a space. The function should return a list ... | ```python
from bs4 import BeautifulSoup
import re
def extract_html_classes(html_code: str) -> List[str]:
# Use BeautifulSoup to parse the HTML code
soup = BeautifulSoup(html_code, 'html.parser')
# Find all HTML tags with class attributes
class_attributes = soup.find_all(attrs={'class': True})
... | magicoder | python |
You are tasked with implementing a method to convert a sequence of ASCII bytes into a string. The method should take a byte array as input and return the corresponding string. Note that no bounds checking is performed on the incoming bytes, and the upper bit is silently discarded during the conversion.
You need to imp... | ```java
public static String fromAsciiBytes(byte[] bytes, int ofs, int len) {
StringBuilder sb = new StringBuilder();
for (int i = ofs; i < ofs + len; i++) {
sb.append((char) (bytes[i] & 0x7F));
}
return sb.toString();
}
```
The `fromAsciiBytes` method iterates through the specified range of by... | magicoder | java |
You are tasked with creating a program that processes user profile pictures. The program should be able to perform basic image manipulation operations such as resizing, cropping, and applying filters. For this problem, you need to implement a function that takes an image and a list of operations as input and returns th... | ```python
from PIL import Image, ImageFilter
def process_image(image: Image, operations: List[str]) -> Image:
processed_image = image.copy()
for operation in operations:
operation_parts = operation.split()
if operation_parts[0] == "resize":
width, height = int(operation_parts[1]), ... | magicoder | python |
You are tasked with implementing a Python class that manages authentication tokens for different social media platforms. The class should handle the retrieval and invalidation of tokens for various providers. Your task is to complete the implementation of the `TokenManager` class by adding the necessary methods to retr... | ```python
from urllib import parse
class TokenManager:
def __init__(self, blueprint=None, base_url=None, *args, **kwargs):
super().__init__(*args, **kwargs)
self.blueprint = blueprint
self.base_url = parse.urlparse(base_url)
self.tokens = {} # Dictionary to store tokens for differe... | magicoder | python |
You are tasked with implementing a Point class in C++ that can represent points in both Cartesian and polar coordinate systems. The class should have the following functionalities:
1. Constructors to initialize a point in both Cartesian and polar coordinates.
2. Methods to convert a point from Cartesian to polar coordi... | ```cpp
#include <iostream>
#include <cmath>
class Point {
private:
double x, y, radius, angle;
public:
// Constructor for Cartesian coordinates
Point(double x, double y) : x(x), y(y) {
radius = sqrt(x * x + y * y);
angle = atan2(y, x);
}
// Constructor for polar coordinates
Po... | magicoder | cpp |
You are tasked with creating a Python script that simulates the functionality of the `update-rc.d` command in Linux. The `update-rc.d` command is used to install or remove System-V style init script links. The script should be able to add or remove a service from the system's startup sequence.
Your Python script shoul... | ```python
import sys
import os
def add_service_to_startup(service_name):
runlevel_directories = ['/etc/rc0.d/', '/etc/rc1.d/', '/etc/rc2.d/', '/etc/rc3.d/', '/etc/rc4.d/', '/etc/rc5.d/', '/etc/rc6.d/']
for directory in runlevel_directories:
os.symlink('/etc/init.d/{}'.format(service_name), '{}S20{}'.fo... | magicoder | python |
You are tasked with creating a Python script to automate the configuration of iptables for enabling Network Address Translation (NAT) on a Linux system. NAT allows multiple devices within a local network to share a single public IP address when accessing the internet. The script should take input parameters for the net... | ```python
import subprocess
def enable_nat(interface):
try:
subprocess.run(['iptables', '-t', 'nat', '-A', 'POSTROUTING', '-o', interface, '-j', 'MASQUERADE'], check=True)
print(f'NAT enabled successfully for interface {interface}')
except subprocess.CalledProcessError as e:
print(f'Err... | magicoder | python |
You are tasked with creating a Python class that manages a collection of sequence records. Each sequence record has a name and a position. Additionally, some sequence records may have a "rankParent" attribute indicating their parent's rank. Your task is to implement a method in the class that returns a dictionary conta... | ```python
from collections import defaultdict
class SequenceRecordManager:
def __init__(self, data):
self.data = data
def get_parents_rank_list(self):
parents = defaultdict(list)
for ind, seqRec in enumerate(self.data):
if hasattr(seqRec, "rankParent"):
par... | magicoder | python |
You are tasked with implementing a function that removes a node (represented by a `Fiber` object) from a tree structure. The `Fiber` object represents a node in a tree and contains references to its parent, previous sibling, and the container node in the DOM.
You are given the following TypeScript code snippet as a st... | ```typescript
import type { Fiber } from '.';
import { assert } from '../util/assert';
export function remove(
fiber: Fiber,
parent: Fiber,
previous: null | Fiber,
container: Node,
): null | Fiber {
debug: {
assert(fiber.parent === parent, 'fiber must be child of parent');
if (previous === null) {
... | magicoder | typescript |
You are tasked with creating a Django REST framework viewset for managing notes in a note-taking application. The `NoteViewSet` class should handle various CRUD (Create, Read, Update, Delete) operations for notes.
Your task is to implement the `NoteViewSet` class with the following requirements:
- The viewset should b... | ```python
from rest_framework import viewsets
from textify.models import Note
from textify.api.serializers import NoteSerializer
class NoteViewSet(viewsets.ModelViewSet):
queryset = Note.objects.all()
serializer_class = NoteSerializer
```
In this solution, we create a `NoteViewSet` class that inherits from `v... | magicoder | python |
You are tasked with implementing a URL routing system for a web application. The application has four different endpoints: icons, charts, tables, and login. Your goal is to create a URL routing system that directs incoming requests to the appropriate handler functions based on the requested endpoint.
You are given a P... | ```python
# Define handler functions for each endpoint
def icons(request):
# Handler logic for the 'icons' endpoint
# ...
pass
def charts(request):
# Handler logic for the 'charts' endpoint
# ...
pass
def tables(request):
# Handler logic for the 'tables' endpoint
# ...
pass
def lo... | magicoder | python |
You are tasked with implementing a key derivation function in PHP for password-based cryptography. The key derivation function to be implemented is PBEKDF2, which is defined in the namespace `Sop\PKCS5\PBEKD`. This function is used to derive cryptographic keys from passwords and is based on the PBKDF2 algorithm specifi... | ```php
<?php
declare(strict_types = 1);
namespace Sop\PKCS5\PBEKD;
use Sop\PKCS5\PRF\PRF;
/**
* Implements key derivation function #2 used in password-based cryptography.
*
* @see https://tools.ietf.org/html/rfc2898#section-5.2
*/
class PBEKDF2 extends PBEKDF
{
/**
* Derive a cryptographic key from the... | magicoder | php |
You are tasked with creating a registration form for a web application using Angular. The form should include fields for the user to input their name, email, and password. Additionally, the form should have validation to ensure that all fields are filled out and that the email follows a valid format. You are required t... | ```typescript
// RegistrationComponent
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { RegistrationService } from './registration.service';
@Component({
selector: 'app-registration',
templateUrl: './registration.component.html',
styleUrls: ... | magicoder | typescript |
You are tasked with implementing a Python program that utilizes the `dedupe` library to perform record linkage on a dataset. The `dedupe` library provides functions for data deduplication and entity resolution, which are commonly used in data cleaning and integration tasks.
Your task is to create a program that takes ... | ```python
from dedupe.core import randomPairs, randomPairsMatch, frozendict
from dedupe.convenience import consoleLabel, trainingDataDedupe, trainingDataLink, canonicalize
# Load the dataset into memory (Assuming data is loaded into 'data' variable)
data = [...]
# Preprocess the data
canonical_data = [canonicalize(re... | magicoder | python |
You are given a binary tree represented by a pointer to its root node. Your task is to write a function to return the level order traversal of the tree in the form of a 2D array. The level order traversal of a tree is a breadth-first traversal where nodes at each level are visited from left to right.
The function sign... | ```cpp
#include <vector>
#include <queue>
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
vector<vector<int>> levelOrderTraversal(TreeNode* root) {
vector<vector<int>> result;
if (root == nullptr) {
return result... | magicoder | cpp |
You are tasked with implementing a Python function that simulates a simple banking system. The system should support basic operations such as creating accounts, depositing funds, withdrawing funds, and transferring funds between accounts. Each account should have a unique account number and should store the account hol... | ```python
class Account:
def __init__(self, account_number, name, balance):
self.account_number = account_number
self.name = name
self.balance = balance
class BankingSystem:
def __init__(self):
self.accounts = {}
def create_account(self, name: str, initial_balance: float) -... | magicoder | python |
You are tasked with implementing a custom iterator in Rust. The iterator should take an input value `curr` of type `u32` and a shift value `sh` of type `u32`. The iterator should yield the individual bytes of the input value, shifted by the shift value, as `u8` values. The iterator should also keep track of the number ... | ```rust
struct CustomIterator {
curr: u32,
sh: u32,
i: u32,
}
impl CustomIterator {
fn new(curr: u32, sh: u32) -> CustomIterator {
CustomIterator { curr, sh, i: 0 }
}
}
impl Iterator for CustomIterator {
type Item = u8;
fn next(&mut self) -> Option<u8> {
if self.i < 4 {
... | magicoder | rust |
You are tasked with creating a Python function that parses and processes URL routes based on a given configuration. The configuration consists of route names and their corresponding URL patterns. Each URL pattern may contain placeholders for dynamic values, such as IDs. Your function should be able to match a given URL... | ```python
import re
def process_route(url, routes):
for route_name, pattern in routes.items():
regex_pattern = re.sub(r'{\w+}', r'(\w+)', pattern) # Convert placeholders to regex patterns
match = re.match(regex_pattern, url)
if match:
dynamic_values = re.match(pattern, url).gro... | magicoder | python |
You are tasked with implementing a function that processes a collection of advertisement objects and transforms them into a specific format. Each advertisement object contains a call to action, an image name, and a link. The goal is to create a new collection of transformed advertisement objects, where the call to acti... | ```swift
func transformAdvertisements(_ advertisements: [Advertisement]) -> [TransformedAdvertisement] {
var transformedAds: [TransformedAdvertisement] = []
for ad in advertisements {
if let image = UIImage(named: ad.imageName) {
let transformedAd = TransformedAdvertisement(callToAction... | magicoder | swift |
You are tasked with implementing a function to find the last occurrence of a substring within a given string. Your task is to complete the Python function `find_last(a, b)` where `a` is the input string and `b` is the substring to be found. The function should return the index of the last occurrence of the substring `b... | ```python
def find_last(a, b):
last_index = a.rfind(b)
return last_index
```
The `find_last` function uses the `rfind` method of the string `a` to find the last occurrence of the substring `b` within the string. If the substring is found, it returns the index of the last occurrence; otherwise, it returns -1. T... | magicoder | python |
You are tasked with implementing a Rust program that involves working with type aliases and defining new types. Your goal is to create a program that simulates a simple file format parser by using the provided type aliases and defining new types based on them.
Your task is to define a new type called `FileHeader` that... | ```rust
pub type c_long = i64;
pub type time_t = i64;
pub type Elf_Addr = ::Elf64_Addr;
pub type Elf_Half = ::Elf64_Half;
// Define the FileHeader type
pub struct FileHeader {
entry_point: Elf_Addr,
section_count: Elf_Half,
timestamp: time_t,
}
// Implement the parse_file_header function
fn parse_file_he... | magicoder | rust |
You are tasked with creating a program to parse and extract key-value pairs from a JSON object and store them in a data structure for further processing. The JSON object contains information about a software application, including its build number, build type, version, debuggable status, build version, operating system... | ```python
import json
def extract_app_info(json_obj):
app_info = {
"kitBuildNumber": json_obj.get("kitBuildNumber"),
"kitBuildType": json_obj.get("kitBuildType"),
"appVer": json_obj.get("appVer"),
"app_debuggable": json_obj.get("app_debuggable", "0"),
"appBuild": json_obj.ge... | magicoder | python |
You are tasked with implementing a Python function that converts a mnemonic phrase into a private key using the BIP39 standard. The BIP39 standard specifies a method for creating a 12 to 24-word mnemonic phrase that can be used to generate deterministic wallets. The mnemonic phrase is used to derive a seed, from which ... | ```python
import hashlib
import hmac
import binascii
def to_private_key(mnemonic: str) -> str:
mnemonic_bytes = mnemonic.encode('utf-8')
salt = b'mnemonic' + mnemonic_bytes
seed = hashlib.pbkdf2_hmac('sha512', mnemonic_bytes, salt, 2048)
private_key = seed[:32] # First 32 bytes of the seed form the pr... | magicoder | python |
You are tasked with creating a Python function that generates a SQL query to create a table based on the given column specifications. The function should take a list of dictionaries, where each dictionary represents a column and its properties. The properties include the column name, data type, primary key status, uniq... | ```python
def generate_create_table_query(columns: list) -> str:
query = "CREATE TABLE table_name (\n"
for column in columns:
query += f" {column['name']} {column['data_type']}"
if column.get('primary_key'):
query += " PRIMARY KEY"
if column.get('unique'):
quer... | magicoder | python |
You are tasked with creating a Python function that dynamically generates command-line arguments for a distributed training script using the `argparse` module. Your function should add a group of arguments related to Distributed Data Parallel (DDP) training to the given `argparse.ArgumentParser` object.
The function s... | ```python
import argparse
def add_ddp_arguments(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:
group = parser.add_argument_group(
title="DDP arguments", description="DDP arguments"
)
group.add_argument("--ddp.disable", action="store_true", help="Don't use DDP")
group.add_argument(... | magicoder | python |
You are tasked with creating a Python function that processes Jupyter notebooks to generate thumbnail images for code cells. The function should take a Jupyter notebook and a dictionary of resources as input, and return the processed notebook and updated resources. The thumbnail images should be generated for code cell... | ```python
class ThumbnailProcessor:
def __init__(self, basename):
self.basename = basename
def preprocess_cell(self, cell, resources, index):
if cell['cell_type'] == 'code':
template = 'from nbsite.gallery.thumbnailer import thumbnail;thumbnail({{expr}}, {basename!r})'
c... | magicoder | python |
You are tasked with implementing a custom `LinkedList` class in Python. The `LinkedList` class should have the following methods:
- `__init__(self)`: Initializes an empty linked list.
- `append(self, data)`: Appends a new node containing the given `data` to the end of the linked list.
- `__str__(self)`: Returns a strin... | ```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
else:
curren... | magicoder | python |
You are tasked with implementing a function that processes a given configuration object and generates a formatted HTML component based on the provided properties. The configuration object contains properties for the variant, size, and color of the component. Your task is to create a function that takes this configurati... | ```javascript
function generateComponent(config) {
const buttonProps = {
variant: config.variant,
size: config.size,
color: config.color
};
const handleClick = () => {
// Handle click logic here
};
return `
<Card title="Všechny zálohy a faktury" buttonProps={${JSON.stringify(buttonProps)}} handleClick=... | magicoder | javascript |
You are tasked with creating a Python class that manages file transfers and tracks any errors that occur during the process. The class, `FileTransferManager`, has a method `track_errors` that updates an error dictionary with information about the source and destination paths and their corresponding file permissions in ... | ```python
from pathlib import Path
class FileTransferManager:
def __init__(self, last_src, last_dst):
self.last_src = last_src
self.last_dst = last_dst
self._error_dict = {}
def track_errors(self):
try:
last_src_path = Path(self.last_src)
last_src_mode =... | magicoder | python |
You are tasked with implementing a function that classifies the type of a given local variable name in a C# program. The classification is based on the position of the variable name within the source code. The classification function takes the position of the variable name as input and returns the type of the variable.... | ```csharp
public string ClassifyAt(int position, int length)
{
// Your implementation here
// Example implementation:
if (position >= 256 && position < 265) {
return "LocalVariableName";
} else {
return "Unknown";
}
}
```
In the solution, the ClassifyAt function should be implemented... | magicoder | csharp |
You are given a singly linked list and a positive integer `k`. Write a function to reverse the nodes of the linked list `k` at a time and return the modified list. If the number of nodes is not a multiple of `k`, then left-out nodes, in the end, should remain as it is.
For example, given the linked list `1 -> 2 -> 3 -... | ```java
public ListNode reverseKGroup(ListNode head, int k) {
ListNode curr = head;
int count = 0;
while (curr != null && count < k) {
curr = curr.next;
count++;
}
if (count == k) {
curr = reverseKGroup(curr, k);
while (count-- > 0) {
ListNode temp = head.... | magicoder | java |
You are tasked with implementing a function that performs a multi-key retrieval operation from a data store. The function should handle both successful and failed key lookups and return the results accordingly.
You are given a code snippet that partially implements the functionality. The snippet shows a part of a func... | ```python
from typing import List, Optional, Union, Dict, Any
def multi_key_retrieval(keys: List[str]) -> Union[List[Optional[str]], Dict[str, Any]]:
successes = []
failures = []
for key in keys:
value = get_value(key)
if value is not None:
successes.append(value)
e... | magicoder | python |
You are tasked with implementing a function that takes a pointer to a destination array and a 128-bit vector as input and stores the components of the vector into the destination array. The function is expected to handle both intrinsic and non-intrinsic implementations.
You are given the following code snippet as a st... | ```cpp
(
uint32_t* pDestination,
FXMVECTOR V
) noexcept
{
assert(pDestination);
#if defined(_XM_NO_INTRINSICS_)
pDestination[0] = V.vector4_u32[0];
pDestination[1] = V.vector4_u32[1];
pDestination[2] = V.vector4_u32[2];
pDestination[3] = V.vector4_u32[3];
#else
// Intrinsic implementatio... | magicoder | cpp |
You are tasked with implementing a class to parse a binary file containing a sequence of bits with a specific endianness. The file format is as follows:
- The file contains a sequence of bits, where each bit is represented by a single byte.
- The endianness of the sequence is specified by the file format.
Your task is... | ```csharp
using System;
using System.IO;
public class BitsSeqEndianCombo
{
public enum Endianness
{
LittleEndian,
BigEndian
}
public static byte[] FromFile(string filePath)
{
byte[] fileBytes = File.ReadAllBytes(filePath);
byte[] parsedBits = new byte[fileBytes.Leng... | magicoder | csharp |
You are given a snippet of code that manipulates a set of indices for a 3D mesh. The code snippet is part of a function that generates indices for rendering a 3D mesh using a specific pattern. The function takes two parameters: `Meridians` and `k`. The `Meridians` parameter represents the number of longitudinal lines o... | ```cpp
#include <vector>
std::vector<int> generateMeshIndices(int Meridians, int k) {
std::vector<int> Indices;
for (int l = 0; l < Meridians; l++) {
int a = (k * (Meridians + 1)) + l;
int b = a + Meridians + 1;
Indices.push_back(a);
Indices.push_back(b);
Indices.push_... | magicoder | cpp |
You are given a set of constraints in the form of mathematical expressions involving decision variables. Your task is to write a program to determine the feasibility of these constraints and find a feasible solution if one exists.
The constraints are represented in the following format:
```
m.c83 = Constraint(expr= ... | To solve this problem, we can use a mathematical optimization solver to check the feasibility of the constraints and find a feasible solution if one exists. Here's a Python implementation using the `PuLP` library to solve the linear programming problem:
```python
import pulp
# Create a LP problem
prob = pulp.LpProble... | magicoder | python |
You are tasked with implementing a function to analyze a set of binary lines and calculate a metric based on their frequency distribution. The function `task1` takes two parameters: a reference to a vector `lines` containing unsigned integers representing binary lines, and an unsigned integer `bitcount` representing th... | ```rust
fn task1(lines: &Vec<usize>, bitcount: usize) -> usize {
let half_length = ((lines.len() as f32) / 2.0 + 0.5) as usize;
let frequency = calculate_frequency(lines, bitcount);
let gamma_rate = calculate_gamma_rate(&frequency, half_length, bitcount);
let epsilon_rate = calculate_epsilon_rate(gamma... | magicoder | rust |
You are tasked with creating a custom error type in Rust for a version control system. The error type should handle various error cases related to JSON parsing, file cleanliness, input/output operations, and Git operations. Your goal is to implement the custom error type and handle different error scenarios using this ... | ```rust
use thiserror::Error;
use std::io;
use serde_json;
use git2;
#[derive(Error, Debug)]
pub enum VersionControlError {
#[error("Json error: {0}")]
Json(#[from] serde_json::Error),
#[error("NotClean error")]
NotClean,
#[error("Io error: {0}")]
Io(#[from] io::Error),
#[error("Git error: ... | magicoder | rust |
You are tasked with implementing a Python class that manages a database of hosts and their corresponding keys. The class should provide methods for adding hosts, retrieving keys, and joining relations between hosts. You are provided with a code snippet for the `keys` method, which returns a tuple representation of keys... | ```python
from typing import Dict, Tuple
class HostManager:
def __init__(self):
self.hosts = {}
def add_host(self, host_id: str, host_keys: Tuple[str, ...]):
"""
Add a host to the database with its keys.
Args:
host_id (str): Identifier for the host.
hos... | magicoder | python |
You are tasked with creating a program that simulates a simple game using a 5x5 grid. The game involves a player navigating through the grid to reach a goal while avoiding obstacles. The player's position and the goal position are represented by specific characters on the grid. The obstacles are represented by differen... | ```python
from sense_hat import SenseHat
# Initialize the Sense HAT
sense = SenseHat()
# Define the grid dimensions
grid_size = 5
# Define the grid with player, goal, and obstacles
grid = [
[' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' '],
... | magicoder | python |
You are tasked with creating a Python class that validates and processes URLs using Django's forms module. Your task is to implement a custom form class that accepts a URL input from a user and provides a placeholder for the input field. The form should validate the URL and return it in a specific format.
Create a Pyt... | ```python
from django import forms
class CustomUrlForm(forms.Form):
url = forms.URLField(widget=forms.URLInput(attrs={'placeholder': 'Paste your link here...'}))
def clean_url(self):
url = self.cleaned_data['url']
return url.lower()
```
In the solution, we create a class `CustomUrlForm` that e... | magicoder | python |
You are tasked with implementing a learning rate adjustment function for a deep learning optimizer. The function should adjust the learning rate based on the specified mode and parameters. The learning rate adjustment function should support two modes: "step" and "warmup_step".
The "step" mode adjusts the learning rat... | ```python
def adjust_learning_rate(optimizer, warmup_epoch, epoch, args, nums_batches):
if args.lr_mode == 'step':
if epoch in args.lr_step_epochs:
new_lr = args.lr * (args.lr_decay_factor ** (epoch // args.lr_step_epochs))
for param_group in optimizer.param_groups:
p... | magicoder | python |
You are tasked with implementing a simple traffic light control system using Python and Flask. The provided code snippet initializes a `TrafficLights` object and sets up Flask routes for controlling the red traffic light. Your task is to extend this system to include routes for the yellow and green traffic lights, and ... | ```python
from flask import Flask, Response
app = Flask(__name__)
class TrafficLights:
def __init__(self):
self.red = "off"
self.yellow = "off"
self.green = "off"
def set_red(self, state):
self.red = state
def set_yellow(self, state):
self.yellow = state
def s... | magicoder | python |
You are tasked with implementing a simple 2D rendering engine in Rust using the WebGl2 API. The provided code snippet outlines a trait `Renderable` that defines methods for initializing and rendering objects. Your goal is to create a concrete implementation of this trait for a basic shape, such as a square, and then us... | ```rust
use web_sys::WebGl2RenderingContext;
pub struct Square {
// Define the properties of the square, such as position, size, color, etc.
// For simplicity, let's assume the square is defined by its center coordinates and side length.
center_x: f32,
center_y: f32,
side_length: f32,
color: [f... | magicoder | rust |
You are tasked with creating a web application that displays localized content based on the user's language preference. The application uses the Razor view engine in ASP.NET MVC to render the content. The provided code snippet is from a view file in the application, and it sets the title, subtitle, and description for ... | ```csharp
using System.Web.Mvc;
public class WelcomePageRenderer
{
public string RenderWelcomePage(string languagePreference)
{
// Retrieve the appropriate localized resource strings based on the language preference
string title = GetLocalizedTitle(languagePreference);
string subtitle =... | magicoder | csharp |
You are tasked with creating a Python program to analyze data related to signs of the zodiac. The program should calculate the number of days each zodiac sign has been in effect between a given start date and the current date.
The zodiac signs are represented by the following IDs: 1 for Aries, 2 for Taurus, 3 for Gemi... | ```python
import sys
from datetime import date, timedelta
SIGN_IDS = list(range(1, 13))
def calculate_zodiac_days(start_date, end_date):
zodiac_days = {sign_id: 0 for sign_id in SIGN_IDS}
current_date = start_date
while current_date <= end_date:
sign_id = (current_date.month - 1) % 12 + 1
... | magicoder | python |
You are tasked with creating a program to parse and analyze a series of review data from a web application. The reviews are represented in HTML-like syntax, and each review contains a user's rating, company information, review title, and description. Your task is to extract and process the review data to generate a sum... | ```python
import re
def parse_review_data(html_code):
# Parse star ratings
filled_stars = len(re.findall(r'<i class="icon_star"></i>', html_code))
empty_stars = len(re.findall(r'<i class="icon_star empty"></i>', html_code))
total_stars = filled_stars + empty_stars
average_rating = filled_stars / to... | magicoder | python |
You are tasked with creating a program to manage TV show ratings. The program should allow users to add, update, and view ratings for different TV shows. Additionally, it should provide the functionality to iterate through all the ratings and modify them.
Your task is to implement a `TvRatings` struct with the followi... | ```rust
use std::collections::HashMap;
use std::fmt;
struct TvRatings {
ratings: HashMap<String, f64>,
}
impl TvRatings {
fn new() -> TvRatings {
TvRatings {
ratings: HashMap::new(),
}
}
fn add_rating(&mut self, show: &str, rating: f64) {
self.ratings.insert(show.t... | magicoder | rust |
You are tasked with implementing a reusable entity identifier manager in Swift. The manager should provide a way to generate unique entity identifiers and mark them as unused for future reuse.
You are provided with a code snippet that outlines the interface for the entity identifier manager:
```swift
/// - Parameter ... | ```swift
struct EntityIdentifier: Hashable {
let value: Int
}
class EntityIdentifierManager {
private var availableIds: [EntityIdentifier]
init<EntityIds>(startProviding initialEntityIds: EntityIds) where EntityIds: BidirectionalCollection, EntityIds.Element == EntityIdentifier {
self.availableIds... | magicoder | swift |
You are tasked with creating a program that counts the occurrences of specific words in a given text file. The program should read the text file and then output the frequency of each word in the file. For this problem, you should consider a word to be any sequence of characters separated by whitespace.
Your program sh... | ```python
from typing import List, Dict
import re
def count_word_occurrences(file_path: str, words: List[str]) -> Dict[str, int]:
word_counts = {}
with open(file_path, 'r') as file:
text = file.read().lower()
text = re.sub(r'[^\w\s]', '', text) # Remove punctuation
word_list = text.spl... | magicoder | python |
You are working on a scientific computing project and need to implement a numerical differentiation method to compute Jacobian matrices for a system of equations. The code snippet provided is a part of a larger program that aims to calculate the Jacobians using the complex-step differentiation (CSD) method. The `make_n... | ```python
import numpy as np
class Shooting2:
def __init__(self, bvp_test):
self.num_deriv_type = 'csd'
self.n_y = 3 # Example value for the number of equations with respect to the dependent variables
self.n_p_d = 2 # Example value for the number of parameters
def make_num_jacobians(... | magicoder | python |
You are tasked with implementing a PoisoningAttackAdversarialEmbedding class for a machine learning framework. The PoisoningAttackAdversarialEmbedding class is responsible for generating adversarial examples to poison a classifier model. The code snippet provided is a unit test for the PoisoningAttackAdversarialEmbeddi... | ```python
class PoisoningAttackAdversarialEmbedding:
def __init__(self, classifier, backdoor, num_backdoor_patterns, target_labels):
self.classifier = classifier
self.backdoor = backdoor
self.num_backdoor_patterns = num_backdoor_patterns
self.target_labels = target_labels
sel... | magicoder | python |
You are working on a Django project that includes a REST API for managing user data. The code snippet provided is from a test suite for the API. The `fixtures` list contains the name of a JSON file that serves as test data for the API tests. The `setUp` method is used to set up the test environment by obtaining an auth... | ```python
# Create a new management command file named load_user_data.py in the appropriate Django app directory.
# Import necessary modules
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
import json
# Define the command class
class Command(BaseCommand):
help = 'Lo... | magicoder | python |
You are tasked with creating a video search application that interacts with an external API to retrieve a collection of videos based on a user's query. The API client and access token are provided, and you need to implement the `find_videos` function to make the API call and retrieve the videos. Additionally, you need ... | ```rust
use api::Client;
use api::video;
use api::AccessToken;
use api::Collection;
use api::Result;
use std::io;
fn find_videos(api: &Client, token: &AccessToken, query: &str) -> Result<Collection<Video>> {
let search_result = api.call(Some(token),
video::Search::new()
.q(query)
.a... | magicoder | rust |
You are tasked with implementing a test automation script for a web application using Python and Selenium. The provided code snippet is part of a larger test automation framework and contains element locators and a method for navigating to the dashboard page. Your goal is to complete the implementation by writing a tes... | ```python
import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class TestSelectAllItems(unittest.TestCase):
_search_input_field_css = ".search-input"
_r... | magicoder | python |
You are tasked with creating a Python program to automate the process of logging into a university's educational system and retrieving a user's messages. The program should utilize the `zfnew` library, which provides the `Login` and `GetInfo` classes for handling the login process and retrieving user information.
Your... | ```python
from zfnew import GetInfo, Login
base_url = '学校教务系统的主页url' # Replace with the actual main homepage URL
def automate_login_and_message_retrieval(username, password):
lgn = Login(base_url=base_url)
lgn.login(username, password)
cookies = lgn.cookies
person = GetInfo(base_url=base_url, cookies... | magicoder | python |
You are tasked with implementing a program to calculate the area of a regular polygon. A regular polygon is a polygon with all sides of equal length and all angles of equal measure. The formula to calculate the area of a regular polygon is given by:
\[ Area = \frac{n \times s^2}{4 \times \tan(\frac{\pi}{n})} \]
Where:... | ```python
import math
def calculate_polygon_area(n, s):
return (n * s ** 2) / (4 * math.tan(math.pi / n))
# Test the function
n = 5
s = 7.0
print("Area =", calculate_polygon_area(n, s))
``` | magicoder | python |
You are tasked with implementing a progress bar class in Python for tracking the vaccination progress in different regions. The progress bar should visually represent the percentage of the population that has received the first dose of the COVID-19 vaccine. The progress bar class should allow customization of its posit... | ```python
dose1_us_progress_bar = ProgressBar(
US_BAR_X, # Replace with the x-coordinate for the US progress bar
DOSE1_BAR_Y, # Use the same y-coordinate as the NY progress bar
BAR_WIDTH, # Use the same width as the NY progress bar
BAR_HEIGHT, # Use the same height as the NY progress bar
nationa... | magicoder | python |
You are tasked with implementing a text parsing algorithm that extracts information from an XML file and processes the content into distinct sections. The XML file contains an article with a title and textual content. The text parsing algorithm should separate the content into an introduction section, unnamed sections,... | ```python
class XmlParser:
@staticmethod
def parse_article(filename):
# Assume the XML parsing logic to extract title and text from the file
# Sample implementation:
title = "Sample Article Title"
text = "This is the content of the article."
return title, text
class Text... | magicoder | python |
You are tasked with creating a URL shortening service similar to Bitly or TinyURL. Your goal is to write a function that takes a long URL as input and returns a shortened version of it. The shortened URL should be unique and should redirect to the original long URL when accessed.
You are provided with the following co... | ```php
$host = 'https://dwz.cn';
$urls = []; // Store the mapping of long URLs to shortened URLs
function shortenURL($longURL) {
global $host, $urls;
if (array_key_exists($longURL, $urls)) {
return $urls[$longURL]; // Return the previously generated shortened URL
} else {
$uniqueIdentifier... | magicoder | php |
You are tasked with implementing a word autocomplete system using a parallel trie data structure. The parallel trie is a concurrent data structure that allows for efficient concurrent reads and writes. The trie is pre-populated with a list of words, and your task is to implement a function that takes a prefix string as... | ```rust
use par_trie::ParTrie;
const WORDS: &[&str; 20] = &[
"the", "them", "code", "coder", "coding",
"crap", "help", "heft", "apple", "hello",
// Additional words can be added here
];
fn autocomplete(prefix: &str) -> Vec<String> {
let trie = ParTrie::new();
for word in WORDS {
trie.inser... | magicoder | rust |
You are tasked with creating a program that simulates a thermometer display for a given temperature range. The program should take the current temperature as input and display a visual representation of the temperature using a thermometer-like design. The thermometer should be displayed as a colored bar within a define... | ```python
def displayThermometer(currentTemp, maxTemp):
temperature_range = maxTemp - 0
temperature_level = (currentTemp / maxTemp) * 100
if currentTemp <= 10:
color = "blue"
elif currentTemp <= 20:
color = "green"
elif currentTemp <= 30:
color = "yellow"
elif currentTem... | magicoder | python |
You are tasked with implementing a custom string class in C++ that supports various string manipulation operations. Your custom string class should provide functionality for concatenating strings, finding the length of the string, accessing individual characters by index, and comparing strings for equality.
Your custo... | ```cpp
#include <cstring> // For strlen, strcpy, strcat
#include <iostream>
class CustomString {
private:
char* data; // Pointer to the dynamically allocated string data
size_t len; // Length of the string
public:
// Constructs an empty string.
CustomString() : data(new char[1]), len(0) {
data... | magicoder | cpp |
You are tasked with implementing a pagination class in Python. The class should handle the generation of URLs for the next and previous pages based on the current page number and the availability of next and previous pages.
You are given a code snippet that partially implements the pagination class. Your task is to co... | ```python
class Pagination:
def __init__(self, page, request_args, old_vars):
self.page = page
self._request_args = request_args
self._old_vars = old_vars
@property
def has_next(self):
return bool(self.page)
@property
def has_prev(self):
return bool(self.pag... | magicoder | python |
You are tasked with creating a password validation function that checks whether a given password meets certain criteria. The password is stored in a specific format, which includes the actual password, its minimum and maximum length, the hashing algorithm used, and the hashed value. Your task is to implement a function... | ```python
import hashlib
def validate_password(password, stored_format):
parts = stored_format.split('(')
actual_password = parts[0].split('=')[1]
length_range, hash_info = parts[1].split(')')
min_length, max_length, hash_algorithm = length_range.split(',')
hashed_value = hash_info.split('$')[1]
... | magicoder | python |
You are tasked with implementing a class to manage and manipulate 3D dimensions of objects. The class should allow for setting and retrieving the dimensions in terms of height (H), width (V), and depth (D). Additionally, the class should provide a method to serialize the dimensions into an XML format.
You are given a ... | ```cpp
#include <iostream>
#include "tinyxml.h"
class DimensionsManager {
private:
double height;
double width;
double depth;
public:
DimensionsManager(double h = 0.0, double w = 0.0, double d = 0.0) : height(h), width(w), depth(d) {}
void setHeight(double h) {
height = h;
}
void... | magicoder | cpp |
You are tasked with implementing a reinforcement learning algorithm using the Twin Delayed Deep Deterministic Policy Gradient (TD3) approach. TD3 is an off-policy algorithm for continuous action spaces, which aims to learn a deterministic policy that maximizes the expected cumulative reward. In this problem, you will f... | ```python
import haiku as hk
import jax.numpy as jnp
def construct_policy_network(environment_spec):
action_size = jnp.prod(environment_spec.actions.shape, dtype=int)
input_size = environment_spec.observation.shape[0] # Assuming the observation shape is a 1D array
def _policy_fn(obs, is_training=False, k... | magicoder | python |
You are tasked with implementing a Python class that processes a dictionary and generates an XML output based on the keys and values in the dictionary. The keys in the dictionary correspond to specific XML components, and the values represent the content of those components. Your task is to create a class that can hand... | ```python
import xml.etree.ElementTree as ET
class XMLProcessor:
XML_COMPONENTS = {
'element1': 'element1_tag',
'element2': 'element2_tag',
'element3': 'element3_tag'
}
def __init__(self):
self.xml = ET.Element('root')
def process_dictionary(self, dictionary):
... | magicoder | python |
You are tasked with implementing a generic class for managing screens in a software application. The class should be able to handle different types of screens and provide functionality for managing windows associated with these screens.
Create a generic class `SomeGenericScreen<T1, T2>` that extends the `AppScreen` cl... | ```csharp
using System;
public class Window
{
public string Title { get; set; }
public void Display()
{
Console.WriteLine($"Displaying window: {Title}");
}
public void Close()
{
Console.WriteLine($"Closing window: {Title}");
}
}
public class AppScreen
{
// Base class fo... | magicoder | csharp |
You are tasked with implementing a Swift extension for the PhotoAsset class that provides a method to generate a URL for the photo asset. The PhotoAsset class represents a photo in an application, and the URL should be constructed based on the asset's identifier and the specified size.
You are given the following code... | ```swift
// PhotoAsset+URL.swift
import Foundation
extension PhotoAsset {
func generateURL(forSize size: CGSize) -> URL {
let baseURLString = "https://example.com/photos/"
let encodedIdentifier = identifier.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
let sizeQuery =... | magicoder | swift |
You are tasked with implementing a logging system that supports different log levels and log messages. The system should be able to handle a large number of log entries efficiently. Your task is to design and implement a logging class in C++ that meets these requirements.
Your logging class should have the following f... | ```cpp
#include <iostream>
#include <string>
#include <ctime>
class Logger {
public:
virtual void log(const std::string& level, const std::string& message) = 0;
};
class CLog4CXX : public Logger {
public:
void log(const std::string& level, const std::string& message) override {
std::time_t now = std::... | magicoder | cpp |
You are tasked with creating a TypeScript class that manages the window height and provides a method to check if the window height has changed beyond a certain threshold.
You need to implement a class `WindowHeightManager` with the following specifications:
- It should have a private property `_initWinHeight` of type ... | ```typescript
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/debounceTime';
class WindowHeightManager {
private _initWinHeight: number = 0;
minHeight: string;
constructor(minHeight: string) {
this.minHeight = minHeight;
this._initWinHeight... | magicoder | typescript |
You are given a code snippet that is part of a function to perform integer division without using the division or modulo operators. Your task is to complete the function by implementing the missing parts.
The function takes two integers, `dividend` and `divisor`, and is expected to return the result of the division. T... | ```python
def divide(dividend: int, divisor: int) -> int:
INT_MIN = -2**31
INT_MAX = 2**31 - 1
if dividend == 0:
return 0
if divisor == 1:
return min(max(INT_MIN, dividend), INT_MAX)
if divisor == -1:
return min(max(INT_MIN, -dividend), INT_MAX)
sign = (dividend < 0) ^ ... | magicoder | python |
You are tasked with implementing a class that manages a hierarchical data structure. The class should provide methods to set and retrieve the full name of an item in the hierarchy. The full name of an item is a concatenation of the names of all its ancestors, including itself, separated by a specified delimiter.
You a... | ```python
# Sample usage of the HierarchyManager class
si_model = ... # Initialize the si_model with the hierarchical data
manager = HierarchyManager(si_model)
# Set the delimiter to '/'
manager.setDelimiter('/')
# Retrieve the full name of the item at index ind
full_name = manager.getFullName(ind)
``` | magicoder | python |
You are tasked with implementing a simplified order book system for a trading platform. The order book maintains a list of buy and sell orders for a particular financial instrument, with each order containing an identifier, quantity, price, and type (buy or sell).
Your task is to implement the `OrderBook` class and th... | ```python
from enum import Enum
class MessageType(Enum):
MODIFY = 1
CANCEL = 2
# Add other message types as needed
class Message:
def __init__(self, id, type, side, qty_change, price):
self.id = id
self.type = type
self.qty_change = qty_change
self.price = price
... | magicoder | python |
You are tasked with implementing a queue using two stacks. A queue is a data structure that follows the First-In-First-Out (FIFO) principle, where elements are inserted at the back and removed from the front. A stack is a Last-In-First-Out (LIFO) data structure. The challenge is to implement a queue using two stacks an... | ```python
class QueueWithStacks:
def __init__(self):
self.stack1 = []
self.stack2 = []
def enqueue(self, value):
# Move all elements from stack1 to stack2
while self.stack1:
self.stack2.append(self.stack1.pop())
# Add the new element to stack1
self.st... | magicoder | python |
You are tasked with creating a program that processes HTML content to extract specific information. The program should retrieve a URL from a queue, make an HTTP request to the URL, and then extract and process certain data from the HTML content. Specifically, the program should remove unnecessary characters from the HT... | ```python
import requests
import re
from queue import Queue
from typing import List
def process_html_content(q: Queue, headers: dict, pattern: str) -> List[str]:
results = []
index = 0
while not q.empty():
try:
url = q.get(timeout=2)
index += 1
r = requests.get(u... | magicoder | python |
You are tasked with implementing a simplified version of the OpenGL function `nglDrawElementsInstancedARB` in Java. This function draws multiple instances of a set of elements. Your task is to create a Java method that mimics the behavior of this OpenGL function.
You are given the following signature for the method:
`... | ```java
public static void nglDrawElementsInstancedARB(int mode, int count, int type, long indices, int primcount) {
// Your implementation may vary based on the specific requirements, but here's a simplified example using LWJGL library for OpenGL bindings.
GL30.glDrawElementsInstanced(mode, count, type, indice... | magicoder | java |
You are tasked with implementing a Python class that reads a data file and constructs a list object containing hashes representing records in the file. Your task is to complete the implementation of the `Datafile` class by adding the necessary methods to achieve this functionality.
The `Datafile` class should inherit ... | ```python
class Datafile(Plugin, Sequence):
"""Template Toolkit Plugin which reads a datafile and constructs a
list object containing hashes representing records in the file.
"""
def __init__(self, context, filename, params=None):
Plugin.__init__(self)
Sequence.__init__(self)
sel... | magicoder | python |
You are given a function `calculate_impact_factors(s: str, impact_factor: dict) -> List[int]` that takes a string `s` and a dictionary `impact_factor` as input. The function is intended to calculate the impact factors of the characters in the string `s` based on the provided dictionary and return a list of the calculat... | ```python
from typing import List
def calculate_impact_factors(s: str, impact_factor: dict) -> List[int]:
answers = []
for p in range(len(s)):
if s[p] in impact_factor:
answers.append(impact_factor[s[p]])
else:
raise Exception('Unexpected error')
return answers
``` | magicoder | python |
You are tasked with implementing a custom data structure to store personal information. The structure should allow for the storage of standard personal details such as first name, middle name, last name, and suffix, as well as additional properties that are not predefined. You need to create a class that can handle the... | ```java
import org.apache.commons.lang3.builder.ToStringBuilder;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import java.util.HashMap;
import java.util.Map;
public class PersonalInformation {
private String firstName;
private String middleName;
private String lastName;
private String suffix;... | magicoder | java |
You are tasked with creating a custom content pipeline extension for a game development framework using MonoGame. The content pipeline extension will be responsible for importing and processing Aseprite files, a popular sprite creation tool, into the game project.
Your task is to implement a custom importer and proces... | To solve this problem, you can create a custom importer and processor by extending the `ContentImporter` and `ContentProcessor` classes provided by the MonoGame content pipeline. Below is a simplified example of how you can implement the custom importer and processor for Aseprite files:
```csharp
using Microsoft.Xna.F... | magicoder | csharp |
You are tasked with implementing a command verification system for a chatbot application. The system should validate commands based on a set of rules and permissions. Each command is represented as a list of strings, and the verification process involves checking the command against a configuration and user permissions... | ```python
class CommandTypes:
Allowed = 1
Denied = 2
Unknown = 3
def verify_command(command, config, user, command_type):
# Assume config is a dictionary mapping commands to their allowed users or denied users
if tuple(command) in config:
allowed_users = config[tuple(command)]['allowed']
... | magicoder | python |
You are tasked with creating a program that reads a given source code file and counts the occurrences of specific keywords within the comments section of the code. For the purpose of this problem, comments are defined as any text enclosed within `//` or `/* */` in the source code. The keywords to be counted are provide... | ```python
import re
def count_keyword_occurrences_in_comments(file_path, keywords):
keyword_counts = {keyword: 0 for keyword in keywords}
in_comment = False
with open(file_path, 'r') as file:
for line in file:
line = line.strip()
if line.startswith('//'):
for... | magicoder | python |
You are given a graph represented as an adjacency matrix `is_connected` and a starting node `start_node`. Your task is to implement a depth-first search (DFS) algorithm to traverse the graph and return the order in which the nodes are visited.
The graph is represented as a 2D boolean array `is_connected` of size n x n... | ```rust
fn dfs(is_connected: &Vec<Vec<bool>>, start_node: usize) -> Vec<usize> {
let n = is_connected.len();
let mut visited = vec![false; n];
let mut traversal_order = Vec::new();
fn dfs_recursive(is_connected: &Vec<Vec<bool>>, visited: &mut Vec<bool>, node: usize, traversal_order: &mut Vec<usize>) {
... | magicoder | rust |
You are tasked with creating a Python function that processes an XML file and writes its data into a CSV file. The function `request_to_csv` takes three parameters: `xml_file_name` (string) representing the name of the input XML file, `csv_file_name` (string) representing the name of the output CSV file, and `report` (... | ```python
import os
import xml.etree.ElementTree as ET
def request_to_csv(xml_file_name, csv_file_name, report='{http://www.caiso.com/soa/OASISReport_v1.xsd}'):
caiso_report = report
# Parse the xml file
tree = ET.parse(xml_file_name)
root = tree.getroot()
# Open the csv file for writing, appendi... | magicoder | python |
You are tasked with implementing a generic trait and a macro in Rust for managing side effects in a platform-agnostic manner. The provided code snippet contains a trait definition and a macro invocation related to this task.
Your goal is to create a trait `UseEffect` and a macro that allows the implementation of side ... | ```rust
pub trait Platform {
// Define platform-specific functionality here
}
pub struct Key {
// Define Key structure
}
pub struct EffectLink<P: Platform> {
platform: P,
// Define platform-specific data
}
pub trait UseEffect<P>
where
P: Platform + ?Sized,
{
fn use_effect<F>(&mut self, key: K... | magicoder | rust |
You are working on a program to analyze clusters of data. The program uses a data structure called `ClusterCounts` to store the counts of different cluster sizes and a data structure called `PValues` to store the p-values associated with the clusters. The code snippet provided initializes the `PValues` object and decla... | ```java
import java.util.List;
class ClusterCounts {
// Implementation of ClusterCounts data structure
}
class PValues {
// Implementation of PValues data structure
}
public class TSSCalculator {
public long calculateTSS(List<List<Double>> clusters, ClusterCounts clusterSizeCounts, PValues pvals) {
... | magicoder | java |
You are tasked with implementing a custom stacked learner for regression tasks. The stacked learner is a subclass of `StackedLearner` and is designed specifically for regression problems. It utilizes a default regression-specific aggregator called `RidgeRegressionLearner`. The stacked learner takes a list of base learn... | ```python
class StackedRegressionLearner(StackedLearner):
def __init__(self, learners, aggregate=RidgeRegressionLearner(), k=5, preprocessors=None):
super().__init__(learners, aggregate, k=k, preprocessors=preprocessors)
```
In the solution, we define the `StackedRegressionLearner` class as a subclass of `S... | magicoder | python |
You are tasked with implementing a custom `except` function in JavaScript. The `except` function should take two parameters: `ys` and `comparer`, and return a new array containing elements from the first parameter `xs` that are not present in the `ys` array, based on the comparison logic defined by the `comparer` funct... | ```javascript
// Implementation of the except function
function except(ys, comparer) {
return function(xs) {
return xs.filter(x => !ys.some(y => comparer(x, y)));
};
}
// Test case to verify the functionality of the except function
const ys = [3, 4, 5];
const xs = [1, 2, 3, 4, 5];
const comparer = (a, b) => a ... | magicoder | javascript |
You are tasked with implementing a function to process update requests for a file containing chunks of data. The function will take in the updated information, including an identifier, and update the file's contents accordingly. Additionally, the function will parse the updated file contents and store the chunks for fu... | ```cpp
#include <iostream>
#include <string>
struct FileInfo {
int id;
std::string name;
};
struct Parser {
// Assume the existence of a parseRmdSource method
std::string parseRmdSource(const std::string& contents) {
// Implementation of parseRmdSource method
return "Parsed chunks from... | magicoder | cpp |
You are tasked with designing a coordinator pattern for managing different modules in a mobile application. The coordinator pattern is a design pattern used in iOS development to separate navigation and flow control logic from view controllers. In this problem, you will need to create a coordinator for managing a stopw... | ```swift
// Define the StopwatchCoordinator protocol
protocol StopwatchCoordinator {
func start()
}
// Define the TimerCoordinator protocol
protocol TimerCoordinator {
func start()
}
// Implement the StopwatchCoordinator
class StopwatchCoordinatorImpl: StopwatchCoordinator {
let navigationController: UINa... | magicoder | swift |
You are tasked with implementing a function to handle errors in a video stitching application. The given code snippet is part of the error handling mechanism in the application. The `potSurf` object represents a potential surface, and the `ok()` method is used to check if the potential surface is valid. If it is not va... | ```cpp
#include <iostream>
#include <string>
namespace VideoStitch {
enum class Origin { Output };
enum class ErrType { SetupFailure };
class ControllerStatus {
public:
ControllerStatus() {}
ControllerStatus(std::initializer_list<std::string> args) {}
};
class VideoStitcherSignalSlots {
public:... | magicoder | cpp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.