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 simulates a simplified file system cleanup process. The program should recursively remove all core files and set the core file size limit to unlimited. Your task is to implement a function `cleanupFileSystem` that takes in a directory path as input and performs the following...
```python import os def cleanupFileSystem(directory_path: str) -> None: for root, _, files in os.walk(directory_path): for file in files: if file == "core": os.remove(os.path.join(root, file)) os.system("ulimit -c unlimited") ``` The `cleanupFileSystem` function uses the `o...
magicoder
python
You are tasked with implementing a simple in-memory key-value store in Rust. The key-value store should support operations for inserting, retrieving, and deleting key-value pairs. You need to implement the `KeyValueStore` struct with the following methods: - `new`: Creates a new instance of `KeyValueStore`. - `insert`:...
```rust struct LoaderKey { id: String, } struct KeyValueStore { backends: Vec<(String, String)>, } impl KeyValueStore { fn new() -> KeyValueStore { KeyValueStore { backends: Vec::new(), } } fn insert(&mut self, key: String, value: String) { self.backends.push((...
magicoder
rust
You are tasked with creating a function that processes a JSON object based on a given schema and a set of parameters. Your goal is to implement the function `process_json` that takes in three parameters: `scope` of type `Option<&json_schema::Scope>`, `body` of type `&str`, and `params` of type `Params`. The function sh...
```rust use serde_json::{Value, from_str}; use json_schema::Scope; struct Params; impl Params { fn process(&self, json: &mut Value, scope: Option<&Scope>) -> ProcessingState { // Implementation of parameter processing logic // This method should apply the parameters to the JSON object and return t...
magicoder
rust
You are tasked with creating a Python function that processes a list of completed items and generates a list of item URL objects. Each item URL object should contain the following attributes: - `itemId`: The ID of the item, which should default to the item's specification ID if not provided. - `productId`: An object co...
```python def generate_item_urls(completed_items): item_urls = [] for item in completed_items: iut = oseo.ItemURLType() iut.itemId = item.item_specification.item_id if item_id is None else item_id iut.productId = oseo.ProductIdType(identifier=item.identifier) iut.productId.collec...
magicoder
python
You are tasked with developing a Python script to manage datasets for a machine learning project. The script should handle command-line arguments, construct dataset paths, and determine whether to load data from raw files. Your task is to complete the script by implementing the missing parts. Given the provided code s...
```python import argparse import os from datetime import datetime # Define the argument parser parser = argparse.ArgumentParser() parser.add_argument('--load-path', type=str, default=None) parser.add_argument('--test', default=False, action='store_true') parser.add_argument('--dataset_name', type=str, required=True) ...
magicoder
python
You are tasked with implementing a program to perform matrix operations efficiently. The program should be able to multiply two square matrices and measure the time taken for the multiplication operation. You are given a code snippet that prints the title of the operation, the elements of the resulting matrix, and the...
```cpp #include <iostream> #include <vector> #include <chrono> std::vector<int> multiplyMatrices(const std::vector<int>& matrix1, const std::vector<int>& matrix2, int size) { std::vector<int> result(size * size, 0); for (int i = 0; i < size; ++i) { for (int j = 0; j < size; ++j) { for (int...
magicoder
cpp
You are tasked with creating a script that processes data and generates a flame graph visualization based on a given filter. The script takes a filter as an argument, then uses the `uniq`, `awk`, and `flamegraph.pl` commands to process the data and create the visualization. Your task is to write a Bash script that tak...
```bash #!/bin/bash # Check if the filter argument is provided if [ -z "$1" ]; then echo "Usage: generate_flamegraph.sh <filter>" exit 1 fi filter="$1" # Process the data and generate the flame graph visualization # Use the provided code snippet to accomplish the task # Assume the input data is provided thro...
magicoder
shell
You are given a function `divideNumberToSubsets` that takes in a vector of strings `numbers` and an integer `numberPosition`. The function is intended to divide the number at the specified position into subsets of digits and return them as a vector of strings. The function should be implemented to achieve the followin...
```cpp vector<string> divideNumberToSubsets(vector<string> &numbers, int numberPosition) { vector<string> setDigits; string number = numbers[numberPosition]; // Extract the number at the specified position string subset; // Initialize an empty string to store subsets of digits for (char digit : number)...
magicoder
cpp
You are tasked with implementing a simplified version of the card game "No Thanks" in Python. In this game, players take turns either picking up the current card or placing a chip on it to avoid taking it. The game ends when the deck is empty, and the player with the lowest total sum of card values and chips wins. You...
```python import random class NoThanksGame: def __init__(self, players): self.players = players self.deck = list(range(3, 36)) self.pot = [] self.current_card = None self.current_player_index = 0 self.chips = {player: [] for player in players} self.collected_...
magicoder
python
You are tasked with implementing a function that simulates the behavior of the `preload_filters` and `load_controllers` methods in a web framework. The `preload_filters` method preloads filters from a specified directory, while the `load_controllers` method loads controllers from a specified directory. Additionally, th...
```python import os def simulate_framework_behavior(zeekofile_codebase, path, config): def preload_filters(directory): # Simulate preloading filters from the specified directory pass def load_controllers(directory): # Simulate loading controllers from the specified directory pa...
magicoder
python
You are tasked with implementing a filtering mechanism for a software application that manages profiles and folders containing action buttons. The application triggers events and needs to identify the action buttons that are associated with the triggered event. Your task is to write a method that filters the action but...
```csharp public List<ActionButton> FilterActionButtons(string eventName, List<MacroDeckProfile> profiles) { List<ActionButton> filteredActionButtons = new List<ActionButton>(); foreach (MacroDeckProfile profile in profiles) { foreach (MacroDeckFolder folder in profile.Folders) { ...
magicoder
csharp
You are tasked with creating a Python script to manage a cluster of servers. The script should utilize the `multiprocessing` module to run three separate processes: `proc_node`, `proc_joblog`, and `proc_command`. Additionally, the script should handle command-line arguments using the `argparse` module. Your task is to...
```python import argparse import multiprocessing import textwrap def proc_node(): # Define the task for the proc_node process print("proc_node process started") def proc_joblog(): # Define the task for the proc_joblog process print("proc_joblog process started") def proc_command(): # Define the t...
magicoder
python
You are tasked with creating a Swift function that determines the access level for a specific feature based on the user's authorization status. The function should take in the authorization status as an input and return the corresponding access level. The authorization status is represented by an enum called `Authoriz...
```swift enum AuthorizationStatus { case authorized case denied case notDetermined case restricted @unknown default } enum AccessLevel { case granted case denied case notDetermined case restrictedBySystem case unknown } func determineAccessLevel(_ status: AuthorizationStatus) -...
magicoder
swift
You are tasked with implementing a simplified version of a Combine-like framework for handling asynchronous operations in Swift. The framework should include a `Publisher` and a `Subscriber` protocol, as well as a `Subscription` type. The `Publisher` should be able to emit values and completion events, while the `Subsc...
```swift // Implementing a concrete Publisher class MyPublisher: Publisher { typealias Output = Int typealias Failure = Error func receive<S: Subscriber>(subscriber: S) where S.Input == Output, S.Failure == Failure { let subscription = Subscription(subscriber: subscriber) subscriber.rec...
magicoder
swift
You are tasked with implementing a custom deserialization process for a specific class in Java. The class `DataObject` needs to be deserialized from a file using a custom context provided by the `DataObjectInputStream` class, which is a wrapper around the standard `ObjectInputStream`. Your task is to complete the deser...
```java import java.io.*; public class CustomDeserialization { public static void main(String[] args) { // declare streams and objects FileInputStream aFileInputStream = null; DataObjectInputStream aDataObjectInputStream = null; DataObject anObject = null; try { ...
magicoder
java
You are tasked with implementing a function to process a list of parts and their corresponding values. The function should identify specific parts that start with the prefix "blst_param_" and map them to their respective value descriptors. The value descriptors are determined based on the type of the part. The parts ar...
```rust use std::collections::HashMap; enum Part { Bool, Uuid, String(HashMap<String, String>), Number(HashMap<String, i32>), } enum StringDescriptor { Uuid(usize), Patterns(Vec<String>), } enum ValueDescriptor { Bool, String(StringDescriptor), } fn search_for_patterns(keys: Vec<Stri...
magicoder
rust
You are working on a data preprocessing task for a machine learning project. The given code snippet is a part of a function that takes a row of data as input and performs several data transformation operations using the pandas and numpy libraries. The input row contains information about students, including their gende...
```python import numpy as np import pandas as pd from sklearn.preprocessing import StandardScaler def preprocess_data(row): row = np.column_stack(row) cols = ['gender', 'race', 'parent_level_of_education', 'lunch', 'test_prep_course', 'reading_score', 'writing_score'] newdf = pd.DataFrame(row,...
magicoder
python
You are tasked with creating a Python script to merge data from two files into a new file using the ArangoDB Python client. The script should handle authentication using a username and password, or a password file if provided. The script should also prompt for the password if it is not provided in the command line argu...
```python import os import getpass from arango import ArangoClient def merge_data_to_arango(nodes_file, names_file, merged_file, arango_url, database, user, pwd_file=None): nodes = os.path.join(nodes_file) names = os.path.join(names_file) merged = os.path.join(merged_file) client = ArangoClient(hosts=a...
magicoder
python
You are given a list of integers representing the scores of a game. The game has a rule that if a player's score is greater than or equal to the previous player's score, they receive a bonus of 2 points; otherwise, they receive a penalty of 1 point. If the first player's score is greater than 0, they receive a bonus of...
```python from typing import List def calculate_points(scores: List[int]) -> int: total_points = 0 if scores[0] > 0: total_points += 2 for i in range(1, len(scores)): if scores[i] >= scores[i-1]: total_points += 2 else: total_points -= 1 return total_poin...
magicoder
python
You are tasked with implementing a photo editing application that applies various filters to images. The application uses a protocol `FilterType` to define different filter functions. Each filter function takes in a `LevelFilter` enum, an average color represented by a dictionary of strings to integers, and an RGBA ima...
```swift // Define the FilterType protocol protocol FilterType { func FilterImageContrast(Level: LevelFilter, avgColor: Dictionary<String,Int>, myRGBA: RGBAImage) -> UIImage func FilterImageBright(Level: LevelFilter, avgColor: Dictionary<String,Int>, myRGBA: RGBAImage) -> UIImage func FilterImageDark(Level:...
magicoder
swift
You are tasked with implementing a simple package management system for a software repository. The system should allow users to add, remove, and list packages, as well as check if a specific package is present in the repository. You are given the following code snippet as a starting point: ```java package com.example...
```java public class PackageManager { // Existing code remains the same public static void main(String[] args) { PackageManager packageManager = new PackageManager(); // Test the package management functionality packageManager.addPackage("package1"); packageManager.addPackage("...
magicoder
java
You are tasked with creating a Python function that parses the metadata from a Python package's setup file and returns a dictionary containing the relevant information. The setup file follows the standard format for Python packages and contains metadata such as name, version, keywords, description, license, and author....
```python import ast def parse_setup_file(file_path): metadata = {} with open(file_path, 'r') as file: setup_content = file.read() setup_ast = ast.parse(setup_content) for node in setup_ast.body: if isinstance(node, ast.Expr) and isinstance(node.value, ast.Call) and node.val...
magicoder
python
You are tasked with implementing a function to validate a given Ethereum address based on its checksum. Ethereum addresses are 40-character hexadecimal strings, which are case-insensitive. The checksum mechanism is used to prevent errors when entering addresses, and it involves capitalizing some of the characters in th...
```rust use sha3::{Digest, Keccak256}; use hex; enum Token { FixedBytes(Vec<u8>), // Other token types } fn validate_ethereum_address(address: &str) -> bool { if address.len() != 42 || !address.starts_with("0x") { return false; // Ethereum address should be 42 characters long and start with "0x" ...
magicoder
rust
You are tasked with implementing a function to move the pivot point of a 3D object to the top of its boundary box in a 3D modeling software environment. The function should take into account the selection of multiple objects and adjust their pivot points accordingly. You are given a code snippet that contains a functi...
```python def gtu_move_pivot_to_top(): ''' Moves pivot point to the top of the boundary box ''' import maya.cmds as cmds # Assuming Maya as the 3D modeling software selection = cmds.ls(selection=True) for obj in selection: bbox = cmds.exactWorldBoundingBox(obj) # Extracts bounding box ...
magicoder
python
You are tasked with implementing a custom crafting container in a Minecraft mod using the Forge modding framework. The provided code snippet is the beginning of a custom container class called `PortableCraftingContainer` that extends the `WorkbenchContainer` class. Your goal is to complete the implementation of this cu...
```java import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.inventory.container.ContainerType; import net.minecraft.inventory.container.WorkbenchContainer; import net.minecraft.util.IWorldPosCallable; import net.minecraft.world.World; import svenhjol...
magicoder
java
You are tasked with creating a unit test for a function that interacts with a sACN (Streaming ACN) DMX merger and universe data. The code snippet provided is from an existing unit test and uses the Google Test framework's `EXPECT_EQ` macro to verify that two specific function calls have not been made. Your task is to ...
```cpp #include <gtest/gtest.h> // Mocks for updateSACNDMXMerger and getUniverseData class MockFunctions { public: static int updateSACNDMXMergerCallCount; static int getUniverseDataCallCount; static void resetCallCounts() { updateSACNDMXMergerCallCount = 0; getUniverseDataCallCount = 0; } static v...
magicoder
cpp
You are tasked with creating a Python script that interacts with the Discord API using the `discord.py` library and simulates keyboard input using the `keyboard` library. Your script should perform the following tasks: 1. Install or upgrade the `pip`, `discord.py`, and `keyboard` packages using the `pip` package manage...
```python import subprocess import shutil import sys def install_upgrade_packages(): try: subprocess.check_call([sys.executable, "-m", "pip", "install", "--upgrade", "pip", "discord.py", "keyboard"]) print("Packages installed/upgraded successfully") except subprocess.CalledProcessError as e: ...
magicoder
python
You are tasked with creating a program that processes a list of flag action properties and performs specific operations based on the properties provided. Each flag action property consists of a key-value pair representing a specific action and its corresponding properties. Your task is to implement a function that proc...
```python from typing import List, Dict, Union def processFlagActions(flagActions: List[Dict[str, Union[str, int]]]) -> Dict[str, Union[str, int]]: result = {} for action_property in flagActions: action = action_property.get("action") if action == "enable_feature": feature_name = ac...
magicoder
python
You are tasked with implementing a Python program to capture and analyze raw network packets using the `socket` module. Your program should capture packets at the device driver level and extract specific information from the captured packets. Your program should perform the following tasks: 1. Create a raw socket to c...
```python import socket import struct import binascii # Create a raw socket to capture packets at the OSI L2 (Data Link Layer) level rawSocket = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0800)) # Capture a single packet packet = rawSocket.recvfrom(65535) # Extract the Ethernet header from the c...
magicoder
python
You are tasked with implementing a custom data structure called `Distance` that represents a distance value. The `Distance` structure should support negation and conform to the `SignedNumeric` protocol. Your task is to implement the `Distance` structure with the following requirements: - It should have two properties:...
```swift // Define the Distance structure conforming to SignedNumeric protocol struct Distance: SignedNumeric { var digitDistance: Int var bitDistance: Int // Initialize the Distance structure with digitDistance and bitDistance init(digitDistance: Int, bitDistance: Int) { self.digitDistance...
magicoder
swift
You are tasked with creating a validation rule for a Laravel application. The application is designed to store home banner information, including a title, details, image URL, and a unique serial number. The provided code snippet is from the `store` method of a controller, where the request data is being validated befor...
To create a custom validation rule for the `serial` field in Laravel, you can use the `Rule` class to define the rule. Here's how you can implement the custom validation rule and use it in the controller's `store` method: ```php // Custom validation rule for unique serial number use Illuminate\Validation\Rule; public...
magicoder
php
You are tasked with implementing a custom action sheet in iOS using Swift. The action sheet should display a list of options and allow the user to select one. The action sheet should be presented when a button is tapped, and it should dismiss when an option is selected. You need to create a custom class for the action ...
```swift // UACustomActionSheet.swift import UIKit class UACustomActionSheet { private var presentingViewController: UIViewController? private var actionSheet: UIAlertController? func displayActionSheet(withOptions options: [String], from viewController: UIViewController) { presentingViewControll...
magicoder
swift
You are tasked with creating a TypeScript function that validates whether a given object conforms to a specific interface. The interface, `PropTypes`, contains two methods: `buttonClick`, which takes no arguments and returns `void`, and `toggle`, which takes a boolean argument and returns `void`. Write a function `val...
```typescript function validatePropTypes(obj: any): boolean { if (typeof obj.buttonClick !== 'function' || typeof obj.toggle !== 'function') { return false; } if (obj.buttonClick.length !== 0 || obj.toggle.length !== 1) { return false; } return true; } ``` The `validatePropTypes` fu...
magicoder
typescript
You are tasked with implementing a file type manager in Python. The file type manager should allow users to add new file types and specify the default application to open each file type. You need to implement the `FileTypeManager` class with the following methods: - `add(file_type, default_app)`: This method should ad...
```python class FileTypeManager: def __init__(self): self.file_types = {} def add(self, file_type, default_app): self.file_types[file_type] = default_app def get_default_app(self, file_type): return self.file_types.get(file_type, None) # Usage ftype = FileTypeManager() ftype.add("...
magicoder
python
You are tasked with creating a Python function that processes files in a given directory using the `os` and `subprocess` modules. Your function should yield the full path of each file in the directory and then run a specified command using `subprocess.run`. The output of the command should be printed to the console. W...
```python import os import subprocess def process_files_and_run_command(directory_path, command): for file in os.listdir(directory_path): file_path = os.path.join(directory_path, file) if os.path.isfile(file_path): yield file_path result = subprocess.run(command, stdout=subp...
magicoder
python
You are tasked with implementing a simulated annealing algorithm to solve the Traveling Salesman Problem (TSP). The TSP is a classic optimization problem where the goal is to find the shortest possible route that visits each city exactly once and returns to the original city. In this problem, you will be given a distan...
```python import numpy as np from math import exp, sqrt import pandas as pd import random # Import an Excel file into Python file_name, sheet = "TSP.xlsx", "Arkusz1" data = pd.read_excel(file_name, sheet_name=sheet, engine='openpyxl') # Getting initial solution solution = list(range(1, len(data) + 1)) # List of all ...
magicoder
python
You are tasked with implementing a function that retrieves the name of a system group based on its group ID. The system has a predefined set of group IDs and their corresponding group names. Your task is to write a function `system_groupname_from_groupid` that takes an integer `groupid` as input and returns the corresp...
```python def system_groupname_from_groupid(groupid): group_mapping = { 0: "admin", 1: "users", 2: "guests" } return group_mapping.get(groupid, "Unknown Group") ``` The `system_groupname_from_groupid` function uses a dictionary `group_mapping` to store the predefined group IDs and t...
magicoder
python
You are working on a computer vision project that involves detecting keypoints in images. You have a keypoint detector that takes a set of images as input and returns the detected keypoints along with their scores. Additionally, you have a function that translates these keypoints to their original positions in the imag...
```python import numpy as np def translate_to_ori_images(keypoint_results, records): keypoint_vector = [] score_vector = [] for keypoint in keypoint_results: x, y, score = keypoint translated_x = int(x * records.shape[1]) # Translate x coordinate to original image size translated_y...
magicoder
python
You are given a set of rules for a game, each represented by a string. Each rule can consist of multiple lines, but only one line is enough to satisfy the condition of the rule. Your task is to write a program that checks if a given input string satisfies at least one line of each rule. For example, consider the follo...
```java public boolean checkRules(List<String> rules, String input) { for (String rule : rules) { String[] lines = rule.split("}"); boolean ruleSatisfied = false; for (String line : lines) { if (line.contains("if")) { String condition = line.substring(line.indexOf...
magicoder
java
You are tasked with creating a simple web application using Python's Flask framework. Your task is to implement a route that serves a static HTML file and a route that handles a POST request to update a user's information. You are given a code snippet that initializes a Flask application with a static folder. Your tas...
```python from flask import Flask, render_template, request app = Flask(__name__, static_url_path='', static_folder='static') # Route to serve the static HTML file @app.route('/home') def serve_static_html(): return app.send_static_file('index.html') # Route to handle a POST request to update user information @a...
magicoder
python
You are tasked with implementing a class that utilizes the `ConfigLoader` interface to load and process configuration properties from a file. The `ConfigLoader` interface contains a single method `loadConfig` that takes a file name as input and returns a `Properties` object representing the configuration properties loa...
```java import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; public class CustomConfigLoader implements ConfigLoader { @Override public Properties loadConfig(String fileName) throws IOException { Properties properties = new Properties(); try (FileInputStream...
magicoder
java
You are tasked with implementing a function that calculates the average of a list of numbers, excluding the minimum and maximum values from the calculation. Write a Python function called `calculate_average` that takes a list of numbers as input and returns the average of the remaining numbers after excluding the minim...
```python from typing import List def calculate_average(numbers: List[float]) -> float: if len(numbers) < 3: raise ValueError("Input list should contain at least 3 numbers") min_val = min(numbers) max_val = max(numbers) sum_excluding_min_max = sum(numbers) - min_val - max_val count_exclud...
magicoder
python
You are tasked with implementing a configuration parser for a system that reads time intervals specified in a configuration file and converts them to seconds. The configuration file uses a format where time intervals are specified as a number followed by a unit indicator (e.g., "15m" for 15 minutes). If the unit indica...
```python import re class Config: def __init__(self, config): self._config = config def parse_time(self, time_str): units = {"s": 1, "m": 60, "h": 3600, "d": 86400} # Define time units in seconds match = re.match(r'(\d+)([smhd]?)', time_str) # Match digits followed by optional unit i...
magicoder
python
You are tasked with creating a Rust program that processes and displays a 3D point cloud using the kiss3d graphics library. The program should read a point cloud from a file, flip it vertically, and then render it in a 3D window using kiss3d. Your task is to implement the `process_and_display_point_cloud` function, wh...
```rust use crate::errors::*; use image::{imageops::flip_vertical, ImageBuffer, Rgb}; use kiss3d::camera::ArcBall; use kiss3d::light::Light; use kiss3d::point_renderer::PointRenderer; use kiss3d::window::CanvasSetup; use kiss3d::window::NumSamples; use kiss3d::window::Window; use nalgebra::Point3; use std::sync::mpsc::...
magicoder
rust
You are tasked with implementing a simple configuration system for a settings module in a Swift application. The provided code snippet includes partial implementation of the configuration process using Swift classes and extensions. Your goal is to complete the configuration process by implementing the missing parts and...
```swift protocol SettingsViewControllerOut { // Define protocol requirements here } protocol SettingsInteractorOut { // Define protocol requirements here } class SettingsInteractor: SettingsViewControllerOut { // Implement protocol requirements here } class SettingsPresenter: SettingsInteractorOut { ...
magicoder
swift
You are tasked with implementing a data merging algorithm for a machine learning dataset management system. The system consists of collections of datasets, each containing runs and splits. Your goal is to merge the data from multiple source collections into a target collection based on specific criteria. You are given...
```python def merge_data(source_collection_pathes, target_collection, train_set_name_suffix): for source_collection_path in source_collection_pathes[1:]: source_collection = BaseDataset.load(source_collection_path) for run in source_collection.get_run_numbers(): for split in source_colle...
magicoder
python
You are tasked with creating a migration script for a Django application. The application has a model named "relationship" with a field named "people" that represents a many-to-many relationship with another model named "Person" through an intermediary model named "Relation". Your task is to write a migration script th...
```python from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("village_api", "0007_auto_20210830_1327"), ] operations = [ migrations.AlterField( model_name="relationship", name="people", field=models.ManyToM...
magicoder
python
You are given an array of non-negative integers representing the maximum number of steps you can take from each position in the array. You start at the first position and must reach the last position using the minimum number of jumps. Write a function `jump` that takes in an array of integers and returns the minimum nu...
```swift func jump(_ nums: [Int]) -> Int { if nums.count <= 1 { return 0 } var currentMax = 0 var nextMax = 0 var jumps = 0 var i = 0 while i <= currentMax { jumps += 1 while i <= currentMax { nextMax = max(nextMax, i + nums[i]) if ne...
magicoder
swift
You are tasked with creating a Python program that simulates a simple banking system. The program should be able to handle multiple user accounts, allowing users to create accounts, log in, deposit money, withdraw money, and view their balance. The program should also ensure that users cannot withdraw more money than t...
```python class BankingSystem: def __init__(self): self.accounts = {} def create_account(self, username, initial_balance): if username not in self.accounts: self.accounts[username] = initial_balance return f"Account created for {username} with initial balance {initial_ba...
magicoder
python
You are tasked with implementing a class for a 3D convolutional neural network (CNN) in Python using the PyTorch library. The provided code snippet is a partial implementation of the CNN class, and your task is to complete the class by adding the necessary layers and methods. The class should have the following specif...
```python import torch.nn as nn class CNN3D(nn.Module): def __init__(self, out_channels, start_filts, with_logit, in_shape): super(CNN3D, self).__init__() self.out_channels = out_channels self.start_filts = start_filts self.with_logit = with_logit self.in_shape = in_shape ...
magicoder
python
You are given a segment tree implementation in C++ for range queries on an array. The segment tree is represented using a class with the following member functions: ```cpp ll qrl(ll li, ll ri) ll qrr(ll li, ll ri) void clr() ``` Where `ll` is a typedef for a long long integer, and the segment tree has been constructe...
```cpp #include <iostream> #include <vector> using namespace std; typedef long long ll; class SegmentTree { private: ll l, r, dtr; SegmentTree *lc, *rc; public: SegmentTree(ll left, ll right, vector<ll>& arr) { l = left; r = right; if (l == r - 1) { dtr = arr[l]; ...
magicoder
cpp
You are tasked with creating a password strength checker program. The program should prompt the user to enter a new password and then evaluate the strength of the password based on the following criteria: 1. The password must be at least 8 characters long. 2. The password must contain at least one uppercase letter, one...
```python import re from getpass import getpass def is_password_strong(password): if len(password) < 8: return False if re.search(r'[A-Z]', password) is None: return False if re.search(r'[a-z]', password) is None: return False if re.search(r'\d', password) is None: retur...
magicoder
python
You are tasked with creating a program that dynamically generates a serialization function using C# expression trees. The serialization function will take an object and a writer as input and serialize the object using a switch statement to handle different cases based on the object's type. Your task is to implement th...
```csharp using System; using System.Collections.Generic; using System.Linq.Expressions; public class SerializationGenerator { public delegate void SerializeDelegate(object obj, IWriter writer); public static SerializeDelegate GenerateSerializationFunction(List<Case> cases) { var valueParameter = ...
magicoder
csharp
You are tasked with creating a command-line interface (CLI) tool for optical character recognition (OCR) using Python. Your tool should be able to recognize text from images using the Calamari OCR engine. The provided code snippet is a part of a Python setup script (setup.py) for a package called "ocrd_calamari". It de...
```python # ocrd_calamari/cli.py import argparse from calamari_ocr.ocr import MultiPredictor from calamari_ocr.model import load_checkpoint from calamari_ocr.utils import glob_all def ocrd_calamari_recognize(): parser = argparse.ArgumentParser(description='OCR with Calamari') parser.add_argument('image_files'...
magicoder
python
You are tasked with creating a Java program that manages a collection of items using the Tracker class. The Tracker class should have the ability to add, replace, delete, and find items. Additionally, the program should be able to display a list of all items in the collection. Your task is to implement the Tracker cla...
```java package ru.job4j.tracker; import java.util.Arrays; public class Tracker { private Item[] items = new Item[10]; private int position = 0; public void add(Item item) { items[position++] = item; } public void replace(String id, Item item) { for (int i = 0; i < position; i++)...
magicoder
java
You are tasked with implementing a custom collection type in Swift that conforms to the `AppendableCollection` protocol. The `AppendableCollection` protocol extends the standard `Collection` protocol and requires the implementation of a `mutating` method `append(_ newElement: Self.Iterator.Element)`. Your task is to c...
```swift // Your implementation of CustomCollection conforming to AppendableCollection protocol struct CustomCollection<T>: AppendableCollection { private var elements: [T] = [] // Implementing the append method as required by AppendableCollection protocol mutating func append(_ newElement: T) { el...
magicoder
swift
You are tasked with creating a function that parses a given HTML document to extract menu items and their corresponding dates. The HTML document contains a list of menu items, each with a date associated with it. The menu items are represented as list items within an unordered list, and the date is specified within a s...
```javascript import cheerio from "cheerio"; import { IMenuItem } from "./IMenuItem"; import { getDateRegex } from "./parserUtil"; function parseMenuItems(html: string): IMenuItem[] { const $ = cheerio.load(html); const menuItems: IMenuItem[] = []; $("#menu li").each((index, element) => { const name = $(ele...
magicoder
javascript
You are tasked with implementing a memory management system for a programming language that supports manual memory management. The system should allow for the explicit control of memory deallocation to prevent memory leaks and optimize memory usage. Your task is to create a function `withExtendedLifetime` that takes a...
```swift class ManagedReference<T> { var value: T init(_ value: T) { self.value = value } } func withExtendedLifetime<T>(_ reference: ManagedReference<T>, _ closure: (T) -> Void) { // Perform memory management operations to extend the lifetime of the reference closure(reference.value) } //...
magicoder
swift
You are tasked with implementing a job assignment system for a colony on a distant planet. The colony has various managerial tasks, including managing job assignments, job priorities, mining/construction positions, etc. Your goal is to create a program that efficiently assigns jobs to the colony's inhabitants based on ...
```python def assignJobs(jobs, colonists): job_assignments = {} available_jobs = jobs[:] # Create a copy of the jobs list to track available jobs # Sort jobs by priority in descending order available_jobs.sort(key=lambda x: x["priority"], reverse=True) # Iterate through available jobs and assign ...
magicoder
python
You are working on a robotics project that involves identifying and distinguishing between red and green objects using computer vision techniques. The given code snippet is a part of the image processing module of the robot's software. The snippet uses the OpenCV library to process the input image in the HSV color spac...
```cpp bool FilterAndFind(const std::vector<std::vector<Point>>& contours) { int validContours = 0; for (const auto& contour : contours) { double area = contourArea(contour); if (area > MIN_AREA_THRESHOLD && area < MAX_AREA_THRESHOLD) { // Calculate the bounding box of the contour ...
magicoder
cpp
You are tasked with creating a Python function that processes a list of videos to detect clothing items in each frame. The function should utilize a clothing detection pipeline and be able to handle a large number of videos efficiently. The provided code snippet gives a glimpse of the existing codebase and the configur...
```python from typing import List, Dict from esper.clothing_detection import ClothingDetectionPipeline from esper.models import Video def detect_clothing_in_videos(videos: List[Video]) -> Dict[str, List[str]]: # Initialize the clothing detection pipeline runner detect_clothing = ClothingDetectionPipeline.make_...
magicoder
python
You are tasked with creating a TypeScript module loader utility that can dynamically import and export modules based on a given directory path. Your utility should be able to load all the TypeScript files from the specified directory and export them as named exports. Write a function `loadModules` that takes a directo...
```typescript import * as path from 'path'; import * as fs from 'fs'; export async function loadModules(directoryPath: string): Promise<void> { const files = fs.readdirSync(directoryPath); for (const file of files) { if (file.endsWith('.ts')) { const moduleName = file.split('.')[0]; const modulePat...
magicoder
typescript
You are tasked with implementing a simple correlation algorithm to find the correlation coefficient between two arrays of data. The correlation coefficient measures the strength and direction of a linear relationship between two variables. It ranges from -1 to 1, where 1 indicates a perfect positive linear relationship...
```python def calculate_correlation_coefficient(array1, array2): n = len(array1) mean_array1 = sum(array1) / n mean_array2 = sum(array2) / n numerator = sum((array1[i] - mean_array1) * (array2[i] - mean_array2) for i in range(n)) denominator = (sum((array1[i] - mean_array1)**2 for i in range(n)) * ...
magicoder
python
You are tasked with creating a Python class that implements a simple logging system. The class should have the ability to log messages at different levels of severity and store them for later retrieval. Additionally, the class should support the ability to filter messages based on their severity level. Your task is to...
```python from abc import ABC, abstractmethod from typing import List class Logger(ABC): def __init__(self): self.logs = {} @abstractmethod def log(self, message: str, severity: str) -> None: pass @abstractmethod def get_logs(self, severity: str) -> List[str]: pass class ...
magicoder
python
You are tasked with creating a Rust function that processes geographic features and generates a schema based on their properties. The schema should map property names to their corresponding data types. The input features are represented using the `geojson::Feature` type, and their properties are stored as key-value pai...
```rust use std::collections::HashMap; use geojson::Feature; use serde_json::Value; #[derive(Debug, PartialEq, Eq)] enum PropType { String, Long, Double, JsonVal, } fn schema<'a>(features: impl Iterator<Item = &'a Feature>) -> HashMap<String, PropType> { let mut schema = HashMap::<String, PropType...
magicoder
rust
You are tasked with implementing a function that manages a library's collection of books. The library has a system for categorizing books into different collections, and each user can have access to specific collections based on their preferences. Your task is to implement a function `collectionBooksCollection` that re...
```swift func collectionBooksCollection(of collection: Collection, for user: User) -> CollectionReference { guard user.preferredCollections.contains(collection) else { // If the user does not have access to the requested collection, return a reference to an empty collection return CollectionReferenc...
magicoder
swift
You are tasked with creating a script to automate the deployment process for a software project. The deployment process involves executing a series of commands to set up the necessary environment and generate documentation. Your script should perform the following steps: 1. Run a bash script named `credentials.sh` to ...
```bash #!/bin/bash # Run the credentials script if ! bash scripts/credentials.sh; then echo "Error: Failed to set up credentials." exit 1 fi # Install project dependencies if ! make deps; then echo "Error: Failed to install project dependencies." exit 1 fi # Generate project documentation if ! make docs; th...
magicoder
shell
You are tasked with creating a Python class that generates input files for VASP (Vienna Ab initio Simulation Package) calculations. VASP requires several input files to execute, such as INCAR and KPOINTS. Your task is to create a class called `VASPInputGenerator` that provides methods to generate these input files from...
```python class VASPInputGenerator: def generate_incar_file(self, incar_params): """Generate INCAR file from the given parameters.""" with open('INCAR', 'w') as f: for key, value in incar_params.items(): f.write(f"{key} = {value}\n") def generate_kpoints_file(self, k...
magicoder
python
You are tasked with creating a program that can parse and extract specific attributes from HTML data. Your program should be able to extract the value of the `data-offset-y` attribute from a given HTML tag. Write a function `extractOffsetY` that takes a string representing an HTML tag as input and returns the value of...
```python import re def extractOffsetY(html_tag: str) -> int: match = re.search(r'data-offset-y="(\d+)"', html_tag) if match: return int(match.group(1)) else: raise ValueError("Invalid HTML tag format or missing data-offset-y attribute") ``` The `extractOffsetY` function uses the `re.searc...
magicoder
python
You are tasked with simulating the behavior of a winch system in a Python class. The class contains methods to control a slider and a winch. The `retract()` method is used to retract the slider, and the `windWinch()` method is used to control the winch. The `windWinch()` method is decorated with `@state()`, indicating ...
```python class state: def __init__(self): self.initial_call = True def __call__(self, func): def wrapper(*args, **kwargs): result = func(*args, self.initial_call, **kwargs) self.initial_call = False return result return wrapper class SliderWinch: ...
magicoder
python
You are given a snippet of code that initializes variables for a simple program. Your task is to complete the program by implementing a specific function. The program is a simulation of a simple assembly-like language. The `reg` list represents the registers, and `ip_reg` is the instruction pointer register. The progra...
```python def execute_program(instructions: list) -> int: ip_reg = 4 reg = [0, 0, 0, 0, 0, 0] i = 0 seen = set() lst = [] while reg[ip_reg] < len(instructions): if reg[ip_reg] == 1: if reg[0] in seen: return reg[0] seen.add(reg[0]) op, a,...
magicoder
python
You are tasked with implementing a function to analyze a given Java test class and extract information about its test methods. The test class follows the JUnit testing framework and contains various test methods annotated with `@Test`. Each test method may have different characteristics, such as having a topology name ...
```java import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class TestMethodCharacteristics { public static List<TestMethodInfo> analyzeTestMethods(String sourceCode) { List<TestMethodInfo> testMethodCharacteristics = new ArrayList<>(); ...
magicoder
java
You are tasked with implementing a TypeScript class that handles HTTP requests for authentication. The class should have a method `route` that takes a request object and returns a Promise of an HTTP response containing authentication data. The `route` method should accept any type of request object and return a Promis...
```typescript class AuthHandler { async route(request: any): Promise<HttpBaseResponse<AuthDto>> { // Simulate authentication logic const authData: AuthDto = { token: "randomToken", userId: "12345" }; // Simulate HTTP response const httpResponse: HttpBaseResponse<AuthDto> = { sta...
magicoder
typescript
You are working on a data processing project and need to manipulate and save data using Python's pandas library. Your task is to write a Python function that takes a list of dataframes, sets the index of each dataframe to a specific column, concatenates the dataframes into a single dataframe, and then saves the concate...
```python import pandas as pd def process_and_save_dataframes(dataframes, index_column, output_file_path): frames = [] for _df in dataframes: _df.set_index(index_column, inplace=True) frames.append(_df) concatenated_df = pd.concat(frames) concatenated_df.to_pickle(output_file_path)...
magicoder
python
You are tasked with implementing a visitor pattern for a simple SQL query parser. The given code snippet is part of the visitor implementation for the parser. The visitor pattern is used to separate algorithm from the object structure on which it operates. In this case, the visitor pattern is used to traverse the abstr...
```java @Override public void visit(Select select) { _sb.append("SELECT "); // Append columns for (int i = 0; i < select.getColumns().size(); i++) { select.getColumns().get(i).accept(this); if (i < select.getColumns().size() - 1) { _sb.append(", "); } } // Append ...
magicoder
java
You are tasked with creating a Python function that securely retrieves sensitive API keys from a configuration file and validates their correctness. The configuration file, `config.py`, contains two variables: `CENSUS_KEY` and `FIREBASE_SERVICE_KEY`, which store the API keys for accessing the Census and Firebase servic...
```python # Import necessary modules import config def validate_api_keys(): # Validate Census API key if not isinstance(config.CENSUS_KEY, str) or config.CENSUS_KEY == '': raise ValueError("Invalid Census API key in config file") # Validate Firebase service API key if not isinstance(config.FIR...
magicoder
python
You are tasked with creating a Python class that simulates a stock portfolio and provides methods for rendering the portfolio and volume charts. The class should have the following functionalities: 1. Initialize the portfolio with an initial investment amount and a list of stock prices. 2. Provide a method to update t...
```python import matplotlib.pyplot as plt import numpy as np from typing import List class StockPortfolio: VOLUME_CHART_HEIGHT = 5 # Constant for volume chart height def __init__(self, initial_investment: float, stock_prices: List[float]): self.initial_investment = initial_investment self.sto...
magicoder
python
You are tasked with implementing a function that takes a list of integers and a target sum as input and returns a pair of integers from the list that add up to the target sum. If no such pair exists, the function should return an empty list. Additionally, the function should handle duplicate values in the input list an...
```python from typing import List def find_pair_sum(nums: List[int], target: int) -> List[int]: num_indices = {} for i, num in enumerate(nums): complement = target - num if complement in num_indices: return [complement, num] if num_indices[complement] < i else [num, complement] ...
magicoder
python
You are given a Python class method that processes an array of data and updates certain attributes of the class instance. The method is responsible for parsing the input array and updating the attributes based on the parsed data. Your task is to implement the method that correctly processes the input array and updates ...
```python class DataProcessor: def __init__(self, num_steps, max_iter): self.num_steps = num_steps self.max_iter = max_iter self.iters_per_step = [0] * num_steps self.resid_per_step = [[0] * max_iter for _ in range(num_steps)] self.delq0_per_step = [[0] * max_iter for _ in ra...
magicoder
python
You are tasked with implementing a logging system for a software application. The system should support different log levels and be able to output log messages to various destinations such as the console, files, or a network service. Your task is to design and implement a flexible logging system that can be easily exte...
To implement the flexible logging system, you can use the following design pattern: 1. Define a Logger interface that declares methods for logging messages at different levels and to different destinations. ```java public interface Logger { void log(LogLevel level, String message); } ``` 2. Implement concrete Log...
magicoder
java
You are tasked with creating a custom field for a Django model that stores the names of files in a specific directory. The custom field should be a subclass of `models.CharField` and should have the following characteristics: - It should accept an optional `widget` argument to specify the type of widget to use for rend...
```python from django.db import models class WidgetCharField(models.CharField): def __init__(self, *args, **kwargs): self.widget = kwargs.pop('widget', None) self.blank_text = kwargs.pop('blank_text', 'No image selected') super().__init__(*args, **kwargs) def formfield(self, **kwargs):...
magicoder
python
You are tasked with implementing a function that performs clustering on a given dataset using the K-means algorithm. The function `split()` takes as input a dataframe, an initial cluster, an action, a target column name, a contradiction cluster `c`, a time horizon `T`, the number of features, and an iterator `k` (index...
```python from sklearn.cluster import KMeans def split(dataframe, initial_cluster, action, target_colname, c, T, num_features, k): # Extract features for clustering features = dataframe[[target_colname] + [f'feature{i}' for i in range(1, num_features)]] # Initialize KMeans model with 2 clusters kmeans...
magicoder
python
You are tasked with implementing a custom query set in a Django model to filter and retrieve published news articles. The provided code snippet is a part of a Django model manager, which includes a method to return a query set and another method to filter the query set for published news articles. Your task is to comp...
```python class BaseNewsQuerySet(models.QuerySet): def published(self): return self.filter(publication_status='published') ``` In the solution, the `BaseNewsQuerySet` class is completed with the `published` method, which filters the query set based on the publication status field of the news articles. The `...
magicoder
python
You are tasked with implementing a rendering system for different types of lights in a 3D graphics engine. The code snippet provided is part of a function that handles different types of lights and their corresponding rendering logic. The function processes each light and populates a vector of camera constant buffers f...
```cpp void RenderLights(const std::vector<LightData>& lights, std::vector<CameraConstantBuffer>& cameraBuffers) { for (const auto& lightData : lights) { if (lightData.m_lightType == ELightType::Directional) { int renderTargetOffset = lightData.m_renderTargetOffset; Came...
magicoder
cpp
You are tasked with implementing a function to process and insert data into a graph database. The function will read data from JSON files and insert it into the graph database using a specific query. The provided code snippet gives a glimpse of the process, including the use of Cypher queries and environment settings. ...
```python import os import json import time from py2neo import Graph def main(user_file_path, business_file_path, review_file_path, graph): # Set socket timeout http.socket_timeout = 9999 # Load environment settings secrets.env()() # Read user data from JSON file with open(user_file_path, 'r'...
magicoder
python
You are tasked with implementing a simple library for managing book metadata. The library should provide functionality to store and retrieve information about books, such as the title, author, and last updated timestamp. You are provided with a partial implementation of the `Book` struct and its associated methods in ...
```rust struct Book { title: String, author: Option<String>, updated: Option<String>, } impl Book { pub fn new(title: String, author: Option<String>, updated: Option<String>) -> Book { Book { title, author, updated, } } pub fn title(&self) ->...
magicoder
rust
You are tasked with implementing a custom exception class in Java for handling RPC (Remote Procedure Call) errors. The provided code snippet is a partial implementation of the `GenericRpcException` class using the Lombok library's `@Getter` annotation to generate the getters for the class fields. Your task is to compl...
```java import lombok.Getter; @Getter public class GenericRpcException extends RuntimeException { private final String errorKey; private final String errorMessage; private final int errorCode; public GenericRpcException(String errorKey, String errorMessage, int errorCode) { super(errorMessage...
magicoder
java
You are tasked with creating a Python unit test for a provisioning framework called Provy. The framework allows users to define roles, provisions, cleanups, and contexts for server provisioning. Your goal is to write a unit test that ensures the correct execution of the `run` function from the `provy.core.runner` modul...
```python import unittest from mock import patch, Mock from provy.core.runner import run from tests.functional.fixtures.provyfile import provisions, cleanups, contexts, Role1, Role2, Role3 class TestProvyFramework(unittest.TestCase): @patch('provy.core.runner.run') def test_provisioning_roles(self, mock_run): ...
magicoder
python
You are tasked with creating a Python script that dynamically imports modules and executes specific functions based on user input. The script should be able to load command tables and arguments from the imported modules and optionally initialize them. Your task is to implement the necessary functionality to achieve thi...
```python from importlib import import_module # Imported modules MUST implement load_command_table and load_arguments # Imported modules CAN optionally implement init module_names = ['ad', 'aks', 'browse', 'cloudshell', 'functionapp', 'loganalytics', 'self_destruct', 'vm'] # Example module as a clean place to start ...
magicoder
python
You are tasked with implementing a custom ZipStream class in C++ that allows for zipping two streams together. The ZipStream class should take a BaseStream and another Stream as input and return a new ZipStream object. The ZipStream class should have the following member function: ```cpp ZipStream<BaseStream<Out>, Str...
```cpp template <typename Out, typename Stream2> class BaseStream { // Implementation of BaseStream class }; template <typename Out, typename Stream2> class ZipStream { public: ZipStream<BaseStream<Out>, Stream2> Zip(const Stream2 &other) { // Implement the zipping logic here // Ensure proper m...
magicoder
cpp
You are working on a file management system and need to create a Python script to organize directories based on a given set of rules. Your script should be able to handle directory paths and perform operations such as creating, moving, and deleting directories. You are given a Python script `Dirs.py` with the followin...
```python import os import shutil def organize_directories(directory_path): backup_dir = os.path.join(directory_path, "backup") os.makedirs(backup_dir, exist_ok=True) for root, dirs, files in os.walk(directory_path): for file in files: if file.endswith(".txt"): file_pat...
magicoder
python
You are tasked with implementing a function to decode a stream of base64-encoded data. The function should take an iterator as input and yield decoded bytes as output. The input iterator will provide chunks of base64-encoded data, and your function should decode these chunks and yield the decoded bytes. You are provid...
```python import base64 from typing import Iterator, Generator, bytes def stream_decode_response_base64(stream: Iterator) -> Generator[bytes, None, None]: partial_chunk_buffer = bytearray() for chunk in stream: if len(partial_chunk_buffer) > 0: chunk = partial_chunk_buffer + chunk ...
magicoder
python
You are tasked with creating a parallel processing algorithm to optimize convolutional neural networks (CNNs) for image classification. The goal is to parallelize the optimization process across multiple GPUs to speed up the training and hyperparameter tuning. You are given a code snippet that demonstrates the use of ...
To solve this problem, we can use the `joblib` library to parallelize the optimization process across multiple GPUs. We will define the `optimize_cnn` function and use the `Parallel` and `delayed` functions to parallelize the optimization across the specified number of GPUs. The results will be collected and logged, in...
magicoder
python
You are tasked with creating a program that processes a file containing a list of slide names and their corresponding heatmap values. Each line in the file represents a slide name followed by a space and then the heatmap value. The program should read the input file, calculate the average heatmap value for each slide, ...
```python import sys def calculate_average_heatmap(input_file): slide_heatmap = {} slide_count = {} try: with open(input_file, 'r') as file: for line in file: slide, heatmap = line.strip().split() heatmap = float(heatmap) if slide in ...
magicoder
python
You are tasked with implementing a custom class loader in Java that can dynamically load and instantiate classes at runtime. Your class loader should provide two methods: `loadClass` and `loadDefaultClass`. The `loadClass` method should take a fully qualified class name as a parameter and return an instance of the loa...
```java import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class CustomClassLoader extends ClassLoader { private String[] additionalDirectories; public CustomClassLoader(String[] additionalDirectories) { this.addi...
magicoder
java
You are tasked with implementing a Python class that generates a sequence of random integers based on a given seed. The class should allow for different modes of generating the sequence and provide flexibility in specifying the seed. Your task is to create a class called `RandomIntegerSequence` with the following spec...
```python from random import Random from randomgen.seed_sequence import SeedSequence from typing import Union, Sequence class RandomIntegerSequence: def __init__(self, seed: Union[int, Sequence[int], SeedSequence], mode: str): self.seed = seed self.mode = mode self.random = Random() ...
magicoder
python
You are tasked with implementing a function to determine the number of times a specific word appears in a given text. The function should be case-insensitive and should only count the word if it appears as a whole word, not as part of another word. For example, in the text "The cat and the cattle are playing with a cat...
```c #include <stdio.h> #include <string.h> #include <ctype.h> int countWordOccurrences(const char *text, const char *word) { int count = 0; const char *ptr = text; int wordLen = strlen(word); while ((ptr = strcasestr(ptr, word)) != NULL) { if ((ptr == text || !isalpha(*(ptr - 1))) && !isa...
magicoder
c
You are tasked with implementing a password validation system. The system should accept a list of passwords and determine whether each password meets the specified criteria. A valid password must satisfy the following conditions: 1. It must be at least 8 characters long and at most 20 characters long. 2. It must conta...
```swift func validatePasswords(_ passwords: [String]) -> [Bool] { var results: [Bool] = [] for password in passwords { let lengthCondition = (password.count >= 8 && password.count <= 20) let uppercaseRegex = ".*[A-Z]+.*" let lowercaseRegex = ".*[a-z]+.*" let digitRegex = "....
magicoder
swift
You are tasked with implementing a simple messaging system in Rust. The system should support different types of payloads with varying versions and commands. Your goal is to create a trait and implement methods for serialization and deserialization of payload messages. You are provided with a trait `Payload` which def...
```rust use std::io; // Define a custom error type for messaging operations type MessageResult<T> = Result<T, io::Error>; // Define a reader and stream types for deserialization and serialization struct Reader<T>(T); struct Stream; // Define the Message struct implementing the Payload trait struct Message { vers...
magicoder
rust
You are tasked with implementing a message vault system that securely stores and retrieves messages. The system should support asynchronous operations and ensure that messages are encrypted before being stored. Your task is to implement the `MessageVault` class with the following requirements: 1. The `MessageVault` cl...
```csharp using System; using System.IO; using System.Threading; using System.Threading.Tasks; using System.Security.Cryptography; namespace MessageVault { public class MessageVault { private readonly Dictionary<Guid, byte[]> messageStore = new Dictionary<Guid, byte[]>(); public async Task<Guid> S...
magicoder
csharp