query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with creating a custom fuzzer for a specific data structure. In this problem, you will be using the Rust programming language and the libfuzzer library to implement a custom fuzzer for a simple data structure. Your task is to create a custom fuzzer for a binary tree data structure. The binary tree node ...
```rust use libfuzzer_sys::arbitrary; use libfuzzer_sys::fuzz_target; #[derive(Debug)] struct TreeNode { value: i32, left: Option<Box<TreeNode>>, right: Option<Box<TreeNode>>, } impl arbitrary::Arbitrary for TreeNode { fn arbitrary(u: &mut arbitrary::Unstructured) -> arbitrary::Result<Self> { ...
magicoder
rust
You are tasked with automating the testing of a web application using TestCafe and BrowserStack. Your goal is to set up the necessary environment variables and execute the test suite with specific configurations. Given the provided code snippet, you need to write a script that accomplishes the following tasks: 1. Set ...
```bash #!/bin/bash # Set environment variables export BROWSERSTACK_PROJECT_NAME="Answers SDK" export BROWSERSTACK_BUILD_ID="${CIRCLE_BRANCH} - ${CIRCLE_BUILD_NUM}" COMMIT_MSG_TITLE=$(git log -n 1 --pretty=format:%s) export BROWSERSTACK_TEST_RUN_NAME=$COMMIT_MSG_TITLE # Execute the test suite using TestCafe npx testc...
magicoder
shell
You are tasked with creating a Python function that dynamically generates URL patterns for a Django web application based on a given set of view sets. The function should take a list of view sets as input and return a list of URL patterns that can be included in the Django application's URL configuration. The URL patt...
```python from rest_framework import routers def generate_url_patterns(view_sets): router = routers.DefaultRouter() url_patterns = [] for view_set in view_sets: router.register(view_set.resource_name, view_set) url_patterns += router.urls return url_patterns ``` In the solution, the `gener...
magicoder
python
You are tasked with implementing a function that extracts information about a Rust macro expansion. The function should take ownership of the current object and return an `Option` containing the expansion information if available. You are provided with the following code snippet as a starting point: ```rust pub fn exp...
```rust pub fn expn_info(self) -> Option<ExpnInfo> { // Assuming ExpnInfo is a type provided elsewhere // Implement the logic to retrieve the expansion information // For example, if the expansion information is available, return Some(expn_info) // Otherwise, return None } ``` The solution provided is a...
magicoder
rust
You are tasked with creating a program that reads data from a CSV file, processes it, and writes the processed data to a new CSV file. The input CSV file contains rows of data, and the program needs to process the data in batches of 50,000 rows. After processing each batch, the program should append the processed data ...
```python import csv def process_csv(input_file, output_file): batch_size = 50000 rows = [] with open(input_file, 'r', newline='') as input_csv: reader = csv.reader(input_csv) header = next(reader) # Assuming the first row is the header rows.append(header) for cnt, row in...
magicoder
python
You are tasked with implementing a Python function that simulates a simple text-based game. The game involves a player navigating through a grid-based world, collecting treasures, and avoiding obstacles. The player's position and the layout of the world are represented by a 2D grid. The player can move up, down, left, ...
```python def play_game(grid, moves): rows, cols = len(grid), len(grid[0]) player_row, player_col = -1, -1 collected_treasures = 0 for r in range(rows): for c in range(cols): if grid[r][c] == 'P': player_row, player_col = r, c break directions = ...
magicoder
python
You are tasked with implementing a simple GraphQL server using Python's Tornado web framework. Your goal is to create a Tornado RequestHandler that can handle incoming GraphQL queries and mutations. The TornadoGraphQLHandler class should be able to parse incoming GraphQL requests, execute the corresponding resolver fun...
```python import tornado.web import tornado.ioloop from graphql.execution.executors.asyncio import AsyncioExecutor from graphql import graphql from graphql.execution import execute from graphql.type import GraphQLSchema import json class TornadoGraphQLHandler(tornado.web.RequestHandler): async def post(self): ...
magicoder
python
You are tasked with creating a program that simulates a simple banking system. The system should allow users to create accounts, deposit and withdraw funds, and check their balance. Each account should have a unique account number, and the system should be able to handle multiple accounts. Your task is to implement th...
```python from typing import Union class Account: def __init__(self, name: str, balance: float): self.name = name self.balance = balance class BankingSystem: def __init__(self): self.accounts = {} self.account_number = 1 def create_account(self, name: str, initial_balance:...
magicoder
python
You are tasked with creating a smart contract for a decentralized application (dApp) on a blockchain platform. The smart contract will handle the transfer of a custom token between users. The code snippet provided is a starting point for the smart contract, using the Rust programming language and the `contract` and `ty...
```rust use contract::contract_api::runtime; use types::ApiError; // Define the custom token struct to represent user balances struct CustomToken { balances: std::collections::BTreeMap<AccountId, U256>, } impl CustomToken { // Function to transfer tokens from sender to recipient fn transfer(&mut self, sen...
magicoder
rust
You are tasked with creating a Python function that processes a list of file paths and their corresponding destination directories. The function should extract the file names from the paths and move the files to their respective destination directories. If a file with the same name already exists in the destination dir...
```python import os import shutil import glob from typing import List, Tuple def move_files(datas: List[Tuple[str, str]]) -> None: for source, destination in datas: files = glob.glob(source) for file in files: filename = os.path.basename(file) dest_file = os.path.join(destin...
magicoder
python
You are tasked with creating a Python class that represents a product in an e-commerce system. The product has a field to indicate its type, which can be either "local" or "international". You need to implement the class with the following requirements: 1. The class should be named `Product`. 2. It should have an attr...
```python class Product: def __init__(self, product_type): valid_types = ('local', 'international') if product_type not in valid_types: raise ValueError("Invalid product type. Please choose 'local' or 'international'.") self.product_type = product_type # Example usage try: p...
magicoder
python
You are tasked with creating a Python function that simulates a robot's actions based on a given sequence of commands. The robot has a set of predefined actions it can perform, and the sequence of commands will dictate the robot's behavior. Each command corresponds to a specific action that the robot should execute. T...
```python def simulate_robot_actions(commands): for command in commands: exec(command) ``` Note: Using `exec` to execute arbitrary commands can be potentially unsafe, and it's important to ensure that the input commands are trusted and validated before execution in a real-world scenario.
magicoder
python
You are tasked with implementing a date processing algorithm for a receipt management system. The system receives a series of dates and needs to determine the highest date encountered so far, as long as it is not in the future. The algorithm should update the highest date found if a new date surpasses it, but only if t...
```csharp DateTime receiptdate = DateTime.MinValue; // Initialize receiptdate with the minimum date value // Process a series of extracted dates foreach (DateTime extractedDate in extractedDates) { if (extractedDate > receiptdate && extractedDate <= DateTime.Today) { receiptdate = extractedDate; // Upd...
magicoder
csharp
You are tasked with implementing a password management system using Python. The system should include functions for generating a random password, hashing a password, and checking a password against its hash. You are provided with a code snippet that includes the implementation of the `generate_password` function and th...
```python import bcrypt import random import string def generate_password(length: int) -> str: all_char = string.ascii_letters + string.digits + string.punctuation return "".join(random.sample(all_char, length)) def check_password(password: str, password_hash: str) -> bool: return bcrypt.checkpw(password....
magicoder
python
You are given a function `optimize_solution` that takes three parameters: `distances`, a list of distances between nodes in a graph, `connections`, a map representing the connections between nodes, and `endpoints`, a list of endpoints in the graph. The function returns two values: `nopt`, the number of optimal solution...
```python def optimize_solution(distances, connections, endpoints): def dijkstra(graph, start, end): queue = [(0, start, [])] visited = set() while queue: (cost, node, path) = heappop(queue) if node not in visited: visited.add(node) pat...
magicoder
python
You are tasked with implementing a Python function that calculates the core functional derivative loop for the CIDER (Core-Integrated Density-Functional Exchange and Correlation Response) features. The function is called by NLNumInt and takes several arguments including rho_data, density, ovlps, and grid. Your goal is ...
```python def core_functional_derivative_loop(rho_data, density, ovlps, grid): """ Core functional derivative loop for the CIDER features, called by NLNumInt. Args: rho_data: Data related to electron density density: Electron density ovlps: Overlaps grid: Grid information...
magicoder
python
You are tasked with implementing a simplified event emitter in JavaScript. An event emitter is an object that can register event listeners for specific events and then trigger those events when needed. Your task is to complete the implementation of the `emitEvent` method, which is responsible for triggering the registe...
```javascript emitEvent: (eventName, callback) => { if (eventName === '' || eventName === null) { throw new Error('eventName can not be empty'); } if (callback === undefined || callback === null) { callback = () => null; } return emitter .listeners(eventName) .reduce((prevCallback, currentHa...
magicoder
javascript
You are tasked with implementing a custom `CancellationTokenTaskSource` class that provides a mechanism for creating a `Task` that completes when a specified `CancellationToken` is canceled. Your task is to complete the implementation of the `CancellationTokenTaskSource` class by adding the necessary methods and proper...
```csharp using System; using System.Threading; using System.Threading.Tasks; public class CancellationTokenTaskSource { private readonly CancellationToken cancellationToken; private readonly TaskCompletionSource<bool> taskCompletionSource; public CancellationTokenTaskSource(CancellationToken cancellation...
magicoder
csharp
You are tasked with implementing a class to represent geographic coordinates and providing methods to retrieve the latitude, longitude, and altitude from these coordinates. The coordinates are represented in a three-dimensional space using the Coordinate class, which has methods to retrieve the ordinate values for X, Y...
```java // Coordinate class to represent geographic coordinates public class Coordinate { private double x; private double y; private double z; public Coordinate(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } public double getX() { return ...
magicoder
java
You are tasked with implementing a bracket order function for a trading platform. A bracket order is a type of order that allows traders to set a profit target and a stop-loss order simultaneously. The function should take in the symbol of the stock, the quantity to trade, the target profit limit price, the stop-loss p...
```python import requests endpoint = "https://api.tradingplatform.com" def bracket_order(symbol, quantity, tp_limit_price, sl_stop_price, sl_limit_price, side="buy", tif="day"): order_url = endpoint + "/v2/orders" params = { "symbol": symbol, "qty": quantity, "side": side, "tak...
magicoder
python
You are tasked with implementing a genetic algorithm for a binary string representation. The genetic algorithm uses single-point crossover to create offspring from parent genotypes. Your task is to complete the implementation of the `SinglePointCrossover` class by filling in the `Cross` method. The `SinglePointCrossov...
```csharp public class SinglePointCrossover : ICrossover { protected Random RandomNumberGenerator { get; set; } = new(); public int ParentsCount { get; } = 2; public int ChildrenCount { get; } = 2; public int BitAlign { get; set; } = 1; public IGenotype[] Cross(IGenotype[] parents) { if...
magicoder
csharp
You are working on a project management system that uses an API to retrieve labels associated with specific tasks. The code snippet provided is a part of a Python class method that performs a basic GET request to retrieve a label using its unique identifier (uid). The method raises different custom exceptions based on ...
```python class AuthenticationError(Exception): pass class AuthorisationError(Exception): pass class ResourceNotFoundError(Exception): pass class UnknownError(Exception): pass class OperationNotAllowed(Exception): pass class YourClass: def get_label(self, uid): try: labe...
magicoder
python
You are given a list of non-negative integers representing the power of various electronic devices. The goal is to find the maximum length of contiguous subarray such that the product of all the elements in the subarray is less than or equal to a given power limit. Write a function `max_contiguous_subarray_length` tha...
```python from collections import deque def max_contiguous_subarray_length(power, powerlimit): if powerlimit <= 0: return 0 max_len = 0 left = right = 0 product = 1 while right < len(power): product *= power[right] while product > powerlimit and left <= right: pr...
magicoder
python
You are tasked with creating a program that simulates a simplified version of a Vulkan shader compilation pipeline. The pipeline consists of several stages, each of which performs a specific task on the shader code. Your goal is to implement a program that replicates this pipeline by performing the necessary operations...
```python import subprocess def preprocess_shader(shader_code): with open('temp_shader.glsl', 'w') as file: file.write(shader_code) subprocess.run(['cpp', 'temp_shader.glsl', '|', 'node', 'preprocess.js', '>', 'preprocessed_shader.comp'], shell=True) def compile_shader(): subprocess.run(['glslangV...
magicoder
python
You are tasked with implementing a hash table data structure in Python. The hash table should support the following operations: 1. Insertion of key-value pairs. 2. Retrieval of values based on keys. 3. Deletion of key-value pairs. Your task is to complete the implementation of the `HashTable` class by filling in the m...
```python class HashTable: def __init__(self, size): self.size = size self.__buckets = [[] for _ in range(size)] def __hash(self, key): return hash(key) % self.size def insert(self, key, value): idx = self.__hash(key) self.__buckets[idx].append((key, value)) de...
magicoder
python
You are tasked with creating a custom extension method for the `StaticFileMiddleware` in a C# OWIN (Open Web Interface for .NET) application. The `StaticFileMiddleware` is responsible for serving static files and is commonly used in web applications to serve CSS, JavaScript, images, and other static content. Your task...
```csharp using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Owin; using Owin; namespace OwinExtensions { public static class StaticFileMiddlewareExtensions { public static IAppBuilder UseCustomHeaders(this IAppBuilder app, CustomHeaders customHeaders) ...
magicoder
csharp
You are tasked with implementing a graph data structure that supports both real and fake edges. Real edges represent actual connections between nodes, while fake edges are used for various purposes such as testing or simulation. Your goal is to implement a method that returns the neighbors of a given node based on the ...
```python class Graph: def __init__(self): self.__real_edges = {} # Initialize an empty dictionary for real edges self.__fake_edges = {} # Initialize an empty dictionary for fake edges def add_real_edge(self, node, neighbor): if node in self.__real_edges: self.__real_edges...
magicoder
python
You are tasked with creating a Python function that processes XML output from a firewall device and extracts specific information based on predefined criteria. The function will take the XML output as input and return a list of dictionaries containing the extracted information. The XML output will contain data related...
```python from xml.etree import ElementTree def process_op_commands(xml_output): # Parse the XML output root = ElementTree.fromstring(xml_output) # Define the list to store extracted information extracted_info = [] # Iterate through the XML elements to extract specific fields for entry in roo...
magicoder
python
You are tasked with creating a script to manage the lifecycle of processes on a Unix-based system. The script should be able to start, stop, and check the status of a given process. Additionally, it should handle cases where a process does not stop gracefully within a specified timeout period. Your script should inclu...
```bash #!/bin/bash # Function to start a process and store its PID in a file start_process() { command=$1 $command & # Start the process in the background echo $! > "$command.pid" # Store the process ID in a file echo "$command started with PID $!" } # Function to stop a process stop_process() { command=...
magicoder
shell
You are tasked with implementing a PrefixSet data structure in Rust. The PrefixSet is a set-like data structure that stores IP prefixes and supports efficient lookup operations. An IP prefix is a numerical representation of an IP address and its associated subnet mask. Your task is to implement the `PrefixSet` data st...
```rust use std::collections::HashSet; use std::iter::FromIterator; // Define the IpPrefix trait for working with IP prefixes trait IpPrefix { // Define the necessary functionality for IP prefixes // For example, methods for checking containment and parsing IP addresses } // Define the Node type to represent ...
magicoder
rust
You are tasked with implementing a custom traversal policy for a user interface component in Java. The component is a collection of buttons, and the traversal policy should define the order in which these buttons are focused when the user navigates using the keyboard. The traversal policy should follow a specific index...
```java @Override public Component getComponentAfter(Container focusCycleRoot, Component a) { int index = -1; for (int i = 0; i < buttons.length; i++) { if (buttons[i] == a) { index = i; break; } } if (index != -1) { int nextIndex = (index + 1) % buttons.l...
magicoder
java
You are tasked with implementing a Python class that validates and manipulates phone numbers. The class should provide methods to validate whether a given string is a valid phone number and to format the phone number in a standardized way. Your task is to complete the implementation of the `Solution` class, which shou...
```python from typing import AnyStr import re class Solution: def is_valid_phone_number(self, phone_number: str) -> bool: pattern = re.compile(r'^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$') match = pattern.match(phone_number) return bool(match) def format_phone_number(self, phone_number: ...
magicoder
python
You are tasked with creating a Python module that securely handles sensitive API keys and secrets for a cryptocurrency trading application. To achieve this, you will utilize the `decouple` library to manage changeable variables, while ensuring that other configuration settings remain static and cannot be modified outsi...
```python # secure_config.py from decouple import Config, Csv class SecureConfig: _immutable_settings = { "BITVAVO_BASE_URL": "https://api.bitvavo.com/v2", "BITVAVO_API_VERSION": "v2", # Add other immutable settings based on Bitvavo's documentation } def __init__(self, env_file='....
magicoder
python
You are tasked with creating a custom shortcode in WordPress to display a section with specific content on a page. The shortcode should retrieve the current page's ID and use it to fetch the content to be displayed within the section. Additionally, the shortcode should utilize the theme's directory URI to reference ass...
```php function section_shortcode_function($atts) { $atts = shortcode_atts(array( 'content_id' => '', ), $atts, 'section_shortcode'); $page_id = get_the_ID(); $dir = get_stylesheet_directory_uri(); $content_id = $atts['content_id']; $content = get_post_field('post_content', $content_id)...
magicoder
php
You are tasked with implementing a program that simulates a simple game of guessing a randomly generated number. The program should continuously prompt the user to guess the number until they guess it correctly. The program should also provide feedback to the user after each guess, indicating whether the guess was too ...
```python import random def guessing_game(min_num, max_num): target_number = random.randint(min_num, max_num) attempts = 0 while True: guess = int(input("Guess the number: ")) attempts += 1 if guess < target_number: print("Too low!") elif guess > target_number: ...
magicoder
python
You are given a directed acyclic graph representing a project's tasks and their dependencies. Each task is represented by a unique integer, and the graph is represented as a list of edges. Additionally, you are given the time it takes to complete each task. Your task is to implement a function that calculates the mini...
```python from collections import defaultdict, deque def minimum_completion_time(num_tasks, edges, build_time): orders = defaultdict(list) indegree = [0] * num_tasks rt = [0] * num_tasks for a, b in edges: orders[a].append(b) indegree[b] += 1 q = deque() for i in range(num_tas...
magicoder
python
You are tasked with creating a custom placement feature for a game similar to Minecraft. The game uses the Minecraft Forge modding platform, which provides a set of classes and interfaces for customizing world generation. Your goal is to implement a custom placement feature called "FumarolePlacement" that will generate...
```java import net.minecraft.util.math.BlockPos; import net.minecraft.world.gen.placement.FrequencyConfig; import net.minecraft.world.gen.placement.SimplePlacement; import net.minecraft.world.gen.placement.Placement; import net.minecraft.world.gen.Heightmap; import net.minecraft.world.IWorld; import net.minecraft.world...
magicoder
java
You are tasked with creating a Python function that connects to a database and retrieves data from a specific table. The database name and table name are provided as constants. Your function should handle potential connection errors and return the retrieved data. You are given the following code snippet as a starting ...
```python import database_library # Assuming the existence of a database library DATABASE = 'EMPLOYEE' TABLE = 'COREVIEW' def connect(): try: connection = database_library.connect(DATABASE) # Establish connection to the specified database cursor = connection.cursor() cursor.execute(f"SEL...
magicoder
python
You are tasked with implementing a function to update the mesh in a 3D mesh viewer application. The provided code snippet is a part of the MeshViewer class, and the updateMesh function is responsible for recomputing face and vertex normals before updating the OpenGL buffers. Your task is to complete the implementation...
```cpp void MeshViewer::updateMesh() { // Compute face normals for each face in the mesh for (const auto& face : m_mesh.faces()) { Vector3f v0 = m_mesh.vertices()[face[0]]; Vector3f v1 = m_mesh.vertices()[face[1]]; Vector3f v2 = m_mesh.vertices()[face[2]]; Vector3f edge1 = v1 - ...
magicoder
cpp
You are working on a computer vision application that involves drawing bounding boxes and labels on images. You have a set of helper functions and parameters to assist with this task. Your goal is to implement a class method that utilizes these helper functions to draw a labeled bounding box on an input image. You are...
```cpp void BboxDrawer::DrawLabeledBox(cv::Mat image, const cnstream::CNInferObject &object, const std::string &label_text, const cv::Scalar &box_color) const { // Get the bounding box corners std::pair<cv::Point, cv::Point> bbox_corners = GetBboxCorner(object, image.cols, image.row...
magicoder
cpp
You are tasked with creating a program that processes XML files and handles any potential schema exceptions that may arise. Your program should read an XML file, validate it against a given XML schema, and handle any schema exceptions that occur during the validation process. Your task is to implement a function or me...
```csharp using System; using System.Xml; using System.Xml.Schema; public class XmlValidator { public void ValidateXmlAgainstSchema(string xmlFilePath, string schemaFilePath) { try { // Load the XML file XmlDocument xmlDocument = new XmlDocument(); xmlDocumen...
magicoder
csharp
You are tasked with implementing a network packet processing system that supports both IPv4 and IPv6 packets. However, the current code snippet only supports IPv4 packets, and an assertion is made to ensure that only IPv4 packets are processed. Your task is to extend the existing code to support IPv6 packets and handle...
To extend the existing code to support both IPv4 and IPv6 packets, you can use conditional statements to differentiate between the two protocols and create the corresponding packet objects. Here's a possible solution in C++: ```cpp NetworkPacket *processPacket(Protocol proto, const uint8_t *data, size_t data_len) { ...
magicoder
cpp
You are tasked with creating a utility to forcibly close a specific process on a Windows system. The process to be terminated is "DeadByDaylight-Win64-Shipping", which corresponds to the game "Dead by Daylight". You need to implement a method that checks for the existence of this process and, if found, prompts the user...
```csharp using System; using System.Diagnostics; using System.Windows.Forms; public class ProcessTerminator { private readonly string KILL_TITLE = "Kill Dead by Daylight"; private readonly string KILL_MESSAGE = "Do you want to forcibly close Dead by Daylight?"; private readonly string DBD_PROCESS_NAME = "...
magicoder
csharp
You are tasked with implementing a custom data structure in C# to represent a simplified version of a binary search tree (BST). The BST should support the following operations: 1. Insertion of a new node with a given value. 2. Deletion of a node with a given value. 3. Searching for a node with a given value. 4. Travers...
```csharp using System; namespace CustomDataStructures { public class BinarySearchTree { private class Node { public int Value; public Node Left; public Node Right; public Node(int value) { Value = value; ...
magicoder
csharp
You are tasked with creating a program that retrieves the number of stars for a given GitHub repository. Your program should utilize the GitHub API to fetch this information and display it to the user. You are provided with a code snippet from a TypeScript file, `git.ts`, which imports the necessary module and contains...
```typescript import fetch from 'node-fetch'; async function getRepoStars(owner: string, repo: string): Promise<number> { try { const response = await fetch(`https://api.github.com/repos/${owner}/${repo}`); if (response.ok) { const data = await response.json(); return data.stargazers_count; }...
magicoder
typescript
You are working on a data processing pipeline for analyzing astronomical spectra. One of the tasks involves generating dummy spectral data for testing purposes. You need to create a Python function that generates a dummy spectral data specification based on the provided parameters. Write a Python function `generate_du...
```python import numpy as np def generate_dummy_spec(wave=None, npix=2000, s2n=10.0, seed=None): if wave is None: wave = np.linspace(4000, 7000, npix) # Default wavelength range if not provided dummy_spec = { 'wave': wave, 'npix': npix, 's2n': s2n, 'seed': seed } ...
magicoder
python
You are tasked with implementing a function that calculates the total number of test cases in a given Jest test suite. Jest is a popular JavaScript testing framework commonly used for unit testing. Test cases are defined using the `it` function, which takes a description and a callback function as arguments. The descri...
```javascript function countTestCases(testSuiteCode) { const itFunctionRegex = /it\(['"](.+?)['"],\s*()?\s*=>/g; const matches = testSuiteCode.match(itFunctionRegex); return matches ? matches.length : 0; } ``` The `countTestCases` function uses a regular expression to match occurrences of the `it` function calls ...
magicoder
javascript
You are tasked with implementing a custom data structure to manage a table view in a mobile application. The data structure should support the following operations: 1. `return 1`: A method that returns the number of rows in the table view. 2. `cellForRow(_ row: Int) -> UITableViewCell`: A method that returns the cell ...
To implement the custom data structure for managing the table view, you can use a class that encapsulates the necessary data and methods. Here's a possible implementation using Swift: ```swift class CustomTableView { private var cells: [UITableViewCell] init(cells: [UITableViewCell]) { self.cells ...
magicoder
swift
You are tasked with creating a Python script that processes a FreeMind outline file and generates an output file. Your script should take the path to the FreeMind outline file as a command-line argument and produce an output file in a specified directory. Additionally, the script should perform a comparison between the...
```python import sys import os import subprocess def generate_outline(input_file, output_dir): if not os.path.exists(input_file): print("Error: Input file does not exist.") return if not os.path.exists(output_dir): print("Error: Output directory does not exist.") return ou...
magicoder
python
You are tasked with implementing a simple user authentication system for a command-line application. The system should allow users to register, login, and perform certain actions only when logged in. Your task is to implement the following functionalities: 1. User Registration: Users should be able to register by prov...
```python # User Authentication System Implementation class User: def __init__(self, username, password): self.username = username self.password = password self.logged_in = False class AuthenticationSystem: def __init__(self): self.users = {} def register_user(self, userna...
magicoder
python
You are tasked with creating a Python function that processes an OpenAPI specification file and modifies it based on certain conditions. The function should take into account the presence of an environment variable and make appropriate changes to the OpenAPI specification. Write a Python function `process_openapi_spec...
```python import os import yaml import connexion def process_openapi_spec(anonymous_access, specification_file_path): if anonymous_access: parsed_yaml_file = yaml.load(open(specification_file_path), Loader=yaml.FullLoader) parsed_yaml_file.pop('security', None) return parsed_yaml_file e...
magicoder
python
You are tasked with implementing a weak array data structure in Swift. A weak array is an array that holds weak references to its elements, allowing them to be deallocated when no strong references are held. Your goal is to create a `WeakArray` struct that conforms to the `Collection` protocol, allowing for iteration a...
```swift import Foundation public struct WeakArray<Element: AnyObject> { private var items: [WeakBox<Element>] = [] public init(_ elements: [Element]) { items = elements.map { WeakBox($0) } } public var startIndex: Int { return items.startIndex } public var endIndex: Int { return items...
magicoder
swift
You are tasked with implementing a custom hashable class in Python. Your class should have a method to convert its instance to a JSON-compatible format and a custom hash method. Create a class `CustomHashable` with the following specifications: - The class should have a constructor that takes a single parameter `value...
```python import json class CustomHashable: def __init__(self, value): self.value = value def to_json(self): return json.dumps(self.value) def __hash__(self): return hash(self.value) # Example usage obj = CustomHashable("example") print(obj.to_json()) # Output: "example" print(h...
magicoder
python
You are tasked with implementing a PDF processing class that handles recipient groups and their associated recipients. The class has a method for checking the consistency of the number of recipients with the length of the PDF. The code snippet provided is a part of this class and includes a private method `__check_pdf_...
```python class PDFProcessor: def __init__(self, pdf_length, start_page_index): self.pdf_length = pdf_length self.start_page_index = start_page_index def process_recipient_groups(self, recipient_groups): total_groups = len(recipient_groups) total_recipients = sum(len(group) for ...
magicoder
python
You are tasked with implementing a caching system for a web application. The caching system should store unique identifiers (IDs) of recently accessed resources to improve performance by reducing the need to fetch the same resources repeatedly. Your task is to design and implement a cache data structure that supports t...
```python class Cache: def __init__(self): self.cache = set() def addID(self, id): self.cache.add(id) def containsID(self, id): return id in self.cache def removeID(self, id): if id in self.cache: self.cache.remove(id) def getAllIDs(self): retu...
magicoder
python
You are tasked with creating a Python function that validates and processes image uploads for a gallery application. The function should ensure that the uploaded images are within the maximum file size limit and that the containers for the images are public if specified by authenticated users. You are provided with th...
```python def validate_and_process_image_upload(image_data, container_name): # Check if the container is public is_public = container_name in GALLERY_PUBLIC_CONTAINERS # Validate image size valid = len(image_data) <= GALLERY_IMAGE_MAX_FILESIZE return valid, is_public ``` The `validate_and_process...
magicoder
python
You are tasked with implementing a search functionality for a web application. The provided code snippet is a part of a TypeScript class that handles the search feature. The `search` method is called with a `term` parameter of type `string`, and it is expected to initiate a search operation. Additionally, the class has...
```typescript class SearchService { isLoading: boolean = false; constructor() { // Initialize the class } errorHandler = (err: string) => { this.isLoading = false; console.log('Something went wrong: ' + err); } search(term: string) { console.log('searching'); this.isLoading = true; //...
magicoder
typescript
You are tasked with implementing a file caching system in Swift. Your goal is to create a class that manages the caching of files by storing them in a specified directory using their base64-encoded keys. You are provided with a code snippet that includes a private method `fileUrl(_:)` within a class. This method takes...
```swift import Foundation class FileCache { let directory: String init(directory: String) { self.directory = directory } private func fileUrl(_ key: String) -> URL { let filename = key.toBase64String() let path = (directory as NSString).appendingPathComponent(filename) ...
magicoder
swift
You are tasked with implementing a trajectory clustering algorithm for analyzing users' movement data. The algorithm aims to group similar trajectory points together based on certain thresholds and parameters. Your task is to complete the code snippet provided by defining the value of the variable `RADIUS` based on the...
```python RADIUS = SCALING_FACTOR * (GROUP_SIZE_THRESHOLD + COHERENCE_THRESHOLD * TURNING_ALPHA / TURNING_BETA) ``` In the solution, the value of `RADIUS` is calculated by multiplying the `SCALING_FACTOR` with the expression `(GROUP_SIZE_THRESHOLD + COHERENCE_THRESHOLD * TURNING_ALPHA / TURNING_BETA)`. This expression ...
magicoder
python
You are tasked with implementing a graph convolutional network (GCN) for node classification using PyTorch. The GCN is a type of neural network designed to operate on graph-structured data, where nodes represent entities and edges represent relationships between them. Your goal is to complete the implementation of the ...
```python class GCN(nn.Module): def __init__( self, hidden_channels: int, num_features: int, num_classes: int, dropout: float ) -> None: super().__init__() self.conv1 = GCNConv(num_features, hidden_channels).jittable() self.conv2 = GCNConv(hidden_channels, num_classes).jittable()...
magicoder
python
You are tasked with creating a Python program that processes a document and its footnotes. The program should read a document and a list of footnotes from separate files, then update the document with the full text of each footnote. The footnotes are represented in the document by a specific tag, and the full text of e...
```python def update_document_with_footnotes(document_file, footnotes_file, output_file, verbose): with open(document_file, "r") as doc_file: document = doc_file.read() with open(footnotes_file, "r") as footnotes_file: footnotes = footnotes_file.read().split("\n\n") for footnote in footnot...
magicoder
python
You are given a 2D grid representing a map of land and water. Each cell in the grid can either be land (denoted by 1) or water (denoted by 0). The grid is surrounded by water on all sides. You need to calculate the perimeter of the land in the grid. The perimeter of the land is the length of the boundary between the la...
```python from typing import List def calculate_perimeter(grid: List[List[int]]) -> int: perimeter = 0 for r in range(len(grid)): for c in range(len(grid[r])): if grid[r][c] == 1: for dx, dy in ((0, 1), (1, 0), (-1, 0), (0, -1)): nx, ny = r + dx, c + dy ...
magicoder
python
You are tasked with implementing a custom exception class and using it within a C++ program. Your task is to create a class called `copy_not_implemented` that inherits from the standard library exception class. The `copy_not_implemented` class should override the `what()` method to return a specific error message. Addi...
```cpp #include <iostream> #include <exception> class copy_not_implemented : public std::exception { public: const char *what() const throw() { return "Masolas nincs implementalva!"; } }; int main() { try { throw copy_not_implemented(); } catch (const std::exception& e) { std::cerr << "Exception caught:...
magicoder
cpp
You are tasked with simulating a simplified version of a multi-threaded system. The system consists of two types of threads: `PcThread` and `PcExploreRunThread`. The `PcThread` is responsible for interfacing with a PC's serial API and Android API, while the `PcExploreRunThread` is designed to utilize the `PcThread`'s A...
```python class PcThread: def __init__(self, name, serial_api, android_api): self.name = name self.serial_api = serial_api self.android_api = android_api self.pc_api = PcApi(serial_api, android_api) class PcExploreRunThread: def __init__(self, name, pc_api): self.name = ...
magicoder
python
You are tasked with creating a Python function that processes and analyzes time-series data from environmental sensors. The function should identify and flag any instances where the sensor readings exceed predefined limits. You are given a code snippet that represents a part of the visualization process for the time-s...
```python def flag_sensor_limits(datetime, *sensor_readings): flagged_timestamps = [] limits = {'Shroud1': 100, 'Shroud2': 100, 'channel_11': 50, 'channel_12': 50, 'channel_13': 50, 'channel_26': 200, 'channel_27': 200, 'channel_28': 200} for i in range(len(datetime)): for sensor, rea...
magicoder
python
You are tasked with implementing a custom binary operator in Python that checks if a given object contains a specified value. The code snippet provided gives a glimpse of the implementation, but it is incomplete. Your task is to complete the implementation of the custom binary operator and create a function that utiliz...
```python from typing import Any, TypeVar, Callable # Complete the implementation of the custom binary operator ContainsOperator class ContainsOperatorMeta(type): def __new__(cls, name, bases, dct): dct['__args__'] = "contains", return super().__new__(cls, name, bases, dct) class BinaryOperator: ...
magicoder
python
You are tasked with implementing a function to recursively search for files in a directory and its subdirectories. The function should return a list of all the files found in the directory and its subdirectories. You are given a code snippet that demonstrates part of the recursive file search process. The snippet show...
```cpp #include <iostream> #include <vector> #include <string> #include <filesystem> std::vector<std::string> getFilesList(const std::string& directory) { std::vector<std::string> filesList; for (const auto& entry : std::filesystem::directory_iterator(directory)) { if (entry.is_regular_file()) { ...
magicoder
cpp
You are tasked with implementing a function that processes a list of expressions and returns a modified list based on certain conditions. The function takes a list of expressions as input and should perform the following operations: 1. If the input list is empty, the function should return an error message indicating ...
```cpp #include <list> #include <string> #include <memory> class ScriptCompiler { public: static bool isCommandBreakSign(char c) { return c == ';'; } void setErrorText(const std::string& error) { // Implementation not provided } }; using ExpressionRef = std::shared_ptr<std::string>; ...
magicoder
cpp
You are tasked with creating a script to automate the process of creating accounts and generating API keys for a service. The script will interact with a RESTful API to achieve this. The API endpoints and payload data are provided in the code snippet below. Your task is to write a script that performs the following st...
```bash #!/bin/bash # Send a POST request to create the account and extract the ID ID=$(curl -X POST -H 'Accept: application/json' -H 'Content-Type: application/json' -d '{"kind":"service", "name":"service", "uuid":"service"}' 'http://192.168.11.212:8080/v1/accounts' | jq -r '.id') # Send a POST request to create AP...
magicoder
shell
You are tasked with creating a Python program to scrape and process data from a news website using Selenium. The program should extract the summary and publish date of news articles from the website and store them in separate lists for further processing. Your task is to complete the Python program by implementing the...
```python from selenium import webdriver # Initialize the lists to store the scraped data summary_list = [] date_list = [] # Implement the function to scrape the summary def scrape_summary(driver, summary_list): summaries = driver.find_elements_by_css_selector('.cnn-search__result-body') for summary in summar...
magicoder
python
You are tasked with implementing a Python class for handling unit prefixes in scientific calculations. The class should be able to parse prefix definitions from strings and perform conversions between different units using the defined prefixes. Your task is to implement the `PrefixDefinition` class, which represents a...
```python class Converter: def __init__(self, factor): self.factor = factor def to_reference(self, value): return value / self.factor class PrefixDefinition: def __init__(self, name, aliases, converter): self.name = name self.aliases = aliases self.converter = conve...
magicoder
python
You are working on a project that involves running a computational kernel on a GPU to perform complex number calculations. The given code snippet is a part of the GPU kernel function that takes complex numbers as input and computes a cost and gradient values. Your task is to implement a Python function that simulates t...
```python import numpy as np def compute_gradient_cost(z, zi, ws, Nbd, Nb, Ng, N, dtype): if zi is None: indata = np.concatenate([z.real, z.imag]) else: indata = np.concatenate([z, zi]) indata = np.ascontiguousarray(indata.astype(dtype)) # Simulate GPU computation outdata = np.zero...
magicoder
python
You are tasked with creating a class that simulates a simple web browser. The class, `WebViewController`, should be able to load a given URL and provide basic functionality for interacting with the web page. Your task is to implement the `WebViewController` class with the following requirements: - The class should hav...
```swift class WebViewController { var url: String init(url: String) { self.url = url } func loadURL(_ url: String) { self.url = url } func open() { print("Opening web page at \(url)") // Additional code to actually open the web page can be added he...
magicoder
swift
You are working on a music synthesis library in Python and need to implement factory classes for different types of sound envelopes and waveforms. An envelope is a graph of amplitude against time, used to control the loudness of a sound over time, while a waveform is a representation of a sound wave in the time domain....
```python class SAMEnvelope: def __init__(self, amplitude_values, time_values): self.amplitude_values = amplitude_values self.time_values = time_values class SAMEnvelopeFactory: def create_envelope(self, amplitude_values, time_values): return SAMEnvelope(amplitude_values, time_values) ...
magicoder
python
You are tasked with creating a Python program to retrieve information from a remote SNMP (Simple Network Management Protocol) agent using the PySNMP library. The program should be able to fetch and display the system description and contact information from the remote SNMP agent. You are provided with the following co...
```python from pysnmp.hlapi import * def snmp_get(system_oid, contact_oid, target): errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), CommunityData('public', mpModel=0), target, ContextData(), ObjectType(ObjectIdentit...
magicoder
python
You are tasked with creating a Python function that processes a dataset and handles potential errors. The function should perform certain operations on the input data and then assert the shape of the resulting data. If the assertion fails, the function should remove a specified directory and raise an exception. Your ta...
```python import numpy as np import shutil def process_data(x_train, test_path): try: assert x_train.shape == (3000, 2) # Perform operations on the input data processed_data = x_train # Placeholder for actual processing return processed_data except AssertionError: shuti...
magicoder
python
You are tasked with creating a PHP class that manages a list of gemstones for a jewelry store. The class should have the ability to add new gemstones, remove existing ones, and display the list of gemstones. Additionally, the class should have a method to set the active menu for the jewelry store's website. Create a P...
```php abstract class JewelryManager { abstract protected function setActiveMenu($menu); } class GemManager extends JewelryManager { protected $gemstones = []; protected $activeMenu; public function __construct() { $this->activeMenu = "gemstones_menu"; } public function addGemstone($g...
magicoder
php
You are tasked with implementing a class method that fetches tweets based on a specified tweet type. The class `Tweets` has a method `get()` that retrieves tweets using the Twitter API. Your task is to complete the `_fetch` method in the given class, which takes a `tweet_type` parameter and returns the fetched tweets. ...
```python def _fetch(self, tweet_type): # Create an instance of the Tweets class, passing in the Twitter API, screen name, last tweet ID, and the specified tweet_type tweets = Tweets(self.api, self.screen_name, self.last_tweet_id, tweet_type=tweet_type) # Call the get() method on the created Tweets instance...
magicoder
python
You are tasked with creating a program that simulates a simple module loader for a programming language. The module loader should be able to load and execute functions from external modules. Each module contains a set of functions that can be called from the main program. The module loader should be able to dynamically...
```python # Module loader implementation class ModuleLoader: def __init__(self): self.loaded_modules = {} def load_module(self, module_name): try: module = __import__(module_name) self.loaded_modules[module_name] = module print(f"Module '{module_name}' loaded...
magicoder
python
You are tasked with creating a Swift program to manage and display the results of a simple game. The game can result in three outcomes: the computer wins, the player wins, or it's a draw. The provided code snippet shows a `GameResultViewViewModel` struct that is used to represent the game result in the view. The struct...
```swift // Define the GameResult enum enum GameResult { case computerWins case playerWins case draw } // Define the StringConstants struct struct StringConstants { struct GameResult { static let computerWins = "Computer Wins" static let playerWins = "Player Wins" static let dra...
magicoder
swift
You are working on a project that involves generating and organizing experimental results and images. The provided code snippet is part of a Python script that handles the organization of these files. The script uses the `os` and `subprocess` modules to manipulate directories and execute shell commands. Your task is t...
```python import os import subprocess ROOT_PATH = "/path/to/root" def genFig8WithCOST(quick_run=False): exp_results_path = os.path.join(ROOT_PATH, "exp-results") images_path = os.path.join(ROOT_PATH, "images") if not os.path.exists(exp_results_path): os.mkdir(exp_results_path) if not os.path....
magicoder
python
You are tasked with creating a program that processes a given string to remove all the commented lines. A commented line is defined as any line that starts with the symbol "//". The program should take a string as input and return the modified string with all the commented lines removed. For example, given the input s...
```python import re def remove_commented_lines(s): s_without_commented_lines = re.sub(pattern='//.*\n', repl='', string=s) return s_without_commented_lines ``` The `remove_commented_lines` function uses the `re.sub` method to replace all the lines starting with "//" with an empty string, effectively removing ...
magicoder
python
You are tasked with creating a Python program that processes a sequence of numbers provided by the user. The program should prompt the user to input a sequence of numbers between 1 and 10, separated by commas. The number of elements in the sequence should be even. If the user inputs a non-numeric value, the program sho...
```python def main(): try: seq = input("Type sequence of number 1-10, comma separated. Number of elements should be even:\t") list_of_num = [int(elem) for elem in seq.split(",")] if len(list_of_num) % 2 != 0: print("Number of elements is not even. Exit") return ex...
magicoder
python
You are working on a bioinformatics project that involves analyzing DNA sequences. In the project, you have a Python package structure with the following imports in a file named `main.py`: ```python from .utils import * from .models import * from .dna import * ``` Your task is to create a function that processes DNA ...
```python # main.py from .utils import * from .models import * from .dna import * def process_dna_sequence(dna_sequence): # Preprocess and analyze DNA sequence using functions and classes from utils.py and models.py preprocessed_data = utils.preprocess_dna(dna_sequence) analyzed_data = models.analyze_dna(p...
magicoder
python
You are tasked with implementing a Python class that performs text processing for a sentiment analysis model. The class should include methods for initializing the model, performing a forward pass, and updating the model parameters based on the loss. The model uses an embedding layer to convert input text into numerica...
```python import torch import torch.nn as nn import torch.optim as optim class SentimentAnalysisModel: def __init__(self, embedding): self.embedding = embedding self.word_dict = None self.model = nn.Sequential( nn.Linear(embedding.embedding_dim, 128), nn.ReLU(), ...
magicoder
python
You are tasked with creating a build automation tool similar to `make` for a simplified programming language. Your tool should be able to handle dependencies between source files and execute the necessary commands to build the final executable. You are given a list of source files and their dependencies in the followi...
```python from collections import defaultdict, deque def build_order(source_files): dependencies = defaultdict(list) dependents = defaultdict(list) for source, deps in source_files.items(): dependencies[source] = deps for dep in deps: dependents[dep].append(source) build_or...
magicoder
python
You are tasked with implementing a music bot using the Discord.py library. The bot should be able to play music from a local drive and manage a playlist. You are provided with a partial code snippet that includes the initialization of a Discord Cog class and a command to play music from the local drive. Your task is t...
```python import config from discord.ext import commands class MyCog(commands.Cog): def __init__(self, client): self.client = client self.playlist = [] @commands.command(pass_context=True) # play from local drive async def playlocal(self, ctx, name="random", id=0): if len(self.cli...
magicoder
python
You are tasked with creating a Python function that generates a migration file for a Django project. The migration file should include the necessary dependencies and operations to modify the database schema. You are given the following information: - The name of the app for which the migration is being created (e.g., ...
```python def generate_migration_file(app_name: str, previous_migration: str) -> str: migration_content = f"from django.db import migrations\n\n" \ f"class Migration(migrations.Migration):\n" \ f" dependencies = [\n" \ f" ('{app_name}...
magicoder
python
You are tasked with implementing a data structure to manage a collection of nodes in a graph. The given code snippet provides a partial implementation of a `NodeArgs` enum and its associated methods in Rust. The `NodeArgs` enum represents different configurations of node arguments, and the methods `args` and `args_mut`...
```rust // Complete the implementation of the NodeArgs enum and its methods #[derive(Debug)] pub enum NodeArgs { Base(Vec<NodeId>), BaseFi(Vec<NodeId>), Address(NodeId), BaseOff(Vec<NodeId>), AddressOff(Vec<NodeId>), BaseFiAlignOff(Vec<NodeId>), BaseFiAlignOffOff(Vec<NodeId>), BaseFiOff(...
magicoder
rust
You are given a list of upcoming programming contests and a string representing the name of a contest that has been completed. Your task is to write a program that removes the completed contest from the list and then prints the name of the next upcoming contest. Write a Python program that takes the input string repre...
```python completed_contest = input() upcoming_contests = ["CodeChef", "AtCoder", "Codeforces", "TopCoder"] upcoming_contests.remove(completed_contest) print(upcoming_contests[0]) ``` The solution takes the input string representing the completed contest and the list of upcoming contests. It then removes the completed...
magicoder
python
You are given a list of passport data in a specific format. Each passport is represented as a sequence of key-value pairs separated by spaces or newlines. The passports are separated by blank lines. A passport must contain the following fields: - byr (Birth Year) - iyr (Issue Year) - eyr (Expiration Year) - hgt (Heigh...
```python def count_valid_passports(passport_data: str) -> int: passports = passport_data.strip().split('\n\n') required_fields = {'byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'} valid_count = 0 for passport in passports: fields = passport.replace('\n', ' ').split() field_dict = dict(f...
magicoder
python
You are tasked with implementing a function that performs subsampling of regions of interest (ROIs) and ground truth offsets for a machine learning model. The function takes in three input arrays: `sample_rois`, `sample_gt_offsets`, and `sample_labels`. The `sample_rois` array contains information about the regions of ...
```python def _subsampling_roi_and_gt(sample_rois, sample_gt_offsets, sample_labels): # Perform subsampling logic here # Replace the following line with the actual subsampling implementation subsampled_rois = sample_rois subsampled_gt_offsets = sample_gt_offsets subsampled_labels = sample_labels ...
magicoder
python
You are tasked with refactoring a method for copying gateway logs and moving it to a configuration file. The original method iterates through a list of gateway hosts, collects logs from specified files, and saves them with a timestamp appended to the filename. Your task is to refactor the code to move the file list and...
Refactored code with configuration file: ```python # config.py log_config = { 'files': ['/var/log/messages'], 'filename_format': '{}_{}_{}.log' # Format for saved log file names } ``` Refactored method to copy gateway logs: ```python import time from config import log_config class LogCopier: def __init...
magicoder
python
You are tasked with implementing a function that calculates the length of a valid UTF-8 sequence in a given byte array. UTF-8 is a variable-width character encoding capable of encoding all 1,112,064 valid code points in Unicode using one to four one-byte (8-bit) code units. The length of a valid UTF-8 sequence is deter...
```swift @inlinable internal func fastUTF8ScalarLength(endingAt i: Int) -> Int { var length = 0 var index = i while index >= 0 { let byte = UInt8(byteArray[index]) if (byte & 0xC0) != 0x80 { break } length += 1 index -= 1 } return length } ``` In t...
magicoder
swift
You are working as a software developer for a company that specializes in developing auditing software for Linux operating systems. Your task is to create a program that processes audit policy rules and performs specific actions based on the rules. The audit policy rules are stored in files with a specific naming conve...
```python import re import os def process_test_script(test_script_snippet): # Extracting file path, stars, and delete command using regular expressions pattern = r'<filename>(.*?)<gh_stars>(\d+)\+\n(.*)' match = re.match(pattern, test_script_snippet) if match: file_path = match.group(1) ...
magicoder
python
You are tasked with implementing a generic function that resets the value of a given type to its default state. The function should be able to handle various types, including integers, floats, and custom types. Your task is to create a generic function `reset_value` that takes no parameters and returns the default valu...
```rust // Define a trait to provide a default value for types trait Resettable { fn reset_value() -> Self; } // Implement the trait for built-in types macro_rules! impl_resettable { ($t:ty, $default:expr) => { impl Resettable for $t { fn reset_value() -> Self { $default ...
magicoder
rust
You are working on a computer vision project that involves processing images and calculating rays for a tourism application. The code snippet provided is part of the image processing pipeline. The `pixels` variable contains the reshaped image data, and the `rays_o` and `rays_d` are obtained by calling the `get_rays_tou...
```python import numpy as np def get_rays_tourism(H, W, kinv, pose): # Calculate the pixel coordinates i, j = np.meshgrid(np.arange(W), np.arange(H)) pixel_coords = np.stack((i, j, np.ones_like(i)), axis=-1) pixel_coords = pixel_coords.reshape(-1, 3) # Calculate the rays rays_d = np.dot(pixel_...
magicoder
python
You are tasked with implementing a program that can parse and extract information from a custom document format. The document format is represented by a code snippet as follows: ``` /** * Код документа */ ``` Your task is to write a function or method that takes a string representing the document and ex...
```python def extractDocumentContent(document): start_index = document.find("/*") + 3 end_index = document.find("*/") if start_index != -1 and end_index != -1: return document[start_index:end_index].strip() else: return "No comment block found in the document." ``` The `extractDocumentC...
magicoder
python
You are working on a graphics application that utilizes the OpenSceneGraph (OSG) library. The code snippet provided is a part of a Python script that interacts with the OSG library. The script handles keyboard events to modify certain properties of a graphics object. The `_gt` object is an instance of a graphics tool ...
```python class GraphicsTool: def __init__(self): self.filterWidth = 1.0 self.filterBias = 0.0 def getFilterWidth(self): return self.filterWidth def setFilterWidth(self, width): self.filterWidth = width def getFilterBias(self): return self.filterBias def s...
magicoder
python
You are tasked with simulating a fire-fighting scenario using a Python environment called `EnvFireFighter`. The environment provides a function `generate_tgt_list(agt_num)` that takes an integer `agt_num` as input and returns a list of target locations for the fire-fighting agents to extinguish. Each target location is...
```python from env_FireFighter import EnvFireFighter import random import math def calculate_total_distance(agt_num): env = EnvFireFighter() # Initialize the environment tgt_list = env.generate_tgt_list(agt_num) # Get the target list total_distance = 0 # Calculate the total distance current_loca...
magicoder
python