query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with implementing a Python class for managing inventory items in a warehouse. The class should support adding new items, updating existing items, and retrieving information about items in the inventory. Each item in the inventory has a unique identifier, a name, a quantity, and a price. Your task is to ...
```python class WarehouseInventory: def __init__(self): self.inventory = {} def add_item(self, item_id, name, quantity, price): self.inventory[item_id] = {'name': name, 'quantity': quantity, 'price': price} def update_quantity(self, item_id, new_quantity): if item_id in self.invent...
magicoder
python
You are tasked with implementing a file explorer program that can navigate through a directory structure and display its contents. The program should support listing files and subdirectories within a given directory, as well as providing the ability to navigate into subdirectories and return to the parent directory. Y...
```python import os class FileExplorer: def __init__(self): self.current_directory = os.getcwd() def to_string(self): print(f"Contents of directory '{self.current_directory}':") for item in os.listdir(self.current_directory): print(item) def change_directory(self, dire...
magicoder
python
You are tasked with implementing a Swift extension for arrays that provides a safe way to access elements by index. The extension should include a method called `safe` that takes an index as a parameter and returns the element at that index if it exists, or `nil` if the index is out of bounds. Your task is to complete...
```swift extension Array { func safe(_ index: Int) -> Element? { guard index >= 0 && index < count else { return nil } return self[index] } } ``` The `safe` method is implemented as an extension to the `Array` type in Swift. It takes an index as a parameter and returns an optional element of th...
magicoder
swift
You are tasked with creating a web page that dynamically loads external JavaScript and CSS files based on user input. Your task is to implement a function that takes in a list of file URLs and appends corresponding `<script>` or `<link>` tags to the HTML `<head>` section. The function should also ensure that duplicate ...
```javascript function loadExternalFiles(fileURLs) { const head = document.getElementsByTagName('head')[0]; const existingScripts = Array.from(head.getElementsByTagName('script')).map(script => script.src); const existingLinks = Array.from(head.getElementsByTagName('link')).map(link => link.href); file...
magicoder
javascript
You are working on a graphics rendering engine and need to implement a method for creating render objects. The `create_render_object` function takes in various parameters and returns a `Box` containing a render object. Your task is to complete the implementation of this method by creating a new render object using the ...
```rust fn create_render_object( &self, vertices: VertexBuffer, indices: Vec<u32>, material_def: &MaterialDef, host_dynamic: bool, ) -> Box<dyn RenderObject> { let material = self.create_material(material_def); Box::new(RenderObject { vertices, indices, material, ...
magicoder
rust
You are given a Python code snippet that appears to be part of a larger program. The code snippet includes a series of print statements that display information about solutions and their associated costs and vertex covers (VC) in a graph. Your task is to create a programming problem based on this code snippet. Write a...
```python def isVC(edge_list, vertices): covered_edges = set() for edge in edge_list: if edge[0] not in vertices and edge[1] not in vertices: return False covered_edges.add(edge[0]) covered_edges.add(edge[1]) return len(covered_edges) == len(vertices) def find_minimum_ve...
magicoder
python
You are tasked with implementing a JSON view parser in Java. The parser should be able to parse a given JSON string and extract specific values based on a provided view. The view is a string that represents a path to the desired value within the JSON structure. The JSON string will be a valid JSON object containing key...
```java import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class JsonViewParser { public String parse(String json, String view) { try { ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode = mapper.readTree(json); ...
magicoder
java
You are tasked with creating a program to simulate an Intcode computer. The Intcode computer processes a sequence of integers and performs specific operations based on the opcode and parameter modes. The opcode is the rightmost two digits of the first value in an instruction, and the parameter modes are single digits, ...
```rust struct Intcode { program: Vec<i32>, ip: usize, } impl Intcode { fn from(program: Vec<i32>) -> Intcode { Intcode { program, ip: 0 } } fn parse_instruction(instruction: i32) -> (i32, [i32; 3]) { let opcode = instruction % 100; let mut modes = [0; 3]; let mut i...
magicoder
rust
You are tasked with implementing a Python class for a confusion matrix, which is a specific table layout that allows visualization of the performance of an algorithm. The confusion matrix class should be able to handle multi-class classification problems and provide methods for calculating various performance metrics. ...
```python class ConfusionMatrix: def __init__(self, actual_labels, predicted_labels): self.actual_labels = actual_labels self.predicted_labels = predicted_labels self.unique_labels = set(actual_labels + predicted_labels) def calculate_confusion_matrix(self): confusion_matrix = {...
magicoder
python
You are tasked with creating a program that processes a list of encountered macros and generates a source file containing the macro definitions. The macros are represented as a tuple containing the macro itself, its arguments, and raw arguments. Your task is to implement a function that takes this list of encountered m...
```swift func createMacrosSource(macrosToWrite: [(macro: Disassembler.MutableConfiguration.Macro, arguments: [Int: String], rawArguments: [Int: String])]) -> Source.FileDescription? { guard !macrosToWrite.isEmpty else { return nil } var sourceContent = "" for macroInfo in macrosToWrite { ...
magicoder
swift
You are given a set of SIMD (Single Instruction, Multiple Data) intrinsic functions from the Intel Intrinsics Guide. These intrinsics are used for performing operations on 256-bit vectors using Intel's Advanced Vector Extensions (AVX) instruction set. Your task is to implement a function that takes two 256-bit integer...
```c #include <immintrin.h> __m256i compareVectors(__m256i a, __m256i b) { __m256i greaterThanMask = _mm256_cmpgt_epi64(a, b); return greaterThanMask; } int main() { __m256i vectorA = _mm256_set_epi64x(10, 20, 30, 40); __m256i vectorB = _mm256_set_epi64x(25, 15, 35, 45); __m256i result = comp...
magicoder
c
You are tasked with implementing a RESTful API for a location-based service. The provided code snippet is a partial implementation of a Location class that extends a REST_Controller. Your task is to complete the implementation of the Location class by adding methods to handle various HTTP requests for location-related ...
```php class Location extends REST_Controller { function __construct($config = 'rest') { parent::__construct($config); } // Method to handle GET requests for retrieving location information function index_get() { // Retrieve and return location information // Implement appropri...
magicoder
php
You are tasked with implementing a generic trait for working with binary data in Rust. The trait, named `Word`, is intended to provide methods for loading and storing binary data from a buffer. The `load` method is responsible for reading binary data from a buffer and converting it into the appropriate data type, while...
```rust impl Word for u32 { fn load(buffer: &[u8], bit_order: config::BitOrder) -> Self { match bit_order { config::BitOrder::BigEndian => { ((buffer[0] as u32) << 24) | ((buffer[1] as u32) << 16) | ((buffer[2] as u32) << 8) ...
magicoder
rust
You are tasked with creating a program to manage the production readiness checklist for containerized applications. The checklist consists of various items, each with a name and a corresponding readiness status. Your program should allow users to add new checklist items, update the readiness status of existing items, a...
```python class ChecklistItem: def __init__(self, name, status): self.name = name self.status = status class ChecklistManager: def __init__(self): self.checklist = [] def add_item(self, name, status): item = ChecklistItem(name, status) self.checklist.append(item) ...
magicoder
python
You are tasked with implementing a command-line interface for running package tests. The given code snippet is a simplified representation of a Python class `TestCommand` that inherits from `BaseCommand`. The `TestCommand` class is intended to be used as a command-line interface for running tests for a package. It has ...
```python import argparse import unittest import sys class TestCommand(BaseCommand): """Runs the package tests.""" description = 'Runs all package tests.' user_options = [ ('junit=', None, 'outputs results to a results.xml file.') ] def run_tests(self, junit_output=None): ...
magicoder
python
You are tasked with creating a configuration file parser for a PHP application. The configuration file contains an array of storage drivers, each with specific settings. Your goal is to write a function that parses this configuration and returns an array of storage driver configurations. The configuration file format ...
```php function parseStorageConfig(string $filePath): array { $config = include $filePath; $parsedConfig = []; foreach ($config as $driver => $settings) { $parsedSettings = []; foreach ($settings as $key => $value) { if (strpos($value, 'env(') === 0) { $envVar = ...
magicoder
php
You are tasked with creating a script to manage dotfiles, which are configuration files for various programs and tools. Dotfiles are typically stored in a version-controlled directory and symlinked to the user's home directory. The provided code snippet is the beginning of a shell script for managing dotfiles. The scri...
```bash #!/bin/bash set -e DOTFILES_DIR=$(pwd -P) source helpers/_load # make sure to be able to execute those files chmodx "$DOTFILES_DIR/bin" load_sources setup/helpers COMMAND=$1 SUB_COMMAND=$2 case $COMMAND in link) # Implement logic to create symlinks for dotfiles in the user's home directory ...
magicoder
shell
You are tasked with creating a script to automate the process of generating a temporary authentication token for a relay gateway. The script should execute a specific command to create the token and then extract the token value from the command's output for later use. Your task is to write a Bash script that accomplish...
```bash #!/bin/bash # Define the command for creating the gateway token CREATE_GATEWAY_TOKEN_COMMAND="relay create-gateway ${PUBLIC_HOST}:${SDM_GATEWAY_LISTEN_APP_PORT} 0.0.0.0:${SDM_GATEWAY_LISTEN_APP_PORT}" # Print the command that will be executed echo "running: $CREATE_GATEWAY_TOKEN_COMMAND" # Execute the comman...
magicoder
shell
You are tasked with creating a Python program that processes command-line arguments using the `argparse` module. Your program should accept two optional arguments: `--input` and `--output`. The `--input` argument should specify the input file path, and the `--output` argument should specify the output file path. If the...
```python import argparse import sys def main(): # Define an argument parser using the argparse module parser = argparse.ArgumentParser(description='Process input and output files') # Add two optional arguments to the parser: --input and --output parser.add_argument('--input', help='Input file path') ...
magicoder
python
You are tasked with creating a program that reads a text file, removes any duplicate lines, and writes the unique lines back to the file. You should implement a function `remove_duplicates` that takes a file path as input and modifies the file in place. The function should read the content of the file, remove any dupl...
```python def remove_duplicates(file_path: str) -> None: with open(file_path, 'r') as file: lines = file.readlines() unique_lines = list(set(line.strip().lower() for line in lines)) with open(file_path, 'w') as file: file.write('\n'.join(unique_lines)) ```
magicoder
python
You are given a C++ code snippet that includes the beginning of a function called `sum_digits`. The function takes a parameter of type `BigInteger` and is expected to calculate the sum of the digits of the given `BigInteger` value. Your task is to complete the implementation of the `sum_digits` function and ensure that...
```cpp int sum_digits(BigInteger val){ int sum = 0; string valStr = val.toString(); // Assuming the BigInteger class has a method toString() to convert the value to a string for (char digit : valStr) { if (isdigit(digit)) { sum += digit - '0'; } } return sum; } ``` In th...
magicoder
cpp
You are tasked with creating a Rust function that listens to incoming TCP connections and processes the received messages. Your function should utilize the Tokio asynchronous runtime to handle the TCP connections and messages. Write a function `listen_and_process_tcp` that takes the following parameters: - `address: &...
```rust use tokio::net::{TcpListener, TcpStream}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use std::net::SocketAddr; pub async fn listen_and_process_tcp<F>( address: &str, mut message_handler: F, ) -> Result<(), Box<dyn std::error::Error>> where F: FnMut(AsyncReadMessage<TcpStream>), { let listene...
magicoder
rust
You are tasked with creating a Bash script that automates the process of setting ownership for a directory based on certain conditions. The script should take in two arguments: the directory path and the owner's username. The script should perform the following steps: 1. Check if the directory exists. If it does not ex...
```bash #!/bin/bash # Check if the number of arguments is correct if [ "$#" -ne 2 ]; then echo "Usage: $0 <directory_path> <owner_username>" exit 1 fi directory="$1" owner="$2" # Check if the directory exists if [ ! -d "$directory" ]; then echo "Error: Directory does not exist" exit 1 fi # Check if the owne...
magicoder
shell
You are tasked with creating a validation function for optional address parameters in a Node.js application. The function should check if a specific parameter exists in the request object and, if so, call another validation function to handle the address parameter. If the parameter does not exist, the function should a...
```typescript import { Request, Response, NextFunction } from 'express'; // Define the RaidenError type and ErrorCodes enum for completeness type RaidenError = { code: ErrorCodes; // other error properties }; enum ErrorCodes { DTA_NEGATIVE_NUMBER, // other error codes } export function validateOptionalAddres...
magicoder
typescript
You are tasked with creating a program to render 3D shapes using OpenGL. Your goal is to implement a function that generates a textured torus on the GPU and then renders it using a specified pipeline. You are given the following code snippet as a starting point: ```python glEnable(GL_DEPTH_TEST) # Creating s...
```python def createTexTorusNode1(pipeline, major_radius, minor_radius): # Generate the vertices and texture coordinates for the torus torus_vertices, torus_tex_coords = generateTorusVertices(major_radius, minor_radius) # Create a GPU shape for the torus torus_shape = createGPUShape(pipeline, torus_ver...
magicoder
python
You are tasked with creating a Python class for visualizing time series data using matplotlib. The class should be able to plot time series data and provide interactive features for exploring the data. Your task is to implement the `TimeSeriesViewer` class with the following requirements: 1. The class should inherit f...
```python class TimeSeriesViewer(FigureBase): """ A class for visualizing time series data using matplotlib. Attributes: title (str): Title of the time series plot. xlabel (str): Label for the x-axis. ylabel (str): Label for the y-axis. Methods: plot_time_series(time, d...
magicoder
python
You are tasked with creating a custom annotation in Java that can be used to annotate classes and specify a numeric data type. The annotation should allow the user to define the type of numeric data that the annotated class will work with. Your task is to implement the custom annotation `LinguisticPartition` and demons...
```java import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface LinguisticPartition { Class<? extends Number> value() default Double.class; } @LinguisticPartition(Double.class) class DataProcessor { public void processData(Number data) { System.ou...
magicoder
java
You are tasked with creating a program to validate credit card numbers based on the first digit and the Luhn algorithm. The Luhn algorithm is used to validate a variety of identification numbers, such as credit card numbers. The algorithm is as follows: 1. Starting from the rightmost digit, double every second digit. ...
```python def validate_credit_card(card_number): # Check if the first digit corresponds to a known card type first_digit = int(card_number[0]) if first_digit == 4: card_type = "Visa" elif first_digit == 5: card_type = "MasterCard" elif first_digit == 6: card_type = "Discover"...
magicoder
python
You are tasked with creating a validation function for a medical form that collects information about patients. The form includes various fields, each with specific validation requirements. Your task is to implement a function that takes in the form data and validates it based on the given rules. The form fields and t...
```php function validateFormData($formData, $validationRules) { $errors = []; foreach ($validationRules as $field => $rules) { $ruleList = explode('|', $rules); foreach ($ruleList as $rule) { if ($rule === 'required' && (empty($formData[$field]) || $formData[$field] === '')) { ...
magicoder
php
You are tasked with creating a Python function that retrieves files from a Telegram chat and calculates the total size of all the files combined. You are given a code snippet that iterates through the files in a chat and makes a request to the Telegram API to retrieve each file's information. Your task is to complete t...
```python import requests def calculate_total_file_size(users_files, chat_id): total_size = 0 for file_id in users_files[chat_id]: file_info = bot.get_file(file_id) response = requests.get( 'https://api.telegram.org/file/bot{0}/{1}'.format( API_TOKEN, file_info.file_...
magicoder
python
You are tasked with creating a Python function that analyzes the memory usage of a system and returns the total free memory in kilobytes. The function should also retrieve a list of currently logged-in users on the system. You are provided with a partial code snippet that includes a method for calculating free memory ...
```python import os class SystemAnalyzer: def getFreeMemory(self, memory_values): total_memory = sum(memory_values) free_memory_kb = total_memory / 1024 return int(free_memory_kb) def getUsers(self): users = '' try: cmdline = '/usr/bin/users | /usr/bin/tr " ...
magicoder
python
You are given a string `s` of length `n`. Your task is to write a function or method to find the length of the shortest substring that can be repeated to form the original string. If no such substring exists, return 0. For example, given the string "abcabcabc", the shortest repeating substring is "abc", and its length...
```java public int shortestRepeatingSubstringLength(String s) { int n = s.length(); for (int len = 1; len <= n / 2; len++) { if (n % len == 0) { String sub = s.substring(0, len); boolean valid = true; for (int i = len; i < n; i += len) { if (!sub.equal...
magicoder
java
You are tasked with implementing a custom iterator class in Python that iterates over a sequence of Fibonacci numbers. The iterator should return the next Fibonacci number in the sequence each time it is called. Additionally, the iterator should have a maximum iteration limit to prevent infinite iteration. Your task i...
```python class FibonacciIterator: def __init__(self, maxiters): self.maxiters = maxiters self.current_iter = 0 self.prev, self.curr = 0, 1 def __iter__(self): return self def __next__(self): if self.current_iter >= self.maxiters: raise StopIteration ...
magicoder
python
You are tasked with creating a Python function that validates a given dictionary against a set of predefined validation rules. The function should check if the dictionary adheres to the specified rules and return a boolean value indicating whether the validation was successful or not. The validation rules are defined ...
```python def validate_data(data, rules): for rule in rules: field_name = rule['name'] field_description = rule['description'] field_location = rule['in'] expected_type = rule['type'] if field_name in data and field_location in data: if not isinstance(data[field_...
magicoder
python
You are tasked with creating a Python class that represents a product in an inventory management system. The class should have attributes for the unit price and units of the product. Additionally, you need to implement a method that calculates the total price based on the quantity of units purchased. Create a Python c...
```python class Product: def __init__(self, unit_price, units): self.unit_price = unit_price self.units = units def calculate_total_price(self, quantity): try: quantity = float(quantity) if quantity < 0: raise ValueError("Quantity cannot be negati...
magicoder
python
You are tasked with creating a program to match users with nearby locations based on their geographical coordinates and search radius. Given a list of users with their email addresses and zip codes, along with a list of locations and their coordinates, the program should identify which users are near which locations wi...
```python import copy from haversine import haversine, Unit def zip_to_coors(zip_code): # Function to retrieve geographical coordinates from a zip code # Implementation not provided as it depends on external services or databases def match_users_to_locations(user_data, loc_data, tick_list): match_list = [...
magicoder
python
You are tasked with creating a Python program that simulates a simple task queue system using the `rq` library. The program should allow users to enqueue tasks, process them, and retrieve the results. Each task represents a simple computation, and the results should be stored for later retrieval. Your program should h...
```python from rq import Queue from redis import Redis # Connect to Redis server redis_conn = Redis() # Create a queue queue = Queue(connection=redis_conn) # Function to enqueue a task def enqueue_task(task_function, *args, **kwargs): job = queue.enqueue(task_function, *args, **kwargs) return job.id # Funct...
magicoder
python
You are tasked with creating a function that reads a CSV file containing job information and validates its format. The CSV file contains the following columns: ID, LAT, LNG, DEMAND, DURATION, TW_START, and TW_END. Each row represents a job with its corresponding attributes. The function should check for any format erro...
```rust use std::io::{BufRead, Error, ErrorKind}; use csv::Reader; use serde::Deserialize; #[derive(Debug, Deserialize)] struct Job { ID: String, LAT: f64, LNG: f64, DEMAND: u32, DURATION: u32, TW_START: Option<String>, TW_END: Option<String>, } fn read_csv_problem(jobs_reader: impl BufRea...
magicoder
rust
You are tasked with implementing a class hierarchy for a 2D game development framework. The framework includes a base class `GameObject` and a subclass `Prefab` that represents predefined settings for game objects. Your goal is to implement the `Prefab` class and its method `getPrefabSettings` to return the default set...
```typescript class GameObject { // Base class for game objects } class Prefab extends GameObject { protected getPrefabSettings(): PrefabSettings { return { x: 0, y: 0, rotation: 0, id: 'terrain', tag: 'terrain', layer: Layer.Terrain }; } } ``` In the solution, we defi...
magicoder
typescript
You are tasked with implementing a multi-threaded locking mechanism for a shared resource. The provided code snippet outlines the interface for the locking mechanism, which includes two functions `tryLockRead()` and `tryLockWrite()` for attempting to acquire read and write locks, and a function `lockStatus()` for check...
```cpp #include <mutex> #include <condition_variable> class MultiThreadedLock { private: std::mutex mtx; std::condition_variable cv; int numReaders; bool isWriter; public: MultiThreadedLock() : numReaders(0), isWriter(false) {} bool tryLockRead() { std::unique_lock<std::mutex> lock(mt...
magicoder
cpp
You are tasked with implementing a Python class that processes data requests for an Advanced Planning and Scheduling (APS) system. The APS system uses a custom protocol for communication, and the provided code snippet is a partial definition of a data request class. Your task is to complete the implementation of the `...
```python import attr import typing as t class ApsDataRequest(pt.Command): _lpad = pt.LPAD SCHEMA = ( t.uint16_t, # payload length # Add additional fields as per the specific requirements of the APS system ) def __init__(self, payload: bytes): self.payload = payload def ...
magicoder
python
You are tasked with implementing a custom PHP class that manipulates single-line strings. The class, `SingleLineString`, should provide methods for performing various operations on single-line strings, such as concatenation, trimming, and checking for specific substrings. Your task is to implement the following method...
```php declare(strict_types=1); namespace Coduo\PHPMatcher\Value; final class SingleLineString { private string $value; public function __construct(string $value) { $this->value = $value; } public function concatenate(string $string): string { return $this->value . $string; ...
magicoder
php
You are tasked with implementing a Rust module system for managing environments, statuses, templates, and workspaces. The provided code snippet outlines the module structure and the public exports for each module. Your goal is to create the necessary structs and traits to support the functionality of the module system....
```rust // Define the Environment struct pub struct Environment { name: String, description: String, // Add other relevant fields } // Define the Environments collection pub struct Environments { environments: Vec<Environment>, } impl Environments { // Method to add an environment to the collectio...
magicoder
rust
You are tasked with implementing a function to calculate the total number of occurrences of a given word in a collection of text files. The function should take in the directory path where the text files are located and the target word to search for. The function should recursively search through all text files in the ...
```cpp #include <iostream> #include <fstream> #include <string> #include <filesystem> #include <cctype> namespace mirrage::asset { int countWordOccurrences(const std::string& directory, const std::string& targetWord) { int totalOccurrences = 0; std::filesystem::path dirPath(directory); for...
magicoder
cpp
You are tasked with creating a program that simulates a simple compiler pass system. A compiler pass is a specific stage in the compilation process where the compiler performs a particular analysis or transformation on the code. In this problem, you will implement a simplified version of a compiler pass system using ob...
```java /** * Represents a compiler pass that is aware of the request. */ class RequestAwarePass implements CompilerPassInterface { private String author; /** * Constructs a RequestAwarePass with the specified author. * @param author the name and email of the author */ public RequestAwareP...
magicoder
java
You are tasked with creating a program to parse HTML content and extract specific information from it. In this problem, you will focus on extracting the URL and the displayed text from an anchor tag in an HTML snippet. Given an HTML snippet as a string, you need to write a function that extracts the URL and the displa...
```python from bs4 import BeautifulSoup def extractAnchorInfo(html): soup = BeautifulSoup(html, 'html.parser') anchor_tag = soup.find('a') if anchor_tag: return { "url": anchor_tag.get('href'), "text": anchor_tag.get_text() } else: return { "u...
magicoder
python
You are tasked with implementing a tab completion feature for a text editor. Tab completion is a common feature in many programming environments that suggests and completes partially typed words or commands when the user presses the "Tab" key. Your task is to create a function that takes in the current input, the curso...
```java import java.util.ArrayList; import java.util.List; public class TabCompletion { public List<String> addTabCompletionOptions(String input, int cursorPosition, List<String> completionOptions) { String partialInput = input.substring(0, cursorPosition); List<String> matchingCompletions = new Ar...
magicoder
java
You are tasked with implementing a Python class to represent the days of the week and a function to calculate the nth day from a given day. The code snippet provided contains a partial implementation of the Day class and the nthDayFrom function. Your task is to complete the implementation of the Day class and the nthDa...
```python class Day: def __init__(self, value): self.value = value def __add__(self, other): d = (self.value + other - 1) % 7 + 1 if d == 1: return Day(1) else: return Day(d) def nthDayFrom(n, day): return day + n ``` In the solution, the Day class i...
magicoder
python
You are tasked with implementing a lock management system using Python's asyncio library. Your goal is to create a class that can acquire and release locks to ensure exclusive access to a shared resource. The provided code snippet outlines the beginning of a `LockOps` class, which is a subclass of `CoordinatorOp`. Your...
```python import asyncio class LockOps(CoordinatorOp): def __init__(self, *, c: Coordinator, op_id: int, stats: StatsClient, locker: str, ttl: int = 60): super().__init__(c=c, op_id=op_id, stats=stats) self.locker = locker self.ttl = ttl self.lock_acquired = False async def loc...
magicoder
python
You are working on a project that involves processing and analyzing textual data. As part of this project, you need to implement a custom text vectorization function that maps textual data to numerical vectors. The vectorization process involves creating a mapping between item IDs and subject IDs, and then using a vect...
```python from typing import List, Dict, Optional, Union from sklearn.feature_extraction.text import CountVectorizer def custom_vectorization(item_ids: List[str], ix_to_item_id: Dict[int, str], subject_ids: List[str], subject_id_to_ix: Dict[str, int], ix_to_subject_id: Dict[int, str], amortized: bool, vectorizer: Opti...
magicoder
python
You are tasked with implementing a singleton pattern for a class called `CodeObjectManager`. The provided code snippet outlines a part of the implementation for this class. The `CodeObjectManager` class is responsible for managing code objects and providing access to them. The class has the following methods: 1. `Inst...
```python class CodeObjectManager: _instance = None def __init__(self, directory, codeObjectVersion): self.directory = directory self.codeObjectVersion = codeObjectVersion self.codeObjects = {} # Assuming this dictionary holds the code objects @classmethod def Instance(cls): ...
magicoder
python
You are tasked with implementing a function that emulates the behavior of the `groupby` and `size` functions in Python. The `groupby` function is used to group data based on specified columns, and the `size` function is used to count the occurrences of each group. Your task is to create a function that takes a DataFram...
```python import pandas as pd from typing import List def custom_groupby_size(data: pd.DataFrame, group_cols: List[str], count_cols: List[str]) -> pd.DataFrame: grouped = data.groupby(group_cols) if count_cols: result = grouped[count_cols].size().reset_index(name='count') else: result = gro...
magicoder
python
You are tasked with implementing a graph data structure in Python to represent a network of interconnected nodes. Each node in the graph has a unique identifier and may be connected to other nodes through edges. The graph is represented using an adjacency list. Your task is to implement a Python class `Graph` with the...
```python class Graph: def __init__(self): self.adjacency_list = {} def add_node(self, node_id): if node_id not in self.adjacency_list: self.adjacency_list[node_id] = [] def add_edge(self, node_id1, node_id2, weight): if node_id1 in self.adjacency_list: self...
magicoder
python
You are given a scenario where ladybugs are placed on a line. Each ladybug is initially represented by a number, where 0 indicates an empty position and 1 indicates the presence of a ladybug. The ladybugs are currently arranged in an array called `ladybugs`. Your task is to implement a function that rearranges the lady...
```python from typing import List def rearrangeLadybugs(ladybugs: List[int]) -> List[int]: for ladybugIndex in range(len(ladybugs)): if ladybugs[ladybugIndex] == 1: # Check if the current position has a ladybug continue # Skip if the current position already has a ladybug in its correct posit...
magicoder
python
You are tasked with implementing a command-line tool for analyzing electronic band structures in a material simulation. The tool will parse user-provided arguments to customize the analysis. Your task is to implement the logic for parsing the command-line arguments and performing the specified actions based on the prov...
```python import argparse def analyze_band_structure(): parser = argparse.ArgumentParser(description='Band structure analysis tool') parser.add_argument('-o', '--orbitals', help='orbital indices for band projection (default: sum over all orbitals)', nargs='+', type=int) parser.add_argument('-e', '--efermi'...
magicoder
python
You are working on a web application that uses the Django framework for its backend. The application has a URL configuration file where different URL patterns are mapped to corresponding views. The code snippet provided is a part of the URL configuration file. Your task is to create a function that takes a URL pattern...
```python import re def get_view_function(url_pattern, url_patterns): for pattern, view_function in url_patterns: if re.match(pattern, url_pattern): return view_function return None ``` The `get_view_function` function iterates through the `url_patterns` list and uses the `re.match()` func...
magicoder
python
You are tasked with implementing a Swift protocol for managing transactions of consumable products in an e-commerce application. The protocol should include two properties: `transactionIdentifier` and `quantity`. The `transactionIdentifier` property should be a string representing the unique identifier for the transact...
```swift // ConsumableTransaction protocol protocol ConsumableTransaction { var transactionIdentifier: String { get } var quantity: Int { get } } // Sample implementation conforming to ConsumableTransaction protocol struct ProductTransaction: ConsumableTransaction { let transactionIdentifier: String le...
magicoder
swift
You are tasked with implementing a simple stack data structure in Swift. A stack is a last-in, first-out (LIFO) data structure that supports two main operations: push, which adds an element to the top of the stack, and pop, which removes the top element from the stack. Your task is to create a Swift class called `Stack...
```swift import UIKit class Stack<T> { private var elements: [T] = [] func push(_ element: T) { elements.append(element) } func pop() -> T? { return elements.popLast() } func isEmpty() -> Bool { return elements.isEmpty } func peek() -> T? { return ele...
magicoder
swift
You are given a code snippet that manipulates a 3D array `function_array` using NumPy operations. The array represents a mathematical function and is indexed by `n` and `m`. The code snippet performs operations to update the values of `function_array` based on certain mathematical calculations involving `n`, `m`, and `...
```python import numpy as np def update_function_array(function_array, nmax, theta): index = np.arange(nmax + 1) function_array[:, index[2:], index[1:-1]] = np.sqrt(2 * index[2:] + 1) * np.cos(theta[:, np.newaxis]) * \ function_array[:, index[1:-1], index[1:-1]] ...
magicoder
python
You are tasked with creating a program that simulates a simple online shopping system. The program should allow users to add items to their cart, view the items in their cart, and calculate the total cost of the items in the cart. The program should also handle the connection to the database where the items are stored....
```php class ShoppingCart { private $conn; private $cartItems; // Constructor to establish database connection public function __construct($servername, $username, $password, $dbname) { $this->conn = new mysqli($servername, $username, $password, $dbname); if ($this->conn->connect_error) ...
magicoder
php
You are tasked with implementing a Python interface for managing and measuring data streams using gRPC (Google Remote Procedure Call) in a hypothetical system for evaluating network performance. The provided code snippet outlines the abstract methods and type hints for the interface, but it lacks the actual implementat...
```python import abc import typing import grpclib.const import umbra_pb2 # Assume the protobuf definitions are available class NetworkManager(abc.ABC): @abc.abstractmethod async def Manage(self, stream: 'grpclib.server.Stream[umbra_pb2.Config, umbra_pb2.Report]') -> None: # Implement the Manage method...
magicoder
python
You are tasked with creating a Python function that processes a list of organizations and their associated users. The function should perform the following tasks: 1. Filter out organizations that are associated with a specific registrar. 2. For each remaining organization, count the number of users associated with it. ...
```python def count_users_per_organization(registrar_name, organizations): """ Count the number of users associated with each organization, excluding those associated with a specific registrar. Args: registrar_name (str): The name of the registrar to exclude. organizations (list): A list of diction...
magicoder
python
You are tasked with implementing a text classification model using TensorFlow and Keras. The goal is to create a program that preprocesses a dataset of text documents, trains a neural network model, and evaluates its performance. You are provided with a partial implementation of a Catalog class that will be used to ma...
```python import csv from typing import List, Optional from tensorflow import keras from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow.keras.layers import Embedding, Bidirectional, LSTM, Dense from tensorflow.keras.models import S...
magicoder
python
You are tasked with creating a simple game using the Pygame library in Python. The game involves a player-controlled character that moves across the screen, and the player must avoid obstacles to score points. The player's score increases as they successfully navigate through the obstacles. To make the game challenging...
```python # Complete the game by adding the following code to draw game elements and handle player input # Draw player and obstacle player_rect = pygame.Rect(player_x, player_y, 20, 20) obstacle_rect = pygame.Rect(obstacle_x, obstacle_y, 30, 30) pygame.draw.rect(screen, (255, 0, 0), player_rect) pygame.draw.rect(scree...
magicoder
python
You are tasked with implementing a theme manager for a desktop application. The theme manager is responsible for setting the color scheme and icon for various UI elements based on whether the current theme is light or dark. You are given a partial code snippet from the theme manager implementation, which includes the i...
```csharp void IThemeSetter.SetTheme(bool isLight) { if (isLight) { // LIGHT iconBrush.Drawing = Application.Current.FindResource("MiningAxeIcon") as Drawing; border.Background = new SolidColorBrush((Color)Application.Current.Resources["Colors.Light.Grey.Grey3"]); } else { ...
magicoder
csharp
You are tasked with creating a function to process a tile map for a 2D game. The tile map is represented by layers, and each layer contains tiles with unique global IDs (GIDs). Your goal is to implement a function that retrieves the tiles with a specific global ID from a given layer and then performs a validation check...
```swift // Define the Tile and TileLayer classes class Tile { let globalID: Int // Other properties and methods as needed } class TileLayer { let name: String var tiles: [Tile] // Other properties and methods as needed } // Implement the getTiles function func getTiles(layer: TileLayer, globalID:...
magicoder
swift
You are tasked with implementing a simple rendering system for a user interface library. The library uses a declarative syntax to define the UI structure and components. Your goal is to create a function that can parse the given declarative syntax and render the UI accordingly. You are provided with a code snippet tha...
```rust use std::collections::HashMap; struct Component { component_type: String, attributes: HashMap<String, String>, children: Vec<Component>, } enum RenderError { // Define possible rendering errors here } fn render_ui(ui_structure: Component) -> Result<(), RenderError> { // Implement the rend...
magicoder
rust
You are tasked with implementing a delegate pattern in Swift to handle user selection in a multi-user selection view. The code snippet provided is a method within a Swift class that is responsible for notifying the delegate when the user submits their selection. The `didSubmit` method is called when the user submits th...
```swift class UserSelectionViewController: UserSelectionDelegate { var selected: [User] = [] weak var delegate: UserSelectionDelegate? // Method to handle user selection func selectUser(_ user: User) { selected.append(user) } // Method to handle user submission @objc private func ...
magicoder
swift
You are tasked with creating a Python script that monitors the system's performance and stores the data in a database. The script should utilize multiprocessing to concurrently collect system information and store it in a database. The system information to be collected includes CPU usage, memory usage, disk usage, and...
```python import yaml import json import os import platform import time from multiprocessing import Process import database class SystemMonitor: def collect_system_info(self): # Implement system information collection here # Example: Using psutil library to collect CPU, memory, disk, and network st...
magicoder
python
You are given a partially completed Swift code snippet that defines a generic function. Your task is to complete the function and write a test case to verify its functionality. Complete the function `s` which takes a generic type `D` that conforms to protocol `A` and returns a tuple containing two elements. The first ...
```swift protocol A { var condition: Bool { get } } // Complete the function func s<D: A>(_ input: D) -> (D, Bool) { return (input, input.condition) } // Test case struct TestStruct: A { var condition: Bool } let testInstance = TestStruct(condition: true) let result = s(testInstance) print(result) // Out...
magicoder
swift
You are tasked with implementing a Python class that counts the occurrences of a given pattern in a biomodel. The biomodel is represented using the SBML (Systems Biology Markup Language) format, and the pattern is a specific combination of biomodel elements. Your task is to complete the implementation of the `Biomodel...
```python from sbml_shim import SBMLShim import sys import os.path from typing import List class BiomodelIterator: def __init__(self, sbml_file_path: str): self.sbml_file_path = sbml_file_path self.sbml_shim = SBMLShim(sbml_file_path) self.pattern = [] def set_pattern(self, pattern: Li...
magicoder
python
You are given a code snippet that appears to be part of a program to find the maximum value of a specific function. Your task is to complete the program by implementing the missing parts and then using it to find the maximum value of the function over a given range of values for variable 'a'. The function to be maximi...
```python def is_prime(n): if n < 2: return False for i in range(2, int(n ** 0.5) + 1): if n % i == 0: return False return True def prime_sequence_length(a, b): n = 0 while True: num = n ** 2 + a * n + b if not is_prime(num): return n ...
magicoder
python
You are tasked with creating a PHP class method that handles the deletion of records from a database table. The given code snippet shows a method named `excluir` within a class. This method takes an `$id` parameter and uses it to delete a record from the `categorias` table in the database. Your task is to complete the ...
```php class CategoryManager { private $db; public function __construct($db) { $this->db = $db; } public function excluir($id) { $this->db->where('id', $id); return $this->db->delete('categorias'); } } // Usage: // Assuming $db is the database connection object $categoryMa...
magicoder
php
You are tasked with creating a Rust macro that generates a wrapper struct for a given input struct. The wrapper struct should implement a specific trait for the input struct. Your task is to complete the macro implementation to achieve this functionality. You are provided with the following code snippet as a starting ...
```rust use proc_macro2::TokenStream as TokenStream2; use quote::quote; use syn::{parse::Result, parse_quote, DeriveInput}; #[proc_macro] pub fn impl_wrapper(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); let struct_name = &input.ident; let fields = if let syn::D...
magicoder
rust
You are tasked with implementing an image processing function that performs upsampling on a given image using TensorFlow. The function should take an input image and increase its dimensions by duplicating the pixel values to create a larger image. You are provided with a code snippet that contains a static method `upS...
```python import tensorflow as tf class ImageProcessor: @staticmethod def upSample(image): _, rows, cols, channels = image.get_shape().as_list() # Extract dimensions of the input image image = tf.reshape(image, [-1, rows, cols, 1, channels]) # Reshape the image to add a new dimension ...
magicoder
python
You are tasked with implementing a dynamic array data structure in TypeScript. The dynamic array should be able to grow in size as elements are added to it. You are provided with a `growable_array_buffer.ts` module that contains the necessary functionality for managing the underlying buffer of the dynamic array. Your t...
```typescript // Import the functionality from the growable_array_buffer.ts module import { GrowableArrayBuffer } from "../util/growable_array_buffer.ts"; class DynamicArray<T> { private buffer: GrowableArrayBuffer<T>; private length: number; constructor(initialCapacity: number) { this.buffer = new Growable...
magicoder
typescript
You are given an array of integers representing the weights of ropes and an integer `n`. The goal is to find the maximum possible weight that can be achieved by connecting the ropes in a specific way. The weight of each rope is multiplied by `n`, where `n` starts from 1 and increments by 1 for each subsequent rope. Aft...
```cpp #include <iostream> #include <algorithm> int maxWeightAfterConnectingRopes(int weight[], int rope, int n) { std::sort(weight, weight + rope); // Sort the array of rope weights int result[rope]; // Array to store the results after multiplying weights by n for (int j = rope - 1; j >= 0; j--) { ...
magicoder
cpp
You are tasked with implementing a Python class for a multilabel classifier. The class should include a method for training the classifier and a method for making predictions. Additionally, you need to implement a class for the multilabels head, which will be used as part of the classifier. Your task is to complete th...
```python class MultilabelsHead: def __init__(self): # Initialize the list of labels self.labels = [] def add_label(self, label): # Add the label to the list of labels self.labels.append(label) class Classifier: def __init__(self): # Initialize the list of labels a...
magicoder
python
You are tasked with implementing a class that manages a bulk processing system for a database. The class should handle the configuration of the database connection and the bulk processing of data. You are provided with a code snippet that contains some configuration settings and constants related to the database conne...
```cpp #include <string> #include <vector> #include <sqlite3.h> enum class Index { No, Yes, Unique } _seq_index = Index::Unique; enum class Journal { Default, Wal } _journal = Journal::Wal; class DatabaseBulkProcessor { private: sqlite3* _db; size_t _bulk_size = 0; size_t _bulk_counter = 0; public: D...
magicoder
cpp
You are tasked with implementing a contact merging algorithm to consolidate duplicate contacts in a contact list. Each contact is represented as a list of strings, where each string represents a piece of contact information (e.g., name, phone number, email). The algorithm should merge contacts that share at least one p...
```python def merge_contacts(): def dfs(node, i, temp, visited, graph): if visited[i]: return visited[i] = True temp.append(node[i]) for neighbor in graph[i]: dfs(node, neighbor, temp, visited, graph) def build_graph(contacts): graph = {} ...
magicoder
python
You are given a binary tree and a function that performs a level-order traversal of the tree and returns a list of the traversed nodes. The code snippet provided is a part of the level-order traversal function. The function uses a queue to traverse the tree level by level and appends the traversed nodes to a list calle...
```python from collections import deque class TreeNode: def __init__(self, value=0, left=None, right=None): self.data = value self.left = left self.right = right def level_order_traversal(root, write): """ Perform level-order traversal of the binary tree and return the list of trav...
magicoder
python
You are working on a script to automate the configuration of a system's hosts file. The hosts file is a plain text file used by operating systems to map IP addresses to hostnames. Your script needs to add entries to the hosts file in a specific format. The code snippet provided is a part of the script and is responsibl...
```bash HOSTS_COMMENT="Custom comment for host" FIRST_LOCAL_IP="192.168.1.100" echo >> /etc/hosts echo "# $HOSTS_COMMENT" >> /etc/hosts echo "$FIRST_LOCAL_IP master" >> /etc/hosts ``` In the solution, we define the variables `HOSTS_COMMENT` and `FIRST_LOCAL_IP` with the desired values. Then, we use the `echo` command ...
magicoder
shell
You are tasked with implementing a C++ template meta-programming problem. Your goal is to create a meta-function called `tuple_template_forward_t` that takes a template template parameter and a tuple type as its arguments and returns a new tuple type with the same element types as the input tuple type, but wrapped in t...
```cpp #include <tuple> template <template <typename...> class T, typename Tuple> struct tuple_template_forward_t; template <template <typename...> class T, typename... Args> struct tuple_template_forward_t<T, std::tuple<Args...>> { using type = T<Args...>; }; // Test the implementation static_assert(std::is_sam...
magicoder
cpp
You are tasked with creating a command-line utility that simulates a simple file system navigation and execution of Java programs. The utility should support changing directories and executing Java programs within the specified directory. Your task is to implement a program that takes a series of commands as input and...
```java import java.util.*; class FileSystem { private String currentDirectory; public FileSystem() { this.currentDirectory = "root"; } public void changeDirectory(String newDirectory) { // Implement logic to change the current directory // This can involve checking if the new...
magicoder
java
You are tasked with implementing a Java class that manages the configuration for saving authentication results in a web application. The class should handle the storage of authentication results and provide methods for retrieving and manipulating the saved data. Your task is to create a class named `AuthenticationResu...
```java package com.stormpath.sdk.servlet.filter.account.config; import com.stormpath.sdk.authc.AuthenticationResult; import com.stormpath.sdk.lang.Assert; import com.stormpath.sdk.servlet.config.Config; import com.stormpath.sdk.servlet.filter.account.AuthenticationResultSaver; import com.stormpath.sdk.servlet.http.Sa...
magicoder
java
You are tasked with implementing the insertion sort algorithm for sorting a list of integers in non-decreasing order. Insertion sort works by iteratively building a sorted portion of the list, one element at a time, by shifting larger elements to the right. Your task is to complete the implementation of the `insertion_...
```python def insertion_sort(array: list[int]): for i in range(1, len(array)): key = array[i] j = i - 1 while j >= 0 and key < array[j]: array[j + 1] = array[j] j -= 1 array[j + 1] = key ``` The provided solution completes the implementation of the `insertion_...
magicoder
python
You are tasked with implementing a Python function that calculates the gradient of a given function with respect to its input parameters using the finite difference method. The finite difference method is a numerical technique for estimating the derivative of a function at a particular point by evaluating the function ...
```python import numpy as np def finite_difference_gradient(f, x, h): n_params, n_train = x.shape grad = np.zeros((n_params, n_train)) for i in range(n_params): x_plus_h = x.copy() x_plus_h[i] += h x_minus_h = x.copy() x_minus_h[i] -= h grad[i] = (f(x_plus_h) - f(x_...
magicoder
python
You are tasked with implementing a StateManager class that manages multiple StateMachine instances. Each StateMachine represents a state machine with a specific name and a set of possible states. The StateManager should allow adding StateMachine instances and provide methods to transition the states of the machines. Y...
```python class StateMachine: def __init__(self, name, states, initial_state): self.name = name self.states = states self.current_state = initial_state def transition(self, new_state): if new_state in self.states: self.current_state = new_state else: ...
magicoder
python
You are given an array of positive integers. Your task is to write a function `ArrayAdditionI` that will determine whether any combination of the numbers in the array can be added together to produce the largest number in the array. The function should return `true` if such a combination exists, and `false` otherwise. ...
```python def ArrayAdditionI(arr): max_num = max(arr) # Find the largest number in the array arr.remove(max_num) # Remove the largest number from the array # Check if the sum of any combination of the remaining numbers equals the largest number def is_sum_combination(target, numbers): if targ...
magicoder
python
You are tasked with implementing a custom macro in Rust that mimics the behavior of the `hset!` macro shown in the code snippet. The `hset!` macro is designed to create a `HashSet` with literal values that are automatically converted into the appropriate type. Your task is to create a similar macro called `my_hset!` th...
```rust /// The `my_hset!` macro creates a HashSet with literal values automatically converted into the appropriate type. /// /// # Arguments /// /// * `($($value:expr),*)`: A list of literal values separated by commas. /// /// # Example /// /// ```rust /// # use std::collections::HashSet; /// macro_rules! my_hset ...
magicoder
rust
You are tasked with implementing a function that processes styles and functions to generate CSS for a React component. The function takes in styles, an array of functions, and a theme object. The styles can be an array of strings, a function, or a string. The functions in the array can take the props and theme as argum...
```javascript function generateCSS(styles, fns, theme) { const applyFunctions = (str, fns, props, theme) => { return fns.reduce((result, fn, i) => { const value = typeof fn === 'function' ? fn({ props, theme }) : ''; return result + str[i] + value; }, ''); }; if (Array.isArray(styles)) { ...
magicoder
javascript
You are tasked with creating a command-line utility that simulates a simple fishing game. The game will take a list of fish species and their corresponding probabilities as input, and then simulate the act of fishing for a certain number of times. The output should display the number of times each fish species was caug...
```python import random def simulate_fishing(species, probabilities, num_simulations): catches = {s: 0 for s in species} for _ in range(num_simulations): rand_num = random.random() cumulative_prob = 0 for i, prob in enumerate(probabilities): cumulative_prob += prob ...
magicoder
python
You are tasked with creating a custom hook in a Yew-based web application. Yew is a modern Rust framework for creating multi-threaded front-end web apps with WebAssembly. In this problem, you will be implementing a custom hook called `use_is_mounted` that returns a boolean value indicating whether the component is curr...
```rust use yew::prelude::*; use yew_hooks::prelude::*; fn use_is_mounted() -> bool { let is_mounted = use_state(|| false); use_effect({ let is_mounted = is_mounted.clone(); move || { move || { is_mounted.set(true); || is_mounted.set(false) ...
magicoder
rust
You are given a task to write a function to determine whether a given integer is a power of three. Write a Python function called `is_power_of_three` that takes an integer `n` as input and returns `True` if `n` is a power of three, and `False` otherwise. For example, if the input is `27`, the function should return `...
```python class Solution: def isPowerOfThree(self, n: int) -> bool: if n <= 0: return False while n % 3 == 0: n /= 3 return n == 1 ``` The `isPowerOfThree` function checks if the input integer `n` is a power of three. It first checks if `n` is less than or equal to 0...
magicoder
python
You are tasked with implementing a class for a table editor in Python. The class contains three methods: `cancelEdits`, `canEditColumn_atRow_`, and `deleteSelectedRows`. The `cancelEdits` method is responsible for canceling any ongoing edits in the table. The `canEditColumn_atRow_` method takes a column and row as inpu...
```python class TableEditor: def __init__(self, py): self.py = py def cancelEdits(self): self.py.cancel_edits() def canEditColumn_atRow_(self, column, row): return self.py.can_edit_cell(column, row) def deleteSelectedRows(self): # Implementation for deleting selected r...
magicoder
python
You are tasked with creating a function that extracts and counts the occurrences of specific HTML tags within a given HTML string. The HTML string will contain various tags, and the function should return a dictionary where the keys are the tag names and the values are the counts of each tag in the string. For example...
```python from bs4 import BeautifulSoup def count_html_tags(html_string): soup = BeautifulSoup(html_string, 'html.parser') tags = [tag.name for tag in soup.find_all()] tag_counts = {tag: tags.count(tag) for tag in set(tags)} return tag_counts ``` The `count_html_tags` function uses the BeautifulSoup l...
magicoder
python
You are tasked with implementing a function to calculate the word count of each news article in a dataset using parallel processing. The dataset is initially loaded from disk, and then a word count column is added to each article. The dataset is processed in batches using multiple processes to improve efficiency. Your...
```python from datasets import load_from_disk from pathlib import Path import multiprocessing def word_count(batch): import nltk nltk.download('punkt') from nltk.tokenize import word_tokenize def count_words(text): tokens = word_tokenize(text) return len(tokens) batch["n_tokens"] ...
magicoder
python
You are tasked with creating a Python function that generates a configuration file for a machine learning model. The function should take in several input parameters and construct a configuration file with the appropriate paths and settings. The configuration file will be used to store paths for model output, model dir...
```python def generate_fast_text_config(path_top, path_root): config_content = '''# fast_text config path_out = {} + "/out/" # 模型目录 path_model_dir = {} + "/data/model/fast_text/" # 语料地址 path_model = {} + '/data/model/fast_text/model_fast_text.h5' # 超参数保存地址'''.format(path_top, path_root, path_root) config_fil...
magicoder
python
You are tasked with implementing a custom error renderer for a 3D graphics engine. The provided code snippet is the beginning of the header file for the `GLErrorRenderer` class, which is a subclass of `DefaultRenderer`. Your task is to complete the implementation of the `GLErrorRenderer` class by adding member function...
```cpp class GLErrorRenderer : public DefaultRenderer { private: // Add any necessary member variables here public: GLErrorRenderer(/* Add any necessary parameters for the constructor */) { // Implement constructor as needed } void initialize(const G3MContext* context) override { // Im...
magicoder
cpp
You are tasked with implementing a health check system for a distributed system. The system consists of multiple daemons running on different machines, and it is essential to periodically check the health of these daemons to ensure the overall system's reliability. Each daemon sends a heartbeat signal at regular interv...
```python def all_daemons_healthy(instance, heartbeat_tolerance_seconds): # Assume `instance` has a method to retrieve the status of all daemons daemons_status = instance.get_daemons_status() for daemon_status in daemons_status: last_heartbeat_time = daemon_status.get_last_heartbeat_time() ...
magicoder
python