query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with creating a Rust function that extracts and decodes HTML entities from a given web page. You will need to use the `reqwest`, `scraper`, and `html_escape` crates to accomplish this task. Your function should take a URL as input and return a vector of decoded HTML entities found in the page. The funct...
```rust use html_escape::decode_html_entities; use lazy_static::lazy_static; use reqwest::{Url, cookie::Jar}; use scraper::{Html, Selector}; fn extract_and_decode_html_entities(url: &str) -> Result<Vec<String>, reqwest::Error> { let response = reqwest::blocking::get(url)?; let body = response.text()?; let ...
magicoder
rust
You are working on a computer vision project that involves object detection using a deep learning framework such as PyTorch. As part of the project, you need to implement a matching algorithm to associate default boxes (dboxes) with ground truth targets for training a detection model. The provided code snippet is a par...
```python # Define the centroids2corners function to convert centered coordinates to minmax coordinates def centroids2corners(dboxes): # Calculate minmax coordinates from centered coordinates dboxes_mm = torch.zeros_like(dboxes) dboxes_mm[:, 0] = dboxes[:, 0] - 0.5 * dboxes[:, 2] # xmin = cx - 0.5*w db...
magicoder
python
You are given a list of integers representing the scores of a game. The game has a rule that a player can either take the score at the current position or skip one score and take the score at the next position. The objective is to find the maximum possible total score that can be achieved by following this rule. Write...
```python from typing import List def max_total_score(nums: List[int]) -> int: n = len(nums) if n == 0: return 0 if n == 1: return nums[0] dp = [0] * n dp[0] = nums[0] dp[1] = max(nums[0], nums[1]) for i in range(2, n): dp[i] = max(dp[i-1], dp[i-2] + nums[i...
magicoder
python
You are tasked with implementing a class `Solution` that contains a method `findMaxConsecutiveOnes` which takes in an array of integers `nums` representing a binary array (consisting of only 0s and 1s). The method should return the maximum number of consecutive 1s in the array. The method signature is: ``` int findMax...
```cpp #include <vector> using namespace std; class Solution { public: int findMaxConsecutiveOnes(vector<int>& nums) { int maxCount = 0; int count = 0; for (int num : nums) { if (num == 1) { count++; maxCount = max(maxCount, count); ...
magicoder
cpp
You are tasked with implementing a class hierarchy for testing fault behavior in a finite element modeling framework. The code snippet provided is a part of the class `TestFaultKin` and its associated data class `TestFaultKin_Data`. Your goal is to create the missing parts of the class hierarchy and implement the neces...
```cpp // Complete the TestFaultKin class hierarchy and implement the necessary methods for fault behavior simulation. // ===================================================================================================================== class pylith::faults::FaultCohesiveKin { // Add necessary members and metho...
magicoder
cpp
You are tasked with creating a Python class that filters platforms based on their attributes. The class should inherit from three different filter sets and implement specific filtering functionality. Create a class `PlatformFilterSet` that inherits from the following three filter sets: 1. `BaseFilterSet` 2. `CreatedUp...
```python from django_filters import BaseFilterSet, CharFilter, DateFilter from .models import Platform class PlatformFilterSet(BaseFilterSet, CreatedUpdatedFilterSet, NameSlugSearchFilterSet): start_date = DateFilter(field_name="created_at", lookup_expr='gte') end_date = DateFilter(field_name="created_at", lo...
magicoder
python
You are tasked with creating a Python program that retrieves real-time cryptocurrency data from the CoinMarketCap API and displays it in a user-friendly format. Your program should take a cryptocurrency symbol as a command-line argument and then fetch the corresponding data from the API. The retrieved data should be di...
```python import argparse import requests def main_activity(): # ArgParsing p = argparse.ArgumentParser() p.add_argument("coin", help="Coin to view") args = p.parse_args() api = "https://api.coinmarketcap.com/v1/ticker/{}/?convert=CAD".format(args.coin) headers = {'User-Agent': "Mozilla/5.0 (Wi...
magicoder
python
You are tasked with implementing a Python class to control a 16x2 LCD display. The class should support various functionalities such as shifting the display, moving the cursor, and setting the display entry mode. The provided code snippet includes some flags and constants that can be used to control the behavior of the...
```python class Lcd16x2: def __init__(self): # Initialize the LCD display def move_cursor_right(self): # Move the cursor one position to the right # Use _LCD_MOVERIGHT flag to control the cursor movement def move_cursor_left(self): # Move the cursor one position to the left...
magicoder
python
You are tasked with creating a Python class that calculates the distance between two shapes represented by their bitmaps. The bitmaps are stored as binary data and are used to compare the shapes' similarity. You need to implement the `ShapeDistance` class with a method `calculate_distance` that takes two instances of t...
```python import numpy as np class ShapeDistance: @staticmethod def calculate_distance(glyph1: Glyph, glyph2: Glyph) -> float: bitmap1 = np.frombuffer(glyph1.bitmap, dtype=np.uint8) bitmap2 = np.frombuffer(glyph2.bitmap, dtype=np.uint8) # Calculate Hamming distance between the ...
magicoder
python
You are given the definition of a ListNode class and a method reverseList in the ReverseLinkedList class. The ListNode class represents a node in a singly linked list and has the following structure: ```java class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } ``` The revers...
```java public class ReverseLinkedList { public ListNode reverseList(ListNode head) { ListNode prev = null; ListNode current = head; ListNode next; while (current != null) { next = current.next; current.next = prev; prev = current; cu...
magicoder
java
You are given a code snippet written in Swift. Your task is to identify and fix the syntax error in the code. Once the error is fixed, the code should be able to be parsed successfully by the Swift compiler. Code snippet: ``` // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %...
The syntax error in the given code snippet is the incomplete declaration of the `class` keyword. To fix this error, we need to complete the class declaration and provide a valid class name and body. Here's the corrected code: ```swift // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // R...
magicoder
swift
You are tasked with implementing a multi-bar slider component in Unity for a game development project. The multi-bar slider should allow the user to manipulate multiple bars simultaneously to control various parameters in the game. Each bar represents a different parameter, and the user can adjust the value of each par...
```csharp using UnityEngine; [ExecuteInEditMode] public class MultiBarSliders : MonoBehaviour { // Array of sliders representing different parameters public Slider[] sliders; // Update method to handle parameter value updates void Update() { for (int i = 0; i < sliders.Length; i++) ...
magicoder
csharp
You are tasked with creating a Python function that simulates the behavior of a pipetting robot. The robot has two pipettes, one mounted on the left and the other on the right. Each pipette has a memory that can store its unique identifier and model. Your task is to implement a function that writes the identifier and m...
```python from typing import Union class Pipette: def __init__(self, mount: str): self.mount = mount self.identifier = None self.model = None def write_to_pipette_memory(mount: str, identifier: str, model: str) -> str: left_pipette = Pipette("left") right_pipette = Pipette("right")...
magicoder
python
You are working on a package management system and need to implement a function to handle dependencies. The function takes in a set of package dependencies to add and remove, and it needs to ensure that the resulting solution is satisfiable. The code snippet provided is part of the implementation and involves manipulat...
```python def check_solution_satisfiability(solution_precs, specs_to_add, specs_to_remove): # Create a set of all package dependencies after adding and removing updated_solution = solution_precs.union(specs_to_add).difference(specs_to_remove) # Check if the updated solution is satisfiable satisfiable =...
magicoder
python
You are tasked with creating a Java program to manage repair costs for mythical items in a game. The program should read item lore and repair costs from a configuration file and store them in appropriate data structures. Additionally, it should provide functionality to calculate the total repair cost for a given item b...
```java import java.util.List; import java.util.ArrayList; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.ConfigurationSection; public class MythicItemRepairManager { private List<String> itemLore; private List<MythicRepairCost> costList; public MythicItemRepairMan...
magicoder
java
You are tasked with implementing a function that generates a broadcast schedule for a tensor operation in a computational graph. The function `tir_broadcast_schedule` takes in the output tensor shape `out_m`, input tensor shapes `input_a` and `input_b`, as well as their respective layouts. Additionally, it takes the na...
```python def tir_broadcast_schedule(out_m, input_a, input_b, output_layout, input_a_layout, input_b_layout, op_name): # Determine the dimensions of the input and output tensors out_dims = len(out_m) input_a_dims = len(input_a) input_b_dims = len(input_b) # Initialize the broadcast schedule bro...
magicoder
python
You are tasked with implementing a custom view controller in Swift that tracks the time spent on each view. The provided code snippet is a part of the view controller class. The `viewWillAppear` and `viewWillDisappear` methods are overridden to call the `viewWillAppear` and `viewWillDisappear` functions respectively. Y...
```swift // MARK: - Private properties private var startTime: Date? // MARK: - Private functions private func viewWillAppear() { startTime = Date() } private func viewWillDisappear() { if let startTime = startTime { let timeSpent = Date().timeIntervalSince(startTime) print("Time spent on \(Str...
magicoder
swift
You are tasked with creating a script to automate the installation and execution of a Node.js project. The script should handle the installation of project dependencies using npm and then start a watch process to monitor and rebuild the project when changes are detected. Your script should perform the following steps:...
```bash #!/bin/bash # Function to handle errors handle_error() { echo "Error: $1" exit 1 } # Install project dependencies using npm npm install || handle_error "Failed to install project dependencies" # Start watch process to monitor and rebuild the project npm run watch & watch_pid=$! # Monitor the watch proce...
magicoder
shell
You are tasked with implementing a custom error handling mechanism in Swift. Your goal is to create a custom error type and demonstrate its usage in a practical scenario. Create a Swift struct called `NetworkError` that conforms to the `Error` protocol. This error type should have two properties: `errorCode` of type `...
```swift import UIKit struct NetworkError: Error { let errorCode: Int let errorMessage: String } func fetchData() throws { // Simulate a network error let networkError = NetworkError(errorCode: 404, errorMessage: "Data not found") throw networkError } // Practical scenario demonstrating error han...
magicoder
swift
You are tasked with implementing a function to calculate the nth Fibonacci number using Binet's formula. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. Binet's formula provides a direct way to calculate the nth Fibonacci number wit...
```python def fibonacci_binet(n: int) -> int: phi = 1.61803398875 sqrt_5 = 5 ** 0.5 return int((phi ** n - (1 - phi) ** n) / sqrt_5) ``` The `fibonacci_binet` function calculates the nth Fibonacci number using Binet's formula. It first initializes the golden ratio \( \phi \) and the square root of 5. Then,...
magicoder
python
You are tasked with creating a program that can efficiently translate a given search term from English to Portuguese based on a predefined dictionary. The dictionary contains key-value pairs where the keys are English phrases and the values are their corresponding Portuguese translations. Your program should take a sea...
```python def translate_search_term(dictionary, search_term): if search_term in dictionary: return dictionary[search_term] else: return "Translation not found" # Example usage dictionary = { 'Search Groups': 'Buscar Grupos', 'Search Homes': 'Search Homes', 'Search Human Resources': 'Pesqu...
magicoder
python
You are tasked with implementing a function that extracts the value of the `data-xhr` attribute from an HTML element. The function should take an HTML string as input and return the value of the `data-xhr` attribute if it exists, or an empty string if the attribute is not present. Write a function `extractDataXhr(html...
```typescript function extractDataXhr(html: string): string { const match = html.match(/data-xhr="([^"]+)"/); return match ? match[1] : ''; } ``` The `extractDataXhr` function uses a regular expression to match the `data-xhr` attribute and extract its value from the input HTML string. If a match is found, it retur...
magicoder
typescript
You are tasked with creating a Python class that simulates a simple directed graph using the Park library. The graph will consist of nodes and edges, and the class should provide methods to add nodes, add edges, and perform a depth-first search (DFS) traversal of the graph. Your task is to implement the `DirectedGraph...
```python from park.spaces import Tuple, Box, Discrete, Graph, Null from park.param import config from park.utils import seeding from park.utils.directed_graph import DirectedGraph class DirectedGraph: def __init__(self): self.graph = {} # Initialize an empty graph def add_node(self, node): i...
magicoder
python
You are tasked with implementing a function that processes a list of lines from a file and identifies the lines that contain novel content. A line is considered novel if it does not appear in a reference list of lines from another file. The function should also handle cases where the lines are displayed with color, and...
```rust use std::collections::HashSet; #[derive(Debug, PartialEq, Eq, Hash)] struct Color { name: String, } impl Color { fn new(name: &str) -> Color { Color { name: name.to_string(), } } fn is_dark(&self) -> bool { // Implementation of is_dark method // Ret...
magicoder
rust
You are tasked with creating a Python function that generates a color plot of a given 2D dataset. The function should take in the dataset, x and y labels, and a title as input, and produce a color plot with a color bar, labeled x and y axes, and a title. The function signature should be: ```python def generate_color_p...
```python import matplotlib.pyplot as plt import numpy as np def generate_color_plot(data, x_label, y_label, plot_title): plt.imshow(data, cmap='viridis', interpolation='nearest') plt.colorbar() plt.xlabel(x_label) plt.ylabel(y_label) plt.title(plot_title) plt.show() # Example usage data = [[1...
magicoder
python
You are tasked with creating a custom routing constraint for an ASP.NET MVC application. The custom constraint should validate whether a given parameter value matches a specific pattern. The pattern is defined as follows: the parameter value should consist of exactly 8 characters, where the first two characters are let...
```csharp using System; using System.Web.Routing; public class AlphaNumericConstraint : IRouteConstraint { public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { if (values.TryGetValue(parameterName, out object val...
magicoder
csharp
You are given a code snippet that represents a test case for a specific instruction in x86 assembly language. Your task is to understand the instruction and its operands, and then decode the mnemonic and operands to determine the exact operation being performed. The code snippet represents a test case for the `VFMADD1...
The `VFMADD132PS` instruction performs a vector floating-point multiply-add operation, where the first and third operands are multiplied and then added to the second operand. In this specific test case, the instruction operates on 512-bit vectors of single-precision floating-point values. The operands in the test case...
magicoder
assembly
You are tasked with implementing a Merkle Tree comparison algorithm. A Merkle Tree is a fundamental data structure used in cryptography and computer science for efficiently summarizing and verifying the integrity of large sets of data. Each leaf node of the Merkle Tree is a hash of a portion of the original data, and e...
```python def diff(self, other): """ Automatically find the differences between two trees Argument other has to be a Merkle Tree Optimized if two trees have the same height """ if not isinstance(other, self.__class__): raise Exception("You have to compare Merkle Tree with Merkle Tree...
magicoder
python
You are tasked with implementing a class `ParseInput` that can parse and validate a given input string based on a specific format. The input string should consist of a series of key-value pairs separated by a delimiter. Each key-value pair should be in the format `key:value`. The class should provide methods to parse t...
```typescript export class ParseInput { private delimiter: string; constructor(delimiter: string) { this.delimiter = delimiter; } parse(input: string): Map<string, string> { const keyValuePairs = input.split(this.delimiter); const parsedMap = new Map<string, string>(); for (const pair of keyV...
magicoder
typescript
You are tasked with implementing a builder pattern for a data processing pipeline in Rust. The builder pattern is a creational design pattern that allows the construction of complex objects step by step. In this case, the pipeline will process data of type `T1` and produce a result of type `T2`. The builder has several...
```rust use std::vec::Vec; type ExtractStartFunction<T1> = Option<fn() -> T1>; type TransformFunction<T> = fn(T) -> T; type ExtractFinishFunction<T2> = Option<fn(T2) -> T2>; struct PipelineBuilder<T1, T2> { extract_start: ExtractStartFunction<T1>, transform_functions: Vec<TransformFunction<T1>>, extract_f...
magicoder
rust
You are tasked with creating a PHP function that simulates the behavior of the `get_sidebar()` function and the `get_footer()` function in a WordPress theme. The `get_sidebar()` function is responsible for including the sidebar template file, while the `get_footer()` function includes the footer template file. Your tas...
```php function custom_get($template_name) { if ($template_name === 'sidebar') { include 'sidebar.php'; } elseif ($template_name === 'footer') { include 'footer.php'; } else { // Handle invalid template names echo "Invalid template name"; } } ``` In this solution, the `c...
magicoder
php
You are tasked with creating a Python function to manage High Availability (HA) settings for a system. The function will interact with various components of the HA infrastructure and make decisions based on the current state of the system. You are provided with a code snippet that contains mock function calls and thei...
```python def manage_ha_settings(setup_maas_api, write_maas_dns_addr): # Extracting the return values from the mock function calls validate_dns_ha = setup_maas_api crm_opt_exists = setup_maas_api is_leader = setup_maas_api related_units = setup_maas_api get_cluster_nodes = setup_maas_api rel...
magicoder
python
You are given a Python class representing a convolutional neural network (CNN) architecture. The class contains several layers of depthwise separable convolutions, which are commonly used in mobile and embedded vision applications due to their efficiency. Each depthwise separable convolution layer is defined by the `co...
```python def total_parameters(self): total_params = 0 for layer in self.children(): if isinstance(layer, nn.Conv2d): total_params += layer.weight.numel() if layer.bias is not None: total_params += layer.bias.numel() elif isinstance(layer, nn.BatchNorm2d):...
magicoder
python
You are tasked with creating a Python script that utilizes the DepthAI library to perform real-time object detection on a live video stream. DepthAI is a powerful platform for building spatial AI applications, combining depth perception, object detection, and neural inference in a single device. The DepthAI library pro...
```python import cv2 import depthai # Create a pipeline pipeline = depthai.Pipeline() # Define the object detection model model_path = "path_to_object_detection_model.blob" # Replace with the actual path to the object detection model detection_nn = pipeline.createNeuralNetwork() detection_nn.setBlobPath(model_path) ...
magicoder
python
You are working on a medical imaging project and need to process NIfTI (Neuroimaging Informatics Technology Initiative) files. Your task is to write a Python function to perform specific operations on the NIfTI data and save the processed data as a NumPy array. You are given a code snippet that loads NIfTI data from a...
```python import numpy as np def process_and_save_nifti(file_name, folder, data_type, i): # Load the NIfTI data from the file data = nifti_to_nparray(file_name + '.nii') # Concatenate an end-token at the end of the volume/segmentation x = data.shape[1] y = data.shape[0] end_token = np.ones((y,...
magicoder
python
You are tasked with implementing a multi-threaded program to perform a series of mathematical operations. The program will utilize Python's threading module to concurrently execute two functions that interact through a shared queue. The `add_num` function takes a queue `q` as an argument and appends the result of subt...
```python import threading import queue results2 = [] def add_num(q): while True: num1, num2 = q.get() if num1 is None and num2 is None: break results2.append(num1 - num2) q.task_done() def take_numbers(q): numbers = [(10, 5), (20, 8), (15, 3)] # Example numbers t...
magicoder
python
You are tasked with creating a custom assertion method for a testing framework. The testing framework uses a Mink context to interact with web elements and perform assertions. Your goal is to implement a new assertion method that checks for the absence of a specific text within a grid element on a web page. You are pr...
```php public function assertElementNotContainsText(string $cssSelector, string $text): void { $element = $this->getSession()->getPage()->find('css', $cssSelector); if ($element === null) { throw new \InvalidArgumentException("The element with CSS selector '$cssSelector' was not found on the page."); ...
magicoder
php
You are tasked with creating a Python function that parses details from a web response and yields a dictionary containing specific information. The function should take a `response` object as an argument, which contains the web page content, and should extract the name, image URL, telephone number, and email address fr...
```python def parse_detail(self, response): obj = response.request.meta # Extract the size of the response content size = len(response.css("div.descricao p::text").extract()) # Extract the telephone number and email address using CSS selectors tel = response.css("div.descricao p::text").extract()[...
magicoder
python
You are tasked with creating a program that simulates a simple text-based game. The game involves a player navigating through a series of rooms, each with its own set of challenges and rewards. The player's goal is to reach the final room and claim the ultimate prize. Your task is to implement the function `navigate_r...
```python def navigate_rooms(rooms, actions): current_room = 0 for action in actions: if action in rooms[current_room]["actions"]: current_room = rooms[current_room]["next_room"] if current_room is None: return rooms[current_room - 1]["reward"] else: ...
magicoder
python
You are tasked with implementing a custom loss function in PyTorch for a semantic segmentation task. The loss function, named CEPlusDice, combines the Cross Entropy (CE) loss and the Dice loss to improve the training of the model. The CEPlusDice class has an __init__ method and a forward method. The __init__ method ini...
```python import torch import torch.nn as nn import torch.nn.functional as F class CEPlusDice(nn.Module): def __init__(self, weight=None, ignore_index=None, **kwargs): super(CEPlusDice, self).__init__() self.kwargs = kwargs self.weight = weight self.ignore_index = ignore_index ...
magicoder
python
You are tasked with creating a C++ program that manages and manipulates various types of resource information in a graphics application. The program should include the necessary headers and classes to handle resource usage, shader visibility, stencil operators, resource information, sampler information, window informat...
```cpp #include <iostream> #include <unordered_map> #include "ResourceInfo.hpp" #include "SamplerInfo.hpp" #include "WindowInfo.hpp" #include "BlendProperty.hpp" #include "DebugReport.hpp" #include "LayoutElement.hpp" enum class ResourceUsage { /* ... */ }; enum class ShaderVisibility { /* ... */ }; enum class Stencil...
magicoder
cpp
You are tasked with implementing a simple networking component for a mobile application. The networking component is responsible for making API requests to a server and handling the responses. Your goal is to create a class that encapsulates the networking functionality and an extension to a reactor class that uses thi...
```swift // NetWorking class definition class NetWorking<API: APIProtocol> { func request(_ endpoint: APIEndpoint, completion: @escaping (Result<Data, Error>) -> Void) { // Implementation of network request using the provided endpoint // ... } } // FindPswdConfirmReactor extension extension Fin...
magicoder
swift
You are tasked with implementing a function that converts all keys of an input object from snake_case to camelCase. The function should take an object as input and return a new object with the keys converted to camelCase. The camelCase conversion should follow these rules: 1. The first word is all lowercase. 2. Subse...
```javascript function objectToCamel(inputObject) { const camelCaseObject = {}; for (const key in inputObject) { if (inputObject.hasOwnProperty(key)) { const value = inputObject[key]; const camelCaseKey = key.replace(/_([a-z])/g, (match, group) => group.toUpperCase()); camelCaseObject[camelCa...
magicoder
javascript
You are tasked with creating a Telegram bot that can conduct a simple quiz game. The bot should be able to handle user commands, receive and process user answers, and handle any errors that may occur during the quiz. You will need to implement the necessary handlers and error callbacks using the python-telegram-bot lib...
```python from telegram import Update from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext # Initialize the bot and dispatcher updater = Updater("YOUR_BOT_TOKEN", use_context=True) dispatcher = updater.dispatcher # Function to handle the "/start" command and initiate the quiz def...
magicoder
python
You are tasked with implementing a Pareto Front class in Python. The Pareto Front is a concept used in multi-objective optimization to represent a set of non-dominated solutions. A solution is considered non-dominated if there is no other solution that is better in all objectives and at least as good in one objective. ...
```python class ParetoFront: def __init__(self, solutions): self.solutions = self._remove_duplicates(solutions) def _remove_duplicates(self, solutions): unique_solutions = [] for solution in solutions: if solution not in unique_solutions: is_dominated = False...
magicoder
python
You are tasked with creating a Python function that processes a list of file paths and identifies the number of files that import a specific module. Your function should take in the list of file paths and the name of the module as input and return the count of files that import the specified module. Function Signature...
```python from typing import List import re def count_imported_files(file_paths: List[str], module_name: str) -> int: import_count = 0 for file_path in file_paths: with open(file_path, 'r') as file: content = file.read() if re.search(rf"from\s+{module_name}\s+import", content) o...
magicoder
python
You are tasked with implementing a custom image processing pipeline using the Insight Segmentation and Registration Toolkit (ITK) library in C++. The provided code snippet demonstrates the initialization and configuration of an ITK image processing pipeline using the SliceBySliceImageFilter and MedianImageFilter classe...
```cpp // Include necessary ITK header files #include "itkSliceBySliceImageFilter.h" #include "itkMedianImageFilter.h" #include "itkGaussianImageFilter.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" // Define input and output image types using InputImageType = itk::Image<float, 2>; using OutputImag...
magicoder
cpp
You are tasked with creating a Python function to optimize the retrieval of stock market data using a web crawler. The web crawler has two methods for fetching 30-minute and 60-minute candlestick (k-line) data for a given stock symbol. The time taken to retrieve the data using these methods needs to be minimized. You ...
```python import time def optimize_data_retrieval(symbol, granularity): start = time.time() if granularity == "30m": data = crawler.get_30_minutes_k_data_no_adjust(symbol, []) elif granularity == "60m": data = crawler.get_60_minutes_k_data_pre_adjust(symbol, []) else: raise Valu...
magicoder
python
You are working on a system that manages offers for various categories of products. The system has a method `filterMyOffers` that filters offers based on certain criteria and a method `isDuplicatedOffer` that checks if a new offer with the same name and category already exists in the filtered offers. The `filterMyOffe...
```python def isDuplicatedOffer(self, name, categoryId): filteredOffers = self.filterMyOffers(name, 'ACTIVE', 1, categoryId) for offer in filteredOffers: if offer['name'] == name and offer['category']['id'] == categoryId: return True return False ``` In the solution, the `isDuplicatedOff...
magicoder
python
You are tasked with creating a Python function that generates a summary report for a given dataset. The function should produce kernel density estimation (KDE) plots for each numerical attribute in the dataset. The KDE plots should display the distribution of each attribute's values. You are provided with a code snipp...
```python import pandas as pd import matplotlib.pyplot as plt def plot_single_kde(data, attr): data[[attr]].plot.kde(figsize=(4, 2), legend=None) ax = plt.gca() ax.set_xlim([data[attr].min(), data[attr].max()]) ax.set_xlabel(attr, fontsize=14) ax.set_ylabel('Density', fontsize=14) def generate_kde...
magicoder
python
You are tasked with implementing a function to generate a random name for a new user account. The function should take into account the existing user names and ensure that the generated name is unique. You are provided with a list of existing user names and a function to generate a random name. You are given the follo...
```python import random import string from typing import List def gen_random_name() -> str: """Generates a random name.""" return ''.join(random.choices(string.ascii_lowercase, k=8)) def generate_unique_name(existing_names: List[str]) -> str: """Generates a unique random name not present in the existing_n...
magicoder
python
You are tasked with implementing a Python class that represents a simple bank account. The class should have methods to deposit funds, withdraw funds, and check the current balance. Additionally, the class should be able to handle overdrafts by allowing a specified overdraft limit. Your task is to implement the `BankA...
```python class BankAccount: def __init__(self, account_holder, initial_balance, overdraft_limit): self.account_holder = account_holder self.balance = initial_balance self.overdraft_limit = overdraft_limit def deposit(self, amount): self.balance += amount def withdraw(self,...
magicoder
python
You are tasked with designing a system to manage material requests and issues for an organization. The provided code snippet represents a portion of the model definitions in a Django application. Each model represents a relationship between different entities in the system. The models include `organization`, `grant`, `...
The `process_material_request` function retrieves the material request details, checks the availability of the requested material, and processes the request accordingly. If the material is available, it creates a material request issue record, updates the material quantity, and sends an email notification. If the mater...
magicoder
http
You are tasked with converting a callback-based asynchronous operation to a promise-based approach. The provided code snippet involves Microsoft Teams development, where an authentication process is initiated using a callback-based method. Your goal is to refactor the code to use promises instead of callbacks. Given t...
To convert the callback-based `msft.authentication.authenticate()` method to a promise-based approach, you can use the `Promise` constructor to wrap the asynchronous operation. Here's the refactored code: ```typescript function authenticateWithPromise(): Promise<void> { return new Promise((resolve, reject) => { ...
magicoder
typescript
You are tasked with creating a program that processes data from a weather API and provides a summary of the weather conditions for a given location. The weather data is obtained from the OpenWeatherMap API, which provides current weather information for any location on Earth. Your program should make a request to the A...
```python import requests def get_weather_summary(api_key, location): base_url = "http://api.openweathermap.org/data/2.5/weather" params = { "q": location, "appid": api_key, "units": "metric" } response = requests.get(base_url, params=params) if response.status_code == 200: ...
magicoder
python
You are given an array of integers `nums`. Your task is to find the shortest subarray that, when sorted, makes the entire array sorted in non-decreasing order. Return the length of the subarray. If the array is already sorted, return 0. For example, given the array `nums = [1, 3, 5, 4, 2]`, the subarray `[3, 5, 4]` ne...
```python from typing import List def findUnsortedSubarray(nums: List[int]) -> int: sorted_nums = sorted(nums) start, end = len(nums), 0 for i in range(len(nums)): if nums[i] != sorted_nums[i]: start = min(start, i) end = max(end, i) return end - start + 1 if e...
magicoder
python
You are tasked with implementing a custom transition animation for a navigation controller in an iOS app. The given code snippet defines two properties: `fromCenter` of type `CGPoint` and `operation` of type `UINavigationController.Operation`. The `operation` property is set to default to `.push` and has a `didSet` obs...
```swift import UIKit func createTransitionPaths(fromCenter: CGPoint, radius: CGFloat, operation: UINavigationController.Operation) -> (CGPath, CGPath) { let smallCirclePath = UIBezierPath(arcCenter: fromCenter, radius: 1, startAngle: 0, endAngle: CGFloat.pi * 2, clockwise: true).cgPath let bigCirclePath = UIB...
magicoder
swift
You are tasked with implementing a Python function that takes a directed graph as input and returns the number of strongly connected components in the graph. A strongly connected component is a subgraph in which every vertex is reachable from every other vertex. You are required to use the `retworkx` library to accompl...
```python import retworkx def count_strongly_connected_components(graph: retworkx.PyDiGraph) -> int: scc_count = 0 scc_generator = retworkx.strongly_connected_components(graph) for _ in scc_generator: scc_count += 1 return scc_count ``` The `count_strongly_connected_components` function initia...
magicoder
python
You are working with a database system that uses SQL for data manipulation. Your task is to write a SQL query to retrieve specific information from the given tables. Consider the following two SQL table creation statements: Table T: ``` CREATE TABLE T ( A INT64, B INT64, C INT64, ) PRIMARY KEY(A) ``` Table U: ...
The SQL query to retrieve the specified information from the given tables is as follows: ```sql SELECT T.A, T.B, T.C, U.X, U.Y FROM T JOIN U ON <join_condition> WHERE T.A > 100 AND U.Y < 50; ``` In the above query, `<join_condition>` should be replaced with the appropriate join condition based on the relationship bet...
magicoder
sql
You are tasked with implementing a type casting mechanism for a polymorphic system. The provided code snippet outlines a `cast_graph` class with a `cast` method that facilitates type casting between polymorphic objects. The `cast` method takes in a pointer to a polymorphic object, the source and target class IDs, a dyn...
```cpp #include <typeinfo> #include <utility> // Define class_id as an alias for a unique identifier for each class using class_id = int; class cast_graph { public: cast_graph(); ~cast_graph(); std::pair<void*, int> cast( void* p, class_id src, class_id target, class_id dynamic_id, void const* dy...
magicoder
cpp
You are tasked with implementing a program to analyze particle shower data from a high-energy physics experiment. The program takes command-line arguments to set various parameters for the analysis. The provided code snippet shows the parsing of command-line arguments using the `argparse` module in Python. Your task i...
```python import numpy as np def analyze_shower_data(args: dict) -> float: nbins = args['nbins'] tmax = args['tmax'] nsh = args['nsh'] shower_cutoff = args['cutoff'] beta = args['beta'] # Perform the analysis using the provided arguments # Example analysis (replace with actual analysis bas...
magicoder
python
You are tasked with simulating a producer-consumer problem using Java. The producer-consumer problem is a classic synchronization problem where there are two threads involved: a producer that produces data and puts it into a shared buffer, and a consumer that takes data from the buffer and consumes it. The challenge is...
```java @Override public void run() { while (true) { synchronized (buffer) { // Produce a new product Product newProduct = randomOperations.generateProduct(); // Put the product into the buffer buffer.put(newProduct); // U...
magicoder
java
You are tasked with implementing a simple numeric library in Rust to handle numerical values with units. The library should support the creation of numerical values with associated units and provide basic operations for these values. You are provided with a partial implementation of the `Numeric` struct and its associ...
```rust impl Numeric { /// Adds two numerical values with compatible units. pub fn add(&self, other: &Numeric) -> Option<Numeric> { if self.unit == other.unit { let new_value = Rational { numerator: self.value.numerator * other.value.denominator + other.value.numerator * self...
magicoder
rust
You are tasked with implementing a function to merge two sorted arrays into a single sorted array. The function should take in two arrays of integers, `arr1` and `arr2`, and return a new array containing all the elements from both input arrays in sorted order. The function signature is: ```java public static int[] mer...
```java public static int[] mergeSortedArrays(int[] arr1, int[] arr2) { int n1 = arr1.length; int n2 = arr2.length; int[] merged = new int[n1 + n2]; int i = 0, j = 0, k = 0; while (i < n1 && j < n2) { if (arr1[i] < arr2[j]) { merged[k++] = arr1[i++]; } else { ...
magicoder
java
You are tasked with implementing a method that finds reference methods asynchronously in a code analysis service. The method takes a document ID and a cancellation token as input parameters. Your task is to create a C# method that accomplishes this functionality using asynchronous programming and logging. Your method ...
```csharp public async Task<List<ReferenceMethod>> FindReferenceMethodsAsync(DocumentId documentId, CancellationToken cancellationToken) { var referenceMethods = new List<ReferenceMethod>(); try { using (Logger.LogBlock( FunctionId.CodeAnalysisService_FindReferenceMethodsAsync, ...
magicoder
csharp
You are tasked with implementing a function that serializes a given step value into a JSON object and then converts it into a vector of characters. Your task is to complete the implementation of the `EndSignal` function, which takes a `size_t` step as input and returns a shared pointer to a vector of characters contain...
```cpp #include <iostream> #include <vector> #include <memory> #include "nlohmann/json.hpp" class DataManSerializer { public: static std::shared_ptr<std::vector<char>> EndSignal(size_t step) { nlohmann::json j; j["FinalStep"] = step; std::string s = j.dump() + '\0'; std::shared_ptr<...
magicoder
cpp
You are tasked with implementing a Swift extension for the String data type. The extension should provide a computed property that converts a hexadecimal string representation into NSData. The hexadecimal string may contain characters that need to be stripped before conversion. Write a Swift extension for the String d...
```swift internal extension String { var dataFromHexEncoding: Data? { let strip = [Character]([" ", "<", ">", "\n", "\t"]) let cleanedHex = self.filter { !strip.contains($0) } guard let data = cleanedHex.data(using: .utf8) else { return nil } var...
magicoder
swift
You are tasked with implementing a preferential attachment algorithm for predicting new links in a social network. In the preferential attachment model, the likelihood of a new link forming between two nodes is proportional to the product of their degrees. Your task is to write a Python function that takes a graph and ...
```python class LinkPredictor: def __init__(self, graph): self.graph = graph def predict(self, node_pairs): pass class PreferentialAttachement(LinkPredictor): def predict(self, node_pairs): predictions = [] for pair in node_pairs: node1, node2 = pair ...
magicoder
python
You are tasked with implementing a function that utilizes the `Crypto` API to generate random values and store them in an array buffer view. The `get_random_values_with_array_buffer_view` function takes a reference to a `Crypto` object and an array buffer view as input, and returns a result containing the generated ran...
```rust use wasm_bindgen::JsValue; use js_sys::Object; use web_sys::Crypto; pub fn get_random_values_with_array_buffer_view( this: &Crypto, array: &Object, ) -> Result<Object, JsValue> { let crypto = web_sys::Crypto::get_random_values(this, array)?; Ok(crypto) } ``` In the solution, the `get_random_va...
magicoder
rust
You are tasked with creating a program to manage the emailing of PDF reports to users based on certain conditions. The program should interact with a database of users and their AWS keys, and use a template to generate the email content. The following requirements should be met: 1. The program should use a template na...
```python for user in users: if user.report_last_emailed_at is None: user.report_last_emailed_at = datetime.datetime.utcnow() db.session.add(user) db.session.commit() last_emailed_days = (now - user.report_last_emailed_at).days if last_emailed_days >= 30: for key in user.aws_...
magicoder
python
You are tasked with creating a program that simulates a simple text-based adventure game. The game will involve the player navigating through different rooms, encountering obstacles, and making decisions that affect the outcome of the game. Your task is to implement a Python program that models this text-based adventu...
```python class Room: def __init__(self, description, items, adjacent_rooms): self.description = description self.items = items self.adjacent_rooms = adjacent_rooms class Player: def __init__(self, current_room, inventory): self.current_room = current_room self.inventory...
magicoder
python
You are tasked with creating a program that can efficiently determine the number of unique contributors to a specific GitHub repository. Given a list of commit authors, your program should output the count of unique contributors to the repository. You are provided with a code snippet from a GitHub repository: ```plai...
```python def count_unique_contributors(commit_authors): unique_contributors = set(commit_authors) return len(unique_contributors) # Test the function commit_authors = ["Alice", "Bob", "Alice", "Charlie", "Bob", "David", "Alice"] print(count_unique_contributors(commit_authors)) # Output: 4 ```
magicoder
python
You are tasked with creating a Rust program that simulates a simple banking system. The program should allow users to create accounts, deposit funds, withdraw funds, and check their balance. The program should also enforce basic validation rules for account creation and fund transactions. Your program should consist o...
```rust use std::collections::HashMap; struct Account { username: String, balance: f64, } struct BankingSystem { accounts: HashMap<String, Account>, } impl BankingSystem { fn new() -> Self { BankingSystem { accounts: HashMap::new(), } } fn create_account(&mut self...
magicoder
rust
You are tasked with implementing a method to truncate a time line based on a given start time and end time. The time line is represented as an array of double values, and the method should return a new array containing only the time values that fall within the specified range. Additionally, the method should allow for ...
```java public static double[] getTruncatedTimeLine(final double[] allTimes, final double startTime, final double endTime, final boolean sorted) { // Find the index of the first element greater than or equal to startTime int startIndex = 0; while (startIndex < allTimes.length && allTimes[startIndex] < start...
magicoder
java
You are tasked with implementing a custom memory management system for a mobile application. The system should keep track of the memory usage of different components within the application and provide a way to release memory when necessary. To achieve this, you need to create a MemoryManager class that can register mem...
```swift class MemoryManager { var memoryUsage: [String: Int] = [:] var totalMemoryUsage: Int = 0 let memoryThreshold: Int init(threshold: Int) { self.memoryThreshold = threshold } func registerMemoryUsage(component: String, memory: Int) { if let previousMemory = memoryUsage[co...
magicoder
swift
You are tasked with creating a Python program that generates a plot with Chinese characters using Matplotlib. Your program should utilize the provided code snippet as a starting point and incorporate the necessary steps to display Chinese text on the plot. Additionally, you need to ensure that the plot has appropriate ...
```python import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties # Sample data for plotting x = [1, 2, 3, 4, 5] y = [2, 3, 5, 7, 11] # Create a plot plt.plot(x, y) # Set the font properties for Chinese characters chFont = FontProperties(family="SimHei") # SimHei font for Chinese characte...
magicoder
python
You are tasked with implementing a particle system for a game using object-oriented programming in TypeScript. The `ParticlesEvent` class is a subclass of the `GameEvent` class and is responsible for handling events related to particles in the game. Your task is to extend the `ParticlesEvent` class and implement the ne...
```typescript class Particle { position: { x: number; y: number }; velocity: { x: number; y: number }; color: string; size: number; lifespan: number; constructor(x: number, y: number, velocityX: number, velocityY: number, color: string, size: number, lifespan: number) { this.position = { x, y }; th...
magicoder
typescript
You are tasked with creating a program that analyzes a GitHub repository's information and provides insights into the repository's activity. Your program should specifically focus on the commit history of the repository and extract relevant statistics. Write a Python function `analyze_repository` that takes a GitHub r...
```python import requests def analyze_repository(repo_name): url = f"https://api.github.com/repos/{repo_name}/commits" try: response = requests.get(url) if response.status_code == 200: commits_data = response.json() total_commits = len(commits_data) authors =...
magicoder
python
You are working on a project that involves processing and manipulating JSON data using Java. You have been tasked with implementing a method that takes a JSON string as input and returns a specific value extracted from the JSON using JSONPath. You are provided with the following code snippet as a reference: ```java i...
```java import com.jayway.jsonpath.Configuration; import com.jayway.jsonpath.DocumentContext; import com.jayway.jsonpath.JsonPath; public class JsonExtractor { public static String extractJsonValue(String jsonString, String jsonPathExpression) { Configuration conf = Configuration.defaultConfiguration(); ...
magicoder
java
You are tasked with implementing a Python class for managing S3 encryption configurations in an EMR (Elastic MapReduce) profile. The EMR profile class provides methods for setting S3 encryption modes and keys. Your task is to complete the implementation of the `set_s3_encryption` method in the `EMRProfile` class, ensur...
```python from enum import Enum class EMRProfile: def __init__(self, default_profile): self.default_profile = default_profile self.resolved_profile = default_profile.copy() class S3EncryptionMode(Enum): SSE_KMS = 'SSE-KMS' SSE_S3 = 'SSE-S3' CSE_KMS = 'CSE-KMS' #...
magicoder
python
You are working on a Node.js application that utilizes Redux for state management and interacts with a database. Your task is to create a function that fetches data from the database and updates the Redux store with the retrieved information. The database connection is asynchronous, and you need to handle errors approp...
```javascript import configureStore from 'redux-mock-store'; import { browserHistory } from 'lib/client/api/store'; import { systemDbName, waitForConnection } from 'lib/server/db'; import * as models from 'lib/server/models'; import * as mockModels from 'lib/server/models/mocks'; const middleware = []; const mockStore...
magicoder
javascript
You are working on a security system that requires generating a hash for function names. The hash is calculated using a custom algorithm that involves bitwise operations and string manipulation. Your task is to implement a function that takes a function name as input and returns its corresponding hash value. You are g...
```python import struct def ror8(v): return ((v >> 8) & (2 ** 32 - 1)) | ((v << 24) & (2 ** 32 - 1)) def calculate_function_hash(name): function_hash = 0 for segment in [s for s in [name[i:i + 2] for i in range(len(name))] if len(s) == 2]: partial_name_short = struct.unpack('<H', segment.encode())...
magicoder
python
You are tasked with implementing a simplified version of a proof-of-work algorithm used in blockchain technology. The provided code snippet is a part of a Rust function that calculates the proof-of-work for a given block header and difficulty level. The `pow20` function is a custom implementation of the `pow_size` func...
```rust use std::error::Error; use sha2::{Digest, Sha256}; struct BlockHeader { // Define the fields of the block header } enum Difficulty { // Define the difficulty levels } fn find_nonce(bh: &BlockHeader, diff: Difficulty) -> Result<u64, Box<dyn Error>> { let mut nonce: u64 = 0; let mut hasher = Sh...
magicoder
rust
You are tasked with creating a Python function that utilizes the Behave testing framework and the Germanium library to automate the testing of a web application. The function should perform the following steps: 1. Open a web browser and navigate to a specified URL. 2. Locate a specific element on the web page using it...
```python from behave import given, when, then from germanium.static import open_browser, go_to, find, assert_true @given('the web page "{url}" is open') def step_open_web_page(context, url): open_browser() # Navigate to the specified URL go_to(url) @when('the element with CSS selector "{css_selector}" i...
magicoder
python
You are tasked with implementing a simplified version of a chainable API client using Python. The goal is to create a class that allows for dynamic method chaining to construct URLs for various API endpoints. The provided code snippet serves as a starting point for this task. Your task is to extend the `Chain` class t...
```python class Chain: def __init__(self, path=''): self._path = path def __getattr__(self, path): return Chain('%s/%s' % (self._path, path)) # Test the implementation c = Chain() url = c.users('123').repos print(url._path) # Output: /users/123/repos ``` In the solution, the `Chain` class is...
magicoder
python
You are tasked with creating a Python program to test the functionality of a gamepad connected to a computer. The gamepad has buttons and axes that need to be tested for their values and real-time readings. Your program should be able to verify the connection of the gamepad, check the values of each button, and monitor...
```python import gamepad_library # Replace with the actual library for interfacing with the gamepad def test_gamepad_connection(): # Function to verify the connection of the gamepad if gamepad_library.is_connected(): print("Gamepad connection successful") else: print("Gamepad connection fa...
magicoder
python
You are tasked with implementing a program to generate a 3D mesh for a non-periodic structure. The program should take as input the crystal structure and the bounding surfaces of the object to be cut out. The crystal structure is defined by its lattice parameters and basis atoms, while the bounding surfaces are defined...
```python def generate_mesh(lattice_parameters, basis_atoms, bounding_surfaces): # Import necessary libraries for mesh generation import numpy as np from mpl_toolkits.mplot3d.art3d import Poly3DCollection # Define function to create a cuboid mesh def cuboid_mesh(x, y, z): xx, yy, zz = np.me...
magicoder
python
You are tasked with implementing a function to guess the MIME type of a given URL. The function `guess_mime_type` takes in a URL and a default MIME type as a tuple of strings. It calls a private function `_guess_mime_type` to attempt to guess the MIME type of the given URL. If the private function returns `(None, None)...
```python def _guess_mime_type(url): # Implement the logic to guess the MIME type of the given URL # This could involve checking the file extension, making HTTP requests, or using external libraries def guess_mime_type(url, default=("application", "octet-stream")): guess = _guess_mime_type(url) if gues...
magicoder
python
You are tasked with implementing a simplified version of a key-value store using a hash table. The key-value store should support operations for adding, updating, and removing key-value pairs. Additionally, it should provide a method for committing the changes made to the key-value store. You are provided with a parti...
```csharp using System; using System.Collections.Concurrent; public class KeyValueStore { private ConcurrentDictionary<string, object>[] innerData; private KeyValuePair<string, object>[][] writeBatch; public KeyValueStore(int size) { innerData = new ConcurrentDictionary<string, object>[size]; ...
magicoder
csharp
You are tasked with implementing a label drawing callback for a mapping plugin in X-Plane. The callback function will enable the plugin to draw text labels using X-Plane's built-in labeling functionality. The plugin should be able to request an arbitrary number of text labels to be drawn. Your task is to write a funct...
```c #include <XPLMGraphics.h> void drawLabels(int numLabels, const char** labels, float* positions, int numPositions) { for (int i = 0; i < numLabels; i++) { float x = positions[i * 2]; // Extract x coordinate float y = positions[i * 2 + 1]; // Extract y coordinate XPLMDrawString(XPLM_CO...
magicoder
c
You are tasked with creating an asynchronous web service using Python's aiohttp library. Your goal is to implement an endpoint that makes a GET request to a specified URL and returns the response as plain text. You will need to write the necessary code to achieve this functionality. Your task is to complete the `aioht...
```python import aiohttp from aiohttp import web from aiohttp.web_response import PlainTextResponse HIT_URL = "https://example.com" # Replace with the actual URL to be hit async def aiohttp_single(request): async with aiohttp.ClientSession() as client: async with client.get(HIT_URL) as r: res...
magicoder
python
You are tasked with implementing a response mapping procedure for `NSManagedObject` subclasses or arrays of `NSManagedObject` subclasses. The provided code snippet is a part of a Swift library that facilitates data manipulation and mapping for Core Data entities. Your task is to create a function that generates a respo...
```swift public func responseMappingProcedure<T>(for type: T.Type) throws -> AnyProcedure<Any, T> { guard let managedObjectContext = managedObjectContext else { throw MagicalRecordMappingProcedureError.invalidManagedObjectContext } if let objectType = type as? NSManagedObject.Type { ret...
magicoder
swift
You are tasked with implementing a function to create a Tukey plot, a type of statistical visualization used to compare multiple groups of data. The function `tukeyplot` takes in the following parameters: - `results`: A list of tuples, where each tuple contains the results of pairwise comparisons between groups. - `dim...
```python import matplotlib.pyplot as plt import numpy as np def tukeyplot(results, dim=None, yticklabels=None): npairs = len(results) fig = plt.figure() fsp = fig.add_subplot(111) fsp.axis([-50, 50, 0.5, 10.5]) fsp.set_title('95 % family-wise confidence level') fsp.title.set_y(1.025) fsp....
magicoder
python
You are tasked with implementing a simple translator class in C++ that can interface with a Java-based API. The translator class is responsible for invoking methods in a Java class using JNI (Java Native Interface). Your goal is to implement the `Translator` class and its `destroy` method, which will call a correspondi...
```cpp #include <jni.h> class Translator { public: // Constructor Translator(const std::string& className) { // Initialize JNI environment and load the Java class // ... } // Destructor ~Translator() { // Release JNI resources // ... } // Methods void d...
magicoder
cpp
You are tasked with creating a Python program to manage a library of electronic components and their associated footprints. The program should provide a user interface for searching and managing parts and footprints. The code snippet provided is a part of the program and includes the import statements for two modules: ...
```python class FootprintSearchPanel: def __init__(self, library): self.library = library def search_footprints(self, keyword): results = [footprint for footprint in self.library.footprints if keyword.lower() in footprint.name.lower()] return results def add_footprint(self, new_foo...
magicoder
python
You are given a list of integers `nums` containing distinct elements. Your task is to write a function `backtrack(nums, path)` that generates all possible permutations of the elements in `nums` using backtracking. The function should return a list of lists, where each inner list represents a unique permutation of the e...
```python from typing import List def backtrack(nums: List[int], path: List[int]) -> List[List[int]]: result = [] if len(path) == len(nums): result.append(path[:]) # Append a copy of the current permutation return result for num in nums: if num not in path: # Skip elements alread...
magicoder
python
You are tasked with implementing a symbolic lambdify function for a given set of symbolic expressions. The lambdify function is used to convert symbolic expressions into callable functions that can be evaluated with numerical inputs. The provided code snippet contains some commented-out lines that demonstrate the inten...
```python import sympy as sp class SymbolicLambdify: def __init__(self): pass def lambdify(self, symbolic_expression, parameters, replacement_dict=None): if replacement_dict: symbolic_expression = symbolic_expression.xreplace(replacement_dict) func = sp.lambdify(parameters,...
magicoder
python
You are tasked with implementing a Python function that processes a list of tuples representing header mappings. Each tuple contains four elements: the renamed header, the original header, a transformation function, and a flag indicating whether an error should be raised if the original header is not found. Your functi...
```python def process_header_map(header_map: list) -> dict: result = {} for renamed, org, transform, raise_err in header_map: if org in data: result[renamed] = transform(data[org]) elif raise_err: raise ValueError(f"Original header '{org}' not found") return result ``...
magicoder
python
You are tasked with creating a Python function that processes a given file and extracts specific information from it. The file contains Python code, and the function needs to extract the author's name, contact email, file name, and version from the file's header comments. You are given a sample code snippet from a Pyt...
```python def extract_file_info(file_path: str) -> dict: with open(file_path, 'r', encoding='utf-8') as file: lines = file.readlines() header_lines = [line.strip() for line in lines if line.strip().startswith('#')] header_info = {} for line in header_lines: if line.starts...
magicoder
python
You are tasked with creating a Python class that represents a group of WMS (Web Map Service) layers. The class should have the ability to exclude certain layers, flatten the layer hierarchy, and apply custom configurations to specific layers. Additionally, you need to implement a method to configure the WMS provider as...
```python import typing as t import gws.lib.gis import gws.base.layer.types import gws.base.layer.group import provider # Assuming the provider module is available class WMSLayerGroup: def __init__( self, excludeLayers: t.Optional[gws.lib.gis.SourceLayerFilter] = None, flattenLayers: t.Opt...
magicoder
python