query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with creating a Python class that interacts with a database using SQLAlchemy. Your class should be able to perform basic CRUD (Create, Read, Update, Delete) operations on a specific table in the database. The table represents a collection of books, with columns for `id`, `title`, `author`, and `published...
```python import sqlalchemy as sa from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Book(Base): __tablename__ = 'books' id = sa.Column(sa.Integer, primary_key=True) title = sa.Column(sa.String) author = sa.Column(sa.String) ...
magicoder
python
You are tasked with implementing a stack data structure using a given allocator class. The stack should support standard operations such as push, pop, and top, and should dynamically resize itself as needed. The allocator class provides memory allocation and deallocation functionalities. You are provided with a partia...
```cpp #include <cstdint> template<class Allocator> class Stack { Allocator mAllocator; uint32_t mSize, mCapacity; T* mData; public: // Constructor Stack() : mSize(0), mCapacity(10), mData(mAllocator.allocate(10)) { // Initialize the stack with initial capacity } // Destructor ...
magicoder
cpp
You are tasked with implementing a parallel processing algorithm for training a machine learning model using the Stochastic Gradient Descent (SGD) method. The SGDClassifier.fit method fits a linear model with stochastic gradient descent, supporting different parallel processing backends. The backends include "loky", "m...
```python from sklearn.linear_model import SGDClassifier import numpy as np import joblib import threading def train_model(backend, X, y): if backend == "loky": model = SGDClassifier(n_jobs=-1) elif backend == "multiprocessing": model = SGDClassifier(n_jobs=-2) elif backend == "threading": ...
magicoder
python
You are tasked with creating a BMI calculator program in Rust. The program should prompt the user to input their weight in kilograms and then calculate their BMI (Body Mass Index) based on the weight and a predefined height. The BMI should then be used to determine the classification of the user's weight status. The cl...
```rust fn calculate(height: f64, weight: f64) -> f64 { height / (weight * weight) } fn get_classification_by_bmi(bmi: f64) -> &'static str { if bmi < 18.5 { "Underweight" } else if bmi < 25.0 { "Normal weight" } else if bmi < 30.0 { "Overweight" } else { "Obese" ...
magicoder
rust
You are working on a game development project and need to implement a system for repairing items using specific ingredients. The code snippet provided is a method from a class that represents an item in the game. The method `getRepairIngredient` is supposed to return the ingredient required to repair the item. In this ...
```java // ItemRegistry.java public class ItemRegistry { public static final Item TOURMALINE_INGOT = new Item("tourmaline_ingot"); } // ItemRepairManager.java public class ItemRepairManager { public int calculateItemsRepaired(int tourmalineIngotCount, int ingotsRequiredForRepair) { if (ingotsRequiredFo...
magicoder
java
You are tasked with implementing a function that loads properties from an XML node in a specific format. The function should be able to handle different types of nodes and extract relevant information based on the node's local name and attributes. Write a function `loadProperty` that takes in an XML node `__node` and ...
```swift func loadProperty(__node: DDXMLElement, __request: EPA_FdV_AUTHZ_RequestResultHandler) -> Bool { if __node.localName == "ReferenceList" { if EPA_FdV_AUTHZ_Helper.isValue(node: __node, name: "ReferenceList") { // Perform property loading logic here // If successful, return tr...
magicoder
swift
You are tasked with implementing a custom annotation processor for a simplified version of the ButterKnife library. The library uses annotations to bind views to fields in Android activities and fragments. Your goal is to create a processor that generates the necessary code to bind views annotated with `@Bind` to their...
```java import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.tools.Diagnostic; import java.io.IOException;...
magicoder
java
You are tasked with implementing a custom input validation system for a web application. The system should enforce specific input purposes for different types of input fields. The input purposes are represented by constants as shown in the following code snippet: ```rust pub const WEBKIT_INPUT_PURPOSE_PHONE: WebKitInp...
```rust // Define the WebKitInputPurpose enum enum WebKitInputPurpose { Phone, Url, Email, Password, } // Implement the validate_input function fn validate_input(input_value: &str, input_purpose: WebKitInputPurpose) -> bool { match input_purpose { WebKitInputPurpose::Phone => { ...
magicoder
rust
You are tasked with implementing a Python class that extends a base class and overrides its methods. Your task is to create a class called `TestsslFinding` that inherits from the `VSFinding` class. The `VSFinding` class is not explicitly defined in the given code snippet, but it is assumed to be a base class with certa...
```python class TestsslFinding(VSFinding): def process_finding(self, finding): # Custom implementation of processing finding for TestsslFinding pass # Additional methods or attributes can be added as per specific requirements ``` In the solution, the `TestsslFinding` class is defined to inherit...
magicoder
python
You are tasked with implementing a retry mechanism for a command execution in a multi-threaded environment. The goal is to handle concurrent changes to the system state that may occur during the execution of the command. You are provided with a code snippet that logs a message when a retry is triggered due to a concurr...
To implement a retry mechanism that can handle concurrent changes, you can use a combination of exponential backoff and retry limits. Here's a sample solution in Java: ```java import java.util.concurrent.TimeUnit; public class RetryMechanism { private static final int MAX_RETRIES = 3; private static final lon...
magicoder
java
You are tasked with implementing a function to calculate the weighted mean of a set of angles represented in degrees. The weighted mean is calculated by converting the angles to unit vectors, computing the mean of the unit vectors, and then converting the resulting mean vector back to an angle. You are given a code sn...
```python import numpy as np def calc_wd_mean_radial(angles_array_deg, axis=0): # Use unit vectors to calculate the mean wd_x = np.cos(angles_array_deg * np.pi / 180.) wd_y = np.sin(angles_array_deg * np.pi / 180.) # Calculate the mean of the unit vectors mean_wd_x = np.mean(wd_x, axis=axis) ...
magicoder
python
You are tasked with creating a room generation algorithm for a 2D map. The given code snippet is part of the algorithm and is responsible for generating a new room dimension and ensuring that it does not overlap with any existing rooms on the map. The `GenerateDimension` function is used to create a new room dimension,...
```csharp using System; using System.Collections.Generic; public class Room { public Rectangle Rectangle { get; set; } public string RoomInfo { get; set; } public RoomType Type { get; set; } public Orientation Orientation { get; set; } } public class Rectangle { public int X { get; set; } publ...
magicoder
csharp
You are tasked with implementing a Python function that simulates a web page downloader with retry functionality. The function should be able to handle HTTP errors and retry downloading the web page if a server error (5XX HTTP status code) is encountered. The function should take into account the number of retry attemp...
```python import requests def download(url: str, retry_count: int, headers: dict, proxy: str, data: dict) -> str: try: response = requests.post(url, headers=headers, proxies={"http": proxy, "https": proxy}, data=data) response.raise_for_status() # Raise an HTTPError for 4XX and 5XX status codes ...
magicoder
python
You are tasked with creating a program that processes a list of file names and determines whether each file should be included or excluded based on certain criteria. The program should iterate through the list of file names, remove any leading or trailing whitespace from each file name, and then determine whether the f...
```python def process_files(all_files): included_files = [] for f in all_files: f = f.strip() if "temp" in f: continue if f.endswith(".txt"): included_files.append(f) if f.startswith("data_") and len(f) > 10: included_files.append(f) return...
magicoder
python
You are tasked with implementing a custom batch sampler for a machine learning model. The batch sampler will be used to generate batches of data for a prototypical learning algorithm. The prototypical learning algorithm is used for few-shot learning tasks, where the model is trained on a small number of examples per cl...
```python import random import numpy as np class PrototypicalBatchSampler: def __init__(self, num_classes, num_support, num_query, iterations, max_caption_length=20, in_memory=False): ''' Initialize the PrototypicalBatchSampler object Args: num_classes: An integer representing the n...
magicoder
python
You are tasked with creating a system to manage software integrations and their associated features. The provided code snippet includes a class method `run_pre_runner` that iterates through the features of an integration and calls the `pre_runner` method for each valid feature. Similarly, the method `run_post_runner` i...
```python class IntegrationFeatureRegistry: def __init__(self): self.integrations = {} def register_integration(self, integration): self.integrations[integration.name] = [] def register_feature(self, integration_name, feature): if integration_name in self.integrations: ...
magicoder
python
You are tasked with implementing a trait in Scala called `FloatingPointOnly`, which will be used to restrict a class to only allow floating-point numbers. The trait should provide a method `process` that takes a list of numbers and returns a new list containing only the floating-point numbers from the input list. Addit...
```scala // Define the FloatingPointOnly trait trait FloatingPointOnly { def process(numbers: List[Double]): List[Double] = { numbers.filter(_.isInstanceOf[Double]) } def calculateSum(numbers: List[Double]): Double = { numbers.sum } } // Create a class NumberProcessor that extends the FloatingPointOnl...
magicoder
scala
You are tasked with creating a script to automate the notification of a Cloud Build status update to a GitHub repository using the `curl` command and a JSON payload. The script should take into account the target URL, build state, and GitHub credentials. Your task is to write a Bash script that accomplishes the follow...
```bash #!/bin/bash # Define the target URL with placeholders target_url="https://console.cloud.google.com/cloud-build/builds;region=global/${build_id};step=${build_step}?project=${project_id}" # Set the build state state="${test_state}" # Construct the JSON payload json_payload="{context: $context, target_url: $tar...
magicoder
shell
You are tasked with implementing a simplified version of a plugin system for an integrated development environment (IDE). The provided code snippet is part of a utility class `PsiIconUtil` that is responsible for obtaining icons for various elements within the IDE. The method `getProvidersIcon` takes a `PsiElement` and...
```java import javax.swing.*; public interface IconProvider { Icon getIcon(PsiElement element, int flags); } public class FileIconProvider implements IconProvider { @Override public Icon getIcon(PsiElement element, int flags) { if (element instanceof PsiFile) { String extension = ((Psi...
magicoder
java
You are given an array of integers. An equilibrium index of this array is any integer `i` such that the sum of elements at indices less than `i` is equal to the sum of elements at indices greater than `i`. Write a function to find the equilibrium index of the given array. If no equilibrium index exists, return -1. The...
```python from typing import List def find_equilibrium_index(arr: List[int]) -> int: total_sum = sum(arr) left_sum = 0 for i in range(len(arr)): total_sum -= arr[i] if left_sum == total_sum: return i left_sum += arr[i] return -1 ``` The `find_equilibrium_index` funct...
magicoder
python
You are working on a programming platform that hosts a variety of coding problems. Your task is to analyze the statistics of the problems and calculate certain averages and ratings. The given code snippet is a part of this analysis process. The snippet calculates the average acceptance rate, onsite time, and access cou...
```python from typing import List, Dict, Union import datetime def calculate_problem_stats(uniq_problems_array: List[Dict[str, Union[int, float]]]) -> List[Dict[str, Union[str, float]]]: p_len = len(uniq_problems_array) ac_avg = sum(problem['AcceptRate'] for problem in uniq_problems_array) / p_len onsite_a...
magicoder
python
You are tasked with implementing a function to validate a given string of parentheses. The function should return true if the parentheses are balanced and false if they are not. You are given the following code snippet as a starting point for your implementation: ```cpp >(a0) ) { } javax::crypto::spec::DESKeySpec::D...
```cpp #include <stack> #include <string> bool validateParentheses(std::string s) { std::stack<char> stack; for (char c : s) { if (c == '(') { stack.push(c); } else if (c == ')') { if (stack.empty() || stack.top() != '(') { return false; // Unbalanced pa...
magicoder
cpp
You are tasked with creating a Python program to scrape the title, date, and URL of the latest notices from the website of the Department of Information and Communication Technology (ICT) at Chung-Ang University. The code snippet provided initializes empty lists for the title, date, and URL of the notices and then atte...
```python from urllib.request import urlopen from bs4 import BeautifulSoup ict_title_list = [] ict_date_list = [] ict_url_list = [] ictnotice_url = "http://ict.cau.ac.kr/20150610/sub05/sub05_01_list.php" ictnotice_page = urlopen(ictnotice_url) soup = BeautifulSoup(ictnotice_page, 'html.parser') # Extracting notice t...
magicoder
python
You are tasked with implementing a parallel optimizer for a deep learning framework using Chainer. The goal is to create a class that can distribute the optimization process across multiple devices or nodes, allowing for faster training of large models. Your task is to implement the missing methods and classes required...
```python # Import necessary modules from chainer import optimizer class ParallelOptimizerUpdateModelParameters(optimizer.UpdateRule): """Update model parameters in a parallel optimizer""" def __init__(self, device): super(ParallelOptimizerUpdateModelParameters, self).__init__() self.device = ...
magicoder
python
You are tasked with creating a currency trading validation service for a financial institution. The service will utilize a provided `CurrencyRepository` to validate trades using the `TradeValidator` and return any potential errors as `ErrorCodeDto` objects. The `CurrencyRepository` class provides access to currency da...
```java import com.cs.fx.domainmodel.CurrencyRepository; import com.cs.fx.fxservice.validation.TradeValidator; import com.cs.fx.service.model.ErrorCodeDto; import java.util.ArrayList; import java.util.List; public class TradeValidationService { private CurrencyRepository currencyRepository; private TradeValid...
magicoder
java
You are tasked with implementing a session management system for a web application. The session management system should be able to create and manage user sessions. Each session should have a unique identifier and should be associated with a user. You are provided with a code snippet that creates a new session object ...
```python import uuid class Session: def __init__(self): self.session_id = None self.user = None def generate_session_id(self): self.session_id = str(uuid.uuid4()) def associate_user(self, user): self.user = user # Example usage app = Session() app.generate_session_id() a...
magicoder
python
You are tasked with creating a program that simulates a simple voting eligibility check. The program should prompt the user to input their age and then determine if they are old enough to vote. If the user is eligible to vote, the program should display a message indicating their eligibility and prompt them to mark a b...
```python # Prompt the user to input their age age = int(input("Enter your age: ")) # Check if the user is old enough to vote if age >= 18: print("You are old enough to vote (yay!)") print("Loading...") print("Please put an 'X' in the box") else: print("Please come back in {} years".format(18 - age)) ...
magicoder
python
You are tasked with implementing a simple data collection system for a hypothetical urban planning application. The system is designed to collect data from various sensors placed around a city to monitor environmental conditions, traffic, and other relevant parameters. The data collection process involves configuring t...
```python import urarand def configure_data_collection(): # Retrieve the configuration for data collection config = urarand.config.get_config() return config def define_data_collection_strategy(config): # Define the data collection strategy based on the configuration strategy = config["data_collec...
magicoder
python
You are given a list of coin denominations and a target amount. Your task is to write a function to determine the minimum number of coins needed to make up that amount. If the amount cannot be made up by any combination of the given coins, return -1. Write a function `minCoinsNeeded(coins: List[int], amount: int) -> i...
```python from typing import List def minCoinsNeeded(coins: List[int], amount: int) -> int: inf = float('inf') dp = [inf] * (amount + 1) dp[0] = 0 for coin in coins: for x in range(coin, amount + 1): dp[x] = min(dp[x], dp[x - coin] + 1) return dp[amount] if dp[amount] != inf e...
magicoder
python
You are tasked with implementing a color generation algorithm for a graphics library. The algorithm should generate a random color in the RGB color space and convert it to the HSB (Hue, Saturation, Brightness) color space. You are given a code snippet that partially implements the color generation algorithm. Your task ...
```swift public static func rgbToHSB(red: Double, green: Double, blue: Double) -> (hue: Double, saturation: Double, brightness: Double) { let maxColor = max(red, green, blue) let minColor = min(red, green, blue) let delta = maxColor - minColor var hue: Double = 0.0 var saturation: Double = 0.0 v...
magicoder
swift
You are tasked with implementing a function that checks if a given string matches a given pattern. The pattern consists of letters and dots, where each dot can represent any character. The function should return true if the string matches the pattern, and false otherwise. The function signature is: ```java public bool...
```java public boolean matchPattern(String str, String pattern) { int strIndex = 0; int patternIndex = 0; int strLength = str.length(); int patternLength = pattern.length(); while (strIndex < strLength && patternIndex < patternLength) { char ch = pattern.charAt(patternIndex); if (ch...
magicoder
java
You are given a 2D grid of integers representing an image, where each integer represents a color. You are also given the starting pixel (row and column) and a new color. Your task is to implement a function to fill the image with the new color starting from the given pixel. To achieve this, you need to perform a depth-...
```python from typing import List def floodFill(image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]: rows, cols = len(image), len(image[0]) currColor = image[sr][sc] def dfs(x: int, y: int): if x < 0 or x >= rows or y < 0 or y >= cols or image[x][y] != currColor or image[x]...
magicoder
python
You are tasked with implementing a command-line tool for compiling C code using the provided code snippet as a reference. The tool should parse command-line arguments and compile the given C source file into an assembly file using the specified options. Your task is to create a function `compile_c_code` that takes in ...
```python import subprocess def compile_c_code(source, output_filename, args, remainder): cpp_args = ["cpp", "-nostdinc", "-undef"] if args['version']: cpp_args.append(f"-DVERSION={args['version']}") if args['preproc']: cpp_args.append(f"-I{args['preproc']}") if args['charmap']: ...
magicoder
python
You are tasked with implementing a custom asynchronous stream in Rust. The stream will yield a sequence of integers and provide a method to poll for the next value. Your task is to complete the implementation of the `poll` method for the custom stream. You are given the following code snippet as a starting point: ```...
```rust use std::pin::Pin; use std::task::{Context, Poll}; use futures::stream::Stream; struct CustomStream { // Fields and state for the custom stream sequence: Vec<i32>, current_index: usize, } impl Stream for CustomStream { type Item = i32; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Conte...
magicoder
rust
You are tasked with breaking a custom encryption scheme implemented in the Python code snippet below. The encryption function `my_encryption_oracle` takes a plaintext as input and returns the encrypted ciphertext using the AES block cipher in ECB mode. The encryption process involves appending a fixed suffix to the pla...
```python from Crypto.Cipher import AES import binascii def break_encryption_oracle(ciphertext): # Since the encryption is done using ECB mode, we can exploit the deterministic nature of ECB to break the encryption # We'll use a chosen plaintext attack to recover the original plaintext # Create a dictiona...
magicoder
python
You are tasked with implementing a concurrent memory allocation algorithm using Rust's async/await feature. The provided code snippet is part of a larger program that manages memory allocation in a concurrent environment. The `self.allocator.tso.val.store(last_limit, Ordering::SeqCst)` line is responsible for updating ...
```rust use std::sync::{Arc, Mutex}; use std::sync::atomic::{AtomicUsize, Ordering}; use tokio::sync::Mutex as AsyncMutex; struct Allocator { tso: Arc<AtomicUsize>, tso_limit_initialized: Arc<Mutex<bool>>, } impl Allocator { async fn init_tso_limit(&self) -> usize { // Acquire a lock to ensure exc...
magicoder
rust
You are tasked with implementing a single-state generator function in Python. The function should take in an initial state, a goal state, a set of operators, and a successors function, and return a generator that yields valid states based on the given inputs. The single-state generator function should have the followi...
```python def single_generator(initial, goal, operators, successors): visited = set() # To keep track of visited states stack = [(initial, [])] # Stack to store states and their paths while stack: state, path = stack.pop() if state == goal: yield path + [state] # Yield the pa...
magicoder
python
You are tasked with creating a Python class that simulates a user account system. The class should have methods to set and retrieve the username and password, as well as a method to check if the password meets certain criteria. Create a class `UserAccount` with the following methods: 1. `set_username(self, username)`:...
```python class UserAccount: def __init__(self): self.username = None self.password = None def set_username(self, username): self.username = username def set_password(self, password): self.password = password def get_username(self): return self.username de...
magicoder
python
You are working on a Django project that includes three models: `Race`, `Skill`, and `Character`. Each of these models has a field named `name` of type `CharField` with a maximum length of 32 characters and is marked as unique. However, due to a change in requirements, the maximum length of the `name` field needs to be...
```python from typing import List def generate_migration_code(model_names: List[str], new_max_length: int) -> str: migration_code = "" for model_name in model_names: migration_code += f"migrations.AlterField(\n" migration_code += f" model_name='{model_name.lower()}',\n" migration_cod...
magicoder
python
You are tasked with creating a Python program that subscribes to a ROS (Robot Operating System) camera node, captures images at a frequency of 10Hz, and saves these images to a specified directory. Additionally, the program should display the captured images in real-time using OpenCV. Your program should accomplish th...
```python import rospy import cv2 import numpy as np from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvBridgeError import time import os class ImageSubscriber: def __init__(self): self.bridge = CvBridge() self.image_sub = rospy.Subscriber("/camera_topic", Image, self.image_callbac...
magicoder
python
You are tasked with creating a utility function to manage the appearance of navigation bars in a mobile application. The function should set specific visual properties for all navigation bars throughout the app. The properties to be set include the bar's background color, tint color, title text attributes, and bar styl...
```swift enum ColorType: String { case tabBar = "TabBarColor" case active = "ActiveColor" } enum BarStyle { case `default` case black } func setupNavigationBarAppearance(barTintColor: String, tintColor: String, titleTextAttributes: [NSAttributedString.Key: Any], barStyle: BarStyle) { UINavigationB...
magicoder
swift
You are tasked with implementing a C++ class for generating random numbers with a uniform real distribution. The class should be able to generate random numbers within a specified range. Your task is to create a class `UniformRealDistribution` with the following specifications: - The class should be a template class, ...
```cpp #include <random> template <typename T> class UniformRealDistribution { public: UniformRealDistribution(T min, T max) : distribution_(min, max) { random_engine_.seed(std::random_device()()); } T generate() { return distribution_(random_engine_); } private: std::uniform_real...
magicoder
cpp
You are tasked with creating a Python plugin for a Discord bot called Peacebot. The plugin should include a command that allows users to schedule events at specific times using the `apscheduler` library. The plugin should also include a utility function for converting time to a specific format. Your task is to impleme...
```python # peacebot/core/plugins/Miscellaneous/__init__.py import lightbulb from apscheduler.schedulers.asyncio import AsyncIOScheduler from peacebot.core.utils.time import TimeConverter scheduler = AsyncIOScheduler() scheduler.start() @lightbulb.command() async def schedule_event(ctx, time: str, event_name: str): ...
magicoder
python
You are tasked with creating a program that generates a random image with a specific pattern and color scheme. The image should be displayed using Python's matplotlib library. Your task is to write a function that takes in the dimensions of the image and generates a random back_coloring pattern with the specified dimen...
```python import numpy as np import matplotlib.pyplot as plt def generate_and_display_image(width, height): back_coloring = np.random.rand(height, width, 3) plt.axis("off") plt.figure() plt.imshow(back_coloring, interpolation="bilinear") plt.axis("off") plt.show() # Example usage generate_and_...
magicoder
python
You are tasked with creating a script to set up the environment for a continuous integration (CI) pipeline for a documentation website. The script will take in several required inputs and one optional input, and then call a setup script to configure the environment. The required inputs are: - `GIT_BRANCH`: The branch ...
```bash #!/bin/bash # Assign required inputs GIT_BRANCH="${GIT_BRANCH}" DOCKER_USER="${DOCKER_USER}" DOCKER_PASS="${DOCKER_PASS}" APP_ID="${APP_ID}" # ex: /docs-site/docs2-dev DCOS_URL="${DCOS_URL}" # ex: https://leader.mesos DCOS_USER_NAME="${DCOS_USER_NAME}" # ex: docs-bot DCOS_USER_PRIVATE_KEY_PATH="${DCOS_USER_PRI...
magicoder
shell
You are tasked with implementing a file management system that supports file retrieval and storage across different cloud services. Your task is to create a Python class that can interact with Amazon S3 and Dropbox APIs to retrieve and store files. Your class should have the following methods: 1. `get_file(filename)`:...
```python import boto3 import dropbox class Amazon: def __init__(self): # Initialize Amazon S3 client self.s3 = boto3.client('s3') def get_file(self, filename): # Retrieve file from Amazon S3 try: self.s3.download_file('bucket_name', filename, filename) ...
magicoder
python
You are working on a project that involves visualizing mathematical functions using Python's NumPy and Matplotlib libraries. You have been given a code snippet that involves plotting two functions, `y1` and `y2`, against a variable `n1`. Your task is to understand the code snippet and write a Python function to calcula...
```python import numpy as np import matplotlib.pyplot as plt def plot_functions(n1_min, n1_max, Y): n1 = np.arange(n1_min, n1_max+1) # Generate an array of n1 values from n1_min to n1_max y1 = np.log(n1+1) / (1 + 1/n1) # Calculate y1 values for the given n1 range y2 = np.sin(Y*np.log(n1+1)) / np.sin(Y*np...
magicoder
python
You are tasked with implementing a function to extract the Resin app ID from a given environment file. The Resin app ID is only available on a Raspberry Pi and is stored in the `/proc/1/environ` file. The function should read the contents of this file and extract the Resin app ID. However, the function should raise a `...
```python import os def get_resin_app_id() -> str: if not config.IS_ROBOT: raise RuntimeError('Resin app id is only available on the pi') with open('/proc/1/environ', 'r') as environ_file: environ_data = environ_file.read() # Extracting the Resin app ID from the environment data ...
magicoder
python
You are tasked with creating a function that generates a quantum circuit to implement a Multiple-Control Toffoli (MCT) gate. The MCT gate performs a Toffoli operation on a target qubit, controlled by multiple control qubits. The function should take the number of control qubits as input and return a quantum circuit tha...
```python from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit.library import MCMT def create_mct_circuit(num_controls): # Create quantum registers for control and target qubits c = QuantumRegister(num_controls, name='c') t = QuantumRegister(1, name='t') # Crea...
magicoder
python
You are tasked with creating a Python function that processes a given dictionary and converts it into a JSON or YAML file based on the file extension provided. The function should also include a helper function that returns the Python type based on a given string representation. Write a function `convert_and_save(data...
```python import json import yaml from typing import Type def convert_and_save(data: dict, file_name: str) -> None: """ Converts the given dictionary into a JSON or YAML file based on the file extension. Args: data (dict): The dictionary to be saved. file_name (str): The name of the file t...
magicoder
python
You are tasked with implementing a function that processes a dataset using a tree structure and updates the leaf nodes with new values. The tree is represented as a collection of nodes, and each leaf node contains a tensor of distribution parameters. The function iterates through the dataset, processes the input data, ...
```python def process_and_update(tree, train_iter, device): """ Process the dataset and update the leaf nodes in the tree. Args: - tree: A tree structure containing nodes, where each leaf node contains a tensor of distribution parameters. - train_iter: An iterator over the training dataset, yieldin...
magicoder
python
You are tasked with implementing a simplified email management system. The system should allow users to add email accounts and mark selected messages as read. You are provided with a partial code snippet from the system, which includes two methods: `addEmailAccount` and `setRead`. The `addEmailAccount` method adds a ne...
```java public void addEmailAccount(EmailAccount emailAccount){ emailAccounts.add(emailAccount); EmailTreeItem<String> treeItem = new EmailTreeItem<String>(emailAccount.getAdress()); treeItem.setGraphic(iconResolver.getIconForFolder(emailAccount.getAdress())); FetchFoldersService fetchFoldersService = n...
magicoder
java
You are tasked with implementing a function to perform whole image prediction with variable overlap. Given an input image and a model for prediction, the function should produce a prediction for the entire image with the ability to control the overlap between adjacent prediction patches. The function signature is as f...
```python import numpy as np def predict_whole_image(image: np.ndarray, model: Any, patch_size: int, overlap: float) -> np.ndarray: height, width = image.shape[:2] stride = int(patch_size * (1 - overlap)) predictions = np.zeros_like(image) for y in range(0, height - patch_size + 1, stride): fo...
magicoder
python
You are tasked with implementing a class to calculate the probability of drawing a specific card from a deck in a card game. The class should be able to handle different scenarios such as drawing multiple cards, considering the number of specific cards in the deck, and the turn at which the draw is taking place. You a...
```python import math class CardDrawnProbability: def __init__(self, total_cards, specific_cards, num_drawn, num_specific_drawn, turn, num_specific_required): self.total_cards = total_cards self.specific_cards = specific_cards self.num_drawn = num_drawn self.num_specific_drawn = num...
magicoder
python
You are tasked with creating a Python function that processes a JSON Web Token (JWT) and extracts specific claims from it. The JWT contains user information in the form of key-value pairs. Your function should extract the following claims from the JWT and return them as a dictionary: - "nonce" - "aud" - "acr" - "nsAcco...
```python import base64 import json def extract_jwt_claims(jwt: str, user_given_name: str, user_family_name: str) -> dict: # Split the JWT into its three parts: header, payload, and signature header, payload, _ = jwt.split('.') # Decode the payload from base64 and convert it to a dictionary decoded_pa...
magicoder
python
You are tasked with creating a PHP class that implements a simple annotation reader. Annotations are a form of metadata that can be added to classes, methods, or properties in PHP. Your annotation reader should be able to parse and retrieve annotations from class properties. Your task is to implement the `AnnotationRe...
```php class AnnotationReader { public static $reader; public static function getPropertyAnnotations(ReflectionProperty $refProperty): array { $annotations = []; $propertyName = $refProperty->getName(); $propertyAnnotations = self::$reader->getPropertyAnnotations($refProperty); ...
magicoder
php
You are tasked with creating a function that parses an SVG icon data and extracts specific information from it. The SVG icon data is represented as an object with properties `name`, `viewBox`, and `icon`. The `icon` property contains the SVG path data in string format. The function should extract the following informat...
```javascript function parseSVGIcon(iconData) { const path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); path.setAttribute('d', iconData.icon); const pathCommands = path.getTotalLength(); const totalLength = path.getTotalLength(); return { pathCommands, totalLength }; } ```
magicoder
javascript
You are tasked with implementing a concrete class that fulfills the contract defined by the `IUserService` interface in the `LicenseManager.Infrastructure.Services` namespace. The interface outlines methods for managing user data, such as browsing users, retrieving user details, adding, removing, and updating users. Y...
```csharp using System; using System.Collections.Generic; using System.Threading.Tasks; namespace LicenseManager.Infrastructure.Services { public class UserService : IUserService { // Implementing the BrowseAsync method to retrieve all users public async Task<IEnumerable<UserDto>> BrowseAsync()...
magicoder
csharp
You are tasked with implementing a class that represents a document with various types of information. The class should support adding, retrieving, and removing different types of information entries. Each entry has a unique identifier and a description. The class should also provide a method to retrieve all the unique...
```csharp using System; using System.Collections.Generic; public class DocumentManager { private Dictionary<string, string> entries; public DocumentManager() { entries = new Dictionary<string, string>(); } public void AddEntry(string identifier, string description) { if (!entr...
magicoder
csharp
You are tasked with implementing a custom UIViewController subclass that manages a list of tasks. The tasks are represented by a Task struct, which has a title and a completion status. Your goal is to add functionality to the view controller to display the list of tasks and allow the user to mark tasks as completed. Y...
```swift // Solution for TaskListViewController // Implementing UITableViewDataSource methods to populate the table view with tasks extension TaskListViewController { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tasks.count } func tableView(_ tab...
magicoder
swift
You are tasked with simulating the Hodgkin-Huxley model, a mathematical model that describes how action potentials in neurons are initiated and propagated. The model involves a system of differential equations that represent the dynamics of ion channels in the neuronal membrane. The given code snippet provides the con...
```python import numpy as np import matplotlib.pyplot as plt # Constants GNa = 120 # Maximal conductance(Na+) ms/cm2 Gk = 36 # Maximal condectance(K+) ms/cm2 Gleak = 0.3 # Maximal conductance(leak) ms/cm2 cm = 1 # Cell capacitance uF/cm2 delta = 0.01 # Axon condectivity ms2 ENa = 50 # Nernst potential (Na+) mV E...
magicoder
python
You are tasked with fixing a Swift code snippet that contains several errors. The code snippet is attempting to define a generic struct and a closure, but it contains syntax errors and incomplete definitions. Your goal is to identify and correct these errors to make the code snippet valid and functional. Your task is ...
```swift // Corrected and completed code snippet var e: (Int) -> Int = { return $0 } struct d<f: Equatable, g: Equatable> { // Complete the struct definition as per the requirements } // The corrected code snippet should now be free of syntax errors and type-check successfully. ``` In the solution, the closu...
magicoder
swift
You are tasked with creating a program that parses a given HTML file and extracts the URLs of all anchor tags within a specific section of the file. The section of interest is defined by a specific class attribute in the HTML. Write a function `extract_urls_from_html` that takes two parameters: 1. `html_content` (stri...
```python from bs4 import BeautifulSoup def extract_urls_from_html(html_content, section_class): urls = [] soup = BeautifulSoup(html_content, 'html.parser') section = soup.find(class_=section_class) if section: anchor_tags = section.find_all('a') for tag in anchor_tags: href...
magicoder
python
You are tasked with implementing a packet processing system for a network protocol. The system processes packets, each of which may contain a tag and additional data. The code snippet provided is a part of the packet processing logic and includes a match statement to handle different packet tags. For each packet with a...
```rust use std::collections::HashMap; // Define the Tag and Signature types for demonstration purposes enum Tag { SubkeyTag1, SubkeyTag2, Signature, // Add other tag variants as needed } struct Signature { // Define the Signature struct as needed } // Define the process_packets function fn proce...
magicoder
rust
You are tasked with creating a Python program that utilizes the Azure Cognitive Services Speech SDK to recognize and process speech input. Your program should prompt the user to speak a sentence, then use the speech recognizer to transcribe the spoken words into text. Finally, the program should display the transcribed...
```python import azure.cognitiveservices.speech as speechsdk # Set up the speech configuration speech_key = "your_subscription_key" service_region = "your_service_region" speech_config = speechsdk.SpeechConfig(subscription=speech_key, region=service_region) # Create a speech recognizer recognizer = speechsdk.SpeechRe...
magicoder
python
You are tasked with implementing a Python decorator that logs the execution of methods in a class. The decorator should be able to intercept method calls, log the method name, and then execute the method as usual. You are provided with a code snippet that partially implements this functionality using the `inspect` modu...
```python import inspect def log_method_execution(method): def wrapper(self, *args, **kwargs): frame = inspect.currentframe(1) methodName = frame.f_code.co_name print(f"Executing method: {methodName}") return method(self, *args, **kwargs) return wrapper class Logger: @log_m...
magicoder
python
You are tasked with implementing a simplified version of an asynchronous task execution framework. The framework consists of a `Container` class that can execute tasks asynchronously and a `Dependant` class that represents a task dependency. The `Container` class has a method `execute_async` that takes a `Dependant` ob...
```python import asyncio class Container: async def execute_async(self, dependant): await self.solve(dependant) async def solve(self, dependant): await dependant.callback() class Dependant: def __init__(self, callback): self.callback = callback # Example usage async def task_to...
magicoder
python
You are tasked with implementing a Python function to set user and group permissions on a file based on a given mode, user permissions, and group permissions. The function should take the following parameters: - `uids`: A list of integers representing user IDs to be set on the file. - `target_file`: A string representi...
```python import os import subprocess import re def set_uids(target_file: str, uids: list[int], mode: str, user_perms: str, group_perms: str) -> None: # Set file mode subprocess.run(('chmod', mode, target_file), check=True) # Set user and group permissions os.chmod(target_file, int(mode, 8)) # Co...
magicoder
python
You are tasked with implementing a class that handles angle measurements in both degrees and radians. The class should provide conversion operators to seamlessly convert between the two units. You need to create a class called `Angle` with the following requirements: - The class should have private member variables to...
```cpp #include <iostream> #include <cmath> class Radian { double value; public: explicit Radian(double val) : value(val) {} operator double() const { return value; } }; class Degree { double value; public: explicit Degree(double val) : value(val) {} operator double() const { ...
magicoder
cpp
You are tasked with implementing a function that processes a list of data points and organizes them into a dictionary based on their timestamps. Each data point is represented as a tuple in the format `(timestamp, frequency, value)`, where `timestamp` is an integer representing the time in milliseconds, `frequency` is ...
```python from typing import List, Tuple, Dict def process_data(data: List[Tuple[int, str, float]]) -> Dict[int, List[Tuple[str, float, int]]]: result_dict = {} for point in data: anchor_time = point[0] if anchor_time not in result_dict: result_dict[anchor_time] = [] result_...
magicoder
python
You are tasked with implementing a function that can parse and extract comments from a given piece of C# code. The comments can be of two types: single-line comments starting with `//` and multi-line comments enclosed within `/*` and `*/`. Your function should return a list of all the extracted comments in the order th...
```csharp using System; using System.Collections.Generic; using System.Text; class Program { static List<string> ExtractComments(string code) { List<string> comments = new List<string>(); bool inSingleLineComment = false; bool inMultiLineComment = false; StringBuilder currentCom...
magicoder
csharp
You are tasked with simulating a simplified build and test process for a software project. The provided code snippet represents a portion of a build script for a cryptocurrency project. Your goal is to parse the given commands and execute the appropriate actions based on the conditions and environment variables. The s...
```bash # Sample solution in Python # Define the environment variables HOST = "linux" # Replace with actual value BITCOIN_CONFIG_ALL = "--enable-debug" BITCOIN_CONFIG = "" MAKEJOBS = "-j4" GOAL = "all" RUN_TESTS = "true" RUN_BENCH = "true" TRAVIS_EVENT_TYPE = "cron" DEBUG_MODE = "true" # Simulate the execution of th...
magicoder
shell
You are tasked with creating a user registration and verification system for a web application. The system should handle user input, email validation, captcha verification, and user database operations. You are provided with a code snippet from the backend of the registration process. Your task is to implement the miss...
```python # Import necessary modules and classes from flask import request, flash, gettext from models import User # Assuming User model is defined in models.py import utils # Assuming utility functions are defined in utils.py # Function to verify the captcha def verify_captcha(): # Implement captcha verificatio...
magicoder
python
You are tasked with implementing a Python class to calculate the future value of an annuity. An annuity is a series of equal payments made at regular intervals. The future value of an annuity is the value of the series of payments at a specified date in the future, assuming a certain interest rate. The formula to calcu...
```python class FutureValue: def __init__(self, payment, interest_rate, years, periods_per_year, is_annual): self.payment = payment self.interest_rate = interest_rate self.years = years self.periods_per_year = periods_per_year self.is_annual = is_annual def calculate(sel...
magicoder
python
You are tasked with creating a Rust program that manages the configuration of validators for a blockchain network. The program should be able to deserialize a given configuration file into a `ValidatorConfig` struct and perform certain operations based on the configuration. The `ValidatorConfig` struct is defined as f...
```rust use serde::Deserialize; use std::path::PathBuf; use std::fs; use std::io; #[derive(Debug)] pub struct Address(String); #[derive(Debug)] pub struct Id(String); #[derive(Clone, Deserialize, Debug)] pub struct ValidatorConfig { pub addr: Address, pub chain_id: Id, #[serde(default = "reconnect_defaul...
magicoder
rust
You are tasked with implementing a simplified version of the PageRank algorithm using Apache Spark. PageRank is an algorithm used by Google Search to rank web pages in their search engine results. The algorithm works by counting the number and quality of links to a page to determine a rough estimate of the website's im...
```python from operator import add from pyspark.sql import SparkSession def computeContribs(urls, rank): num_urls = len(urls) if num_urls == 0: return [] contrib = rank / num_urls return [(url, contrib) for url in urls] ``` The `computeContribs` function first calculates the total number of ou...
magicoder
python
You are tasked with implementing a prefetching mechanism for a web browser. The mechanism should predict and fetch web pages before the user even navigates to them, based on the user's browsing history. To achieve this, you need to create a data structure and algorithm that efficiently stores and predicts the next web ...
```javascript class Prefetcher { constructor() { this.pageMap = new Map(); // Map to store visited pages and their visit counts this.currentPage = null; // Variable to store the current page } visitPage(page) { if (this.pageMap.has(page)) { this.pageMap.set(page, this.pageMap.get(page) + 1); //...
magicoder
javascript
You are tasked with implementing a generic method for retrieving the value of a specified property from an object using expression trees in C#. The method should be able to extract the property value from the given object based on the provided property expression. Write a method `GetPropertyValue` within the `ObjectEx...
```csharp using System; using System.Linq.Expressions; namespace More.Net.Reflection { public static class ObjectExtensions { public static TProperty GetPropertyValue<TSource, TProperty>( this TSource source, Expression<Func<TSource, TProperty>> propertyExpression) { ...
magicoder
csharp
You are tasked with implementing a migration script for a database schema using a PHP framework that follows the Yii framework conventions. The snippet provided is a part of a migration file and is a method declaration for rolling back the changes made to the database schema. Your task is to complete the implementation...
```php /** * {@inheritdoc} */ public function safeDown() { $this->dropTable('{{%your_table_name}}'); } ``` In the `safeDown` method, the `dropTable` method is used to remove the table that was created in the corresponding `safeUp` method. The `{{%your_table_name}}` placeholder should be replaced with the actual ...
magicoder
php
You are tasked with understanding and analyzing a C++ code snippet related to metadata retrieval and method manipulation. Your goal is to identify the purpose and functionality of the provided code. Given the code snippet: ```cpp struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespac...
The provided code snippet is related to the manipulation and retrieval of metadata for the `ColorHueSlider` class in the context of IL2CPP (Intermediate Language to C++). The `MetadataGetter` struct is used to define a static method `get()` that retrieves metadata for the `add_colorHueDidChangeEvent` method of the `Col...
magicoder
cpp
You are tasked with implementing a Tri-gram language model using the Reuters dataset as the corpus. The Reuters dataset is a collection of news documents that can be used for various natural language processing tasks. In this problem, you will create a Tri-gram model to analyze the language patterns in the Reuters data...
```python from collections import defaultdict import re def create_tri_gram_model(reuters_dataset): model = defaultdict(lambda: defaultdict(lambda: 0)) for document in reuters_dataset: words = document.split() for i in range(len(words) - 2): tri_gram = ' '.join(words[i:i+2]) ...
magicoder
python
You are working on a computer vision project and need to implement object detection using the YOLO (You Only Look Once) algorithm. You have been provided with a code snippet that specifies the configuration file, weights file, image size, confidence threshold, and non-maximum suppression (NMS) threshold for the YOLO al...
```python from typing import List, Tuple import cv2 def perform_object_detection(input_image: str) -> Tuple[List[Tuple[int, int, int, int]], List[str], List[float]]: # Load YOLO model with the provided configuration and weights files net = cv2.dnn.readNet(yolo_cfg_file, yolo_weights_file) # Load input ima...
magicoder
python
You are tasked with creating a JavaScript function that parses a given HTML snippet to extract specific information. The HTML snippet contains a script tag with embedded JavaScript code and a placeholder `<gh_stars>` that needs to be replaced with the number of GitHub stars for a repository. Your task is to write a fun...
```javascript function extractGitHubStars(htmlSnippet) { // Find the index of the <gh_stars> placeholder const index = htmlSnippet.indexOf('<gh_stars>'); // Extract the GitHub stars count as a substring after the <gh_stars> placeholder const starsCountStr = htmlSnippet.substring(index + 10, index +...
magicoder
javascript
You are tasked with creating a script to automate the process of waiting for an Android emulator to fully boot and then sending a key event to the emulator using the Android Debug Bridge (ADB). The script should wait for the emulator to be fully booted before sending the key event. Your script should perform the follo...
```bash #!/bin/bash # Output the current UTC date and time followed by the message echo $(date -u "+%F %H:%M:%S") - Waiting for emulator to fully boot... # Wait for 5 seconds sleep 5 # Check if the emulator is fully booted # Assuming a hypothetical function is_emulator_fully_booted() that returns 0 if fully booted, ...
magicoder
shell
You are tasked with implementing a blockchain interface in Python. The interface contains abstract methods for retrieving the canonical block root and importing a new block. Your goal is to create a concrete class that inherits from this interface and provides implementations for these abstract methods. You are provid...
```python class MyBlockchain(BlockchainInterface): def __init__(self): # Initialize blockchain data structures or connections here pass def get_canonical_block_root(self, slot: int) -> str: # Implement logic to retrieve the canonical block root for the given slot # Example: retu...
magicoder
python
You are tasked with implementing a game system using the Amethyst game engine in Rust. The given code snippet is a part of the system setup, where various plugins and bundles are being added to the game engine. Your task is to create a custom game system that handles the collision detection between entities in the gam...
```rust use amethyst::{ core::SystemDesc, derive::SystemDesc, ecs::{Join, ReadStorage, System, SystemData, World, WriteStorage}, }; #[derive(SystemDesc)] pub struct CollisionSystem; impl<'s> System<'s> for CollisionSystem { type SystemData = ( ReadStorage<'s, Collider>, // Assuming Collider is...
magicoder
rust
You are tasked with creating a Python function that simulates the behavior of a package utility and a task submission system. Your function should take in a source directory, a destination directory, a configuration object, and additional arguments, and then perform the necessary operations to package the source direct...
```python def process_task(src: str, dest: str, config: dict, interactive: bool, exclude: list) -> str: package_with_utils(src, dest) # Package the source directory task_info = bolt.submit(config, tar=str(dest), interactive=interactive, exclude=exclude) # Submit the task return simcloud_good_citizen_remin...
magicoder
python
You are tasked with creating a Python function that extracts and processes system information related to hardware and software components. The function should retrieve and display the versions of various libraries and tools, as well as information about the available CPUs and GPUs. Write a Python function called `syst...
```python import torch import cv2 import rasterio import torch.backends.cudnn import os def system_info(): print("Torch " + torch.__version__) print("OpenCV " + cv2.__version__) print("GDAL " + rasterio._base.gdal_version()) print("Cuda " + torch.version.cuda) print("Cudnn " + str(torch....
magicoder
python
You are tasked with implementing a simplified version of a Microchip DAC (Digital-to-Analog Converter) library for the MCP4822 chip. The library should support the basic functionality of setting the output voltage and powering the chip on or off. The MCP4822 chip uses a specific protocol for communication, and the libr...
```cpp #include <Arduino.h> class DAC { private: // Private variables for communication protocol and state // ... void sendCommand(uint16_t command) { // Implementation of sending command to the DAC // ... } public: void begin() { // Initialization code for the DAC ...
magicoder
cpp
You are tasked with implementing a Python function that generates a random string based on a given pattern. The pattern consists of lowercase letters, uppercase letters, and special characters. The function should take the pattern as input and return a random string that matches the pattern. The pattern can contain th...
```python import random import string def generate_random_string(pattern: str) -> str: placeholders = { '?l': string.ascii_lowercase, '?u': string.ascii_uppercase, '?s': '!@#$%^&*()_+-=[]{}|;:,.<>?' } random_string = '' for char in pattern: if char in placeholders: ...
magicoder
python
You are tasked with creating a program that processes a given string to extract specific information. The input string will contain a series of tasks denoted by uppercase letters, each followed by a description in lowercase letters. Your program needs to extract the tasks and descriptions and then rearrange them in a s...
```python def processTasks(inputString: str) -> str: task_desc_pairs = inputString.split(', ') # Split the input string into task-description pairs task_desc_dict = {} # Create a dictionary to store the tasks and descriptions # Populate the dictionary with tasks and descriptions for pair in task_desc...
magicoder
python
You are tasked with implementing a Python class that represents a matrix and provides various operations on matrices. Your task is to complete the implementation of the `Matrix` class by adding methods for matrix addition, subtraction, and multiplication. The `Matrix` class should have the following methods: 1. `__ini...
```python import numpy as np class Matrix: def __init__(self, rows, cols, data): self.rows = rows self.cols = cols self.data = data def add(self, other): if self.rows != other.rows or self.cols != other.cols: raise ValueError("Matrices must have the same dimensions ...
magicoder
python
You are tasked with creating a Python class that simulates a simple data storage system. The class should be able to load and store data, and handle exceptions gracefully. Your task is to implement the `DataStorage` class with the following specifications: - The class should have a method `load` that returns the last ...
```python import utils import GPIO class DataStorage: def __init__(self): GPIO.setmode(GPIO.BOARD) def load(self): return utils.Load() def store(self, value): try: # Store the value # (Implementation details not provided in the code snippet) pas...
magicoder
python
You are tasked with creating a Python function that parses a configuration file and extracts specific information related to Prometheus metrics. The configuration file contains various settings and comments, and your function should be able to identify and extract the relevant information related to Prometheus metrics....
```python def parse_prometheus_config(config_file_path: str) -> dict: metrics_info = {} with open(config_file_path, 'r') as file: content = file.read() # Extracting metrics type and additional settings metrics_type = re.findall(r'Type:\s*(\w+)', content) additional_settings = re....
magicoder
python
You are working on a project that involves building a web application using Angular 2. As part of the build process, you need to copy the output files generated by webpack to a specific directory. The code snippet provided shows a series of `cp` commands being used to copy the output files to the destination directory....
```python import os import shutil def copy_webpack_output(source_dir: str, destination_dir: str) -> None: files_to_copy = ["webpack-dev-server.js", "polyfills.bundle.js", "vendor.bundle.js", "main.bundle.js"] for file in files_to_copy: source_file = os.path.join(source_dir, file) destinati...
magicoder
python
You are tasked with creating a program that simulates a simple banking system. The program should be able to handle various exceptions that may occur during the execution. One of the key exceptions to handle is the `InsufficientFundsException`, which is thrown when a user attempts to withdraw more money than their acco...
```java // Custom exception class for insufficient funds class InsufficientFundsException extends Exception { public InsufficientFundsException(String message) { super(message); } } // BankAccount class class BankAccount { private double balance; // Constructor public BankAccount(double in...
magicoder
java
You are working as a DevOps engineer for a company that is deploying a WordPress application using Docker containers. Your task is to create a script that automates the deployment process. The script should use the `weave` command to run a Docker container for WordPress with specific configurations. The `weave` comman...
```python def generate_weave_command(ip_address, db_host, db_password, host_port, container_port): return f"sudo weave run {ip_address} -itd -e WORDPRESS_DB_HOST={db_host} -e WORDPRESS_DB_PASSWORD={db_password} -p {host_port}:{container_port} wordpress" # Test the function ip_address = "10.0.100.2/24" db_host = "1...
magicoder
python
You are tasked with creating a function that processes data using a series of transformations. The function will take a list of values, input data, expected output data, and an optional configuration. The function will then apply the transformations to the input data and compare the result with the expected output data...
```python from visuanalytics.analytics.control.procedures.step_data import StepData from visuanalytics.analytics.transform.transform import transform def prepare_test(values: list, data, expected_data: dict, config=None) -> bool: if config is None: config = {} step_data = StepData(config, "0", 0) ...
magicoder
python
You are tasked with creating a Python program that simulates a simple text editor with a word count feature. The program should take a text input from the user and display the word count in real-time as the user types. To achieve this, you need to implement a graphical user interface (GUI) using the `tkinter` library. ...
```python import tkinter as tk def count_words(event=None): text = text_entry.get() words = text.split() word_count_label.config(text=f"Word Count: {len(words)}") def copy_to_clipboard(): text = text_entry.get() root.clipboard_clear() root.clipboard_append(text) root.update() root = tk.Tk...
magicoder
python
You are tasked with implementing a Python class that simulates a simple bank account. The class should support basic operations such as depositing funds, withdrawing funds, and checking the current balance. Additionally, the class should keep track of the total number of transactions performed on the account. Your tas...
```python class BankAccount: def __init__(self, initial_balance): self.balance = max(0, initial_balance) self.transactions = 0 def deposit(self, amount): if amount > 0: self.balance += amount self.transactions += 1 def withdraw(self, amount): if amou...
magicoder
python