query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with creating a program that analyzes a given text file to determine the frequency of each word in the file. Your program should read the text file, tokenize the words, and then count the occurrences of each word. Additionally, the program should ignore common stop words (e.g., "the", "and", "is") and sh...
```python import re from collections import Counter def word_frequency_analysis(file_path): with open(file_path, 'r') as file: text = file.read().lower() # Convert the text to lowercase words = re.findall(r'\b\w+\b', text) # Tokenize the words using regular expression stop_words = {'the',...
magicoder
python
You are tasked with creating a Python function that processes a list of database migration dependencies and operations. The function should analyze the dependencies and operations to identify any potential circular dependencies within the migration plan. The input to the function will be a list of dependencies and a l...
```python def detect_circular_dependencies(dependencies, operations): graph = {} for dep in dependencies: if dep[0] not in graph: graph[dep[0]] = set() graph[dep[0]].add(dep[1]) def has_cycle(node, visited, rec_stack): visited[node] = True rec_stack[node] = True ...
magicoder
python
You are tasked with implementing a simple event system for a game engine. The game engine uses the ECS (Entity-Component-System) architecture, and events are used to trigger various actions within the game. Your goal is to create a system that processes play control events and updates the corresponding entities based o...
```rust use bevy::{ecs::system::Query, prelude::*}; struct NotationTheme { _bypass_systems: bool, // Other theme settings } enum PlayControlEvent { Play, Pause, Stop, // Other control events } struct PlayButtonShape; fn main() { // Define the system for handling play control events f...
magicoder
rust
You are given a square matrix of size `n x n` filled with zeros. Starting from the top-left corner, you need to fill the matrix with consecutive numbers in a spiral pattern, moving in the directions of right, down, left, and up. If the next cell in the current direction is already filled or out of bounds, change the di...
```python def generateSpiralMatrix(n): def dirToIndex(x, y, d): if d == "r": return (x, y + 1, "r") if y + 1 < n and matrix[x][y + 1] == 0 else (x + 1, y, "d") elif d == "d": return (x + 1, y, "d") if x + 1 < n and matrix[x + 1][y] == 0 else (x, y - 1, "l") elif d == ...
magicoder
python
You are tasked with creating a Python class to manage transactions and transaction batches for a financial system. The class should be able to perform various operations such as adding transactions, retrieving transactions by ID, and calculating the total amount for a given batch of transactions. Your task is to imple...
```python class Transaction: def __init__(self, transaction_id, amount, description): self.id = transaction_id self.amount = amount self.description = description class TransactionBatch: def __init__(self, batch_id): self.batch_id = batch_id self.transactions = [] class...
magicoder
python
You are tasked with implementing a simplified version of an app management system in Swift. The system consists of a `CoreAppManager` class that manages a collection of apps and provides functionality to select and navigate to app details. Your task is to complete the implementation of the `CoreAppManager` class by add...
```swift // CoreApp model representing an app struct CoreApp { // Properties and methods of CoreApp } // CoreAppManager class managing a collection of apps class CoreAppManager { var apps: [CoreApp] = [] var selectedApp: CoreApp? func selectApp(_ app: CoreApp) { selectedApp = app } } // N...
magicoder
swift
You are tasked with implementing a custom iterator for a data structure. The iterator should support both forward and backward traversal. The iterator should have two methods: `has_next()` which returns true if there is a next element, and `has_prev()` which returns true if there is a previous element. You need to impl...
```python class CustomIterator: def __init__(self, data): self.data = data self.index = 0 self.has_next = True self.has_prev = False def has_next(self): return self.index < len(self.data) - 1 def has_prev(self): return self.index > 0 def next(self): ...
magicoder
python
You are given a weighted directed graph with n nodes numbered from 0 to n-1. The graph is represented using an adjacency list where each node is associated with a vector of pairs, where each pair represents an edge to a neighboring node along with its weight. The code snippet provided initializes the adjacency list for...
```cpp #include <vector> #include <queue> #include <climits> using namespace std; vector<int> shortestPath(vector<pair<int, int>> adj[], int n, int src) { vector<int> dist(n, INT_MAX); dist[src] = 0; priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq; pq.push({0, src})...
magicoder
cpp
You are tasked with implementing a Principal Component Analysis (PCA) class in Python using the PyTorch library. The PCA class should have the following functionalities: fitting the model to the data, transforming the data into the principal components space, and reconstructing the original data from the principal comp...
```python import torch class PCA: def __init__(self, n_components): self.n_components = n_components self._components = None self._mean = None def fit(self, x): mean = torch.mean(x, dim=0) if torch.is_tensor(self._mean): x.sub_(mean) else: ...
magicoder
python
You are tasked with implementing a thread-safe data structure using the ScopedLock class provided. The ScopedLock class is designed to manage access to a critical section, ensuring that only one thread can access the critical section at a time. The class is derived from the Uncopyable class, which prevents the ScopedLo...
```cpp #include <mutex> #include <stack> class Uncopyable { protected: Uncopyable() {} ~Uncopyable() {} private: Uncopyable(const Uncopyable&); Uncopyable& operator=(const Uncopyable&); }; class CriticalSection { public: void Lock() { mutex.lock(); } void Unlock() { mutex...
magicoder
cpp
You are tasked with implementing a function to process object detection results and generate a detection annotation. The function takes in the following parameters: - `imgf`: a string representing the image filename - `box`: a 2D numpy array representing the bounding boxes of detected objects, where each row contains t...
```python import os def generate_detection_annotation(imgf, box, label_t, opts, out_path, threshold): if opts.visualize: visualize(imgf, box, label_t, out_file=out_path) box = box[box[:, -1] >= 1e-2] detection_annotation = { 'image_filename': os.path.basename(imgf), 'detection_thre...
magicoder
python
You are tasked with implementing a simple graphics rendering system using the OpenGL library. The code snippet provided initializes the OpenGL context, sets the application to exit when the escape key is pressed, and builds the rendering window. Your task is to extend this code to render a simple 2D shape, such as a tr...
```cpp #include <GL/glew.h> #include <GLFW/glfw3.h> #include <iostream> const char* vertexShaderSource = R"( #version 330 core layout (location = 0) in vec3 aPos; void main() { gl_Position = vec4(aPos, 1.0); } )"; const char* fragmentShaderSource = R"( #version 330 core out vec4 Fr...
magicoder
cpp
You are tasked with implementing a class that simulates an air traffic control system. The class should have a property called `air_control` that allows setting and getting the current air traffic control status. When setting the `air_control` property, the system should perform validation to ensure that the input valu...
```python class AirTrafficControl: def __init__(self): self._air_control = 0 @property def air_control(self): return self._air_control @air_control.setter def air_control(self, value): if 0 <= value <= 100: self._air_control = value print(f"Air contr...
magicoder
python
You are tasked with implementing a custom maximum function for both CPU and GPU using CUDA C++. The provided code snippet shows a template function `odin_max` that returns the maximum of two input values. Your task is to extend this concept and create a complete CUDA C++ program that includes the custom maximum functio...
```cpp #include <iostream> #include <cuda_runtime.h> template <typename T> __host__ __device__ T odin_max(T x, T y) { return x > y ? x : y; } // CPU function using odin_max void cpuMaxDemo() { int a = 10, b = 20; int maxResult = odin_max(a, b); std::cout << "CPU Max Result: " << maxResult << std::endl; } // ...
magicoder
cpp
You are working on a project that involves optimizing and compiling mathematical operations for a machine learning framework. As part of this project, you need to create a function that performs element-wise addition of two arrays, with the option to specify an axis for broadcasting and a flag for enabling broadcasting...
```python import jax.numpy as jnp from jax import jit, partial @partial(jit, static_argnums=(2, 3)) def onnx_add(a, b, axis=None, broadcast=False): if broadcast: b_shape = list(a.shape) # Initialize b_shape with the shape of array a if axis is not None: axis = axis if axis >= 0 else le...
magicoder
python
You are tasked with implementing a simple neural network training loop using Python and TensorFlow. The provided code snippet is part of a larger program that trains a Generative Adversarial Network (GAN) using a custom `GanTrainer` class. Your task is to complete the implementation by defining the `GanTrainer` class a...
```python import tensorflow as tf class GanTrainer: def __init__(self, generator, discriminator, config): self.generator = generator self.discriminator = discriminator self.config = config self.optimizer = tf.keras.optimizers.Adam(config.learning_rate) def train_step(self, real...
magicoder
python
You are tasked with implementing a script to train a machine learning model using a command-line interface. The script takes various parameters and options, and it is essential to understand and manipulate these settings for optimal model training. The provided code snippet is a part of the command used to launch the ...
```bash #!/bin/bash # Define the variables SAVE_STEPS=1000 WARMUP_PROPORTION=0.1 VALID_STEPS=500 EPOCH=10 LR_RATE="5e-5" num_labels=10 # Construct the full command for training python train_script.py \ --checkpoints ./checkpoints \ --save_steps $SAVE_STEPS \ --weight_decay 0.01 \ --warmup_proportion $...
magicoder
shell
You are tasked with implementing a Red-Black Tree data structure in Swift. A Red-Black Tree is a self-balancing binary search tree, where each node has an extra bit representing its color, either red or black. The tree satisfies several properties to ensure balanced and efficient operations. Your task is to implement ...
```swift func rebalance() { guard let parent = self.parent, let grandparent = parent.parent else { // If there is no parent or grandparent, the tree is already balanced return } if parent.color == .red && parent.sibling?.color == .red { // Case 1: Parent and uncle are both red ...
magicoder
swift
You are tasked with developing a script to automate the setup and shutdown procedures for a cloud infrastructure. The script will interact with various functions to perform specific tasks. One of the functions, `physical_do_setupironicnodes()`, is responsible for setting up the physical nodes for the cloud infrastructu...
```python def physical_do_setupironicnodes(): # Implementation for setting up physical nodes pass def physical_do_shutdowncloud(): # Implementation for shutting down the cloud infrastructure pass def main(): try: physical_do_setupironicnodes() # Start cloud services print("...
magicoder
python
You are tasked with creating a utility function that can merge multiple JavaScript modules into a single module. The function should take an array of module names as input and return a single module that exports all the named exports from the input modules. Write a function `mergeModules` that takes an array of module...
```javascript function mergeModules(moduleNames) { const mergedModule = {}; for (const moduleName of moduleNames) { const module = require(moduleName); Object.assign(mergedModule, module); } return mergedModule; } const moduleNames = [ './utils/IProgressFunction', './utils/IPromptFunction', './...
magicoder
javascript
You are tasked with implementing a Python function that converts a given log message into an XML format based on the log level provided. The function should take in three parameters: `log_level` (a string representing the log level), `log_message` (a string representing the log message), and `template` (a string repres...
```python def convert_to_xml(log_level: str, log_message: str, template: str) -> str: xml_str = template.replace('<log level="{}">'.format(log_level), '<log level="{}">'.format(log_level.lower())) xml_str = xml_str.replace('<log>', '<log>{}</log>'.format(log_message)) return xml_str ```
magicoder
python
You are tasked with implementing a function to create a sphere within a 3D volume data structure. The volume data structure is represented by the `LargeVolume` class, which holds `MaterialDensityPair44` elements. The function `createSphereInVolume` takes the volume data, the center of the sphere, and the radius as inpu...
```cpp #include <iostream> #include <cmath> // Define the MaterialDensityPair44 class if not already defined class MaterialDensityPair44 { // Define the class members if necessary }; // Define the LargeVolume class if not already defined template <class T> class LargeVolume { public: // Define the class membe...
magicoder
cpp
You are tasked with implementing a file system traversal algorithm that operates on absolute paths. The file system is represented as a tree structure, where each node can be a directory or a file. Each directory contains a list of files and subdirectories. Your goal is to write a function that takes in the root direct...
```python def traverse_file_system(directory, file_map, entrypoint): stack = [entrypoint] result = [] while stack: current = stack.pop() if current in file_map: for item in file_map[current]: if item.endswith(".txt"): result.append(current + "...
magicoder
python
You are tasked with implementing a rolling mean calculation function for a given list of numbers. The rolling mean is a method of smoothing time series data by averaging values within a sliding window. Your task is to create a Python function that takes a list of numbers and a window size as input and returns a new lis...
```python from typing import List def rma(data: List[float], window_size: int) -> List[float]: rolling_means = [] window_sum = sum(data[:window_size]) rolling_means.append(window_sum / window_size) for i in range(window_size, len(data)): window_sum = window_sum - data[i - window_size] + data[i...
magicoder
python
You are tasked with creating a Python function that processes data from a home automation system. The function will receive the `hass` object, which represents the Home Assistant system, and the `entity_registry` object, which contains information about entities in the system. The function should extract specific state...
```python def process_entity_states(hass, entity_registry) -> None: treble_state = hass.states.get("treble_number") assert treble_state.state == "-1" audio_delay_number = entity_registry.entities["number.zone_a_audio_delay"] audio_delay_state = hass.states.get(audio_delay_number.entity_id) assert a...
magicoder
python
You are tasked with implementing a custom class in Python that represents a mathematical function. The class should support three types of functions: "liht", "piecewise_linear", and "linear". Each function type has its own behavior when called, and the class should provide a string representation of the function type. ...
```python class MathFunction: def __init__(self, name): self.name = name def __str__(self): return self.name def __repr__(self): return str(self) # Example usage: liht_function = MathFunction("liht") print(liht_function.__str__()) # Output: "liht" print(liht_function.__repr__()) ...
magicoder
python
You are tasked with implementing a spell checker using the BERT language model. The BERTCorrector class is provided as a starting point for the spell checker. The class takes in the directory of the BERT model, the vocabulary file, and the maximum sequence length as input parameters. Your task is to extend the function...
```python from transformers import BertTokenizer, BertForMaskedLM import torch class BERTCorrector: def __init__(self, bert_model_dir, bert_model_vocab, max_seq_length): self.tokenizer = BertTokenizer.from_pretrained(bert_model_vocab) self.model = BertForMaskedLM.from_pretrained(bert_model_dir) ...
magicoder
python
You are tasked with implementing a lazy loading mechanism for a hierarchical data structure. The data structure consists of a realm, which is the top-level container, and instances, which are bound to the realm and may have eager children. The goal is to create a lazy binding mechanism that binds to the instance in the...
```rust use std::collections::HashMap; // Define the data structures for the realm and instance struct Instance { eager_children: Vec<Instance>, // Other instance fields } struct Realm { instances: HashMap<String, Instance>, // Other realm fields } // Implement the lazy binding mechanism fn lazy_bind...
magicoder
rust
You are tasked with implementing a custom segue in a Swift iOS application. The provided code snippet is a part of a custom UIStoryboardSegue subclass called DrawerEmbedRightControllerSegue. This custom segue is intended to be used in conjunction with a DrawerController, a custom view controller that manages the presen...
```swift final public override func perform() { guard let sourceViewController = source as? DrawerController else { assertionFailure("SourceViewController must be DrawerController!") return } sourceViewController.setViewController(destination, for: .right) } ``` In the perform() method,...
magicoder
swift
You are tasked with implementing a function to calculate the total number of ways to reach the top of a staircase. You are given an integer `n` representing the total number of steps in the staircase. You can climb either 1 or 2 steps at a time. Your task is to write a function `climbStairs` that takes in the number of...
```python def climbStairs(n: int) -> int: if n == 1: return 1 elif n == 2: return 2 else: first = 1 second = 2 for _ in range(3, n + 1): third = first + second first = second second = third return second ``` The `climbStairs...
magicoder
python
You are tasked with designing a real-time word count application using Apache Spark's StreamingContext. The application should read streaming input, count the occurrences of each word in a sliding window, and then output the word counts at regular intervals. Your task is to implement the necessary code to achieve this ...
```scala import org.apache.spark.SparkConf import org.apache.spark.streaming.{Seconds, StreamingContext} // Create a Spark configuration and set the app name val conf = new SparkConf().setAppName("RealTimeWordCount") // Create a StreamingContext with a batch interval of 1 second val ssc = new StreamingContext(conf, S...
magicoder
scala
You are tasked with implementing a function to calculate the total number of parameters in a convolutional neural network (CNN) given its architecture configuration. The architecture configuration is represented as a dictionary containing information about the number of input channels, output channels, kernel sizes, an...
```python def calculate_parameters(architecture_config): total_params = 0 input_channels = architecture_config['input_channels'] for layer in architecture_config['layers']: in_channels = layer['in_channels'] out_channels = layer['out_channels'] kernel_size = layer['kernel_size']...
magicoder
python
You are tasked with creating a Python function that generates a Pandas DataFrame based on a given schema. The schema is represented as a list of tuples, where each tuple contains two dictionaries. The first dictionary represents the column names and their corresponding data types, while the second dictionary contains t...
```python import pandas as pd from typing import List, Tuple, Dict, Callable, Any def generate_dataframe(schema: List[Tuple[Dict[str, str], Dict[str, Callable[[], Any]]]]) -> pd.DataFrame: data = {} for col_types, col_generators in schema: for col_name, data_type in col_types.items(): data[...
magicoder
python
You are tasked with implementing a method for a user interface library that manages the updating and unmounting of UI components. The library provides two methods, `unmount` and `update_attributes`, which are used to remove components from the UI and update their attributes, respectively. The `unmount` method takes in...
```rust impl UIComponent { fn unmount(&mut self, ctx: &mut Context, movements: &[Movement]) { for movement in movements { match movement { Movement::Remove => { // Logic to remove the component from the UI // Example: self.remove_from_ui();...
magicoder
rust
You are tasked with implementing a Swift function that creates a custom Heads-Up Display (HUD) for an iOS application. The HUD will display a message and an image, and it should animate into view from the top of the screen. You are provided with a partial code snippet that includes an animation block and a function si...
```swift class SBHUD { static var _window: UIWindow? static let WindowHeight: CGFloat = 100.0 class func showMessage(msg: String, img: String) { // Create a new window for the HUD _window = UIWindow(frame: CGRect(x: 0, y: -WindowHeight, width: UIScreen.main.bounds.width, height: WindowHeigh...
magicoder
swift
You are tasked with creating a function that processes a list of application lifecycle events and returns the count of specific events that occurred. The application lifecycle events are represented as a list of strings, where each string corresponds to a specific event. The events are as follows: - "didFinishLaunching...
```swift func countLifecycleEvents(events: [String]) -> [String: Int] { var eventCounts: [String: Int] = [:] for event in events { if let count = eventCounts[event] { eventCounts[event] = count + 1 } else { eventCounts[event] = 1 } } return eventCounts }...
magicoder
swift
You are tasked with implementing a custom namespace management system in C++. Your goal is to create a class that allows users to define and manipulate namespaces. A namespace is a declarative region that provides a scope to the identifiers (names of types, functions, variables, etc.) inside it. Your task is to creat...
```cpp #include <iostream> #include <unordered_map> #include <stack> #include <sstream> class NamespaceManager { private: std::unordered_map<std::string, NamespaceManager*> namespaces; std::stack<std::string> currentNamespace; public: void createNamespace(const std::string& name) { namespaces[name...
magicoder
cpp
You are tasked with creating a custom JUnit 5 extension to measure the execution time of test methods in a Java application. Your extension should record the execution time of each test method and print the results to the console. Additionally, the extension should allow for a threshold time to be set, and if any test ...
```java import org.junit.jupiter.api.extension.BeforeTestExecutionCallback; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.AfterTestExecutionCallback; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.api.extension.TestInstancePostProcess...
magicoder
java
You are tasked with implementing a state machine visualization tool that takes in a state machine definition and generates a graphical representation of the states and transitions. The state machine definition is provided as a JSON object, and the visualization tool should use the Graphviz library to create the graphic...
```python import graphviz def visualize_state_machine(state_machine_definition): graph = graphviz.Digraph(format='png') state_colors = { "start": "lightblue", "end": "lightgreen", "normal": "lightgray" } for state_name, state_def in state_machine_definition.items(): no...
magicoder
python
You are tasked with creating a Python class that interfaces with Prometheus, a popular monitoring and alerting toolkit. Your class, `PrometheusInterface`, should have the following functionality: 1. Initialize the class with a `url` parameter representing the base URL of the Prometheus server and a `last_minutes_impor...
```python from prometheus_api.prometheus_connect import PrometheusConnect class PrometheusInterface: def __init__(self, url, last_minutes_importance): self.prom = PrometheusConnect(url) self.last_minutes_importance = last_minutes_importance def query_range(self, query, start_time, end_time): ...
magicoder
python
You are tasked with creating a Django model for a library application. The model should represent a book and include fields for publication time, creation time, update time, and the author of the book. Additionally, the model should have options for ordering the books based on their rank, whether they are marked as top...
```python from django.db import models from articles.models import Author # Assuming the Author model is defined in the articles app class Book(models.Model): pub_time = models.DateTimeField(default=False, verbose_name='发布时间') create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间') upda...
magicoder
python
You are tasked with implementing a language translation tool using Python's Click library. The code snippet provided is a part of a larger program that initializes a new language and defines a command to update the language translation. Your task is to complete the implementation by adding functionality to update the l...
```python import click import json # Initialize a new language dictionary language = {} @click.group() def translate(): """Initialize a new language.""" pass @translate.command() def update(): """Update the language translation.""" # Prompt user for translation key and updated translation key = i...
magicoder
python
You are tasked with creating a command-line interface (CLI) tool to clean Jupyter Notebook files (.ipynb) by clearing their output and formatting the code using isort and black. Your task is to implement the functionality for the command-line interface using Python's argparse library. Your CLI tool should accept the f...
```python import argparse from pathlib import Path def clean_ipynb_file(ipynb_file_path, back_up, keep_output): # Implement the logic to clean the .ipynb file by clearing output and formatting the code using isort and black # Optionally, create a backup of the original file and retain the output cells based on...
magicoder
python
You are tasked with creating a command-line tool that emulates the behavior of the `alias` command in Unix-like operating systems. The `alias` command allows users to create custom shortcuts for other commands or command sequences. For example, the code snippet provided creates two aliases: `ga` for `git add` and `gaa`...
```python aliases = {} def add_alias(alias, command): aliases[alias] = command print(f"Alias '{alias}' added successfully!") def remove_alias(alias): if alias in aliases: del aliases[alias] print(f"Alias '{alias}' removed successfully!") else: print(f"Alias '{alias}' does not e...
magicoder
python
You are tasked with creating a PHP class that manages URL redirections for a web application. The class should handle different types of redirections based on the provided input. Your task is to implement the `RedirectManager` class with the following requirements: - The class should have a method `redirect` that take...
```php <?php class RedirectManager { public function redirect($url, $type = 'internal') { if ($type === 'permanent') { header("HTTP/1.1 301 Moved Permanently"); header("Location: $url"); exit(); } elseif ($type === 'temporary') { header("HTTP/1.1 302 F...
magicoder
php
You are tasked with implementing a search suggestion feature for a web application. The application has a search input field, and as the user types, it should display a dropdown with suggested search results. You are provided with a code snippet that sets up event listeners and references to various DOM elements. Your ...
```javascript searchInput.addEventListener('input', async (event) => { const inputValue = (event?.target as HTMLInputElement)?.value; const searchClearButton = document.querySelector('.cmp-saas__search-clear-button'); // Make an asynchronous request to fetch search suggestions based on the input value try { ...
magicoder
javascript
You are tasked with implementing a trajectory module for a simulation software. The trajectory module should support different types of multidimensional profiles for modeling the movement of objects in a simulated environment. Two specific types of profiles, IncompleteMultidimensionalProfile and OrthogonalMultidimensio...
```python from .profile.im import IncompleteMultidimensionalProfile from .profile.om import OrthogonalMultidimensionalProfile class Trajectory: def __init__(self): self.profile = None self.trajectory_data = None def set_profile(self, profile_type): if profile_type == 'incomplete': ...
magicoder
python
You are tasked with creating a script to automate the setup of a Redis server using Docker. Your script should perform the following tasks: 1. Pull the latest Redis image from Docker Hub. 2. Create a Docker container named "my-redis-server" using the pulled Redis image. 3. Expose the Redis server on port 6379 on the ho...
```bash #!/usr/bin/env bash # Pull the latest Redis image from Docker Hub docker pull redis # Create a Docker container named "my-redis-server" using the pulled Redis image docker run -d --name my-redis-server -p 6379:6379 -v redis_data:/data redis # Set the Redis server to require a password for authentication dock...
magicoder
shell
You are tasked with creating a program that reads and processes data from a Fallout 4 game file. The game file format is proprietary and requires the use of the Gibbed.Fallout4 library to parse and extract information. Your goal is to write a C# program that reads a specific type of data from the game file and performs...
```csharp using System; using System.Collections.Generic; using System.IO; using Gibbed.Fallout4.FileFormats; using Gibbed.IO; using NDesk.Options; class Program { static void Main(string[] args) { string filePath = "path_to_game_file"; // Replace with the actual file path // Read the Fallout 4...
magicoder
csharp
You are tasked with implementing a settings management system for a software application. The system should allow for the modification of existing settings within different categories and persist the changes to a settings file. You are provided with a code snippet that demonstrates the process of changing a setting wit...
```python class SettingsManager: def __init__(self, file_path): self.file_path = file_path self.__config = {} # Initialize settings data as a dictionary self.load_settings() # Load settings data from the file upon initialization def update_setting(self, category, key, value): ...
magicoder
python
You are tasked with implementing a process management system for a software application. The system should handle the graceful termination of processes and provide a mechanism to prevent the closure of a form until a specific process has completed. Your task is to design a class that encapsulates the process manageme...
```csharp using System; using System.ComponentModel; using System.Diagnostics; using System.Windows.Forms; public class ProcessManager { private Process runningProcess; private Form associatedForm; public ProcessManager(Form form) { associatedForm = form; } public void StartProcess(st...
magicoder
csharp
You are tasked with creating a middleware function for a buffet filtering feature in a web application. The application uses the Laravel framework, and the code snippet provided is a route definition that maps a POST request to the `filtrarbuffet` method in the `BuffetController` class. Additionally, it applies the `au...
```php <?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; class BuffetFilterMiddleware { public function handle(Request $request, Closure $next) { // Check if the user is authenticated if (auth()->check()) { // Check if the user has necessary permission...
magicoder
php
You are working on a system recovery script that needs to wait for a specified amount of time before attempting to recover the environment. The script uses a variable `recovery_sequence` to check if a recovery sequence file exists, and if it does, it waits for a default recovery wait time before proceeding with the rec...
```python import os import time from datetime import datetime def wait_for_recovery(recovery_sequence, DEFAULT_RECOVERY_WAIT_TIME): if os.path.isfile(recovery_sequence): current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") print(f"{current_time} - Waiting {DEFAULT_RECOVERY_WAIT_TIME} seconds...
magicoder
python
You are given a list of integers `x` and `y`. Your task is to write a function `calculate_correlation` that calculates the correlation coefficient between the two lists. The correlation coefficient is a measure of the strength and direction of the linear relationship between two variables. It ranges from -1 to 1, where...
```python from typing import List import math def calculate_correlation(x: List[int], y: List[int]) -> float: n = len(x) sum_prod_x_y = sum([xi * yi for xi, yi in zip(x, y)]) sum_x = sum(x) sum_y = sum(y) squared_sum_x = sum_x**2 squared_sum_y = sum_y**2 sum_x_squared = sum([xi**2 for xi i...
magicoder
python
You are tasked with creating a function that performs type inference on the return type of the `?` operator. The function should take a reference to an integer as a parameter and return a `Result` type with a specific error type. Your goal is to implement the function and handle the type inference failure where there a...
To handle the type inference failure and ensure that the function returns a `Result` with the appropriate error type, we can explicitly specify the return type of the `?` operator. In the given code snippet, the function `f` returns a `Result<i32, ()>`, indicating that it can return either an integer value or an empty ...
magicoder
rust
You are tasked with implementing a multithreaded program that simulates a simple banking system. The program should support multiple concurrent transactions, such as deposits and withdrawals, while ensuring data integrity and consistency. Your task is to implement the `BankAccount` class with the following requirement...
```python import threading class BankAccount: def __init__(self, initial_balance=0): self.balance = initial_balance self.lock = threading.Lock() def deposit(self, amount): with self.lock: self.balance += amount def withdraw(self, amount): with self.lock: ...
magicoder
python
You are tasked with creating a Python program that watches for changes in configured files and notifies the user when any modifications occur. The program should be able to handle a specified list of files and directories, and it should provide real-time notifications when any changes are detected. Your program should...
```python import os import time import yaml import platform if platform.system() == 'Windows': import win32file else: import select def load_configuration(config_file): with open(config_file, 'r') as file: config = yaml.safe_load(file) return config def watch_files_and_directories(config): ...
magicoder
python
You are tasked with implementing a variation of the popular game "Marble Solitaire." In this game, marbles are arranged in a board, and the player's goal is to eliminate as many marbles as possible by jumping over them with another marble until no more jumps can be made. The game is played on a board with a specific la...
```python def max_elimination_move(marbles): max_elimination = 0 move = None for i in range(len(marbles)): if marbles[i] == 1: for j in range(len(marbles)): if marbles[j] == 0: distance = abs(j - i) if distance > 1 and distance % 2...
magicoder
python
You are tasked with implementing a function that ensures a given input is decoded JSON. The function should take a single argument and return the decoded JSON if the input is a JSON string, or the input itself if it is already a dictionary. You are provided with a code snippet that partially implements the required fu...
```python import json def ensure_decoded_json(val): if isinstance(val, dict): return val else: try: decoded_json = json.loads(val) if isinstance(decoded_json, dict): return decoded_json else: return "Input is not a valid JSON o...
magicoder
python
You are tasked with implementing a reinforcement learning environment for a robotic arm. The environment has a set of skills that the robotic arm can learn and utilize to perform tasks. Each skill corresponds to a specific action or behavior that the arm can exhibit. The environment provides observations to the robotic...
```python import numpy as np import random class RoboticArmEnvironment: def __init__(self, num_skills): self.num_skills = num_skills self.skill = 0 # Initialize the skill to 0 def reset(self, **kwargs): # Randomly sample a skill and return the observation combined with the skill ...
magicoder
python
You are tasked with implementing a function that processes a series of PTX (Parallel Thread Execution) elements and generates a modified PTX output. The PTX elements are represented as a struct with various fields and methods. Your task is to complete the implementation of the `generate_modified_ptx` function, which ta...
```rust struct PtxElement { // Define the struct fields and methods here } impl PtxElement { // Define the methods for the PtxElement struct here } struct Ptx { ptx_slices: Vec<&'static [u8]>, const_loads: Vec<PtxElement>, } impl Ptx { fn generate_modified_ptx(&self) -> Vec<u8> { let mut ...
magicoder
rust
You are tasked with implementing a custom search filter component in a React application. The component should allow users to input a search string, clear the input, and trigger search actions. The component should also handle keyboard events for enhanced user experience. Your task is to create a React component that ...
```jsx import React, { useRef, useEffect } from 'react'; const CustomSearchFilter = (props) => { const inputRef = useRef(null); useEffect(() => { if (props.focusOnMount && inputRef.current) { inputRef.current.focus(); } }, [props.focusOnMount]); const onKeyDown = (event) => { if (event.key ...
magicoder
jsx
You are tasked with designing a database schema for a system that tracks lost cards and deposits made by visitors. The given code snippet represents a portion of a database migration file in Laravel's Eloquent ORM, which defines the structure of the database tables. The snippet includes the definition of columns for th...
The database schema can be designed as follows: Table: lost_cards Columns: - id: integer (primary key, auto-increment) - boleta_deposito: string (nullable, max length 20) - cuenta: string (nullable, max length 20) - banco: string (nullable, max length 60) - fecha_deposito: date (nullable) - monto: integer (nullable) -...
magicoder
python
You are tasked with implementing a function that parses a given JSON object and extracts specific key-value pairs based on a provided list of keys. The function should return a new object containing only the specified key-value pairs. You are given the following code snippet as a starting point: ```javascript const d...
```javascript function extractData(json, keys) { const extractedData = {}; keys.forEach(key => { if (json.hasOwnProperty(key)) { extractedData[key] = json[key]; } }); return extractedData; } // Example usage const data = { "campaignKey": "px", "with": "products.attributes,products.images.attr...
magicoder
javascript
You are tasked with implementing a program to parse and process a series of coordinates from a string. Each coordinate is represented as a pair of values separated by a comma, and the entire string contains multiple such coordinates separated by semicolons. Your task is to extract and parse these coordinates, and then ...
```java public static double processCoordinates(String input) { String[] coordinatePairs = input.split(";"); double sum = 0.0; for (String pair : coordinatePairs) { String[] coordinates = pair.split(","); double yValue = Double.parseDouble(coordinates[1]); sum += yValue; } re...
magicoder
java
You are tasked with implementing a method to parse and extract information from a given code snippet. The code snippet is written in Swift and defines a private method within a class. Your task is to write a function that can extract the method name, return type, and parameter type from the given code snippet. Write a...
```swift func parseMethodSignature(_ codeSnippet: String) -> [String: String] { var result: [String: String] = [:] // Extract method name if let methodName = codeSnippet.components(separatedBy: "(").first?.trimmingCharacters(in: .whitespaces).components(separatedBy: " ").last { result["methodName"]...
magicoder
swift
You are tasked with implementing a custom registration system for event handlers in a C# application. The system should allow registration of different types of actions to be performed at various stages of the compilation process. Your task is to create a class that manages the registration and invocation of these acti...
```csharp using System; using System.Collections.Generic; public enum SymbolKind { NamedType, Method, Property, Field } public class CustomRegistrationSystem { private Dictionary<Action, SymbolKind> symbolActions = new Dictionary<Action, SymbolKind>(); private Action compilationEndAction; ...
magicoder
csharp
You are tasked with creating a Python program to solve a quantum mechanics problem using numerical methods. The problem involves solving the Schrödinger equation for a given potential and obtaining the wave function and energy eigenvalue for the ground state of a particle in a potential well. The potential well is def...
```python import numpy as np import matplotlib.pyplot as plt # Define the potential energy function V(r) def V(r): # Define the potential energy function here, e.g., V = 0.5 * k * r**2 for a harmonic oscillator return 0.5 * k * r**2 # Example potential energy function for a harmonic oscillator # Constants ħ ...
magicoder
python
You are tasked with creating a custom form builder function in TypeScript for an Angular application. The function should take an object containing form field values and validators, and return a FormGroup with the specified form controls and validators. You are given the following code snippet as a starting point: ``...
```typescript import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms'; class FormService { constructor(private fb: FormBuilder) {} createForm(formValues: Object): FormGroup { const form = this.fb.group({}); Object.keys(formValues).forEach((fieldName) => { const fieldValue = ...
magicoder
typescript
You are tasked with implementing a retry logic for handling responses in a controller. The controller has a method `adjust_to_response` that takes the start time of the request and the response, which is a `Result` containing either the response data or an error. Your goal is to create a retry logic that determines the...
```rust use std::time::{Instant, Duration}; // Define the RetryLogic trait trait RetryLogic { type Response; fn determine_action(&self, start_time: Instant, response: &Result<Self::Response, crate::Error>) -> Action; } // Define the Action enum enum Action { Retry(Duration), Abort, Continue, } //...
magicoder
rust
You are tasked with creating a program that analyzes the distribution of characters in a given text file. Your program should read a text file and output the frequency of each character present in the file, sorted in descending order of frequency. For the purpose of this problem, consider only alphanumeric characters (...
```python from collections import Counter import string # Read the input file with open('input.txt', 'r') as file: data = file.read() # Filter out non-alphanumeric characters and convert to lowercase filtered_data = ''.join(filter(lambda x: x.isalnum(), data)).lower() # Count the frequency of each character freq...
magicoder
python
You are tasked with creating a Rust library for managing components and modifiers in a game engine. The library consists of several modules, including `component`, `error`, and `modifier`. Additionally, the library has a feature called "alloc" that enables memory allocation support. Your task is to implement a functio...
```rust // Define the error module to handle library-specific errors pub(crate) mod error { // Define custom error types if needed } // Define the component module to manage components pub mod component { // Define the Component struct to represent a game component pub struct Component { base_cost:...
magicoder
rust
You are tasked with implementing a Python class that represents a graph node with attributes and constraints. The class should allow setting and accessing attribute values, as well as defining constraints for the node. Your task is to implement the `GraphNode` class with the following requirements: - The class should ...
```python class GraphNode: def __init__(self): self.attributes = {} self.constraint = None def set_attribute(self, name, value): self.attributes[name] = value def get_attribute(self, name): return self.attributes.get(name) def set_constraint(self, constraint): ...
magicoder
python
You are given a list of edges representing a graph. Each edge is a tuple of two vertices, where the first vertex is the origin and the second vertex is the destination. Your task is to find and return the edge that causes a cycle when added to the graph. You are also given a function `find(y)` that returns the parent ...
```python from typing import List, Tuple parents = {} def find(y): if y not in parents: parents[y] = y if parents[y] != y: parents[y] = find(parents[y]) return parents[y] def union(x, y): parent_x = find(x) parent_y = find(y) if parent_x == parent_y: return False p...
magicoder
python
You are tasked with implementing a program to process data from a Kinect sensor using the libfreenect2 library. The provided code snippet is part of a larger program that interfaces with the Kinect sensor to capture color, infrared, and depth frames. Your task is to complete the implementation of the `Libfreenect2OpenC...
```cpp void Libfreenect2OpenCV::updateMat() { // Acquire frames from the Kinect sensor libfreenect2::FrameMap frames; if (!m_dev->waitForNewFrame(frames, 10 * 1000)) { // Wait for new frames with a timeout of 10 seconds std::cerr << "Timeout waiting for new frames" << std::endl; return; ...
magicoder
cpp
You are tasked with implementing a class that represents a rectangle in a 2D coordinate system. The class should have attributes to store the coordinates of the rectangle's boundaries. Your goal is to create a method that calculates the area of the rectangle. You are given the following code snippet as a starting poin...
```python class Rectangle: def __init__(self, left, right, bottom, top): self.left = left self.right = right self.bottom = bottom self.top = top def calculate_area(self): return (self.right - self.left) * (self.top - self.bottom) # Example usage # Initialize a rectangle...
magicoder
python
You are given a code snippet that was found by fuzzing. Your task is to analyze the code and identify the potential issues or errors present in it. The code appears to be a mix of Swift syntax and seems to define a protocol, an array, and a function. However, due to the random nature of the code snippet, it lacks prope...
The given code snippet is a mix of Swift syntax elements but lacks proper structure and coherence. It seems to define a protocol, an array, and a function, but the syntax is incorrect. Here's the corrected version of the code: ```swift // Corrected code protocol MyProtocol { func myFunction() } let myArray = [1,...
magicoder
swift
You are tasked with implementing a Python function that processes an image array using various NumPy and OpenCV operations. The function takes in an input image array `shuffled_img` of shape (N, H, W, C), where N represents the number of images, H is the height, W is the width, and C is the number of channels. The func...
```python import numpy as np import cv2 def process_image(shuffled_img: np.ndarray, fetch_data_slice: slice) -> np.ndarray: # Remove the first element from the shuffled_img array shuffled_img = np.delete(shuffled_img, 0, axis=0) # Transpose the shape of the shuffled_img array from (N, H, W, C) to (N, W, H...
magicoder
python
You are tasked with implementing a custom view in a Swift iOS application. The view should have a text label that is initially hidden, but becomes visible when a specific condition is met. Your task is to write a function that sets up the view and adds the necessary constraints to achieve this behavior. You are provid...
```swift func setupCustomView(rootView: UIView, text: String?) { let textLabel = UILabel() textLabel.text = text textLabel.isHidden = text == nil textLabel.translatesAutoresizingMaskIntoConstraints = false rootView.addSubview(textLabel) let hiddenConstraint = NSLayoutConstraint( ite...
magicoder
swift
You are tasked with creating a Python script that automates the process of updating a Python package on the Python Package Index (PyPI). The script should perform the following steps: 1. Display a message indicating that PyPI is being updated. 2. Execute the commands to build and upload the package distribution in egg ...
```python import os # Step 1: Display message for updating PyPI print("Updating PyPI...") # Step 2: Execute commands to build and upload egg distribution os.system("./setup.py bdist_egg register upload") # Step 3: Execute commands to build and upload source distribution os.system("./setup.py sdist register upload") ...
magicoder
python
You are tasked with implementing a Python decorator that caches the result of a function call to improve performance. The provided code snippet outlines the basic structure of the decorator, which uses a dictionary to store the cached results. Your task is to complete the implementation of the `cache` decorator and app...
```python def cache(func): cached_results = {} def wrapper(*args, **kwargs): key = (args, frozenset(kwargs.items())) if key not in cached_results: cached_results[key] = func(*args, **kwargs) return cached_results[key] return wrapper @cache def sample_function(a, b): ...
magicoder
python
You are tasked with implementing a simplified version of a text-based adventure game. The game will involve navigating through different rooms, interacting with objects, and making decisions that affect the outcome of the game. Your task is to create a class `Room` that represents a room in the game. Each room will ha...
```python class Room: def __init__(self, name, description): self.name = name self.description = description self.exits = [] def add_exit(self, room): self.exits.append(room) def get_name(self): return self.name def get_description(self): return self.de...
magicoder
python
You are tasked with creating a Python unit test for an asynchronous function using the `unittest` and `pytest` libraries. The function to be tested is asynchronous and requires the use of `pytest.mark.asyncio` to enable asynchronous testing. Your goal is to write a test case that ensures the correct behavior of the asy...
```python import unittest import pytest class TestJMDict(unittest.TestCase): @pytest.mark.asyncio async def test_async_function_success(self): # Assuming async_function takes input and returns an asynchronous result input_data = "example_input" expected_output = "example_output" ...
magicoder
python
You are tasked with designing a caching mechanism for a mobile application that displays dynamic content. The application has a `PageCache` class with a method `getEntry(cacheKey: String)` that retrieves a cached page based on a given cache key. Each page has a hash value, and the application periodically checks for up...
```swift class Page { let hash: String // Other properties and methods related to the page init(hash: String) { self.hash = hash } } class PageCache { static let shared = PageCache() private var cache: [String: Page] = [:] func getEntry(cacheKey: String) -> Page? { return ...
magicoder
swift
You are tasked with implementing a file system manipulation tool that processes a series of rules and arguments to modify files. The tool operates on a list of files in the `filesystem` attribute and uses the `args` attribute to specify the operations to be performed. Additionally, the tool has a set of rules defined u...
```python from typing import List def process_filesystem(filesystem: List[str], args: str, rules: List[str]) -> List[str]: for arg in args.split(): if arg.startswith("--overwrite="): pattern = arg.split("=")[1] filesystem = [f if not f.startswith(pattern) else pattern for f in files...
magicoder
python
You are tasked with implementing a specific type of neural network module called ShuffleNetV2. This module is used for deep learning tasks and is defined by the class `ShuffleNetV2`. The class has an `__init__` method that takes in several parameters and initializes the ShuffleNetV2 module. Your task is to complete the...
```python class ShuffleNetV2(nn.Module): def __init__(self, stages_repeats, stages_out_channels, num_classes=1000, inverted_residual=InvertedResidual): super(ShuffleNetV2, self).__init__() self.num_classes = num_classes self.conv1 = nn.Conv2d(3, 24, kernel_size=3, stride=2, padding=1, bias=F...
magicoder
python
You are tasked with implementing a trading system for futures contracts. In this system, you need to define a class hierarchy for different types of orders and instruments. The provided code snippet includes a partial implementation of the `FutureMarketOrder` class, which inherits from the `MarketOrder` class and is as...
```python from enum import Enum from typing import Union class DIRECTION(Enum): LONG = "LONG" SHORT = "SHORT" class Order: # Base class for different types of orders pass class FutureLimitOrder(Order): # Represents a limit order for futures contracts def __init__(self, price: float, time_in_f...
magicoder
python
You are tasked with creating a program that simulates a simple version control system. Your program should be able to handle basic commands such as "git clone", "push", and "popd". The "git clone" command is used to clone a repository from a remote location to the local machine. The syntax for this command is "git cl...
```python class VersionControlSystem: def __init__(self): self.repository_url = None self.directory_stack = [] def git_clone(self, repository_url): self.repository_url = repository_url print(f"Cloning repository from {repository_url}") def push(self): if self.reposi...
magicoder
python
You are tasked with creating a bash script that processes a given directory and its subdirectories to find all files with a specific file extension. Your script should then display the total count of files found and their respective sizes in a human-readable format. Your bash script should accept the following command...
```bash #!/bin/bash # Check if the correct number of arguments are provided if [ "$#" -ne 2 ]; then echo "Usage: $0 <directory_path> <file_extension>" exit 1 fi # Assign command-line arguments to variables directory_path="$1" file_extension=".$2" # Prepend a dot to the file extension # Check if the specifie...
magicoder
shell
You are tasked with implementing a simplified SIR (Susceptible, Infectious, Recovered) model for simulating the spread of an infectious disease within a population. The SIR model divides the population into three compartments: Susceptible (S), Infectious (I), and Recovered (R). The model assumes that individuals move t...
```python import numpy as np from scipy.integrate import odeint def sir_model(y, t, beta, gamma): S, I, R = y dSdt = -beta * S * I dIdt = beta * S * I - gamma * I dRdt = gamma * I return dSdt, dIdt, dRdt def simulate_sir_model(S, I, R, beta, gamma, days): t = np.linspace(0, days, days) y0 ...
magicoder
python
You are tasked with implementing a safe abstraction for accessing a hardware peripheral in an embedded system. The peripheral in question is OTG_FS_PWRCLK, and you need to create a safe API for interacting with it. The provided code snippet includes a constant `reset` that holds the initial reset values for the fields ...
```rust // Define a module for safe abstraction of OTG_FS_PWRCLK peripheral mod otg_fs_pwrclk { // Define the struct representing OTG_FS_PWRCLK peripheral pub struct OtgFsPwrclk { pcgcctl: u32, // Field representing PCGCCTL register } // Implement methods for the peripheral impl OtgFsPwrclk...
magicoder
rust
You are given a string `s`. Write a function `reverseVowels` to reverse only the vowels of the string. The vowels are 'a', 'e', 'i', 'o', and 'u', and they can be in both uppercase and lowercase. Function signature: `def reverseVowels(s: str) -> str:` **Input** - A string `s` where 1 <= len(s) <= 10^5 **Output** - R...
```python class Solution: def reverseVowels(self, s: str) -> str: vowels = set('aeiouAEIOU') s = list(s) left, right = 0, len(s) - 1 while left < right: while s[left] not in vowels and left < right: left += 1 while s[right] not in vowels and le...
magicoder
python
You are tasked with implementing a TypeScript function that utilizes the `GetUserPermissionsFn` interface to retrieve and filter user permissions based on a given user ID. The `GetUserPermissionsFn` interface is defined as follows: ```typescript export interface GetUserPermissionsFn<Permissions extends PermissionsList...
```typescript export async function filterUserPermissions<Permissions extends PermissionsList>( userId: string, getUserPermissions: GetUserPermissionsFn<Permissions> ): Promise<string[]> { try { const userPermissions = await getUserPermissions(userId); const filteredPermissions = Array.from(...
magicoder
typescript
You are tasked with implementing a command-line interface for a simple text-based adventure game. The game has a player character that can perform various actions such as moving, picking up items, and interacting with the environment. Your task is to implement the `cmd` module in Python to create a command-line interfa...
```python import cmd class AdventureGame(cmd.Cmd): def __init__(self): super().__init__() self.location = "start" self.inventory = [] @property def action(self): return self.lastcmd def do_move(self, direction): if direction in ["north", "south", "east", "west"...
magicoder
python
You are given a Swift code snippet that extends the `Edge` type to conform to the `Equatable` protocol. The `Edge` type is a generic type with associated type `T`. The extension specifies that `Edge` is equatable when the associated type `T` is equatable. Your task is to implement a generic function that takes an array...
```swift func countUniqueEdges<T: Equatable>(edges: [Edge<T>]) -> Int { var uniqueEdges: Set<Edge<T>> = [] for edge in edges { uniqueEdges.insert(edge) } return uniqueEdges.count } ```
magicoder
swift
You are tasked with creating a C# program that interfaces with a Java Virtual Machine (JVM) using the Java Native Interface (JNI). The program should be able to call Java methods from C# and handle the data exchange between the two languages. Your task is to implement a C# class that demonstrates the interaction with ...
```csharp using System; using System.Runtime.InteropServices; namespace Clr2Jvm.Interop.Native { public class JvmInterop { private IntPtr jvmHandle; private IntPtr jniEnv; public JvmInterop(string jvmPath, string[] jvmOptions) { // Load the JVM and initialize the JN...
magicoder
csharp
You are tasked with creating a Python script that automatically updates the version number in a file whenever a new release is made. The version number is stored in a file named `_version.py` and follows the format `VERSION = "x.y.z"` where `x`, `y`, and `z` are integers representing the major, minor, and patch version...
```python def update_version(version_part): with open(DEFAULT_VERSION_UP_NAME, 'r') as file: content = file.read() current_version = content.split('=')[1].strip().strip('"') major, minor, patch = map(int, current_version.split('.')) if version_part == "major": major += 1 min...
magicoder
python
You are tasked with implementing a money transfer command for a banking system. The code snippet provided is a Python class `MoneyTransferCommand` that inherits from `CompositeBankAccountAbstractCommand`. The `MoneyTransferCommand` is initialized with the source account (`from_acct`), destination account (`to_acct`), a...
```python class MoneyTransferCommand(CompositeBankAccountAbstractCommand): def __init__(self, from_acct, to_acct, amount): super().__init__([ BankAccountAbstractCommand(from_acct, amount), BankAccountAbstractCommand(to_acct, -amount) ]) self.from_acct = from_acct ...
magicoder
python
You are tasked with implementing a simplified version of an authentication system in Swift. The system consists of an `AuthManager` class responsible for managing the authentication flow. The `AuthManager` has an initializer that takes several parameters, including a listener object conforming to the `AuthListener` pro...
```swift class AuthManager { private weak var listener: AuthListener? private let scene: AuthScene private let show: AuthShow private let signUpBuilder: SignUpBuilder private let signInBuilder: SignInBuilder init(scene: AuthScene, show: AuthShow, signUpBuilder: SignUpBuilder, ...
magicoder
swift
You are tasked with implementing a Python module for handling environment variables stored in a .env file. The module should provide a function to retrieve and print the environment variables from the file. Your task is to complete the implementation of the `envpy` module by writing the `get_variables` and `printenv` f...
```python # Implementation of the envpy module import os def get_variables(filepath, filename): """ Retrieve environment variables from the specified .env file. Args: filepath (str): The path to the directory containing the .env file. filename (str): The name of the .env file. Returns: di...
magicoder
python