query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with implementing a wallet settings manager for a mobile wallet application. The wallet settings manager is responsible for storing and retrieving various user settings related to the wallet functionality. The settings are stored persistently on the device and need to be accessible throughout the applica...
```swift // WalletSettingsManager.swift import Foundation class WalletSettingsManager { private let userDefaults = UserDefaults.standard func setPreferredCurrency(_ currency: String) { userDefaults.set(currency, forKey: "PreferredCurrency") } func getPreferredCurrency() -> String? { ...
magicoder
swift
You are working for a telecommunications company that is concerned about the high rate of customer cancellations. The company has identified that customers who have been with the company for a short period of time are more likely to cancel their plans. They suspect that the initial experience of the customer with the c...
To solve this problem, we will follow these steps: 1. Data Preprocessing: - Load the dataset and perform exploratory data analysis to understand the distribution of features and the target variable (churn). - Handle missing values, encode categorical variables, and scale numerical features if necessary. - Spl...
magicoder
python
You are tasked with creating a Rust function that processes command-line arguments to establish a secure connection to a given URL. The function should handle the parsing of the URL and the optional custom Root-CA store. Additionally, it should utilize the `Uri` and `error` types to handle potential errors. Your task ...
```rust use std::env; use std::str::FromStr; // Define the error type for handling errors #[derive(Debug)] struct CustomError(String); // Implement the Display trait for the CustomError type impl std::fmt::Display for CustomError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f,...
magicoder
rust
You are tasked with creating a web application for managing boutique stores. As part of this application, you need to implement a feature that allows the selection of managers for each boutique. The code snippet provided is a part of the HTML form used for this feature. The form is submitted to the URL specified by the...
```php function validateManagers($formData) { // Check if at least one manager is selected if (empty($formData['select3'])) { return ['success' => false, 'message' => 'Please select at least one manager for the boutique']; } // Simulate checking if selected managers exist as user accounts $...
magicoder
php
You are given a list of commands and an initial energy level. Your task is to simulate a journey through a rabbit hole by following the given commands and updating the energy level accordingly. The journey ends when a specific condition is met. You are provided with a list of commands in the format "command|value", wh...
```csharp using System; using System.Collections.Generic; public class RabbitHoleJourney { public static string SimulateJourney(List<string> commands, int initialEnergy) { int energy = initialEnergy; for (int i = 0; i < commands.Count; i++) { var splited = commands[i].Split...
magicoder
csharp
You are tasked with implementing a chat application using Django Channels. The provided code snippet is a starting point for creating a WebSocket consumer that handles the connection and messaging logic. Your task is to extend this code to support sending and receiving messages within the "test_room". Your implementat...
```python from channels.generic.websocket import JsonWebsocketConsumer class TestConsumer(JsonWebsocketConsumer): """ Create the Seller room, and is the only available to send messages to client""" def connect(self): self.room_name = "test_room" # Accept the WebSocket connection self.a...
magicoder
python
You are tasked with implementing a function to estimate surface normals for a given set of 3D point cloud data using the k-nearest neighbors (KNN) algorithm. The function should take in the 3D positions of the points, an estimation radius, and a parameter for the number of nearest neighbors to consider for the estimati...
```python import numpy as np from scipy.spatial import cKDTree def estimate_normals(positions, estimation_radius, estimation_knn): normals = [] tree = cKDTree(positions) for i, pos in enumerate(positions): neighbors = tree.query_ball_point(pos, estimation_radius) if len(neighbors) < estimat...
magicoder
python
You are tasked with creating a shell script to automate the process of managing symbolic links for a specific file. The script should check if the symbolic link for a file named "quickjs.xcframework" exists, and if so, update it to point to a new location. If the symbolic link does not exist, the script should create i...
```bash #!/bin/bash # Check if the symbolic link "quickjs.xcframework" exists if [ -L "quickjs.xcframework" ]; then # Get the absolute path of the current working directory ROOT=$(pwd) # Remove the existing symbolic link rm quickjs.xcframework # Create a new symbolic link pointing to the new location ln -s...
magicoder
shell
You are tasked with implementing a membership service for a web application. The membership service should handle user authentication, registration, and management. You are provided with a partial code snippet for the `MembershipService` class, which implements the `IMembershipService` interface and also implements the...
```csharp public class MembershipService : IMembershipService, IDisposable { private readonly IMembershipUnitOfWork _membershipUnitOfWork; private readonly UserManager _userManager; public MembershipService(IMembershipUnitOfWork membershipUnitOfWork, UserManager userManager) { _membershipUnitOf...
magicoder
csharp
You are tasked with creating a program that processes a given dataset and constructs a DataFrame using the pandas library in Python. The dataset contains lines of text, each labeled with a specific category. Your task is to organize the data into a DataFrame where each category label corresponds to a column, and the li...
```python import pandas as pd from Levenshtein import distance # Sample dataset dataset = [ {"label": "category1", "text": "example text 1"}, {"label": "category2", "text": "example text 2"}, {"label": "category1", "text": "example text 3"}, {"label": "category3", "text": "example text 4"} ] # Initial...
magicoder
python
You are tasked with creating a web application that allows users to save and backup their Reddit posts. The application uses ASP.NET Core MVC and Razor Pages for the front-end. The code snippet provided is the starting point of the application, where the necessary namespaces and tag helpers are being imported. Your ta...
```csharp // Controller for handling user authentication with Reddit public class RedditAuthController : Controller { private readonly IRedditAuthService _redditAuthService; public RedditAuthController(IRedditAuthService redditAuthService) { _redditAuthService = redditAuthService; } public...
magicoder
csharp
You are tasked with implementing a function that parses a URI and extracts various components from it. The URI follows the format `scheme://username:password@host:port/path?query#fragment`. Your goal is to create a Python function `parse_uri` that takes a URI string as input and returns a dictionary containing the pars...
```python import urllib.parse def parse_uri(uri): parsed_uri = urllib.parse.urlparse(uri) query_params = urllib.parse.parse_qs(parsed_uri.query) port = parsed_uri.port if parsed_uri.port else None query_dict = {key: value[0] if len(value) == 1 else value for key, value in query_params.items()} ...
magicoder
python
You are tasked with creating a Python script that simulates the functionality of the `docker-compose stop` command. The script should take a container name as a command-line argument and stop the specified container. You are not allowed to use any external libraries or modules for this task. Your Python script should ...
```python import subprocess import sys def stop_container(container_name): try: # Check if the container is running ps_output = subprocess.check_output(['docker', 'ps', '--filter', f'name={container_name}', '--format', '{{.Names}}']) running_containers = ps_output.decode('utf-8').splitlines...
magicoder
python
You are tasked with implementing a command-line tool that processes user input to perform various operations. The tool should support the following options: - `-a <value>`: Add the provided value to a running total. - `-s <value>`: Subtract the provided value from the running total. - `-m <value>`: Multiply the running...
```bash #!/bin/bash running_total=0 while [ $# -gt 0 ]; do case "$1" in -a) shift running_total=$((running_total + $1)) ;; -s) shift running_total=$((running_total - $1)) ;; -m) shift running_to...
magicoder
shell
You are tasked with implementing a custom module system in TypeScript. Your goal is to create a class that allows other parts of the codebase to import and use its functionality. The module system should support importing and exporting of classes, functions, and variables. Your task is to extend the `CommonModule` cla...
```typescript // Define a data structure to store the exported items type ExportedItem = { name: string; value: any; }; export class CommonModule { private exports: ExportedItem[] = []; // Method to export a class, function, or variable export(name: string, value: any) { this.exports.push({ name, value ...
magicoder
typescript
You are tasked with implementing a Python function that processes image files and generates HTML code to display the images on a web page. The function takes in various parameters and returns the HTML code as a string. The function `figure_function` is partially implemented and needs to be completed. It takes the foll...
```python from pathlib import Path from base64 import b64encode from toolz import curry, pipe, map, find def find_files(start): # Function to find image files starting from the specified directory # (Implementation not provided for brevity) pass def b64encode_str(data): # Function to encode data to ba...
magicoder
python
You are working on a computer vision project and need to implement a custom evaluation dataset and data loader for testing a classifier. The code snippet provided is a part of the infrastructure for setting up the test loader. Your task is to complete the implementation of the `EvalDataset` class and the `collate_eval`...
```python class EvalDataset(torch.utils.data.Dataset): def __init__(self, data_root, dataset, res, split, mode, stuff, thing): # Initialize the dataset with the provided parameters self.data_root = data_root self.dataset = dataset self.res = res self.split = split sel...
magicoder
python
You are working for an e-commerce company that sells various products. Your task is to write a function that processes product data and returns a formatted string containing relevant information. The product data is provided as an associative array, where the keys represent different attributes of the product and the v...
```php function formatProductInfo($productData) { $formattedInfo = "Product ID: " . $productData['id_producto'] . "\n"; $formattedInfo .= "Product Name: " . $productData['nombre'] . "\n"; $formattedInfo .= "Product Description: " . $productData['descripcion'] . "\n"; $formattedInfo .= "Product Price: " ...
magicoder
php
You are tasked with implementing a Python class that simulates a simple investment portfolio. The class should support different investment algorithms for managing the portfolio. One such algorithm is the Stochastic Volatility Index (SVI) strategy. Your task is to implement the SVI algorithm within the `Portfolio` clas...
```python import math class Portfolio: def __init__(self, algo, stocks): self.algo = algo self.stocks = stocks def execute_algorithm(self): if self.algo == 'SVI': # Simulated individual stock volatilities for demonstration purposes individual_stock_volatilities ...
magicoder
python
You are tasked with creating a function that determines whether a given string is a "go view" or not. A "go view" is defined as a string that contains the word "go" and ends with the word "view". The function should return True if the input string meets this criteria, and False otherwise. You are provided with the fol...
```python def is_go_view(s: str) -> bool: s = s.lower() # Convert the input string to lowercase for case-insensitive comparison return "go" in s and s.endswith("view") ``` The `is_go_view` function first converts the input string to lowercase using the `lower()` method to ensure case-insensitive comparison. I...
magicoder
python
You are tasked with implementing a custom adapter for a RecyclerView in an Android application. The adapter will be responsible for populating the RecyclerView with data from a list of ActivityGroup objects. Each ActivityGroup object has a name and a list of activities associated with it. Your task is to create the ada...
```java import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.colorhaake.traveler.R; import com.colorhaake.traveler.pl...
magicoder
java
You are tasked with creating a JavaScript function that simulates a simple animation effect using fake timers. The function should accept a duration in milliseconds and an element to animate. The animation should change the element's opacity from 0 to 1 over the specified duration. You should use Jest's fake timers to ...
```javascript function animateOpacity(duration, element) { const startTime = Date.now(); const endTime = startTime + duration; const timeInterval = 10; // Interval for updating opacity const opacityChangePerInterval = 1 / (duration / timeInterval); let currentOpacity = 0; const updateOpacity = () => { ...
magicoder
javascript
You are tasked with creating a program that simulates the process of managing collections and configurations in Apache Solr, a popular open-source search platform. Your program should handle the creation of collections and the assignment of configurations to these collections. Your program should support the following...
```python class SolrManager: def __init__(self): self.collections = {} def create_collection(self, collection_name, config_name=None): if collection_name in self.collections: return f"Collection '{collection_name}' already exists" else: self.collections[collectio...
magicoder
python
You are tasked with creating a program to manage an online auction system. The provided code snippet is a part of the user interface setup for displaying auction details. The code creates and configures two UI elements, a `UITextView` and a `UILabel`, to display information about the auction item and bidding details. T...
```swift func calculateTimeRemaining(currentTime: String, auctionEndTime: String) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" guard let currentDateTime = dateFormatter.date(from: currentTime), let auctionEndDateTime = dateFormatter.date(fro...
magicoder
swift
You are tasked with creating a script to automate the deployment of NGINX containers using Docker Compose. The script needs to handle the generation of a Docker Compose file, pulling images, and recreating containers. Additionally, it should consider the presence of certain environment variables to configure the NGINX ...
```bash #!/bin/bash # Check if the existing NGINX generator network is not set if [ -z $HABIDAT_EXISTING_NGINX_GENERATOR_NETWORK ] then # Check if Let's Encrypt is not enabled if [ "$HABIDAT_LETSENCRYPT" != "true" ] then # Disable Let's Encrypt configuration export HABIDAT_LETSENCRYPT_DISABLE='#' fi # Genera...
magicoder
shell
You are tasked with creating a program that analyzes a given text file to count the occurrences of specific words. The program should read the text file and count the occurrences of each word in the file, ignoring case sensitivity and punctuation. The program should then output the word count for each unique word in th...
```python import re def count_word_occurrences(file_path): word_count = {} with open(file_path, 'r') as file: text = file.read() words = re.findall(r'\b\w+\b', text.lower()) for word in words: if word in word_count: word_count[word] += 1 else: ...
magicoder
python
You are tasked with implementing a class that manages image layers in a C# application using the ImageMagickSharp library. The library provides an enum `ImageLayerType` with three possible values: `MergeLayer`, `FlattenLayer`, and `MosaicLayer`. Your task is to create a class `ImageLayerManager` that allows adding, rem...
```csharp using System; using System.Collections.Generic; namespace ImageMagickSharp { internal class ImageLayerManager { private Dictionary<ImageLayerType, List<string>> imageLayers; public ImageLayerManager() { imageLayers = new Dictionary<ImageLayerType, List<string>>();...
magicoder
csharp
You are tasked with implementing a Swift class that represents a transient image, which is used as an intermediate step after decoding an image from data or a file on disk. The class should provide functionality to manipulate the image data before creating an image object for display. Your task is to implement the `Tr...
```swift import Foundation import ImageIO import ImageDecoder import CoreGraphics class TransientImage { private var imageData: Data init(imageData: Data) { self.imageData = imageData } func resizeImage(to size: CGSize) throws -> Data { guard let source = CGImageSourceCreateWithData(i...
magicoder
swift
You are tasked with implementing a Swift extension for processing keyboard input rows. The extension should provide functionality to convert a 2D array of strings representing keyboard input rows into a custom data structure and to retrieve characters from the input rows based on a specified casing. You are given the ...
```swift // Define the KeyboardInputRow type to represent a single row of keyboard input public struct KeyboardInputRow { private var characters: [String] init(_ characters: [String]) { self.characters = characters } func characters(for casing: KeyboardCasing) -> [String] { swi...
magicoder
swift
You are given a list of software licenses, each represented as a string. Each license contains a disclaimer text followed by a set of terms and conditions. Your task is to extract the disclaimer text from each license and return it as a list of strings. The disclaimer text is defined as the portion of the license that...
```python from typing import List def extract_disclaimer(licenses: List[str]) -> List[str]: disclaimers = [] for license in licenses: disclaimer = "" index = license.find("LIMITED") if index != -1: disclaimer = license[:index] disclaimers.append(disclaimer) retur...
magicoder
python
You are tasked with implementing a job scheduling system that allows users to define and execute daily jobs. The system should support defining job definitions and waiting for specific conditions to be met before proceeding with the next steps. You are provided with a code snippet that demonstrates the usage of the jo...
```python # Define the assert_daily_job_definition function to store the job definition def assert_daily_job_definition(job_name, config): # Implementation to store the job definition with the provided configuration # This function will store the job definition for later execution # Define the wait class with ...
magicoder
python
You are tasked with implementing a function to process a collection of `AutoType` settings associated with different entries in a system. Each `AutoType` setting contains a boolean flag indicating whether it is enabled, an optional sequence string, and a list of associations with other entities. You need to implement ...
```rust use std::collections::HashSet; pub fn process_auto_types(auto_types: &[AutoType]) -> (usize, String, Vec<AutoTypeAssociation>) { let enabled_count = auto_types.iter().filter(|at| at.enabled).count(); let sequence_string = auto_types .iter() .filter_map(|at| at.sequence.as_ref()) ...
magicoder
rust
You are tasked with creating a Python class to model a chemical combustion process. The class should have the following attributes: initial temperature (`init_temp`), initial pressure (`init_press`), fuel type (`fuel`), oxidizer composition (`oxidizer`), equivalence ratio (`equivalence`), and diluent type (`diluent`). ...
```python class CombustionProcess: def __init__(self, init_temp, init_press, fuel, oxidizer, equivalence, diluent): self.init_temp = init_temp self.init_press = init_press self.fuel = fuel self.oxidizer = oxidizer self.equivalence = equivalence self.diluent = diluent ...
magicoder
python
You are tasked with creating a Python function that processes COVID-19 data to analyze the spread of the virus in different regions. The function should take in a DataFrame containing COVID-19 data and two region names. It should then calculate the total number of confirmed cases for each region and return the region w...
```python import pandas as pd def compare_regions(data, region, other_region): region_cases = get_total_cases(data, region) other_region_cases = get_total_cases(data, other_region) if region_cases > other_region_cases: return region else: return other_region def get_total_cases(data, ...
magicoder
python
You are tasked with implementing a function that processes textual content to extract specific information based on predefined patterns. Your goal is to create a function that extracts the date mentioned in the content and returns it in a specific format. You are given a Python class with a method `select_data(self, c...
```python import datetime class DateExtractor: def select_data(self, content): if 'tomorrow' in content: today = datetime.date.today() tomorrow = today + datetime.timedelta(days=1) return tomorrow.strftime("%Y-%m-%d") else: date_str = content.split('t...
magicoder
python
You are tasked with implementing a command-line argument parser for a software tool. The parser should extract specific arguments from the command line and provide them as properties for further processing. Your task is to create a class that encapsulates the logic for parsing and accessing these arguments. You are gi...
```csharp using System; public class Program { public static void Main() { string[] args = { "-d", "C:\\ProgramFiles", "-p", "config.properties" }; CommandLineParser parser = new CommandLineParser(); parser.ParseArguments(args); Console.WriteLine("Directory: " + parser.GetDire...
magicoder
csharp
You are tasked with creating a JavaScript function that simulates a simple digital clock. The function should update the time every second and display it in the format "hh:mm:ss" (hours, minutes, seconds). You are provided with a code snippet that sets up an interval to call a function `myFunction` at regular intervals...
```javascript function myFunction() { setInterval(function () { // Get the current time var currentTime = new Date(); var hours = currentTime.getHours(); var minutes = currentTime.getMinutes(); var seconds = currentTime.getSeconds(); // Format the time as "hh:mm:ss" ...
magicoder
javascript
You are tasked with implementing a class that calculates the frequency of a given value in a list of integers. The class should provide a method to return the frequency of the specified value in the list. Additionally, the class should be able to handle a special case where the list is mirrored three times, and the fre...
```cpp #include <iostream> #include <vector> #include <algorithm> class TripleMirrorFreqN { private: std::vector<int> originalList; public: TripleMirrorFreqN(const std::vector<int>& list) : originalList(list) {} int getFrequency(int value) { int frequency = std::count(originalList.begin(), origin...
magicoder
cpp
You are tasked with creating a program to simulate a simple game of "Whack-a-Mole." In this game, moles will randomly appear at different positions on the screen, and the player must click on them to earn points. Your task is to implement the logic for generating the moles at random positions and keeping track of the p...
```swift import UIKit class MoleGameViewController: UIViewController { var scoreLabel: UILabel! var score = 0 let gameArea = CGRect(x: 0, y: 0, width: 800, height: 600) var moles = [CGRect]() override func viewDidLoad() { super.viewDidLoad() setupGameArea() startGame() ...
magicoder
swift
You are tasked with implementing a function to create a multi-layer perceptron (MLP) neural network for a reinforcement learning agent. The function should take in the dimensions of the input features, the action space, network architecture, activation function, and a boolean flag for output squashing. The network arch...
```python import torch import torch.nn as nn import torch.nn.functional as F class MLP(nn.Module): def __init__(self, features_dim, action_dim, net_arch, activation_fn, squash_output=True): super(MLP, self).__init__() layers = [] input_dim = features_dim for layer_size in net_arch: ...
magicoder
python
You are tasked with implementing a data flow analysis algorithm for a programming language. The algorithm operates on a class `ExpressionMachine` that extends a generic `JSMachine` and contains methods for checking flow, reporting possible flow, and joining sets of static descriptions. The `check` method takes a `sink...
```typescript export default class ExpressionMachine extends JSMachine<Set<StaticDescription>, [Set<StaticDescription>, StaticDescription]> { check(sink: StaticDescription, taint: Set<StaticDescription>): boolean { // Implement the check method to perform data flow analysis // Check if the sink is t...
magicoder
typescript
You are given a sequence of integers, and your task is to find the contiguous subarray with the largest sum. For example, given the sequence [−2, 1, −3, 4, −1, 2, 1, −5, 4], the contiguous subarray with the largest sum is [4, −1, 2, 1], with a sum of 6. Write a function `max_subarray_sum(sequence)` that takes in a lis...
```python def max_subarray_sum(sequence): max_ending_here = max_so_far = sequence[0] # Initialize both to the first element for x in sequence[1:]: # Start from the second element max_ending_here = max(x, max_ending_here + x) # Update max_ending_here to be the maximum of the current element and the su...
magicoder
python
You are tasked with implementing a multithreaded program to manage a queue of tasks. The program should utilize Python's `queue` module to create a thread-safe queue and use multiple worker threads to process tasks concurrently. However, there is a bug in the given code snippet that prevents the program from functionin...
The issue with the given code snippet is that the `q.join()` call is used without first setting the `q` queue to be joinable. To resolve this issue and achieve the desired functionality, the following steps should be taken: ```python import queue import threading # Create a thread-safe queue to hold tasks q = queue.Q...
magicoder
python
You are tasked with implementing a generic cloning mechanism in Swift. You need to create a generic class that provides a method for cloning an object of any type and another method for obtaining a function that can be used to clone objects of a specific type. You are given the following code snippet as a starting poi...
```swift class Cloner { func clone<T: NSCopying>(t: T) -> T { return t.copy() as! T } func getCloneFn<T: NSCopying>(t: T) -> () -> T { return { t.copy() as! T } } } ``` In the solution, the `Cloner` class provides the `clone` method, which takes an object of type `T` conforming to ...
magicoder
swift
You are tasked with implementing a class for performing Fast Fourier Transform (FFT) operations. The provided code snippet includes a partial implementation of the VDspFFT class using the JUCE library for audio processing. Your task is to complete the implementation of the VDspFFT class by adding the necessary methods ...
```cpp #include <juce_audio_basics/juce_audio_basics.h> class VDspFFT { public: VDspFFT(int maxN); ~VDspFFT(); void initialize(const juce::AudioSampleBuffer& audioBuffer); void performFFT(); juce::AudioSampleBuffer getFFTResults(); private: class Pimpl { public: Pimpl(int maxN...
magicoder
cpp
You are tasked with implementing a user authentication system for a Python application using the given code snippet as a starting point. The code snippet includes a client setup for MongoDB and a basic user authentication structure. Your task is to extend this code to create a functional user authentication system with...
```python # Import necessary libraries and modules from pymongo import MongoClient # Initialize MongoDB client client = MongoClient('mongodb://localhost:27017/') db = client['user_db'] collection = db['users'] # Define the user class class User: def __init__(self, username, password, login=False): self.us...
magicoder
python
You are tasked with creating a Ruby script that simulates a simple inventory management system for a small retail store. The script should allow users to add new products to the inventory, update existing product quantities, and display the current inventory status. Your task is to implement the `Inventory` class with...
```ruby class Inventory def initialize @products = {} end def add_product(name, quantity) @products[name] = quantity end def update_quantity(name, quantity_change) if @products[name] @products[name] += quantity_change end end def display_inventory @products.each do |product, q...
magicoder
ruby
You are tasked with creating a Python function that processes a list of file paths and returns a dictionary containing the count of different file types present in the list. The file types are determined by their extensions. The function should ignore any file paths that do not have an extension. The function signatur...
```python def count_file_types(file_paths: list) -> dict: file_type_count = {} for file_path in file_paths: file_name = file_path.split('/')[-1] if '.' in file_name: file_extension = file_name.split('.')[-1] file_type_count[file_extension] = file_type_count.get(file_exten...
magicoder
python
You are given a list of integers representing the stock prices of a company over a period of time. You need to write a function to find the maximum profit that can be obtained by buying and selling the stock at most once. If no profit can be made, return 0. For example, given the stock prices [7, 1, 5, 3, 6, 4], the m...
```python from typing import List def max_profit(prices: List[int]) -> int: if not prices: return 0 min_price = prices[0] max_profit = 0 for price in prices: if price < min_price: min_price = price else: max_profit = max(max_profit, price - min_...
magicoder
python
You are tasked with implementing a TypeScript function that handles the upload of CSV time series data to be processed by an FFC Flask Server. The function should take into account the user's role and the associated permissions. You are provided with the following code snippet as a starting point: ```typescript export...
```typescript export const tsUploadMutations = { /** * Upload CSV time series data to process with FFC Flask Server * * @param uploadTimeSeriesPL It can be a string with value `USER`, `ADMIN` or `SUPER_ADMIN` * @param req Express' `Request` with user attached to it * * @returns services to make the ...
magicoder
typescript
You are given a Python class representing a simple bank account. Your task is to implement a method that calculates the interest earned on the account balance over a specified period of time. ```python class BankAccount: def __init__(self, account_number, balance, interest_rate): self.account_number = acco...
```python class BankAccount: def __init__(self, account_number, balance, interest_rate): self.account_number = account_number self.balance = balance self.interest_rate = interest_rate def calculate_interest(self, years): interest = self.balance * ((1 + self.interest_rate) ** yea...
magicoder
python
You are tasked with creating a Python command-line tool that interacts with a web service to retrieve and display Jupyter notebooks. Your tool should be able to accept a notebook ID as a command-line argument and then fetch and display the notebook content. Your task is to implement the `cli` function in the `nbviewer...
```python import sys from notebook_service import NotebookService # Assuming the existence of NotebookService class def cli(): if len(sys.argv) != 2: print("Usage: python nbviewerbot.py <notebook_id>") return notebook_id = sys.argv[1] notebook_service = NotebookService() # Instantiate th...
magicoder
python
You are tasked with implementing a user authentication system for a web application. The provided code snippet is a part of a Django web application that handles user registration and activation. The `authenticate` function is used to verify the user's credentials, and upon successful authentication, the user is logged...
```python from django.contrib.auth import get_user_model from django.contrib import messages from django.utils.translation import ugettext_lazy as _ from django.views.generic import RedirectView from django.shortcuts import get_object_or_404 class ActivateView(RedirectView): def get_redirect_url(self, *args, **kwa...
magicoder
python
You are given a code snippet that represents a 2D grid. Each '#' character in the grid represents a wall, and each '.' character represents an open space. Your task is to write a function that takes this grid as input and returns the number of walls present in the grid. For example, given the following grid: ``` ####...
```python from typing import List def count_walls(grid: List[str]) -> int: wall_count = 0 for row in grid: wall_count += row.count('#') return wall_count # Test the function with the provided example grid = [ "##########", "#........#", "#..####..#", "#..#..#..#", "#..####..#",...
magicoder
python
You are working on a machine learning project and need to create a custom kernel for a Gaussian process regression model. The kernel is a composite kernel consisting of two sub-kernels: a Radial Basis Function (RBF) kernel and a Periodic kernel. The RBF kernel is sliced into multiple dimensions, and the Periodic kernel...
```python from sklearn.gaussian_process import kernels def create_custom_kernel(lag_dim, output_dim, Xtr, IS_ARD): lag_active_dims_s = [[] for _ in range(output_dim)] for i in range(output_dim): lag_active_dims_s[i] = list(range(lag_dim*i, lag_dim*(i+1))) k_rows = [kernels.CompositeKernel('mul', [...
magicoder
python
You are tasked with implementing a Tic-Tac-Toe game using Python. The game should be playable through the command-line interface (CLI) and should provide a simple and intuitive user experience. The game should handle player turns, validate moves, and determine the winner or a draw. Your task is to create a Python prog...
```python class TicTacToe: def __init__(self): self.board = [' ' for _ in range(9)] self.current_player = 'X' def display_board(self): print(" 1 | 2 | 3 ") print("-----------") print(" 4 | 5 | 6 ") print("-----------") print(" 7 | 8 | 9 ") def make_m...
magicoder
python
You are tasked with creating a Python function that processes a given text to remove all punctuation marks and convert the text to lowercase. Your function should take a string as input and return the processed text as output. You should not use any built-in Python functions for removing punctuation or converting to lo...
```python def process_text(text: str) -> str: punc_remove = ['!', '.', ',', '?', ';', ':', '-', '"', "'", '(', ')'] processed_text = "" for char in text: if char not in punc_remove: processed_text += char return processed_text.lower() ``` The `process_text` function iterates through...
magicoder
python
You are tasked with creating a program to interact with a ClickHouse database. The program needs to execute a series of SQL queries using the `curl` command to retrieve data from a table called `table_with_nullable_keys`. The table contains columns with nullable values of different types, such as strings, arrays, tuple...
```bash #!/bin/bash # Define the ClickHouse URL CLICKHOUSE_URL="http://your_clickhouse_server:8123" # Define the function to execute the curl command with the given SQL query execute_curl_command() { local query="$1" curl -d@- -sS "${CLICKHOUSE_URL}" <<< "$query" # Execute the curl command with the SQL query...
magicoder
shell
You are tasked with implementing a Python class that processes and folds a dataset for machine learning purposes. The `FoldData` class is responsible for dividing a dataset into multiple folds for cross-validation. Each fold will be used as a separate training and validation set during the cross-validation process. You...
```python import numpy as np from sklearn.model_selection import StratifiedKFold class FoldData: def __init__(self, dataset, num_folds): self.dataset = dataset self.num_folds = num_folds self.fold_indices = self._generate_fold_indices() def _generate_fold_indices(self): labels ...
magicoder
python
You are tasked with implementing a custom data structure called `UniqueStack` that behaves like a stack but only allows unique elements to be pushed onto it. The `UniqueStack` should support the following operations: 1. `Push`: Add an element to the top of the stack if it is not already present in the stack. 2. `Pop`: ...
```java import java.util.HashSet; import java.util.Stack; class UniqueStack { private Stack<Integer> stack; private HashSet<Integer> set; public UniqueStack() { stack = new Stack<>(); set = new HashSet<>(); } public void Push(int element) { if (!set.contains(element)) { ...
magicoder
java
You are tasked with creating a custom middleware for a Redux store that logs the actions and the state after each action is dispatched. Your middleware should log the action type and the updated state to the console. You are provided with a code snippet that sets up a Redux store with preloaded state and applies middl...
```typescript import { createStore, applyMiddleware, compose, Middleware, Dispatch, AnyAction, MiddlewareAPI } from 'redux'; import createSagaMiddleware from 'redux-saga'; import { createRootSaga } from './sagas'; import createRootReducer from './reducers'; const loggingMiddleware: Middleware = (store: MiddlewareAPI) ...
magicoder
typescript
You are tasked with creating a Python function to calculate the average price of a cryptocurrency over a given time period. The function will utilize a provided `get_response` function to fetch cryptocurrency price data from a specified URL. The price data is in the form of a dictionary, with the cryptocurrency ticker ...
```python from decimal import Decimal from datetime import timedelta def calculate_average_price(ticker_symbol, start_time, end_time): total_price = Decimal(0) num_data_points = 0 current_time = start_time while current_time <= end_time: price = get_current_ask(ticker_symbol) total_pri...
magicoder
python
You are given a list of integers. Write a function `max_prod_three` to find the maximum product that can be obtained by multiplying three integers from the list. For example, given the input list `[5, -2, 3]`, the maximum product that can be obtained by multiplying three integers is `-30` (5 * -2 * 3). For the input l...
```python from typing import List class Solution: def max_prod_three(self, nums: List[int]) -> int: if nums is None: raise TypeError("Input list cannot be None") if len(nums) < 3: raise ValueError("Input list must have at least three elements") nums.sort() r...
magicoder
python
You are tasked with creating a Python program that retrieves an image from a given URL, performs color clustering using KMeans and Agglomerative Clustering algorithms, and then saves the clustered image to the local file system. Your program should perform the following steps: 1. Retrieve an image from a given URL usi...
```python from PIL import Image import numpy as np from sklearn.cluster import KMeans, AgglomerativeClustering import requests from io import BytesIO import os from dotenv import load_dotenv # Load environment variables load_dotenv() # Function to perform color clustering and save the clustered image def cluster_and_...
magicoder
python
You are working on a chemical reaction simulation program that models the kinetics of various reactions. The program uses a data structure `m` to store information about reactions, reaction parameters, and stoichiometry. The code snippet provided is a part of a validation routine that checks the consistency of reaction...
```python def validate_reaction_order(m) -> bool: if len(m.rparams.reaction_r1.reaction_order) != 4: return False # Length of reaction order dictionary is not 4, validation fails for i, v in m.rparams.reaction_r1.reaction_order.items(): try: stoic = m.rparams.config.rate_reactions....
magicoder
python
You are tasked with creating a custom authentication class for a Django REST framework API. The custom authentication class should implement a token-based authentication mechanism using JSON Web Tokens (JWT). You need to ensure that the custom authentication class can be used to authenticate and authorize users when ac...
Custom JWT Authentication Class: ```python from rest_framework.authentication import BaseAuthentication from rest_framework.exceptions import AuthenticationFailed import jwt from django.conf import settings from django.contrib.auth.models import User class JWTAuthentication(BaseAuthentication): def authenticate(se...
magicoder
python
You are tasked with simulating the behavior of a system that plays a video on different types of devices based on their architecture. The provided code snippet is a part of a shell script function `playVideo()` that is responsible for playing a video file under certain conditions. The function checks if a specific file...
```python import subprocess import platform def play_video(): if not os.path.exists('/tmp/first-boot-video'): open('/tmp/first-boot-video', 'a').close() machine_arch = platform.machine() if 'x86' in machine_arch: # on x86 and x86_64, find connected monitors and play video on all...
magicoder
python
You are tasked with creating a Python function that processes a list of Git tags and returns the latest version number based on semantic versioning rules. Semantic versioning is a versioning scheme that uses three numbers separated by periods (e.g., 1.2.3) to represent major, minor, and patch versions. The function sho...
```python def latest_semantic_version(git_tags: list) -> str: # Remove the 'v' prefix and split the version numbers into tuples of integers versions = [tuple(map(int, tag[1:].split('.'))) for tag in git_tags] # Sort the versions in descending order sorted_versions = sorted(versions, reverse=True) ...
magicoder
python
You are tasked with implementing a custom exception handling mechanism for a Python application. The application has a class `CustomResource` with a method `acquire` that acquires a resource and a method `release` that releases the resource. The `acquire` method may raise a `ResourceUnavailableError` exception if the r...
```python class ResourceUnavailableError(Exception): pass class CustomResource: def acquire(self): try: # Attempt to acquire the resource # If resource is unavailable, raise ResourceUnavailableError # Otherwise, continue with resource usage pass e...
magicoder
python
You are working on a data extraction and manipulation module for a network management system. Your task is to implement a function that extracts subnet information from a given CSV table and splits it into separate columns for further analysis. The function should handle various scenarios, including ensuring the input ...
```python import pandas as pd from copy import deepcopy import logging def extract_and_split_subnets(csv_table, relevant_subnets, tablename): logger = logging.getLogger(__name__) # Ensure iterability of relevant_subnets[0] and obtain lv_subnets hv_subnets = ensure_iterability(relevant_subnets[0]) lv_s...
magicoder
python
You are tasked with implementing a pagination system for a web application. The provided code snippet includes a module for pagination and a constant for the default page size. Your task is to create a Pagination struct that will handle the pagination logic for a list of items. Your Pagination struct should have the f...
```rust use std::cmp::min; pub struct Pagination { page_size: u8, total_items: usize, current_page: u32, } impl Pagination { pub fn new(page_size: u8, total_items: usize) -> Self { Pagination { page_size, total_items, current_page: 1, } } pu...
magicoder
rust
You are tasked with creating a custom implementation of a file processing class in a mobile app development project. The provided code snippet is a simplified representation of a Swift class called `Scanfile` that implements the `ScanfileProtocol`. The comments in the code indicate that this file is provided by a tool ...
```swift // CustomScanfile.swift // Import necessary modules if required // Define a new class that extends the functionality of the Scanfile class public class CustomScanfile: ScanfileProtocol { // Add custom properties and methods as required var customValue: String // Initialize the custom propert...
magicoder
swift
You are tasked with implementing a conference management system in Java. The system should include a class representing a conference, with methods to retrieve and set the conference name. The conference name should be nullable, meaning it can be either a valid string or null. You are provided with a partial code snipp...
```java import org.jetbrains.annotations.Nullable; public class Conference { private @Nullable String name; public @Nullable String getConferenceName() { return name != null ? name : "Unnamed Conference"; } public void setConferenceName(@Nullable String conferenceName) { this.name = c...
magicoder
java
You are tasked with simulating the behavior of a toio cube's LED control system. The toio cube is a small robotic cube with various functionalities, including LED control. The provided code snippet is a part of a larger program that interacts with the toio cube's LED through Bluetooth Low Energy (BLE) communication. Y...
```csharp public class ToioCubeLEDControl { private const int CHARACTERISTIC_LIGHT = 0x0010; // Example value for the characteristic ID public void ControlLED(int red, int green, int blue, int durationMs) { byte[] buff = new byte[7]; buff[2] = 1; buff[3] = 1; buff[4] = (byte...
magicoder
csharp
You are tasked with designing a memory-mapped register interface for a hardware peripheral in an embedded system. The peripheral has various tasks and events that can be subscribed to and triggered. The provided code snippet is a partial definition of the register interface for this peripheral. The code snippet shows ...
```rust // Define the register types for subscribe_out, subscribe_set, and subscribe_clr pub struct Reg<T> { // Define the fields for the register type // ... } // Define the register types for events_in pub struct Reg<T> { // Define the fields for the register type // ... } // Complete the struct def...
magicoder
rust
You are tasked with creating a Python function that finds the most recent IQDM results CSV file within a given directory. The function should be able to handle both recursive and non-recursive searches based on the provided argument. The IQDM results CSV files are named in a specific format and are located within the d...
```python import os def find_latest_results(init_directory, no_recursive_search=False): files = [] if no_recursive_search: files = [f for f in os.listdir(init_directory) if os.path.isfile(os.path.join(init_directory, f)) and f.startswith("IQDM_results_") and f.endswith(".csv")] else: for ro...
magicoder
python
You are tasked with creating a Python function to parse a Terminal Aerodrome Forecast (TAF) and extract specific information from it. The TAF is provided in a text file, and the function should be able to generate a Jabber message containing relevant details. You are given a code snippet that demonstrates the usage of...
```python from datetime import datetime import re def tafparser(taf_file_path, utcnow): # Assume tafparser function is provided for parsing TAF file # Implement the logic to parse the TAF file and extract necessary information # Return the parsed data as required def extract_timestamp_and_airport(taf_cont...
magicoder
python
You are tasked with creating a script that fetches content from a given URL and saves it to a file. However, the script provided has a bug that causes it to exit prematurely. Your goal is to fix the bug and enhance the script to handle potential errors during the fetching process. You are given the following code snip...
```bash # Fixing the bug that causes premature exit if [ $? -ne 0 ]; then echo "Error: Failed to fetch content from '$TARGET_URL'." exit 1 fi # Enhancing the script to handle potential errors during fetching echo "Fetching from '$TARGET_URL'..." if curl --silent --show-error -L -o /root/state/content.txt "$TARGET_...
magicoder
shell
You are tasked with implementing a custom error handling mechanism for a file processing application. The application processes various types of files and encounters different errors during the processing. To handle these errors effectively, you need to create a custom error type and implement the necessary traits to e...
```rust use std::error; use std::fmt; // Define a custom error type for file processing errors #[derive(Debug)] enum FileProcessingError { OperationNotPermittedFault(String), TooManyTagsFault(String), } // Implement the Display trait for custom error type impl fmt::Display for FileProcessingError { fn fmt...
magicoder
rust
You are tasked with creating a Python function that extracts the captcha value from a given URL that points to an image. The function should take the URL as input and return the extracted captcha value as a string. The captcha value is embedded within the URL itself and follows a specific pattern. The URL will be in t...
```python import re def extract_captcha_value(url): # Using regular expression to extract the captcha value from the URL pattern = r"https://example.com/captcha/(\w+)\.png" match = re.search(pattern, url) if match: return match.group(1) else: return "Captcha value not found" ``` Th...
magicoder
python
You are tasked with creating a simple game mechanic for a 3D character movement system. The character should be able to move in the game world and have its orientation automatically adjust to the direction of movement. Additionally, a camera boom needs to be set up to provide a third-person perspective for the player. ...
```cpp void SetupCharacterMovementAndCamera(USpringArmComponent* CameraBoom, USceneComponent* RootComponent, UCharacterMovementComponent* CharacterMovement) { // Set character movement properties CharacterMovement->bOrientRotationToMovement = true; // Rotate character to moving direction CharacterMovement->...
magicoder
cpp
You are working on a project that involves interfacing with a foreign function interface (FFI) to integrate a music notation toolkit written in C/C++ into a Rust application. The C/C++ toolkit provides several functions that allow you to extract information from music notation files. You need to create a Rust wrapper a...
```rust use std::os::raw::c_char; struct Toolkit; // Assume the definition of Toolkit struct MusicToolkit { toolkit: *mut Toolkit, } impl MusicToolkit { fn new(toolkit: *mut Toolkit) -> Self { MusicToolkit { toolkit } } fn get_humdrum(&self) -> String { unsafe { let c_str...
magicoder
rust
You are given a code snippet that manipulates a quantum circuit using a handler. Your task is to write a function that parses a similar code snippet and extracts the sequence of operations performed on the quantum circuit. Write a function `parse_quantum_circuit(code: str) -> List[str]` that takes a string `code` repr...
```python from typing import List def parse_quantum_circuit(code: str) -> List[str]: operations = [] lines = code.split('\n') for line in lines: line = line.strip() if line and not line.startswith("#"): operations.append(line) return operations ``` The `parse_quantum_circui...
magicoder
python
You are tasked with implementing a function to process data read from a table in a database. The `Table` struct has a method `read` that asynchronously reads data from a file associated with the table and returns a vector of strings, where each string represents a line from the file. Your task is to implement a functio...
```rust /// Processes the data read from the table fn process_data(data: Vec<String>) -> Vec<String> { let processed_data: Vec<String> = data .iter() .map(|s| s.trim().to_uppercase()) .filter(|s| !s.is_empty()) .collect(); processed_data } ``` The `process_data` function takes ...
magicoder
rust
You are given a Python code snippet that defines a function `primos_entre(a, b)`. This function is intended to count the number of prime numbers between two given integers `a` and `b` (inclusive). However, the code snippet is incomplete and lacks the implementation of the `eh_primo` function, which is expected to deter...
```python def primos_entre(a, b): count = 0 number = a while number <= b: if eh_primo(number): count += 1 number += 1 return count def eh_primo(n): if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False...
magicoder
python
You are tasked with implementing a simple channel system for inter-thread communication in C++. The channel should support sending and receiving messages between threads. Your task is to implement the `Channel` class with the following methods: 1. `void send(T message)`: This method should allow a thread to send a mes...
```cpp #include <gtest/gtest.h> #include <thread> // Paste the Channel class implementation here TEST(ChannelTest, Creation) { Channel<int> channel; std::thread sender([&channel] { channel.send(42); }); std::thread receiver([&channel] { int message = channel.receive(); ASSERT_E...
magicoder
cpp
You are tasked with creating a Python script to automate the process of connecting to a Wi-Fi network using a pre-shared key (PSK). The script should utilize the `argparse` module to accept command-line arguments, specifically the PSK for the network. If the PSK is not provided as a command-line argument, the script sh...
```python import argparse def connect_to_wifi(psk): # Code to connect to Wi-Fi using the provided PSK if psk: print(f"Connecting to Wi-Fi using provided PSK: {psk}") # Connect to Wi-Fi using the provided PSK else: saved_credentials = get_saved_credentials() if saved_credenti...
magicoder
python
You are tasked with creating a script to automate the installation process for a software package. The script should handle the configuration, compilation, and installation steps for the software. The configuration step involves running the `./configure` script with specific options, the compilation step involves runni...
```bash #!/bin/bash # Check if PREFIX and CPU_COUNT are provided as arguments if [ $# -ne 2 ]; then echo "Usage: $0 PREFIX CPU_COUNT" exit 1 fi PREFIX=$1 CPU_COUNT=$2 # Step 1: Run the configure script echo "Configuring the software..." ./configure --prefix="${PREFIX}" --enable-64bit configure_exit_code=$? if [...
magicoder
shell
You are tasked with implementing a Python class that simulates a simple linear equation. The class should provide methods for performing basic operations on linear equations, such as addition, subtraction, multiplication, and evaluation at a specific value of the independent variable. Your task is to complete the impl...
```python class Linear: def __init__(self, slope, intercept): self.slope = slope self.intercept = intercept def add(self, other): new_slope = self.slope + other.slope new_intercept = self.intercept + other.intercept return Linear(new_slope, new_intercept) def subtra...
magicoder
python
You are tasked with creating a Rust function that processes Bluetooth Low Energy (BLE) characteristics. The function should take a UUID as input and return a specific characteristic associated with that UUID. You are provided with a code snippet that uses asynchronous Rust (async/await) and the `FuturesUnordered` type ...
```rust use futures::stream::FuturesUnordered; use futures::stream::StreamExt; // Define the UUID type type UUID = u32; // Define the Error type type Error = Box<dyn std::error::Error>; // Define the Characteristic struct struct Characteristic { // Define the fields of the Characteristic struct } impl Character...
magicoder
rust
You are tasked with creating a program that parses and extracts license information from source code files. The license information is typically included at the beginning of source files in a specific format. The license text is enclosed within comment delimiters and may span multiple lines. Your program should be able...
```python import re def extract_license_text(source_code): # Regular expression pattern to match multi-line comments multi_line_comment_pattern = r'#(.*?)#' # Regular expression pattern to match single-line comments single_line_comment_pattern = r'#(.*)' # Search for multi-line comments and extrac...
magicoder
python
You are given an array of scores representing the scores of a game over consecutive days. The array `scores` contains `n` elements, where `scores[i]` represents the score on the `i`-th day. Additionally, you are given an integer `k` representing the number of consecutive days required to reach a certain milestone. Your...
```python from typing import List import math def calculate_total_score(scores: List[int], k: int) -> int: min_days = math.ceil(len(scores) / k) output = 0 for i in range(min_days): output += scores[len(scores) - 1 - i] return output ``` The `calculate_total_score` function calculates the total...
magicoder
python
You are tasked with implementing a simple menu system for a graphical user interface (GUI) application. The menu system should allow users to add, remove, and display menu items. Each menu item has a name and a unique identifier. You need to create a class to represent the menu system and implement the necessary method...
```python class MenuSystem: def __init__(self): self.menu_items = [] def addMenuItem(self, name, id): for item in self.menu_items: if item['id'] == id: return False self.menu_items.append({'name': name, 'id': id}) return True def removeMenuItem(s...
magicoder
python
You are tasked with creating a web application that allows users to submit trial data through a form. The form is expected to have multiple input fields, and the submitted data needs to be stored in a database. You are required to implement the backend functionality to handle the form submission and store the data in t...
```php // Controller method to handle the form submission public function store(Request $request) { // Validate the incoming form data $validatedData = $request->validate([ 'field1' => 'required', 'field2' => 'required', // Add validation rules for other fields as per requirements ])...
magicoder
php
You are tasked with creating a script to process genomic data using R. The script will take two input files and additional parameters, and produce a specific output file. The input files are a chromosome interaction matrix file and a TSS (transcription start site) count file, both related to chromosome 18. The script w...
```R # get.PC1.R # Load required libraries library(data.table) library(matrixStats) # Command line arguments args <- commandArgs(trailingOnly = TRUE) # Input file names and parameters input_matrix_file <- args[1] tss_count_file <- args[2] chromosome <- as.numeric(args[3]) output_file <- args[4] # Read input files m...
magicoder
r
You are tasked with creating a Java class that simulates a simple banking system. Your class should include methods for charging a credit card and generating a JSON response based on the success of the transaction. Your task is to implement the `BankingSystem` class with the following methods: 1. `chargeCard(boolean s...
```java import com.google.protobuf.util.JsonFormat; import javax.ws.rs.core.Response; public class BankingSystem { public String chargeCard(boolean success) { try { ChargeCardResponse response = ChargeCardResponse.newBuilder().setSuccess(success).build(); String json = JsonFormat.p...
magicoder
java
You are tasked with implementing the `Equatable` protocol for the `EthereumAddress` type in Swift. An Ethereum address is a 20-byte (40-character) hexadecimal address used to identify an Ethereum account. The `EthereumAddress` type is represented as a string in Swift. Your task is to define the `static func ==` method ...
```swift extension EthereumAddress: Equatable { static func ==(lhs: EthereumAddress, rhs: EthereumAddress) -> Bool { // Remove leading and trailing whitespaces and convert to lowercase for case-insensitive comparison let lhsTrimmed = lhs.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() ...
magicoder
swift
You are tasked with implementing a custom data structure called `CustomStack` that supports the following operations: 1. `push(int x)`: Add an element `x` to the top of the stack. 2. `pop()`: Remove the element at the top of the stack and return its value. 3. `increment(int k, int val)`: Increments the bottom `k` eleme...
```java class CustomStack { private int[] stack; private int maxSize; private int size; public CustomStack(int maxSize) { this.maxSize = maxSize; this.stack = new int[maxSize]; this.size = 0; } public void push(int x) { if (size < maxSize) { stack[si...
magicoder
java
You are tasked with creating a simple game AI for a snake game. The game is played on a grid, and the snake moves around the grid, consuming food to grow longer. The objective is to write a function that determines the next move for the snake based on the current game state. You are provided with a Python class `Statu...
```python class Status(object): def getHeadPosition(gamedata): me = gamedata['you'] my_position = me['body'] head = my_position[0] return head def getMyLength(gamedata): me = gamedata['you'] return len(me['body']) def nextMove(gamedata): head = Status...
magicoder
python
You are working on a web application that manages user registration. The given code snippet is a part of the backend PHP code responsible for adding a new user to the database. The `add_user` function takes three parameters: `$pseudo` (user's username), `$mail` (user's email), and `$pass` (user's password). It then ins...
The `validate_and_add_user` function first checks if the username (`$pseudo`) meets the length and format requirements using a regular expression. It then validates the email address (`$mail`) using the `FILTER_VALIDATE_EMAIL` filter. Finally, it checks the password (`$pass`) against a regular expression that enforces ...
magicoder
php