query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with creating a script to automate the testing of multiple bash scripts within a directory. The script should iterate through each bash script in the directory, run it, and display the name of the test being run along with the directory it's being executed in. Your script should take the following form:...
```bash #!/bin/bash # Iterate through each file in the directory for file in *.sh; do # Extract the name of the file name=$(basename $file) # Get the directory of the file dir=$(dirname $file) # Display the test name and directory echo -n "Running test '$name' in $dir..." # Change to the directory and ex...
magicoder
shell
You are tasked with implementing a multi-dimensional array manipulation program using the Boost C++ library. The program should utilize the `boost::mpi3` and `boost::multi` namespaces for parallel processing and multi-dimensional array operations, respectively. Your task is to create a C++ program that initializes a m...
```cpp #include <iostream> #include <boost/mpi.hpp> #include <boost/mpi/collectives.hpp> #include <boost/multi_array.hpp> namespace mpi = boost::mpi; int main(int argc, char* argv[]) { mpi::environment env(argc, argv); mpi::communicator world; using array_type = boost::multi_array<double, 2>; array_t...
magicoder
cpp
You are tasked with implementing a function to compute the "firstX" set for a given non-terminal symbol in a context-free grammar. The "firstX" set for a non-terminal symbol X is defined as the set of terminal symbols that appear as the first symbol in some string derivable from X. The grammar is enriched with addition...
```python def computeFirstXForNonTerminal(nonterminal, firstXTable, enrichedGrammar): if nonterminal in firstXTable: return productions = enrichedGrammar['productions'][nonterminal] firstX = set() for production in productions: if len(production) == 0: raise Exception('Nonterminal "' + str(nonte...
magicoder
python
You are tasked with implementing a custom database connection for a PHP application using the Yii framework. The provided code snippet is a partial implementation of a `MessageTemplate` class within the `common\models\school` namespace. Your goal is to complete the implementation by defining the custom database connect...
```php namespace common\models\school; use yii\db\Connection; class MessageTemplate extends ActiveRecord { public static function getDb() { return new Connection([ 'dsn' => 'mysql:host=localhost;dbname=school_db', 'username' => 'username', 'password' => 'password', ...
magicoder
php
You are tasked with creating a script to automate the compilation and generation of WebAssembly (WASM) and ABI files for a smart contract in the EOSIO blockchain platform. The script should handle the compilation of a C++ source file into WASM and the generation of the corresponding ABI file using the `eosiocpp` tool. ...
```bash #!/bin/bash # Step 1: Remove existing wast and wasm files rm pradata.wast pradata.wasm # Step 2: Compile pradata.cpp into pradata.wast eosiocpp -o pradata.wast pradata.cpp # Check if compilation was successful if [ $? -ne 0 ]; then echo "Error: Compilation of pradata.cpp failed" exit 1 fi # Step 3: Remo...
magicoder
shell
You are tasked with implementing a simplified version of a promise-based asynchronous programming pattern in Swift. Your goal is to create a function that chains multiple asynchronous network requests using promises. You are provided with a `Promise` class that represents a promise-based asynchronous operation. The `...
```swift func chainRequests(_ urls: [URL]) -> Promise<Void> { var promiseChain = Promise<Void>.resolved(()) for url in urls { promiseChain = promiseChain.then { _ in return URLSession.GET(url) } } return promiseChain } ``` In the solution, the `chainRequests` funct...
magicoder
swift
You are tasked with implementing a Python class that represents medication information. The class should be capable of serializing and deserializing instances to and from JSON format. Additionally, you need to create a method for retrieving the default directory for storing medication files. Your task is to complete t...
```python from dataclasses import dataclass, field from typing import Any import json def json_serializable(cls): cls.to_json = lambda self: json.dumps(self.__dict__) return cls class JSONSerializable: def to_json(self): raise NotImplementedError @json_serializable @dataclass class Med(JSONSer...
magicoder
python
You are tasked with creating a program that simulates a simple banking system. The program should allow users to create accounts, deposit money, withdraw money, and check their balance. Each account should have a unique account number, and the program should be able to handle multiple accounts. Your task is to impleme...
```python class BankAccount: def __init__(self, account_number, initial_balance): self.account_number = account_number self.balance = initial_balance def deposit(self, amount): self.balance += amount print("Amount deposited successfully!") def withdraw(self, amount): ...
magicoder
python
You are tasked with implementing a function that will parse and extract data from an HTML form. The form is represented as a string containing HTML code. The function should extract the form's action URL and all input field names along with their corresponding values. The HTML form code is represented as follows: ```h...
```python import re def parseForm(html: str) -> dict: form_data = {"action": "", "inputs": {}} # Extract action URL action_match = re.search(r'<form.*?action="(.*?)"', html) if action_match: form_data["action"] = action_match.group(1) # Extract input field names and values input_match...
magicoder
python
You are tasked with implementing a file handling class in Python that mimics the behavior of the given JavaScript code snippet. The class should provide methods for reading and writing files, with an option to handle binary data. The `read` method should read the content of a file and return it as a string or bytes dep...
```python import os class FileHandler: def __init__(self, path, flags): self.path = path self.flags = flags self.binary = 'b' in flags def read(self, binary=False): with open(self.path, 'rb' if (binary or self.binary) else 'r') as file: return file.read() def w...
magicoder
python
You are tasked with implementing a Tic-Tac-Toe game using object-oriented programming in C++. The game board is represented by a 3x3 grid, and players take turns marking the spaces with "X" or "O" until one player wins or the game ends in a draw. The game logic is encapsulated within a `TicTacToe` class, which provides...
```cpp #include <iostream> #include <vector> class TicTacToe { private: std::vector<std::vector<char>> board; char currentPlayer; public: TicTacToe() : board(3, std::vector<char>(3, ' ')), currentPlayer('X') {} void mark_board(int position) { int row = (position - 1) / 3; int col = (p...
magicoder
cpp
You are tasked with simulating the behavior of a robot named Vector. Vector has a set of predefined actions that it can perform, such as playing animations, turning in place, driving straight, and speaking. Your goal is to write a Python function that takes a list of actions and simulates Vector's behavior by executing...
```python from anki_vector.util import degrees, distance_mm, speed_mmps def simulate_robot_behavior(actions): class Robot: def __init__(self): self.messages_spoken = [] def play_animation(self, animation_name): # Simulate playing animation pass def turn...
magicoder
python
You are tasked with implementing a C++ class that simulates a simple bank account. The class should have methods to deposit funds, withdraw funds, and check the current balance. Additionally, the class should keep track of the total number of transactions (deposits and withdrawals) made on the account. Your task is to ...
```cpp #include <iostream> class SimCppClass { private: double balance; int transactionCount; public: // Constructor SimCppClass(double initialBalance) { balance = initialBalance; transactionCount = 0; } void deposit(double amount) { balance += amount; transact...
magicoder
cpp
You are tasked with creating a Python program that utilizes the `Daemonize` library to daemonize a given application. The `Daemonize` library allows you to detach a process from the controlling terminal and run it in the background as a daemon. The code snippet provided initializes a `Daemonize` object, specifying the ...
```python import time import logging from daemonize import Daemonize def main(): log_file = '/var/log/test_app.log' logging.basicConfig(filename=log_file, level=logging.INFO, format='%(asctime)s - %(message)s') while True: logging.info('Daemonized application is running') time.sleep(10) pi...
magicoder
python
You are tasked with creating a Python class to manage a machine learning model using the Factorization Machine (FM) algorithm. The class should support model training, prediction, saving, and releasing resources. Your task is to implement the methods of this class based on the given code snippet and additional requirem...
```python from fastFM import als class FactorizationMachineModel: def __init__(self, reg=(0., 0., 0), batch_size_pernode=1, verbose=0): self.reg = reg self.batch_size_pernode = batch_size_pernode self.verbose = verbose self.model = None def fit(self, features, labels): ...
magicoder
python
You are tasked with implementing a lexer for a custom programming language. The lexer should be able to tokenize input code into different types of tokens. Each token should be classified into one of the following categories: UNTERMINATED_DOUBLE_QUOTE_STRING, UNTERMINATED_SINGLE_QUOTE_STRING, NAME, COMMA, BLOCK_COMMENT...
```python class Token: def __init__(self, token_type, value): self.token_type = token_type self.value = value class Lexer: def tokenize(self, input_string): tokens = [] # Tokenization logic goes here # Implement the logic to tokenize the input_string into tokens based on...
magicoder
python
You are tasked with implementing a method to plot cofractions based on a given dataset. The dataset is represented as a DataFrame and the method is part of a class called `sorter`. The method `plotCofractions` takes in two parameters: `is_time_lag` (a boolean indicating whether to consider time lag) and `threshold_frac...
```python import matplotlib.pyplot as plt class Sorter: def __init__(self, data): self.data = data def deleteNanRowsAndColumns(self): # Implementation to delete NaN rows and columns from the DataFrame pass def plotCofractions(self, is_time_lag=False, threshold_frac=0.5): d...
magicoder
python
You are tasked with creating a PHP class method that uploads a file to Google Cloud Storage using the Google Cloud Storage PHP client library. Your task is to complete the `upload` method within the given class. The method should take the file name as a parameter and upload the file to a specified bucket in Google Clou...
```php public function upload($file) { $obj = new \Google_Service_Storage_StorageObject(); $obj->setName($file); $localFilePath = PUBLIC_PATH . '/download/'. $file; $obj = $this->service->objects->insert($this->config['bucket'], $obj, array( 'data' => file_get_contents($localFilePath), ...
magicoder
php
You are tasked with creating a test case for a distributed caching system. The system consists of multiple hosts, each containing one or more virtual machines (VMs). The code snippet provided is a part of a test method that aims to verify the functionality of clearing the image state flag in the caching system. The tes...
```java import org.junit.Test; import static org.junit.Assert.*; public class ImageStateFlagTest { @Test public void testClearImageStateFlag() { // Step 1: Set up the necessary host and VM objects Host host = Host.getHost(0); VM vm0 = host.getVM(0); // Step 2: Invoke a method ...
magicoder
java
You are tasked with implementing a depth-limited search algorithm for a game-playing agent. The game-playing agent is provided with a `game` object that contains a `call_counter` attribute, representing the number of nodes visited during the search. The goal is to ensure that the depth limit is correctly enforced durin...
```python def depth_limited_search(game, depth_limit, expected_node_count): def explore(node, depth): if depth == depth_limit: return 1 # Count the node visited total_nodes = 1 # Count the current node for child in node.children: total_nodes += explore(child, depth ...
magicoder
python
You are tasked with creating a custom parser combinator library in Rust. Parser combinators are higher-order functions that can be used to combine simple parsers into more complex ones. In this problem, you will be extending an existing parser library with additional combinators tailored for specific use cases. The pr...
```rust use super::Input; use nom::IResult; fn custom_combinator(input: Input) -> IResult<Input, Output> { // Your custom combinator implementation here // Example: // Parse the input and modify it in a specific way // Return the modified result } ``` In the solution, you need to implement the `custom_...
magicoder
rust
You are tasked with implementing a Python function that processes a dictionary and returns a list of strings containing the keys and values of the dictionary in a specific format. The function should iterate through the dictionary and construct the strings using the following pattern: "The value of {key} is {value}". I...
```python def process_dictionary(d: dict) -> list: result = [] for key, value in d.items(): if isinstance(value, str): result.append(f'The value of {key} is "{value}"') elif isinstance(value, (int, float)): result.append(f'The value of {key} is {value:.2f}') elif ...
magicoder
python
You are tasked with implementing a C++ asynchronous generator for voxel data using the given code snippet as a starting point. The generator should produce voxel data in a separate thread and allow the consumer to asynchronously iterate over the generated data. Your task is to complete the implementation of the `Async...
```cpp #include <mutex> #include <condition_variable> #include <queue> #include <voxel/async_generator.hpp> namespace VOXEL_NAMESPACE { class AsyncGenerator : public Generator { public: AsyncGenerator(int size) : Generator(size), running(false) {} void start() { running...
magicoder
cpp
You are tasked with creating a custom exception class in Python that inherits from one of the standard built-in exception classes. Your custom exception class should be designed to handle a specific type of error related to a hypothetical banking application. Your custom exception class should be named `InsufficientFu...
```python class InsufficientFundsError(ValueError): def __init__(self, balance, amount): self.balance = balance self.amount = amount super().__init__(f"Insufficient funds. Available balance: {balance}, attempted withdrawal: {amount}") class BankAccount: def __init__(self, balance): ...
magicoder
python
You are tasked with implementing a function that calculates the final score of a game based on a set of rules. The game involves throwing a ball at a target, and the score is determined by the position where the ball hits the target. The target is divided into several concentric circles, each with a different score val...
```python import math def calculateScore(x_center, y_center, radius, x, y) -> int: distance = math.sqrt((x - x_center) ** 2 + (y - y_center) ** 2) if distance > radius: return 0 elif distance <= radius / 5: return 10 elif distance <= 2 * radius / 5: return 5 elif distan...
magicoder
python
You are tasked with implementing a Python function that processes a list of mounts for different computing environments. The function should take in the mode of computing environment and return the appropriate list of mounts based on the mode. The modes are 'local', 'docker', and 'ec2'. The mounts consist of code mount...
```python from typing import List class Mount: def __init__(self, mount_type: str, path: str, mount_point: str, output: bool): self.mount_type = mount_type self.path = path self.mount_point = mount_point self.output = output def get_mounts(mode: str) -> List[Mount]: LOCAL_OUTPU...
magicoder
python
You are tasked with creating a Django model for a transaction system. The model should include specific attributes and configurations to ensure proper functionality and user experience. Your task is to define the model and its configurations based on the given code snippet. The model should have the following attribut...
```python from django.db import models class Transaction(models.Model): tipoTransacao = models.CharField(max_length=100) empresaTransacao = models.CharField(max_length=100) vendendor = models.CharField(max_length=100) dataCadastro = models.DateTimeField(auto_now_add=True) produto = models.CharField...
magicoder
python
You are tasked with creating a function to retrieve bus data from a city's public transportation system. The function `getbusdata` takes two parameters: `city`, a string representing the city name, and `keywords`, a list of strings representing keywords to search for in the bus data. The function should connect to the...
```python def getbusdata(city, keywords): # Assume a function connect_to_database(city) to connect to the database for the specified city # Assume a function retrieve_bus_data(connection) to retrieve bus data from the database # Assume a function filter_bus_data(data, keywords) to filter the bus data based ...
magicoder
python
You are tasked with implementing a Python function that checks whether a given NumPy data type is a floating-point number or a general numeric type. You are provided with a code snippet that contains two incomplete functions, `is_float` and `is_number`, which are intended to perform these checks. Your task is to comple...
```python import numpy as np def is_float(dtype): """Return True if datatype dtype is a float kind""" return np.issubdtype(dtype, np.floating) def is_number(dtype): """Return True if datatype dtype is a number kind""" return np.issubdtype(dtype, np.number) ``` The `is_float` function is completed usi...
magicoder
python
You are tasked with creating a Python function that processes a given list of strings and counts the occurrences of specific substrings within those strings. The function should take in two parameters: a list of strings and a regular expression pattern. The function should then return a dictionary where the keys are th...
```python import re def count_substring_occurrences(string_list, pattern): substring_counts = {} regex = re.compile(pattern) for string in string_list: matches = regex.finditer(string) for match in matches: matched_substring = match.group() if matched_substring ...
magicoder
python
You are tasked with writing a program to compare two sets of pixel data from two images and identify the differences between them. Each image is represented as a 2D array of pixel data, where each pixel is represented by a tuple of RGB values. Your task is to implement a function that takes in the pixel data before and...
```python def find_pixel_differences(pixel_data_before, pixel_data_after): pixel_diff = {} height = len(pixel_data_before) width = len(pixel_data_before[0]) for y in range(height): for x in range(width): if pixel_data_before[y][x] != pixel_data_after[y][x]: pixel_dif...
magicoder
python
You are tasked with creating a program that simulates a photo album management system. The system should allow users to add, view, and delete photos, and it should include modal pop-ups for confirming photo deletion and adding new photos. Your task is to implement a class `PhotoAlbum` with the following functionalitie...
```python class PhotoAlbum: def __init__(self): self.photos = [] def add_photo(self, photo_name): self.photos.append(photo_name) print(f"Added photo: {photo_name}") def view_photos(self): if self.photos: print("Photos in the album:") for photo in sel...
magicoder
python
You are tasked with implementing a user registration system for a web application using Python and FastAPI. Your task is to extend the existing `create_user` endpoint to include functionality that ensures there are no other users with the same email address in the system. You are provided with the following code snipp...
```python from fastapi import HTTPException # Assuming UserData is a Pydantic model for user data # Import necessary modules and define UserData model # Assuming user_data_list is a list of existing user data @router.post('/', status_code=status.HTTP_201_CREATED) def create_user(data: UserData): """Creates a us...
magicoder
python
You are tasked with creating a Python function that serializes user profiles and course statuses into a specific format. The function `serialize_user_profile` takes a `user_profile` object as input and returns a dictionary containing the serialized data. The function `serialize_course` takes a `course_status_object` as...
```python from datetime import datetime def serialize_user_profile(user_profile): serialized_data = { 'full_name': user_profile.full_name, 'mail': user_profile.mail, 'birth_date': user_profile.birth_date.strftime("%d-%m-%Y"), 'avatar': user_profile.avatar } return serialized...
magicoder
python
You are tasked with implementing a function that processes HTML input to extract and manipulate attributes of specific elements. Given an HTML input string and the name of an element and its attribute, you need to extract the attribute value and modify it according to the specified rules. You are provided with the fol...
```javascript function processHtmlAttribute(htmlString, elementName, attributeName) { const regex = new RegExp(`<${elementName}[^>]*?${attributeName}="([^"]*?)"`, 'g'); return htmlString.replace(regex, (match, attributeValue) => { if (!isNaN(attributeValue)) { const newValue = parseInt(attributeValue, 10)...
magicoder
javascript
You are tasked with creating a Python function that parses a given text file to extract and display the copyright information. The copyright information is expected to be in the following format: ``` # Copyright [year] [copyright holder] # # Licensed under the [license name], Version [version number] (the "License"); ...
```python import re def extract_copyright_info(file_path): copyright_info = { "year": "", "holder": "", "license": "", "version": "" } with open(file_path, 'r') as file: content = file.read() match = re.search(r'# Copyright (\d{4}) (.+?)\n#\n# Licensed under...
magicoder
python
You are tasked with implementing a Metric class that represents a performance metric in a monitoring system. The class should have a property to store the name of the metric, and it should provide a method to validate the metric name based on certain criteria. Your task is to complete the Metric class by implementing ...
```csharp using System; using System.Text.RegularExpressions; using Xunit; public class Metric { /// <summary> /// Gets the name of the metric. e.g., CPU, Number of Queries. /// </summary> public string MetricName { get; private set; } public Metric(string metricName) { MetricName = me...
magicoder
csharp
You are tasked with implementing a distributed task queue using Redis and Python. The task queue will be responsible for distributing and executing tasks across multiple workers. Each task will be a function that takes input parameters and returns a result. Your goal is to create a system that efficiently distributes t...
```python # Task Producer from redis import Redis import json def push_task(redis_conn, task_name, *args, **kwargs): task_data = { 'task_name': task_name, 'args': args, 'kwargs': kwargs } redis_conn.rpush('task_queue', json.dumps(task_data)) # Task Worker from redis import Redis im...
magicoder
python
You are tasked with implementing a Python function that sorts a given dictionary based on either its keys or values and returns the top k key-value pairs based on the sorting criteria. You are given the following function signature: ```python def sort_dict(dic: dict, by: str, topk: int, reverse: bool) -> dict: pas...
```python def sort_dict(dic: dict, by: str, topk: int, reverse: bool) -> dict: if by == "value": sorted_items = sorted(dic.items(), key=lambda item: item[1], reverse=reverse) return dict(sorted_items[:topk]) elif by == "key": sorted_items = sorted(dic.items(), key=lambda item: item[0], r...
magicoder
python
You are tasked with creating a ride-sharing system that matches users with available trips based on their preferences and availability. The system should consider various factors such as user location, trip destination, and departure time to provide the best match. Your task is to implement the matching algorithm for t...
```python from math import radians, sin, cos, sqrt, atan2 class User: name: str id: str location: tuple # (latitude, longitude) availability: tuple # (start_time, end_time) def __init__(self, name, _id, location, availability): self.name = name self.id = _id self.location...
magicoder
python
You are tasked with creating a program that processes HTML table data and performs specific operations on it. Given an HTML table with the id "tblDetalleFactura", your program needs to extract the data from the table and perform calculations based on the values. The HTML table has the following structure: ```html <ta...
```python from bs4 import BeautifulSoup def calculateTotalCost(html_table): soup = BeautifulSoup(html_table, 'html.parser') table = soup.find('table', {'id': 'tblDetalleFactura'}) rows = table.find_all('tr')[1:] # Exclude the header row total_costs = {} for row in rows: columns = row.find...
magicoder
python
You are tasked with creating a Python function that interacts with a Quality Gate API to retrieve the status of a project's quality gate. The function should take in the project key and pull request as parameters and return '0' if the quality gate fails and '1' if the quality gate passes. You are provided with a code s...
```python import requests def get_quality_gate_status(url, headers, project_key, pull_request): """ Retrieves the status of the quality gate for a project. Args: url (str): The base URL for the Quality Gate API. headers (dict): The headers to be included in the API request. project_key (str): ...
magicoder
python
You are tasked with implementing a parallel file upload system to Amazon S3 using Python. Your task is to complete the `ParallelUpload` class by implementing the `upload_to_s3` method. The method should take in a source file path, the S3 bucket name, and the target file name in S3. The method should upload the file fro...
```python import boto3 import threading class ParallelUpload: def __init__(self): self.s3_client = boto3.client('s3') def upload_to_s3(self, source, bucket_name, target): try: # Read the file from the source path with open(source, 'rb') as file: file_dat...
magicoder
python
You are tasked with creating a custom module for an Orchard Core CMS website. The module needs to manage permissions for different user roles and provide a navigation menu item to access its features. To achieve this, you will need to implement the necessary classes and configurations using Orchard Core's APIs. Your t...
```csharp using OrchardCore.Modules.Manifest; using OrchardCore.Security.Permissions; using OrchardCore.Navigation; using OrchardCore.Recipes; using OrchardCore.ResourceManagement; namespace CustomModule { public class Permissions : IPermissionProvider { public static readonly Permission ManageCustomMo...
magicoder
csharp
You are tasked with implementing a class that represents an outgoing packet in a network communication system. The provided code snippet is a part of the class definition and contains a constructor and a property. Your task is to complete the implementation of the `OutgoingPacket` class by adding a method that seriali...
```csharp public byte[] Serialize() { byte[] packetTypeBytes = BitConverter.GetBytes((int)PacketType); byte[] creatureData = SerializeCreatureData(); byte[] serializedPacket = new byte[packetTypeBytes.Length + creatureData.Length]; Buffer.BlockCopy(packetTypeBytes, 0, serializedPacket, 0, packetTypeByt...
magicoder
csharp
You are tasked with implementing a class that analyzes loop parallelism in a given program. The provided code snippet is a part of the `LoopAnalyserBase` class, which contains a method `analyse` that takes a `LoopParallelInfo` object as input and returns a shared pointer to a `TargetParallelInfo` object. The `analyse`...
```cpp std::tr1::shared_ptr<TargetParallelInfo> LoopAnalyserBase::analyse(const LoopParallelInfo &loop) { std::tr1::shared_ptr<TargetParallelInfo> info(new TargetParallelInfo(m_target)); bool basicCheckFailed = false; if (!loop.isBasicBlock()) { // Additional analysis for non-basic block loop ...
magicoder
cpp
You are tasked with creating a program that categorizes domain names based on their top-level domain (TLD) and stores them in separate files. The program should read a list of domain names from a file called "domains.txt" and categorize them based on whether they end with ".org" or ".com". If a domain ends with ".org",...
```python # Read domain names from the input file with open("domains.txt", "r") as file: domain_names = file.readlines() # Process each domain name and categorize them based on TLD for domain in domain_names: domain = domain.strip() # Remove leading/trailing whitespaces if domain.endswith('org'): ...
magicoder
python
You are tasked with implementing a function that processes an array of `RunData` objects and returns a new array containing only the unique `RunData` objects based on a specific property. Each `RunData` object has the following structure: ```typescript type RunData = { id: number; distance: number; date: string; ...
```typescript function getUniqueRunsByProperty(data: RunData[], property: string): RunData[] { const uniqueValues = new Set(); const uniqueRuns: RunData[] = []; for (const run of data) { const value = run[property]; if (!uniqueValues.has(value)) { uniqueValues.add(value); uniqueRuns.push(run)...
magicoder
typescript
You are tasked with creating a Python module that handles the processing of triplets of numbers. The module should include functions for calculating the properties of triplets and should import and utilize other modules for specific triplet calculations. Your task is to implement a function `calculate_triplet_properti...
```python from Triplet import Triplet_BCM_LawCooper, Triplet_BCM_LawCooper2 from triplet_julijana import triplet_julijana import process def calculate_triplet_properties(triplet): # Calculate sum, product, and mean using Triplet_BCM_LawCooper triplet_sum = Triplet_BCM_LawCooper.sum_triplet(triplet) triplet...
magicoder
python
You are tasked with implementing a simple assembler for a custom programming language. The assembler takes in a series of instructions and generates corresponding machine code. Each instruction is represented by a struct with a body and a label. The assembler should handle conditional branching and default branching. ...
```rust struct Asm { // Define the Asm struct with necessary methods and fields } struct Assembler { asm: Asm, contexts: Vec<Context>, } struct Body { branch: Option<Branch>, label: Label, } struct Branch { body: Body, } impl Assembler { fn assemble(&mut self, needs: Needs) -> Result<(),...
magicoder
rust
You are working on a project to optimize a graph-based computational model. The code snippet provided is a part of a Python script that manipulates a graph structure representing a computational model. The script defines two functions, `add_dimensions_input` and `set_out_edges_one`, which are used to modify the graph b...
```python def identify_and_update_nodes(graph, naming_convention, indexes, update_graph): matching_nodes = [] for node in graph.nodes: if isinstance(node, Parameters) and naming_convention.check_convention(node.name): node.index = indexes['constant'] indexes['constant'] += 1 ...
magicoder
python
You are tasked with creating a command-line tool that simulates a lossy transmission of data. The tool should accept a parameter to specify the level of lossiness, and then apply that level of lossiness to a given input file. Lossiness refers to the intentional introduction of errors or loss of data during transmission...
```python import argparse import random def simulate_lossy_transmission(input_file, output_file, lossiness): try: with open(input_file, 'r') as file: data = file.read() data_length = len(data) num_chars_to_remove = int(data_length * (lossiness / 100)) indices...
magicoder
python
You are tasked with implementing a function to calculate the maximum amount that can be sent from a wallet. The provided code snippet is part of a larger program and includes the initialization of a `Transaction` object and the addition of output amounts to a `balance` variable. Your task is to complete the implementat...
```swift func MaxSendAmount(minimumAmount: Int, maximumAmount: Int) -> Int { // Assuming balance is a variable accessible within the scope of this function let remainingBalance = balance - minimumAmount return max(0, min(remainingBalance, maximumAmount)) } ``` In the solution, the `MaxSendAmount` function ...
magicoder
swift
You are tasked with implementing a generic factory interface in Java to create instances of various model classes. The interface `ModelFactory` is defined as follows: ```java public interface ModelFactory<ModelClass> { /** * Returns a new instance of the model class using its default constructor. * This ...
```java public class CarFactory implements ModelFactory<Car> { @Override public Car newInstance() { return new Car(); } } ``` The `CarFactory` class implements the `ModelFactory` interface for the `Car` class by providing the `newInstance` method that creates a new instance of `Car` using its defau...
magicoder
java
You are tasked with implementing a role-based access control system in a TypeScript application using decorators. The provided code snippet is a part of the NestJS framework, which is used for building efficient, reliable, and scalable server-side applications. The `Roles` function is a decorator used to specify the ro...
```typescript import { SetMetadata } from '@nestjs/common'; export function Roles(...roles: string[]): MethodDecorator { return SetMetadata('roles', roles); } ``` In the solution, we define a function `Roles` that takes in an array of roles and returns a method decorator. Inside the `Roles` function, we simply retu...
magicoder
typescript
You are tasked with creating a program that analyzes and reports the distribution of bits in a given file. The program should read the contents of the file, calculate the frequency of each bit (0 or 1), and then generate an XML report detailing the distribution. The provided code snippet initializes a file stream, open...
```cpp #include <iostream> #include <fstream> #include <unordered_map> void report_bitstream_distribution_xml_file_head(std::fstream& fp, bool include_time_stamp) { if (include_time_stamp) { fp << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; fp << "<bitstream_distribution_report timestamp=\"" <<...
magicoder
cpp
You are working for a data preprocessing company that specializes in preparing datasets for machine learning tasks. Your task is to create a Python function that performs a specific data preprocessing operation based on the given code snippet. The function should take a pandas DataFrame, an instruction, and a random st...
```python import pandas as pd import numpy as np from sklearn import preprocessing from typing import Tuple def custom_preprocessing(data: pd.DataFrame, instruction: str, random_state: int) -> Tuple[pd.DataFrame, np.ndarray]: # Fill missing values with zeros data.fillna(0, inplace=True) # Remove simil...
magicoder
python
You are tasked with implementing a function to extract and process information from a given configuration model. The configuration model is represented by a Python class `Cfg` and is used to configure a neural network model. The provided code snippet initializes a neural network model `current_network.Net` using the co...
```python def process_config_model(cfg): extracted_info = {} # Extract number of layers num_layers = cfg.get_num_layers() # Assuming a method get_num_layers() exists in the Cfg class extracted_info["num_layers"] = num_layers # Extract learning rate learning_rate = cfg.get_learning_rate() # A...
magicoder
python
You are tasked with implementing a function that simulates the behavior of a command execution system. The system is designed to run a series of processes and handle their shutdown procedures. Your task is to create a function that takes in the necessary parameters and executes the shutdown process for a given process ...
```python def execute_shutdown(procs, idx, env, deadline): if 0 <= idx < len(procs): shutdown_command = procs[idx].shutdown result = execute_command(shutdown_command, env, deadline) return result else: return "Invalid process index" ``` In the solution, the `execute_shutdown` fun...
magicoder
python
You are tasked with creating a script to automate the process of securely wiping a disk on a Linux system. The script should use the `dd` command to write zeros to the entire disk, ensuring that all existing data is irrecoverably erased. Additionally, the script should handle potential errors and provide verbose output...
```bash #!/bin/bash # Check if the disk device argument is provided if [ -z "$1" ]; then echo "Usage: $0 <disk_device>" exit 1 fi # Set the script to exit immediately if any command exits with a non-zero status set -e # Enable verbose output for monitoring the progress set -x # Securely wipe the specified disk ...
magicoder
shell
You are tasked with implementing a Python class that performs matrix operations. The class should support operations such as matrix addition, matrix subtraction, matrix multiplication, and scalar multiplication. Additionally, the class should be able to calculate the determinant of a square matrix and transpose a given...
```python from typing import List from dsplot.matrix import Matrix class MatrixOperations: def __init__(self, matrix_data: List[List[float]]): self.matrix = Matrix(matrix_data) def add(self, other: 'MatrixOperations') -> 'MatrixOperations': result_matrix = self.matrix + other.matrix re...
magicoder
python
You are working on a script that initializes a system with various parameters. The script takes in command-line arguments in the form of flags and values. Each flag is represented by a single letter followed by its corresponding value. For example, `-b 1` represents the flag "b" with the value "1". Your task is to wri...
```python def parseFlags(args, flags): flag_values = {} i = 0 while i < len(args): if args[i] in ['-{}'.format(flag) for flag in flags]: flag = args[i].lstrip('-') value = args[i + 1] if i + 1 < len(args) else None flag_values[flag] = value i += 1 for ...
magicoder
python
You are tasked with implementing a function that processes a series of network requests and returns the appropriate response code. The function should handle various network request scenarios and return the correct response code based on the outcome of the requests. You are given the following C++ code snippet as a st...
```cpp net processNetworkRequests() { // Simulate network requests bool errorOccurred = false; bool timeoutOccurred = false; // Assume network requests are made here and set errorOccurred or timeoutOccurred accordingly // For demonstration purposes, let's assume an error occurred // errorOccurred = true; ...
magicoder
cpp
You are tasked with implementing a method to retrieve a list of ancestor users for a given username. The method should handle potential errors and return the list of ancestor users if successful. You are provided with a code snippet that attempts to log an error message and return null when an error occurs. Your task i...
```java public R<List<SysUser>> ancestorUsers(String username) { try { // Perform the operation to retrieve ancestor users for the given username List<SysUser> ancestorUsers = performAncestorUserRetrieval(username); return new R<>(ancestorUsers); // Return the list of ancestor users if succe...
magicoder
java
You are tasked with implementing a factory design pattern for creating optimized search engine instances. The factory should be able to produce different types of search engine objects based on the specific requirements provided. The search engine objects should be optimized for different use cases, such as web search,...
```java public class NewOptimizeEngineFactory { public WebSearchEngine createWebSearchEngine() { // Add implementation to create and return an instance of a web search engine optimized for web search operations return new WebSearchEngine(); } public ImageSearchEngine createImageSearchEngine...
magicoder
java
You are tasked with implementing a function that processes a list of events related to different aggregate IDs and returns the count of events for each unique aggregate ID. Each event is represented by an object with a property `aggregateId` containing the ID of the aggregate it belongs to. You need to write a functio...
```javascript function countEvents(events) { const eventCounts = {}; for (const event of events) { if (event.aggregateId in eventCounts) { eventCounts[event.aggregateId]++; } else { eventCounts[event.aggregateId] = 1; } } return eventCounts; } const events = [ { aggregateId: 'abc123' ...
magicoder
javascript
You are tasked with creating a Django REST framework view for a new model called `Student`. The `Student` model has the following fields: `id` (auto-generated primary key), `name` (char field), `age` (integer field), and `grade` (char field). Your task is to create a view that allows for the full CRUD (Create, Read, Up...
```python # models.py from django.db import models class Student(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() grade = models.CharField(max_length=10) # serializers.py from rest_framework import serializers from .models import Student class StudentSerializer(serialize...
magicoder
python
You are working on a project that involves handling large amounts of data using the PyTorch library. As part of the data management process, you need to ensure efficient memory usage and proper cleanup of resources. You decide to implement a memory management function that handles PyTorch tensors and performs garbage c...
```python import torch import gc def memory_management(objects): removed_count = 0 for obj in objects: if torch.is_tensor(obj): del obj removed_count += 1 gc.collect() torch.cuda.empty_cache() return removed_count ```
magicoder
python
You are tasked with implementing a simplified version of a crypto-currency account creation system. The system is based on the Hedera™ network and involves creating new accounts using a specific transaction type. Your goal is to create a class that represents the transaction for creating a new account on the Hedera™ ne...
```javascript import Transaction from './Transaction'; export default class AccountCreateTransaction extends Transaction { constructor(client, key, initialBalance) { super(); this.client = client; this.key = key; this.initialBalance = initialBalance; } async execute() { ...
magicoder
javascript
You are tasked with implementing a debugging macro for a C/C++ program. The macro should take a variable number of arguments and print a formatted debug message to the console. The macro should also include the file name and line number where it is called. Your task is to create a macro that fulfills these requirements...
```c #include <stdio.h> #define DEBUG_MSG(format, ...) printf("[%s:%d] " format "\n", __FILE__, __LINE__, ##__VA_ARGS__) int main() { int errorCode = 404; DEBUG_MSG("Error code: %d", errorCode); char* functionName = "exampleFunction"; DEBUG_MSG("Error occurred at function %s", functionName); ret...
magicoder
c
You are tasked with implementing a function to calculate the NIQE (Natural Image Quality Evaluator) metric for a given input image. The NIQE metric is used to assess the quality of natural images without any reference image. The function should take an input image as a torch tensor and return the NIQE score. The NIQE ...
```python import torch import numpy as np from scipy.ndimage import convolve from scipy.stats import skew, kurtosis def calculate_niqe_metric(input_image: torch.Tensor, border_crop_size: int = 0, test_y_channel: bool = False, input_order: s...
magicoder
python
You are tasked with implementing a simple parser for a custom language called "Lari". The language is defined using the `rowan` crate, which provides functionality for creating and manipulating syntax trees. The code snippet provided is a partial implementation of the `rowan::Language` trait for the `Lari` language. Y...
```rust pub(crate) enum LariSyntaxKind { Identifier, Literal, Expression, Statement, // Add more syntax kinds as needed } impl rowan::Language for Lari { type Kind = LariSyntaxKind; fn kind_from_raw(raw: rowan::SyntaxKind) -> Self::Kind { match raw.0 { 0 => LariSyntaxKi...
magicoder
rust
You are tasked with implementing a Python function that processes a given input sequence using a specific recurrent neural network (RNN) architecture. The RNN is defined using TensorFlow, and the function should prepare the input data and construct the RNN model as per the provided code snippet. Your task is to comple...
```python import tensorflow as tf from tensorflow.contrib import rnn def build_rnn_model(input_data, n_hidden, n_steps): # Reshape the input data x = tf.reshape(tensor=input_data, shape=[-1, input_data.shape[2]) # Split to get a list of 'n_steps' tensors of shape (batch_size, input_dimension) x = tf.s...
magicoder
python
You are tasked with creating a Python function that processes a list of programming languages and their associated libraries. The function should perform specific operations based on the presence of certain languages and libraries. Your task is to implement the `process_libraries` function according to the following sp...
```python def process_libraries(languages: list, libraries: list) -> list: actions = [] language_library_map = dict(zip(languages, libraries)) for language in languages: if language in language_library_map: library = language_library_map[language] actions.append(f'Compile {l...
magicoder
python
You are working on a web application using the Craft CMS framework. Your task is to create a custom plugin that adds a new section to the control panel navigation. The plugin should also define custom URL rules for routing within the application. You have been provided with a code snippet that includes the necessary C...
```php use craft\base\Plugin; use craft\events\RegisterUrlRulesEvent; use craft\events\RegisterCpNavItemsEvent; use craft\web\UrlManager; use craft\web\twig\variables\Cp; use yii\base\Event; class CustomPlugin extends Plugin { public function init() { parent::init(); // Register custom URL rul...
magicoder
php
You are tasked with creating a Python function that processes climate data and saves it to a Hadoop Distributed File System (HDFS). The function should read climate data from a file, perform some processing, and then save the processed data to HDFS. Additionally, the function should measure the duration of the processi...
```python import time import hdfs # Assuming the hdfs module is imported for HDFS operations def saveToHadoop(): client = hdfs.InsecureClient('http://hadoop-namenode:50070', user='hadoop') # Replace with actual HDFS namenode URL and user start = time.time() if client.exists('/climate.csv'): # Re...
magicoder
python
You are given a series of strings, each representing a pair of values. The first value is a version of a software package, and the second value is a base64-encoded string. However, due to various issues such as truncation, newline characters, or missing data, the pairs are not consistently formatted. Your task is to wr...
```python import base64 from typing import List, Tuple def parseSoftwareVersions(pairs: List[Tuple[str, str]]) -> List[Tuple[str, str]]: result = [] for version, encoded_str in pairs: version = version.strip() encoded_str = encoded_str.strip() decoded_str = "" if encoded_str: ...
magicoder
python
You are tasked with implementing a function to parse a specific data structure from a binary input stream. The data structure consists of a header followed by a variable-length list of elements. The header contains a type code and a code array, and the elements are arrays of 16 bytes each. The function should read the ...
```cpp #include <iostream> #include <array> #include <vector> // Define the type_code and CODE_ALT_LIST constants constexpr int type_code = 1; constexpr int CODE_ALT_LIST = 2; // Define the data structure to hold the parsed information struct ParsedData { int typeCode; std::array<uint8_t, 16> code; std::v...
magicoder
cpp
You are tasked with creating a Python script to automate the dehazing process for a collection of images using a given model. The script should take a folder containing hazy images and a specific dehazing model as input, and then apply the model to each image to generate dehazed versions. The script should be designed ...
```python import os import subprocess import sys def dehaze_images(input_folder, model_name): output_folder = 'dehazed_images' os.makedirs(output_folder, exist_ok=True) for image_file in os.listdir(input_folder): if image_file.endswith('.jpg') or image_file.endswith('.png'): input_path...
magicoder
python
You are tasked with implementing a Python class for a machine learning model trainer. The class should include methods for validation, training, listing available models, and setting up training data. Your task is to complete the implementation of the class by adding the necessary functionality to each method. You are...
```python class ModelTrainer: def __init__(self): # Initialize any required variables or resources here pass def validation_step(self, batch, batch_idx): # Perform validation step on the given batch # Replace the following line with actual validation logic return self(ba...
magicoder
python
You are tasked with implementing a function that constructs a URL for a search query based on the given parameters. The function should take into account the selected language, cookies, query, paging, and time range. You are provided with a code snippet that handles some of these aspects, and your task is to complete t...
```python from urllib.parse import urlencode def construct_search_url(params, query, offset, number_of_results): # language cookie language = match_language(params['language'], supported_languages, language_aliases).lower() params['cookies']['_EDGE_S'] = 'mkt=' + language + '&F=1' # query and paging ...
magicoder
python
You are tasked with implementing an abstract enumeration interface in C++. An abstract enumeration interface is a design pattern that allows the creation of a set of related constants in a type-safe manner. Your goal is to create a base interface for enumerations that can be inherited by specific enumeration classes. ...
```cpp #include <iostream> #include <string> // Abstract enumeration interface class AbstractEnumInterface { public: virtual int getValue() const = 0; virtual std::string getName() const = 0; virtual ~AbstractEnumInterface() = default; }; // Example of a derived enumeration class class MyEnum : public Abs...
magicoder
cpp
You are tasked with designing a REST API endpoint for a web application that handles SingPass/CorpPass logins for form-fillers. The endpoint should generate a URL to which web agents are obliged to redirect users after successful login. Due to cross-origin restrictions in place by SingPass/CorpPass, the endpoint cannot...
```javascript const express = require('express'); const app = express(); app.get('/spcp/redirect', (req, res) => { const { target, authType, esrvcId } = req.query; if (!target || !authType || !esrvcId) { return res.status(400).json({ error: 'Missing parameters. The redirect URL will be malformed.' }); } ...
magicoder
javascript
You are tasked with creating a Python script that will compress a specific directory and its contents into a tar file. Your script should take the directory path as input and create a tar file with the same name as the directory, suffixed with ".tar". If the directory does not exist, the script should display an error ...
```python import os import sys import tarfile def create_tar(directory_path): if not os.path.exists(directory_path): print("Error: Directory does not exist.") return tar_filename = directory_path + '.tar' with tarfile.open(tar_filename, 'w') as tar: tar.add(directory_path, arcname=...
magicoder
python
You are tasked with implementing a regular expression parser and a corresponding Nondeterministic Finite Automaton (NFA) compiler. Your goal is to create a program that takes a regular expression as input, compiles it into an NFA, and then prints the resulting NFA. The regular expression parser should support the foll...
To solve this problem, you can use the following steps: Step 1: Implement the regular expression parser - Create a class `RegexParser` that takes a regular expression as input and compiles it into an NFA. - Implement methods to handle concatenation, alternation, and Kleene star operations. - Use appropriate data struc...
magicoder
python
You are tasked with creating a Python function that integrates with Grafana, a popular monitoring and observability platform. Your function will be responsible for creating organizations and assigning editor access to specified users. The function will take in three parameters: `name` (the name of the organization), `c...
```python import requests from typing import List def create_organization(name: str, create_users: bool, editors: List[str]) -> None: # Assuming Grafana API endpoint grafana_api_url = "https://your-grafana-instance/api/orgs" # Create organization response = requests.post(grafana_api_url, json={"name":...
magicoder
python
You are tasked with implementing a class that represents a Vulkan image layout. Vulkan is a low-overhead, cross-platform 3D graphics and computing API. The `VkImageLayout` enum specifies the layout of image and image subresources for use in Vulkan commands. Your task is to create a C# class that encapsulates this enum ...
```csharp using System; using System.Collections.Generic; public enum VkImageLayout { Undefined, General, ColorAttachmentOptimal, DepthStencilAttachmentOptimal, DepthStencilReadOnlyOptimal, ShaderReadOnlyOptimal, TransferSrcOptimal, TransferDstOptimal, Preinitialized, PresentSrc...
magicoder
csharp
You are tasked with creating a shell script to automate the installation process of different software development kits (SDKs) based on user input. The script should support multiple SDK versions and provide appropriate download and installation instructions for each version. Your task is to implement a shell script ...
```bash #!/bin/bash if [ "$1" == "" ]; then echo "Supported SDKs are:" echo "[+] 12.4" echo "[+] 13.1" echo "[+] 13.4" echo "[+] 14.0" echo "To use, type: SDK_Installer.sh <SDK_version>" elif [ "$1" == "12.4" ]; then echo "Downloading SDK 12.4..." # Add download and installation command...
magicoder
shell
You are tasked with implementing a custom metaclass in Python that enforces a specific behavior for the initialization of classes. The metaclass should ensure that any class using it will have its `__init__` method wrapped with a try-except block to handle any exceptions that may occur during initialization. Your task...
```python class DocumentBase(type): def __new__(cls, name, bases, dct): original_init = dct.get('__init__') def wrapped_init(self, *args, **kwargs): try: if original_init: original_init(self, *args, **kwargs) except Exception as e: ...
magicoder
python
You are tasked with implementing a Python function that creates a graphical shape with specified properties. The function takes in various parameters to define the shape's appearance, including its dimensions, color, border, and border properties. Your task is to write a function that uses these parameters to generate ...
```python def create_shape(u: str, v: str, b: float, e: float, width: int, depth: int, color: str, border: str, bordercolor: str, borderwidth: int) -> str: shape_representation = f"Shape with vertices {u} and {v}, properties b={b} and e={e}, dimensions {width}x{depth}, color {color}, border style {border}, border c...
magicoder
python
You are working on a software development project that requires specific packages and libraries to be installed on a Linux system. Your task is to create a script that automates the installation process for these packages. The script should also include a verification step to ensure that the base packages were installe...
```bash #!/bin/bash # Function to handle errors handle_error() { echo "Error: $1" >&2 exit 1 } # Install package groups sudo dnf -y groupinstall 'Development tools' || handle_error "Failed to install 'Development tools' group" sudo dnf -y groupinstall 'C Development Tools and Libraries' || handle_error "Failed to...
magicoder
shell
You are tasked with implementing a class that handles attachments for a given API. The `Attachment` class has an `__init__` method that takes in a dictionary representing attachment details and an instance of the `PleasantAPI` class. The dictionary contains the `CredentialObjectId`, `AttachmentId`, and `FileName` of th...
```python import base64 class PleasantAPI: def get_attachment(self, entry_id, attachment_id) -> bytes: # Assume fetching attachment data from the API # Example implementation: # attachment_data = fetch_attachment_data_from_api(entry_id, attachment_id) attachment_data = b'example_att...
magicoder
python
You are given a TypeScript code snippet that defines a function `count` using the `Schedule` type. Your task is to understand the code and implement a similar function using TypeScript. The `Schedule` type is a part of a library that provides scheduling and time-related functionalities. The `count` function is defined...
```typescript import { Schedule } from 'your-schedule-library'; // Import the Schedule type from your library // Define the generateCountSchedule function export function generateCountSchedule(): Schedule<number, unknown, unknown, number> { // Use the unfold method to create the infinite sequence of numbers return...
magicoder
typescript
You are working on a bioinformatics project and need to implement a class for handling transcriptome data. The provided code snippet is part of a larger class that deals with serialized input data and initializes transcriptome objects. Your task is to complete the implementation of the `read_serialized` method and ensu...
```python class TranscriptomeHandler: def __init__(self): self.transcriptome1 = None self.transcriptome2 = None def read_serialized(self, instring): a = decode_64(instring) if 'transcriptome1' in a: if a['transcriptome1']: self.transcriptome1 = Transc...
magicoder
python
You are tasked with creating a Python function that filters and processes a list of enrollments based on various criteria. The function should take in the following parameters: - `external_key` (string): The external key to filter enrollments by. - `enrollment_type` (string): The type of enrollment to filter by. - `sta...
```python from typing import List, Dict, Union class Enrollment: def __init__(self, id: int, enrollment_type: str, external_key: str, enrolled_email: str, enrolled_user_email: str): self.id = id self.enrollment_type = enrollment_type self.external_key = external_key self.enrolled_em...
magicoder
python
You are tasked with implementing a function to process and manipulate a buffer of bytes. The function takes in three parameters: `left`, `right`, and `count`. The `left` and `right` parameters are objects with methods `index_output()` and `count_left`, and the `count` parameter is an integer representing the number of ...
```rust fn process_buffer(left: &Left, right: &Right, count: usize, bytes_per_doc: usize) { let mut count_start = count; let mut right_count = 0; let right_out = right.index_output(); let left_out = left.index_output(); debug_assert!(count <= self.count_left); self.count_left -= count; let...
magicoder
rust
You are tasked with simulating memory protection and manipulation in a low-level programming environment. In this problem, you will be working with memory allocation, protection, and modification using Rust's `NonNull` and memory protection functions. You are given a code snippet that demonstrates memory allocation, p...
```rust use std::ptr::NonNull; use std::mem; use libc::{c_void, PROT_NONE, PROT_READ, PROT_WRITE, MAP_ANON, MAP_PRIVATE, mmap, mprotect, munmap}; fn malloc() -> Result<NonNull<[u8; 32]>, Box<dyn std::error::Error>> { let ptr = unsafe { let ptr = mmap( std::ptr::null_mut(), mem::size...
magicoder
rust
You are tasked with implementing a Python function that collects information from files based on a given pattern. The function should parse each file, extract relevant data, and return a dictionary containing the collected information. You are provided with a code snippet that includes a partial implementation of the ...
```python import libcst as cst from typing import Dict, Any class StringCollector: def __init__(self): self.contexts = [] def open_module(self, fullname: str): # Implementation not shown for brevity pass def visit(self, tree: cst.CSTNode): # Implementation not shown for br...
magicoder
python
You are working on a project that involves processing Earth observation data using the `EOPatch` library in Python. The `EOPatch` object represents a collection of Earth observation data, and it contains various types of data such as time-series data, masks, and other features. In the given code snippet, a specific `E...
```python import numpy as np from scipy import ndimage def largest_connected_component_size(eopatch): eroded_mask = eopatch.mask_timeless['LULC_ERODED'] # Label connected components in the eroded mask labeled_array, num_features = ndimage.label(eroded_mask) # Calculate the size of each connected comp...
magicoder
python
You are given a code snippet that defines an array of strings `STRS` and some boolean constants that compare pairs of strings using a function `str_eq`. Your task is to implement the `str_eq` function and write a program to determine the equality of the given pairs of strings. The `str_eq` function takes two string re...
```rust fn str_eq(s1: &str, s2: &str) -> bool { s1 == s2 } const STRS: &[&str] = &[ "foo", "fooooo", "bar", "baz", ]; fn main() { const ARE_0_0_EQ: bool = str_eq(STRS[0], STRS[0]); const ARE_0_1_EQ: bool = str_eq(STRS[0], STRS[1]); const ARE_1_1_EQ: bool = str_eq(STRS[1], STRS[1]); ...
magicoder
rust