query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with creating a Java program to manage a simple inventory system for a small retail store. The program should allow the user to add new products, update existing products, remove products, and display the current inventory. You are provided with a partial code snippet that includes the necessary imports...
```java import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.*; import javax.swing.table.DefaultTableModel; public class InventoryManagementSystem { private ArrayList<Product> inventory; private JFrame mainFrame; private JTable inventoryTab...
magicoder
java
You are tasked with implementing a downloader middleware for a web scraping application. The middleware should utilize Selenium to handle the downloading of web pages. The provided code snippet configures the middleware and enables the use of Selenium for web scraping. Your task is to create a Python class that serves...
```python from scrapy.http import HtmlResponse from selenium import webdriver from scrapy import signals from scrapy.exceptions import NotConfigured class SeleniumDownloaderMiddleware: @classmethod def from_crawler(cls, crawler): if not crawler.settings.getbool('SELENIUM_ENABLED'): raise No...
magicoder
python
You are tasked with implementing a file processing algorithm that reads a large input file in chunks, processes each chunk, and writes the processed data to an output file. The provided code snippet is a part of the file processing algorithm. It writes the processed data block to a temporary file and measures the time ...
```python import time input_file_path = 'input_file.txt' output_file_path = 'output_file.txt' chunk_size = 1024 # Define the chunk size for reading the input file start = time.clock() with open(input_file_path, 'rb') as input_file, open(output_file_path, 'wb') as output_file: current_byte = 0 while True: ...
magicoder
python
You are tasked with implementing a method to verify the correctness of a one-shot array or span-to-array conversion. A one-shot array is an array that is only used once and then discarded. The goal is to ensure that the conversion from a span to an array, or the direct usage of the array, produces the expected results....
```csharp public void StaticVerifyOneShotArrayDriver(TestCase testCase) { // Implementation to verify the correctness of one-shot array usage // Use testCase to perform the necessary operations and assertions } public void StaticVerifyOneShotSpanToArrayDriver(TestCase testCase) { // Implementation to verif...
magicoder
csharp
You are tasked with implementing a residual dense block for a convolutional neural network. A residual dense block is a key component in many state-of-the-art deep learning architectures, particularly in image processing tasks. The provided code snippet is the beginning of a Python class that defines a residual dense b...
```python import torch import torch.nn as nn class ResidualDenseBlock_5C(nn.Module): def __init__(self, nf=64, gc=32, bias=True): super(ResidualDenseBlock_5C, self).__init__() # gc: growth channel, i.e. intermediate channels self.conv1 = nn.Conv2d(nf, gc, 3, 1, 1, bias=bias) self.co...
magicoder
python
You are tasked with implementing a function that calculates the sum of all prime numbers within a given range. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Your function should take two integers, `start` and `end`, as input and return the sum of all prime numb...
```python def sum_of_primes(start: int, end: int) -> int: def is_prime(num): if num < 2: return False for i in range(2, int(num ** 0.5) + 1): if num % i == 0: return False return True prime_sum = 0 for num in range(max(2, start), end + 1): ...
magicoder
python
You are tasked with creating a function to convert durations (in ticks) to note names based on a given time signature. The time signature is represented by the "ppq" (pulses per quarter note) value, and the note names should be in the format of 'quarter', 'eighth', 'eighth triplet', 'sixteenth', 'thirty-second', 'thirt...
```python def duration_to_note_name(ppq, durations): def gcd(a, b): while b: a, b = b, a % b return a def lcm(a, b): return a * b // gcd(a, b) note_names = ['quarter', 'eighth', 'eighth triplet', 'sixteenth', 'thirty-second', 'thirty-second triplet', 'sixty-fourth'] ...
magicoder
python
You are tasked with implementing a trait for decoding a custom enum type in Rust. The enum `PowerStatus` represents the power state of a device, with variants `Off` and `On` corresponding to the values 0 and 1, respectively. The trait `AtDecode` provides a method `decode` for decoding the enum from a serial input strea...
```rust use std::io::Error as IoError; pub enum PowerStatus { Off = 0, On = 1, } pub trait SerialReadTimeout { // Trait definition for reading from a serial input stream with timeout } pub struct Decoder<B: SerialReadTimeout> { // Decoder implementation details } pub struct Error<E: IoError> { /...
magicoder
rust
You are tasked with creating a program to manage animations for a mobile application. The program should define a class `AnimationManager` that can create and manage different types of animations. The animations should include rotation animations and group animations. The `AnimationManager` class should provide methods...
```swift import UIKit class AnimationManager { func createRotationAnimation(duration: TimeInterval) -> CABasicAnimation { let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation") rotationAnimation.repeatCount = .greatestFiniteMagnitude rotationAnimation.fromValue = 0 ...
magicoder
swift
You are tasked with creating a script to automate the process of formatting C source files using the `uncrustify` tool. The `uncrustify` command is used to apply a specific code style configuration to C files. However, due to a known issue with `uncrustify` not being idempotent, it may flip-flop between two indentation...
```bash #!/bin/bash uncrustify="uncrustify -c .uncrustify.cfg --replace --no-backup" # Function to check if a file needs formatting needs_formatting() { file=$1 diff=$(diff -u <(cat "$file") <($uncrustify -f "$file")) [[ -n $diff ]] } # Iterate through the specified directories for dir in bin include src...
magicoder
shell
You are tasked with creating a PHP class that interacts with a database to retrieve system configuration information. The provided code snippet is a partial implementation of the `System` class, which extends the `Commons` class and is located in the `app\common\model` namespace. The class contains a method `systemBase...
```php /** * 系统配置信息 */ namespace app\common\model; use app\common\model\Commons; use \think\Db; class System extends Commons { protected $pk = 'id'; protected $name = "system_base"; /** * Retrieve system configuration value based on ID * @param string $value * @return mixed */ ...
magicoder
php
You are tasked with implementing a URL path parser for a web server framework. The framework has a class `Route` that represents a route definition, and it contains various properties and methods for handling HTTP requests. The code snippet provided defines a route named `_updateForecast` with a specific URL path patte...
```python class Route: VALIDATOR_OBJECTID = "ObjectId" # Example validation type class _updateForecast(Route): name = "updateForecast" httpMethod = Route.POST path = "/nitro/projects/{project_ID}/datasets/{dataset_ID}/forecasts/{forecast_ID}" _path_keys = { 'project...
magicoder
python
You are tasked with creating a script to automate the generation and execution of training configurations for a deep learning model using the CIFAR-10 dataset. The provided code snippet is part of a larger script that involves modifying a template configuration file, setting environment variables, and executing the tra...
```python import os def generate_and_execute_training_script(N_SECOND_ITER, NJOBS, GRES_GPU, N_TASKS_PER_NODE, TOOLS, N_FIRST_ITER): # Step 1: Read the template configuration file with open('cifar10_quick_solver_lr1.prototxt.template', 'r') as template_file: template_content = template_file.read() ...
magicoder
python
You are tasked with creating a script to automate the deployment process for a GitHub repository. The script should handle the authentication with GitHub and the deployment to Bintray based on certain conditions. Your task is to write a Bash script that accomplishes the following: 1. Set up authentication with GitHub ...
```bash #!/bin/bash # Set up authentication with GitHub using .netrc file saveGitCredentials() { cat <<EOL >> $HOME/.netrc machine api.github.com login ${GITHUB_USERNAME} password ${PASSWORD} EOL chmod 600 $HOME/.netrc } # Check if the build is not a pull request and the branch is "master" if [ "${TRAVIS_PULL...
magicoder
shell
You are tasked with implementing a Python class that performs date and time comparisons. Your class should have a method that compares two given dates and returns the result based on their year, month, day, hour, minute, second, and millisecond values. You are given a code snippet that calculates a value based on the ...
```python class Solution2: def compare(self, d1, d2): d1_list = [d1.year, d1.month, d1.day, d1.hour, d1.minute, d1.second, d1.msec] d2_list = [d2.year, d2.month, d2.day, d2.hour, d2.minute, d2.second, d2.msec] for i in range(len(d1_list)): if d1_list[i] < d2_list[i]: ...
magicoder
python
You are tasked with implementing a Python class that simulates the behavior of a simple 2D game character. The class, named `GameCharacter`, should have the following functionalities: 1. A method named `calculate_distance` that takes two points as input and returns the Euclidean distance between them. 2. A method name...
```python import math class GameCharacter: def __init__(self, maxWait, maxFrame): self.waitCount = 0 self.maxWait = maxWait self.facingChanged = False self.frame = 0 self.maxFrame = maxFrame def calculate_distance(self, pt1, pt2): x1, y1 = pt1 x2, y2 = p...
magicoder
python
You are given a Python code snippet that involves the use of the `sympy` library. Your task is to create a function that takes a mapping and an expression as input and returns the expression with the mapping applied. The mapping is a dictionary where the keys are original elements and the values are the replacements. T...
```python from sympy import Basic def apply_mapping(mapping: dict, expr: Basic) -> Basic: if expr in mapping: return mapping[expr] elif isinstance(expr, Basic): args = [apply_mapping(mapping, arg) for arg in expr.args] return expr.func(*args) else: return expr ``` The `appl...
magicoder
python
You are tasked with implementing a function that repositions a match within a given line and column in a text document. The function `reposition_match` takes four parameters: `line` (the line number), `col` (the column number), `m` (a match object), and `vv` (a variable). The match object `m` has a property `match` whi...
```python class Match: def __init__(self, match, endLine): self.match = match self.endLine = endLine class Variable: def __init__(self, value): self.value = value class TextDocument: def __init__(self, content): self.content = content def reposition_match(self, line, c...
magicoder
python
You are tasked with implementing a Python function that processes a list of environment variables and their associated file names. The function should perform several operations, including repeating file names and environment variable types, and sorting the optional environment variables. Your task is to complete the i...
```python from itertools import repeat def process_environment_variables(environment_variables): """ Process the list of environment variables and their associated file names. Args: environment_variables: A list of tuples containing environment variable names, file names, and variable types. Retu...
magicoder
python
You are tasked with creating a Python class that simulates a simple asynchronous task scheduler. The scheduler should be able to execute tasks concurrently using asynchronous execution. Your task is to implement the `AsyncTaskScheduler` class with the following specifications: - The `AsyncTaskScheduler` class should h...
```python import asyncio class AsyncTaskScheduler: def __init__(self): self.tasks = {} def schedule_task(self, coroutine_func): task_id = id(coroutine_func) self.tasks[task_id] = asyncio.create_task(coroutine_func) return task_id def get_task_status(self, task_id): ...
magicoder
python
You are given an array of integers `a` of length `n`. Your task is to implement a function `moveZerosToEnd` that moves all the zeros in the array to the end without changing the order of the non-zero elements. The function should take the array `a` and its length `n` as input and should modify the array in-place. The ...
```cpp void moveZerosToEnd(int a[], int n) { int id = 0; // Initialize a pointer to keep track of the position to place non-zero elements for (int i = 0; i < n; i++) { if (a[i] != 0) { // Swap non-zero element with the element at position id and increment id swap(a[id++], a[i])...
magicoder
cpp
You are tasked with implementing a Python function that simulates a simple text-based game. The game involves a character navigating through a grid-based world, represented by a 2D array. The character can move up, down, left, or right within the grid, and the objective is to reach a specific destination coordinate. Y...
```python def navigate_grid(grid, start, destination): rows, cols = len(grid), len(grid[0]) directions = [(0, 1), (0, -1), (1, 0), (-1, 0)] def is_valid_move(row, col): return 0 <= row < rows and 0 <= col < cols and grid[row][col] == 0 def dfs(row, col): if (row, col) == destination: ...
magicoder
python
You are tasked with implementing a specific ETL (Extract, Transform, Load) process using Python. The ETL process involves taking a dictionary of DataFrames as input, performing some transformations on the data, and then returning the transformed data in a new dictionary of DataFrames. You are provided with a base clas...
```python from typing import Dict from pyspark.sql import DataFrame from abc import ABC, abstractmethod dataset_group = Dict[str, DataFrame] class EtlBase(ABC): @abstractmethod def etl(self, inputs: dataset_group) -> dataset_group: raise NotImplementedError() class CustomEtl(EtlBase): def etl(sel...
magicoder
python
You are tasked with creating a Python function that parses a netlist file and converts it into a Skidl netlist object. The netlist file represents the connections and components of an electronic circuit. The function should take the filename of the netlist file as input and return the corresponding Skidl netlist object...
```python from skidl import Net, Part, SchLib, Pin, SKIDL, TEMPLATE def netlist_to_skidl(filename): with open(filename, 'r') as file: netlist_content = file.readlines() skidl_netlist = SKIDL() for line in netlist_content: components = line.split() component_type = components[0] ...
magicoder
python
You are tasked with implementing a module resolution algorithm for a JavaScript module system. The system uses the `export` statement to make functions and variables available for use in other modules. When a module imports another module using the `import` statement, the module resolution algorithm must determine the ...
```javascript function resolveModulePath(currentModulePath, importedModulePath) { if (importedModulePath.startsWith("/")) { // Absolute path return importedModulePath; } else if (importedModulePath.startsWith("./") || importedModulePath.startsWith("../")) { // Relative path const currentDir = curren...
magicoder
javascript
You are tasked with implementing a recursive function to select an element from an array based on a set of indices. The function takes in two parameters: `index_bits_be` - a reference to an array of elements of type `Scalar<F>`, and `array` - a reference to an array of elements of type `Scalar<F>`. The function returns...
```rust use std::error::Error; fn recursive_select<F, CS>( index_bits_be: &[Scalar<F>], array: &[Scalar<F>], ) -> Result<Scalar<F>, Box<dyn Error>> where F: Field, CS: ConstraintSystem<F>, { assert!(!array.is_empty(), "internal error in recursive_select 1"); if array.len() == 1 { retur...
magicoder
rust
You are tasked with implementing a simple physics simulation for bouncing balls in a 2D space. You are given a `Ball` class in Swift, which inherits from `UIView` and has the following properties: - `color`: A property representing the color of the ball. - `elasticity`: A property representing the elasticity of the bal...
```swift import UIKit class Ball: UIView { var color: UIColor! { didSet { self.setNeedsDisplay() } } var elasticity: CGFloat! var position: CGPoint = .zero var velocity: CGVector = .zero func updatePosition(elapsedTime: TimeInterval) { let dx = velocity.dx *...
magicoder
swift
You are tasked with implementing a function to process and analyze a list of detections from a sensor. Each detection is represented as a tuple containing the x and y coordinates of the detected object. The goal is to identify and count the number of unique objects detected within a certain range of each other. Two obj...
```python import math def count_unique_objects(detections, threshold): unique_objects = set() for i in range(len(detections)): for j in range(i+1, len(detections)): distance = math.sqrt((detections[i][0] - detections[j][0])**2 + (detections[i][1] - detections[j][1])**2) if ...
magicoder
python
You are tasked with creating a Python function that processes a JSON input to generate a list of commands based on certain criteria. The function should extract specific data from the JSON and use it to construct a list of commands for further processing. The function should handle various conditions and produce the de...
```python def generate_commands_from_json(JSON): MAX_NUM_PHYSICAL_PORTS = 4 # Assuming a specific value for MAX_NUM_PHYSICAL_PORTS class HubTCCmd: def __init__(self, sensorID, port): self.sensorID = sensorID self.port = port # Additional attributes and methods can b...
magicoder
python
You are given an array of integers `nums` and an integer `target`. Write a function `twoSum` that takes `nums` and `target` as input and returns the indices of the two numbers such that they add up to the `target`. You may assume that each input would have exactly one solution, and you may not use the same element twi...
```python from typing import List def twoSum(nums: List[int], target: int) -> List[int]: foo = {} for i, j in enumerate(nums): complement = target - j if complement in foo: return [foo.get(complement), i] foo[j] = i return None ``` The `twoSum` function initializes an em...
magicoder
python
You are working on a project to model different types of aquifers for a hydrology research institute. Aquifers are underground layers of water-bearing rock, gravel, sand, or silt from which groundwater can be extracted. You have been provided with a Python code snippet that defines two classes, `Aquifer_yr` and `Aquife...
```python class Aquifer: def calculate_recharge_rate(self, area, precipitation): return area * precipitation class Aquifer_yr(Aquifer): def calculate_yield(self, recharge_rate, extraction_rate): return recharge_rate - extraction_rate class Aquifer_aa(Aquifer): def calculate_sustainability(...
magicoder
python
You are tasked with creating a program that simulates a build system for a software project. The build system uses a domain-specific language (DSL) for defining project requirements and dependencies. Your goal is to implement a simplified version of the build system that can process project requirements and generate th...
```python class BuildSystem: def __init__(self): self.requirements = {} def parse_jamroot(self, file_path): with open(file_path, 'r') as file: jamroot_content = file.read() # Parse the jamroot content and store the requirements # Implement the parsing logic t...
magicoder
python
You are tasked with creating a Python function that simulates a simple banking system. The function should allow users to create accounts, deposit funds, withdraw funds, and check their balance. Each account should have a unique account number and should store the account holder's name and current balance. The function...
```python def banking_system(): accounts = {} account_number = 1000 # Initialize account number counter def create_account(name, initial_deposit): nonlocal account_number account_number += 1 accounts[account_number] = {'name': name, 'balance': initial_deposit} def deposit(acco...
magicoder
python
You are tasked with implementing a custom content provider for a college database in an Android application. The provided code snippet outlines the initial setup for the content provider, including the definition of the content URI and the base content provider class. Your task is to extend this content provider to han...
```java import android.content.ContentProvider; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; public class StudentsProvider extends ContentProvider { ...
magicoder
java
You are working on a project that involves parsing and processing protocol buffer definitions. Protocol buffers are a language-agnostic, platform-neutral way of serializing structured data. Your task is to write a function that extracts and organizes information from a given protocol buffer definition. You are given a...
```python import re def parse_field_descriptors(code_snippet): field_descriptors = [] fields = re.findall(r"(\w+)=(.*?)(?=(\w+=)|\))", code_snippet) field_descriptor = {} for field in fields: key = field[0].strip() value = field[1].strip().strip(",") if value.startswith("_b...
magicoder
python
You are working as a bioinformatics analyst at a research institute, and your task is to automate the process of aligning DNA sequencing data using the BWA (Burrows-Wheeler Aligner) tool. The provided code snippet is a part of a shell script that automates the indexing and alignment steps using BWA. Your task is to wr...
```bash #!/bin/bash # Load BWA module module load bwa-kit/0.7.15 # Index the reference genome if [ -z "$REF" ]; then echo "Error: Reference genome file not specified. Set the REF variable to the reference genome file path." exit 1 fi if [ ! -f "$REF" ]; then echo "Error: Reference genome file not found at $REF...
magicoder
shell
You are given a string containing a series of characters. Your task is to write a function that finds the longest substring of consecutive vowels (a, e, i, o, u) within the given string. If there are multiple substrings of the same length, return the first one found. If there are no vowels in the string, return an empt...
```python def longest_vowel_substring(s: str) -> str: vowels = "aeiou" max_length = 0 max_substring = "" current_length = 0 current_substring = "" for char in s: if char in vowels: current_length += 1 current_substring += char if current_length > max_...
magicoder
python
You are tasked with implementing a custom logging system in a shell script. The logging system should support different log levels and output messages to both standard output and standard error. You are provided with a code snippet that includes a function for setting the log colors and another function for outputting ...
```bash dev_import dev io dev_import dev io cmd_color() { dev_info "This is a info message." dev_success "This is a success message." dev_warning "This is a warning message." dev_error "This is a error message." } cmd_stdout_and_stderr() { echo "message-0" echo "error-0" >&2 } log_info() { ...
magicoder
shell
You are tasked with creating a Python function that takes a directory path as input and performs a specific operation on the configuration files within that directory. The operation involves loading YAML files, merging their contents into a configuration object, and then returning the merged configuration. You are pro...
```python import os import yaml from dodo_commands.framework.config import merge_into_config from dodo_commands.framework.paths import Paths def create_config_dir(config_dir): # Initialize an empty configuration object merged_config = {} # Iterate through all the files in the specified directory for f...
magicoder
python
You are tasked with creating a Python script that simulates a scenario service for a master system. The scenario service is responsible for generating and managing various scenarios that the master system will execute. The scenarios are defined by a set of parameters and actions to be performed. Your task is to implem...
```python # Import necessary modules import threading import queue # Define the scenario class class Scenario: def __init__(self, parameters, actions): self.parameters = parameters self.actions = actions def execute(self): # Implement the execution logic for the scenario actions ...
magicoder
python
You are tasked with implementing a function to extract information about a generator model used in a deep learning framework. The function should take in various arguments related to the generator model and return specific information about its architecture. You are provided with a code snippet that initializes a gene...
```python import torch def get_generator_info(args, generator, which_layer): # Assuming the get_generator_info function retrieves information about the generator's architecture # Implement the logic to extract the required information based on the provided arguments and the generator model # For the purpos...
magicoder
python
You are tasked with implementing a class hierarchy for a menu theme system. The provided code snippet shows a private constructor for a class named `MenuTheme`, which takes a `name` and a `value` as parameters. Your task is to create the complete class hierarchy for the menu theme system, including the `MenuTheme` clas...
```csharp public class Theme { public string Name { get; set; } public int Value { get; set; } public Theme(string name, int value) { Name = name; Value = value; } } public class MenuTheme : Theme { public string BackgroundColor { get; set; } public string FontColor { get; ...
magicoder
csharp
You are working on a project that involves integrating SDL Translation Studio with a custom desktop application. As part of this integration, you need to develop a C# program that interacts with the SDL Translation Studio Automation API to perform specific translation tasks. Your task is to create a C# program that ut...
```csharp using System; using Sdl.TranslationStudioAutomation.IntegrationApi; using Sdl.TranslationStudioAutomation.IntegrationApi.Extensions; namespace TranslationProjectDetails { class Program { static void Main(string[] args) { // Connect to the SDL Translation Studio Automation ...
magicoder
csharp
You are tasked with creating a program that processes geographical coordinates to determine the distance traveled by a vehicle. The input data consists of latitude and longitude coordinates, which may be provided either as individual points or as a line string. Your task is to develop a function that calculates the tot...
```php function calculateDistance($latitudes, $longitudes) { $distance = 0; $radius = 6371; // Earth's radius in kilometers // Calculate distance for individual points if (count($latitudes) == 1) { return $distance; // No movement, distance is 0 } // Calculate distance for line string ...
magicoder
php
You are tasked with implementing a custom data structure called `SortedStack` that behaves like a stack but maintains its elements in sorted order. The `SortedStack` class should support the following operations: 1. `push(val)`: Adds a new element `val` to the stack while maintaining the sorted order. 2. `pop()`: Remov...
```python import Inserter class SortedStack: def __init__(self): self.stack = [] def push(self, val): temp_stack = [] while self.stack and self.stack[-1] < val: temp_stack.append(self.stack.pop()) self.stack.append(val) while temp_stack: self.sta...
magicoder
python
You are tasked with implementing a Python class that simulates a download manager. The class, named `DownloadManager`, should support the following functionalities: 1. `add_download(url: str)`: A method to add a new download to the manager. The `url` parameter is a string representing the URL of the file to be downloa...
```python class DownloadManager: def __init__(self): self.downloads = [] def add_download(self, url: str): self.downloads.append({'url': url, 'status': 'pending'}) def start_downloads(self): print("Starting downloads") for download in self.downloads: # Simulate ...
magicoder
python
You are tasked with implementing a custom event handling system in a C# application. The provided code snippet is a part of a class that manages focus-related events. The `FocusExit` method is called when the focus is about to exit a particular element in the application. Your task is to complete the implementation of ...
```csharp // Custom event handler delegate for focus-related events public delegate void FocusEventHandler(object sender, FocusArgs args); public class FocusManager { // Custom event for when the focus enters an element public event FocusEventHandler FocusEnterEvent; // Custom event for when the focus exi...
magicoder
csharp
You are working on a project that involves information coupling for various modules related to natural language processing and computer vision. The code snippet provided includes imports from different modules, each responsible for information coupling in a specific domain. Your task is to create a function that dynami...
```python def initialize_info_coupler(module_name: str): module_map = { 'refcocog_infocpler': 'RefCOCOgInfoCpler', 'refclef_infocpler': 'RefClefInfoCpler', 'hatefulememes_infocpler': 'HatefulMemesInfoCpler', 'visualentailment_infocpler': 'VisualEntailmentInfoCpler', 'lxmertpr...
magicoder
python
You are tasked with creating a custom middleware in a Laravel application to perform authentication checks for specific routes. The middleware should verify if the user making the request has the necessary permissions to access the route. Your task is to implement a middleware named `PermissionMiddleware` that will c...
```php // PermissionMiddleware.php namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\Auth; class PermissionMiddleware { public function handle($request, Closure $next, $permission) { $user = Auth::user(); if ($user && $user->permissions && in_array($permission, $user-...
magicoder
php
You are tasked with creating a Python function that simulates a simple URL routing system similar to Django's URL patterns. The function should take a list of URL patterns and a URL as input, and then return the corresponding view function for the given URL. The URL patterns are represented as a list of tuples, where ...
```python import re def find_view_function(url_patterns, input_url): for pattern, view_function in url_patterns: if re.match(pattern, input_url): return view_function return None ``` The `find_view_function` iterates through the `url_patterns` list and uses the `re.match` function to check...
magicoder
python
You are tasked with implementing a color conversion function for a graphics library. The function takes an input color array and converts it to a proper format for further processing. The input color array can be in various formats, such as a list of strings, a numpy array of floats or integers, or a single color value...
```python import numpy as np import warnings def color_conversion(color_array): try: return _handle_array(color_array) except ValueError: warnings.warn( "Couldn't convert input color array to a proper numpy array. " "Please make sure that your input data is in a parsable...
magicoder
python
You are tasked with implementing a Python function that performs a specific type of string substitution. The function should take a string and a dictionary of substitutions as input and return the string with the substitutions applied. Substitutions should be performed in a way that ensures no partial substitutions occ...
```python def perform_substitutions(input_string, substitutions): # Sort the keys in descending order of length to ensure that longer substrings are replaced first sorted_subs = sorted(substitutions.keys(), key=len, reverse=True) # Iterate through the sorted substitutions and perform the replacements ...
magicoder
python
You are tasked with implementing a Python class that represents an image processing tool. The class should have a method to resize the image to a specified dimension. Your task is to complete the implementation of the `resize_image` method in the `ImageProcessor` class. The method should take in the new dimensions (wid...
```python class ImageProcessor: def __init__(self, image, image_dim): self._image = image self._image_dim = image_dim def resize_image(self, new_width, new_height): original_width, original_height = self._image_dim width_ratio = new_width / original_width height_ratio = ...
magicoder
python
You are tasked with implementing a function to distribute a given dataset across multiple GPUs using TensorFlow's MirroredStrategy. The function should take the dataset and the number of GPUs as input and return the distributed dataset. You are given the following code snippet as a starting point: ```python def main(...
```python import tensorflow as tf def distribute_dataset(dataset, num_gpus): # Create a MirroredStrategy for distributing the dataset strategy = tf.distribute.MirroredStrategy(devices=["/gpu:{}".format(i) for i in range(num_gpus)]) # Distribute the dataset using the strategy with strategy.scope(): ...
magicoder
python
You are tasked with creating a program to process radio signals received by a software-defined radio (SDR) device. The program needs to incorporate error handling and configuration settings based on external files. Your program should read the content of a file named "ppm-error.txt" if it exists, and store the content...
```python import os # Read ppm-error.txt file if it exists, otherwise set ppm_error to '0' if os.path.isfile('ppm-error.txt'): with open('ppm-error.txt', 'r') as file: ppm_error = file.read().strip() else: ppm_error = '0' # Define the squelch level squelch_level = 100 # Example squelch level value #...
magicoder
python
You are tasked with implementing a method to remove all special symbols from a given string. Special symbols are defined as any non-alphanumeric characters, excluding spaces. Your task is to create a Java method that takes a string as input and returns a new string with all special symbols removed. Create a method wit...
```java public class SymbolRemover { public static String removeSpecialSymbols(String input) { if (input == null || input.isEmpty()) { return input; } StringBuilder result = new StringBuilder(); for (char c : input.toCharArray()) { if (Character.isLet...
magicoder
java
You are tasked with implementing a user authentication system in Python. Your task is to create a class `User` with the following functionalities: 1. `UpdateUsername(username)`: A method to update the username of the user. 2. `UpdatePassword(password)`: A method to update the password of the user. The `User` class sho...
```python class User: def __init__(self, username, password): self.username = username self.password = password def UpdateUsername(self, username): self.username = username def UpdatePassword(self, password): self.password = password # Example usage user1 = User("user123",...
magicoder
python
You are given two arrays of integers, A and B. Your task is to write a function `intersect` that returns a list of integers representing the intersection of the two arrays. The intersection is defined as the set of elements that are common to both arrays. Each element in the result should appear as many times as it sho...
```python from collections import Counter from typing import List class Solution: def intersect(self, A: List[int], B: List[int]) -> List[int]: count_A = Counter(A) count_B = Counter(B) res = [] for num, freq in count_A.items(): if num in count_B: res.ext...
magicoder
python
You are tasked with creating a PHP script that interacts with a MySQL database using PDO (PHP Data Objects). Your script should perform the following tasks: 1. Connect to a MySQL database named "modulo_8" hosted on "localhost" with the username "root" and an empty password. 2. Create a new table named "users" with the ...
```php <?php try { // Connect to the MySQL database using PDO $pdo = new PDO('mysql:host=localhost;dbname=modulo_8', 'root', ''); // Create the "users" table $createTableQuery = "CREATE TABLE IF NOT EXISTS users ( id INT AUTO_INCREMENT PRIMARY KEY, ...
magicoder
php
You are given a graph represented as an adjacency list and you are required to determine if the graph is bipartite. A graph is bipartite if it can be colored using two colors such that no two adjacent nodes have the same color. Write a function `isBipartite(graph)` that takes in an adjacency list `graph` and returns `...
```python from collections import deque def isBipartite(graph): color = {} # Dictionary to store the color of each node q = deque() # Queue for BFS traversal for node in graph: if node not in color: # If the node has not been colored yet color[node] = 0 # Color the node with color ...
magicoder
python
You are tasked with creating a program that analyzes the frequency of words in a given text. Your program should take a string of text as input and output the frequency of each word in the text. For the purpose of this problem, a word is defined as a sequence of characters separated by spaces, and punctuation should be...
```python def word_frequency(text): # Remove punctuation and convert text to lowercase text = text.lower().replace('.', '').replace(',', '').replace('!', '').replace('?', '') # Split the text into words words = text.split() # Create a dictionary to store word frequencies frequency = {}...
magicoder
python
You are tasked with implementing a program that calculates the sum of all prime numbers within a given range. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Your program should take two integers, `start` and `end`, as input and return the sum of all prime number...
```python def sumOfPrimes(start: int, end: int) -> int: def is_prime(num): if num < 2: return False for i in range(2, int(num ** 0.5) + 1): if num % i == 0: return False return True prime_sum = 0 for num in range(start, end + 1): if is...
magicoder
python
You are tasked with creating a function that processes HTML table data and generates a specific output based on the content of the table. The function should take an HTML string as input and return a modified version of the HTML with specific changes applied. The input HTML string will contain a table with multiple ro...
```javascript function modifyTableHTML(inputHTML) { const modifiedIcon = "<div class='modified-icon'>"; const originalIcon = "<i class='fa fa-trash'></i>"; const newIcon = "<i class='fa fa-edit'></i>"; const anchorRegex = /<a\s+[^>]*>(.*?)<\/a>/g; const modifiedHTML = inputHTML.replace(anchorRegex,...
magicoder
javascript
You are working on a game bot that interacts with an API to equip items, engage in battles, and collect loot. The provided code snippet is a part of the bot's logic. The bot first equips a part using the `api.equip_part` function, then gets an opponent using the `api.get_opponent` function. After that, it iterates thro...
```python def update_strategy(loot_fight: dict, current_strategy: str) -> str: if loot_fight['battle']['result']: win_streak = loot_fight['_u']['WinStreak@Value'] if win_streak >= 10: return 'aggressive' else: return 'normal' else: return 'defensive' ``` T...
magicoder
python
You are tasked with implementing a Python class for a custom loss layer in a neural network. The provided code snippet is a part of the class definition and contains a method for setting up the layer's parameters and printing their values. Your task is to complete the implementation of the class by defining the missing...
```python class WhdrHingeLossLayer: def __init__(self, delta=0.1, margin=1.0, ratio=0.5, eval_dense=True): self.delta = delta self.margin = margin self.ratio = ratio self.eval_dense = eval_dense def setup(self, bottom, top): if len(bottom) != 2 or len(top) != 1: ...
magicoder
python
You are tasked with creating a program that analyzes the frequency of words in a given text. Your program should take a string of text as input and output the frequency of each word in the text. For the purpose of this problem, a word is defined as a sequence of characters separated by spaces. The program should ignore...
```python def word_frequency(text): # Remove punctuation and convert text to lowercase text = text.lower().replace('.', '').replace(',', '') words = text.split() frequency = {} for word in words: if word in frequency: frequency[word] += 1 else: frequency[...
magicoder
python
You are tasked with creating a simple event handling system using Java and the Akka framework. Your goal is to implement an event handler that can process events and perform specific actions based on the type of event received. You are provided with a basic event handling interface `Handler` and a test case using Akka...
```java import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.testkit.TestActorRef; import no.ks.eventstore2.Handler; import org.junit.Test; import java.util.UUID; import static junit.framework.Assert.assertTrue; // Define the event handling interface interface Handler { ...
magicoder
java
You are tasked with creating a Swift function that takes in an HTML string and returns the count of unique HTML tags present in the string. For the purpose of this problem, an HTML tag is defined as any substring enclosed within angle brackets, such as `<div>`, `<p>`, or `<a href="https://example.com">`. Your task is ...
```swift func countUniqueHTMLTags(htmlString: String) -> Int { var uniqueTags = Set<String>() let pattern = #"<[^>]+>"# let regex = try! NSRegularExpression(pattern: pattern, options: []) let matches = regex.matches(in: htmlString, options: [], range: NSRange(location: 0, length: htmlString.utf16.c...
magicoder
swift
You are tasked with implementing a notification system in a C# application. The system should allow the display of toasts in the notification area, with the ability to set an expiration time, handle click and close events, and utilize a cancellation token. Your task is to create a class `NotificationManager` with the ...
```csharp using System; using System.Threading; using System.Threading.Tasks; public class NotificationManager { private int _nextNotificationId = 1; public async Task ShowToast(string content, TimeSpan expirationTime, Action<int> onClick, Action<int> onClose, CancellationToken token) { int notifi...
magicoder
csharp
You are tasked with implementing a command-line interface for a simple text-based application. The application should support a set of predefined commands, including the ability to add, remove, and list items. Your task is to implement the functionality for the "run_command" function, which takes a command as input and...
```rust pub fn run_command(mut command: String) -> String { let mut items: Vec<String> = Vec::new(); if !command.is_empty() { let parts: Vec<&str> = command.splitn(2, ' ').collect(); match parts[0] { ":add" => { if parts.len() > 1 { items.push(par...
magicoder
rust
You are tasked with creating a Python function that processes a given text and returns a dictionary containing the frequency of each word in the text. You are provided with a code snippet that sets up a fixture for the text to be used in testing the function. Your task is to implement the `word_frequency` function, wh...
```python import re def word_frequency(text): # Convert the text to lowercase and remove punctuation text = re.sub(r'[^\w\s]', '', text.lower()) words = text.split() frequency = {} for word in words: if word in frequency: frequency[word] += 1 else: frequency...
magicoder
python
You are tasked with creating a script to automate the generation of a README file for a software project. The script should combine content from multiple files and output the final README file. Write a Bash script that performs the following tasks: 1. Concatenates the content of a file named `readme-intro.md` with the...
```bash #!/bin/bash OUT=../README.md # Concatenate the content of readme-intro.md and self-doc-gen.sh, and append Copyright.md cat ./readme-intro.md > ${OUT} echo -e "\n---\n\n" >> ${OUT} ./self-doc-gen.sh >> ${OUT} echo -e "\n---\n\n" >> ${OUT} cat ./Copyright.md >> ${OUT} ``` In the solution, a Bash script is prov...
magicoder
shell
You are tasked with implementing a thread-safe mechanism for managing authentication triggers in a Swift application. The provided code snippet includes the declaration of some relevant properties and a lock object. You need to create a class `AuthenticationManager` with the following requirements: 1. Implement a meth...
```swift import Alamofire typealias VoidClosure = () -> Void class AuthenticationManager { private var authenticatedTriggers: [VoidClosure] = [] private var authenticationRequest: DataRequest? private let lock = NSLock() func addTrigger(_ closure: @escaping VoidClosure) { lock.lock() ...
magicoder
swift
You are tasked with implementing a Python class that processes image data to identify and remove seams. A seam is a connected path of pixels in an image that has the lowest energy cost. The given code snippet imports the necessary classes `SEAM` and `TileBase` from the module `seam_data`. Your task is to create a clas...
```python from typing import List, Tuple class SeamProcessor: def __init__(self, image: List[List[int]]): self.image = image def calculate_energy(self) -> List[List[int]]: energy_map = [[0 for _ in range(len(self.image[0]))] for _ in range(len(self.image))] # Calculate energy map based...
magicoder
python
You are tasked with implementing a simple memory management system for a programming language that supports object-oriented features. The system should handle the initialization and deinitialization of objects, ensuring that memory is properly allocated and deallocated. You are given a code snippet representing the st...
To implement the memory management system, we can use a simple reference counting mechanism to track the number of references to each object. When an object is initialized, its reference count is set to 1. When an object is referenced by another object or variable, its reference count is incremented. When an object is ...
magicoder
python
You are given a list of events, each represented by a tuple containing the event name and its start time. Your task is to write a function that takes this list of events and returns a new list containing only the events that do not overlap with each other. Two events are considered to be overlapping if their start time...
```python from typing import List, Tuple def non_overlapping_events(events: List[Tuple[str, int]]) -> List[Tuple[str, int]]: events.sort(key=lambda x: x[1]) # Sort events based on start time non_overlapping = [events[0]] # Initialize the non-overlapping list with the first event for event in events[1:]:...
magicoder
python
You are tasked with creating a program that performs various operations on three input numbers. The program should calculate the sum, difference, product, quotient, and average of the three numbers. You need to write a C++ program to achieve this functionality. Your program should prompt the user to enter three number...
```cpp #include <iostream> using namespace std; int main() { float num1, num2, num3, sum, diff, prod, quot, average; cout << "Hello. Welcome to the OPERATIONS program.\n"; cout << "Please enter three numbers to use this program.\n"; cout << "(This program will calculate the sum, difference, product an...
magicoder
cpp
You are tasked with implementing a Python class for a simple ray tracer. The provided code snippet is a part of the `Emissive` class, which is a subclass of the `Material` class. The `Emissive` class is responsible for handling emissive materials in the ray tracer. It takes a color as input and initializes the `texture...
```python class Emissive(Material): def __init__(self, color, intensity, **kwargs): if isinstance(color, vec3): self.texture_color = solid_color(color) elif isinstance(color, texture): self.texture_color = color self.intensity = intensity # Intensity of the emissive ...
magicoder
python
You are tasked with implementing a function to parse experiment configurations from a file and update certain parameters based on the environment and specific requirements. Your task is to complete the function `parse_experiment_config` which takes the name of the experiment as a string and returns the updated experime...
```python import os import util def parse_experiment_config(): if "EXP" in os.environ: name = os.environ["EXP"] print("Running experiment: {} (from environment variable).".format(name)) else: name = "experiment1" config = util.get_config("experiments.conf")[name] config["log_di...
magicoder
python
You are tasked with implementing a function to calculate the repelling force exerted on an object within a 2D window. The code snippet provided contains part of the logic for this calculation. The window dimensions are represented by `win_width` and `win_height`, and the position of the object is represented by the `po...
```cpp void calculateRepellingForce(unsigned int win_width, unsigned int win_height, sf::Vector2f position, sf::Vector2f& repelling_force, float dist_threshold, float epsilon) { if (position.x < dist_threshold) { repelling_force.x += dist_threshold / position.x; } else if (position.x > win_width - dist_...
magicoder
cpp
You are tasked with creating a Python class that processes TrueType font files to extract and store information about the font's features. TrueType font files are commonly used for rendering text in various applications. Your task is to implement a class called `FontProcessor` with the following requirements: 1. The c...
```python from fontTools.ttLib import TTFont class FontProcessor: def __init__(self): self.features = [] def extract_features(self, font_file): with TTFont(font_file) as font: for table in font['GSUB'].table.FeatureList.FeatureRecord: feature = table.FeatureTag ...
magicoder
python
You are working on a distributed task processing system that utilizes Celery, a distributed task queue for Python. In this system, tasks are defined as functions and are executed asynchronously by worker processes. One of the tasks in the system is the `predict_image` task, which is responsible for making predictions o...
```python from celery import Celery from celery.exceptions import MaxRetriesExceededError # Define the Celery application app = Celery('image_processing') # Define the base class for prediction tasks class PredictTask(app.Task): abstract = True def __init__(self): # Initialize any required resources ...
magicoder
python
You are tasked with implementing a Swift class that manages a payload string and supports encoding and decoding operations. The class should have the following requirements: 1. Create a class named `PayloadManager` with a property `payloadString` of type `String`. 2. Implement an initializer `init(payload: String)` th...
```swift class PayloadManager: NSObject, NSCoding { var payloadString: String init(payload: String) { self.payloadString = payload super.init() } required init?(coder: NSCoder) { if let data = coder.decodeObject(forKey: "payloadString") as? Data { payloadStr...
magicoder
swift
You are tasked with implementing a Python function that trains a machine learning model and saves it to a file. The function should take in training data, train the model using a specified algorithm, and then save the trained model to a file in a specified format. You are provided with the following code snippet as a ...
```python import pickle from sklearn.linear_model import LinearRegression from sklearn.ensemble import RandomForestRegressor from sklearn.svm import SVR def train_and_save_model(X_train, y_train, model_type, model_params, file_path): if model_type == 'linear_regression': model = LinearRegression(**model_pa...
magicoder
python
You are tasked with creating a script to automate the testing process for a game developed in Roblox. The game is stored in a file named `studio-tests.rbxl`, and the testing script is located at `tests/init.server.lua`. The `run-in-roblox` command is used to execute the testing process. Your goal is to write a Python s...
```python import subprocess def automate_roblox_testing(game_file, testing_script): # Launch Roblox application subprocess.run(["roblox"]) # Load the game from the file subprocess.run(["roblox", "--place", game_file]) # Execute the testing script testing_output = subprocess.check_output(["rob...
magicoder
python
You are tasked with implementing a caching mechanism for a web application. The cache will store the results of expensive computations to improve performance. Your goal is to create a generic caching system that can be used to store and retrieve the results of any function. The cache should be able to handle different ...
```csharp using System; using System.Collections.Generic; public class Cache { private Dictionary<object, object> cache = new Dictionary<object, object>(); public TOutput GetOrAdd<TInput, TOutput>(TInput key, Func<TInput, TOutput> function) { if (cache.TryGetValue(key, out object result)) ...
magicoder
csharp
You are tasked with designing a data migration script for a legacy system that involves a Django model called `LegacyBillMapping`. This model is used to map legacy bill IDs to modern bill objects in a Django application. The `LegacyBillMapping` model has two fields: `legacy_id` and `bill`. The `legacy_id` field is a ch...
```python import json from myapp.models import LegacyBillMapping def migrate_legacy_bill_mappings(): legacy_mappings = LegacyBillMapping.objects.all() migrated_data = [] for mapping in legacy_mappings: migrated_data.append({ "legacy_id": mapping.legacy_id, "bill_id": mappin...
magicoder
python
You are tasked with creating a program to calculate the final amount to be paid for a purchase, along with the installment details, based on the chosen payment method. The program should take the purchase amount and the payment method as input and then output the final amount to be paid and the installment details. Th...
```python n = float(input("Enter the purchase amount: ")) n2 = int(input("Enter the payment method (1, 2, 3, or 4): ")) if n2 == 1: final_amount = n - (n * (10 / 100)) print(f'The final amount to be paid is R$ {final_amount}.') elif n2 == 2: final_amount = n - (n * (5 / 100)) print(f'The final amount t...
magicoder
python
You are tasked with implementing a module resolution system for a TypeScript project. The system should be able to resolve and export types and modules from a given file. Your task is to write a function that takes a file path and returns an object containing the exported types and modules. You are given the following...
```typescript import * as ts from 'typescript'; import * as fs from 'fs'; function resolveModuleExports(filePath: string): { types: string[], modules: string[] } { const fileContent = fs.readFileSync(filePath, 'utf8'); const sourceFile = ts.createSourceFile(filePath, fileContent, ts.ScriptTarget.Latest, true); ...
magicoder
typescript
You are tasked with creating a Python function that validates the format of an email address. The function should take a string as input and return True if the input string is in a valid email format, and False otherwise. An email address is considered valid if it follows the standard format of "username@domain.extensi...
```python import re def validate_email(email): pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$' return bool(re.match(pattern, email)) ``` The `validate_email` function uses the `re` module to define a regular expression pattern that matches the standard email format. The pattern checks for the p...
magicoder
python
You are tasked with implementing a C++ class that manages information about different types of compilers. The class, `CompilerInfoState`, should be able to store and retrieve information about C++ compilers, Dart analyzers, and fake compilers. The class should also provide a method to update the compiler information an...
```cpp #include "cxx/cxx_compiler_info.h" #include "dart_analyzer/dart_analyzer_compiler_info.h" #include "fake/fake_compiler_info.h" class CompilerInfoState { public: void UpdateCxxCompilerInfo(CxxCompilerInfo* cxx_compiler_info) { cxx_compiler_info_ = cxx_compiler_info; } void UpdateDartAnalyzer...
magicoder
cpp
You are working on a software build system that involves evaluating a set of build numbers based on given ranges. The build numbers are used as references for running tests and builds. However, the same build numbers may be referenced multiple times, leading to redundant evaluations and wasted time. To optimize the pro...
```python def get_unique_build_numbers(ranges): build_nums = set() for single_range in ranges: build_nums.update(range(single_range['start'], single_range['end'])) return build_nums ``` The `get_unique_build_numbers` function iterates through the list of ranges and uses the `range` function to gene...
magicoder
python
You are tasked with implementing a Python class that represents a multi-level neural network. The class should have an `__init__` method that initializes the network with the given input shape, number of input channels, number of levels, and number of features. The `__init__` method should also print a message indicati...
```python import tensorflow as tf class MultiLevelNet: def __init__(self, inshape, in_channels=2, levels=3, features=16): print('Initializing MultiLevelNet') self.inshape = inshape self.levels = levels self.in_channels = in_channels def build_model(self): model = tf.ker...
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 program should include the following features: - The game should start wi...
```python class Room: def __init__(self, name, description, actions): self.name = name self.description = description self.actions = actions class Player: def __init__(self, name, health): self.name = name self.health = health class Game: def __init__(self, player, ...
magicoder
python
You are tasked with implementing a class for solving a simplified elastic shell model using a Newton static solver. The given code snippet is part of a larger program and contains a method `fullSimNewtonStaticSolver` within the `ShellSolver` class. The method takes in an `ElasticSetup` object, an `ElasticState` object,...
```cpp #include <iostream> #include <Eigen/Dense> class ElasticShellModel { public: // Define member variables and methods for the ElasticShellModel class // Method to minimize the model using the initial guess initX void minimize(const Eigen::MatrixXd& model, const Eigen::VectorXd& initX) { // Im...
magicoder
cpp
You are tasked with implementing a Python class method that calculates distances between two sets of observations. The method should handle two scenarios: when `infos_first` and `infos_second` are both provided, and when either of them is `None`. If either `infos_first` or `infos_second` is `None`, the method should fa...
```python class DistanceCalculator: def distances_from_obs(self, session, obs_first, obs_second, hashes_first, hashes_second, infos_first=None, infos_second=None): if infos_first is None or infos_second is None: # fall back to standard distance calculation return super().distances_fr...
magicoder
python
You are tasked with creating a Python function that processes a given convolutional neural network (CNN) model and returns the volume size of the output tensor after passing through the model's convolutional base. The function should take the CNN model as input and return the volume size of the output tensor. The vol...
```python def get_output_volume_size(model): output_tensor_shape = model.layers[0].output_shape[1:] # Get the shape of the output tensor from the convolutional base volume_size = 1 for dim in output_tensor_shape: volume_size *= dim # Calculate the volume size by multiplying the dimensions retu...
magicoder
python
You are tasked with implementing a Python function that can manipulate a list of integers based on a given set of operations. The function should take a list of integers as input and perform the following operations in sequence: 1. Remove all even numbers from the list. 2. Double the value of each remaining number. 3....
```python from typing import List def manipulate_list(nums: List[int]) -> List[int]: # Remove all even numbers from the list nums = [x for x in nums if x % 2 != 0] # Double the value of each remaining number nums = [x * 2 for x in nums] # Sort the list in ascending order nums.sort() ...
magicoder
python
You are tasked with developing a Python script to parse a configuration file and extract specific key-value pairs. The configuration file follows a simple format where each line consists of a key-value pair separated by a colon. The keys and values may contain alphanumeric characters, underscores, and hyphens. Addition...
```python import re import os def parse_config_file(file_path: str) -> dict: config_data = {} with open(file_path, 'r') as file: for line in file: key, value = line.strip().split(': ', 1) value = value.strip() if '${' in value and '}' in value: placeh...
magicoder
python
You are tasked with creating a custom error type in Rust for a WebAssembly (Wasm) compiler. The error type should be able to display an error message when encountered during the compilation process. Your goal is to implement the custom error type and handle it appropriately in the given Rust code. Your task is to comp...
```rust #[macro_use] extern crate snafu; use snafu::Snafu; #[derive(Debug, Snafu)] enum CompileErr { #[snafu(display("Error compiling Wasm: {}", msg))] CustomError { msg: String }, } fn compile_wasm() -> Result<(), CompileErr> { // Simulate a compilation error Err(CompileErr::CustomError { ms...
magicoder
rust