query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with creating a Python program to manage a membership system for a club. The program should allow users to view and update member details, including gender and membership status. The default set of options for gender and membership status is provided in the `_default_options` dictionary as shown below: ...
```python class MembershipSystem: _default_options = { 'gender': ('Male', 'Female', 'Other'), 'member': ('Normal', 'Life', 'New', 'Honourable', 'Banned', 'In-arrears', 'Inactive'), } def __init__(self): self.members = {} def add_member(self, name, gender, membership_status): ...
magicoder
python
You are working on a project that involves a C++ codebase stored in a repository named `officialrafsan/CppDroid`. While examining the code, you come across the following snippet: ```cpp #ifdef TABLE_SIZE int table[TABLE_SIZE]; #endif ``` You realize that the size of the `table` array is conditional upon the value of ...
```cpp #include <iostream> int main() { int TABLE_SIZE; std::cout << "Enter the value for TABLE_SIZE: "; std::cin >> TABLE_SIZE; if (TABLE_SIZE <= 0) { std::cerr << "Error: TABLE_SIZE must be a positive integer." << std::endl; return 1; } int* table = new int[TABLE_SIZE]; ...
magicoder
cpp
You are tasked with creating a Python program that downloads images from a given webpage and saves them locally with their corresponding alternative text as the file name. You will need to utilize web scraping techniques and the `urllib` library to accomplish this task. Your program should perform the following steps:...
```python import urllib.request from bs4 import BeautifulSoup import requests # Specify the URL of the webpage to scrape url = 'https://example.com' # Send an HTTP request to the specified URL and retrieve the HTML content response = requests.get(url) html_content = response.content # Create a BeautifulSoup object t...
magicoder
python
You are given a code snippet that iterates over a range of denominators from `numerator+1` to 99. Your task is to write a function that calculates the sum of fractions where the numerator is fixed and the denominator ranges from `numerator+1` to 99. The sum of fractions should be returned in its simplest form. Write a...
```python from fractions import Fraction def sum_of_fractions(numerator): total_sum = 0 for denominator in range(numerator+1, 100): total_sum += Fraction(numerator, denominator) simplified_sum = total_sum.limit_denominator() return str(simplified_sum.numerator) + "/" + str(simplified_sum.denomi...
magicoder
python
You are tasked with implementing a program to simulate the folding of a piece of paper in an origami-like fashion. The program should take a series of folding instructions and produce the final folded shape. You are given a code snippet that processes folding instructions and constructs an `Origami` struct containing ...
```rust fn fold_paper(origami: &Origami) -> Vec<Point> { let mut folded_points = origami.points.clone(); for fold in &origami.folds { match fold { Fold::Vertical { x } => { for point in &mut folded_points { if point.x > *x { point....
magicoder
rust
You are tasked with implementing a validation function for a session management system. The function should validate a given session ID and user ID against predefined criteria and raise an exception if the validation fails. You are provided with a class `SessionValidator` with a method `validate($sessionId, $userId)`....
```php class SessionValidator { private $predefinedSessionId = '1234567890'; private $predefinedUserId = '099999'; public function validate($sessionId, $userId) { if (!preg_match('/^\d{10}$/', $sessionId)) { throw new InvalidSessionException('Invalid session ID format'); } ...
magicoder
php
You are tasked with creating a script to automate the localization process for a software project. The project contains language files in the gettext format (`.po` files) and needs to be compiled into machine-readable format (`.mo` files) for different languages. The `msgfmt` command is used to perform this compilation...
```python import subprocess def compile_language_files(language_codes): for code in language_codes: input_file = f"{code}/LC_MESSAGES/tickeys.po" output_file = f"{code}/LC_MESSAGES/tickeys.mo" subprocess.run(["msgfmt", "-o", output_file, input_file]) # Example usage languages = ["zh_CN", "...
magicoder
python
You are tasked with creating a password strength checker function in JavaScript. The function should take a password as input and return a strength score based on the following criteria: - Length: 5 points for a password length of 8 characters or more, 3 points for 6-7 characters, and 1 point for 1-5 characters. - Comp...
```javascript function checkPasswordStrength(password) { let score = 0; // Length if (password.length >= 8) { score += 5; } else if (password.length >= 6) { score += 3; } else { score += 1; } // Complexity if (/[A-Z]/.test(password)) { score += 3; } if (/[a-z]/.test(password)) { ...
magicoder
javascript
You are tasked with creating a command-line interface (CLI) tool for installing applications. Your tool should support the installation of applications by specifying their package names or by providing package specifications, URLs, or directories. To achieve this, you need to implement a function that parses the input ...
```python import os import shutil import requests def install_application(app_name, source): if source.startswith('http://') or source.startswith('https://'): # Install from URL response = requests.get(source) if response.status_code == 200: with open(app_name + '.zip', 'wb') as...
magicoder
python
You are given a code snippet that generates a set of angles in radians. Your task is to implement a function that takes this set of angles as input and returns the average angle in degrees. The average angle is calculated by finding the mean of the given angles and converting it from radians to degrees. Write a functi...
```python import numpy as np def average_angle_degrees(theta): mean_angle_rad = np.mean(theta) mean_angle_deg = np.degrees(mean_angle_rad) return round(mean_angle_deg, 2) ``` The `average_angle_degrees` function calculates the mean of the input angles in radians using `np.mean`, converts it to degrees usin...
magicoder
python
You are tasked with creating a Python script to manage database migrations for a web application. The script should handle executing migration scripts and updating a database table to track the executed migrations. You are given a code snippet that partially implements the migration script. The snippet checks if a mig...
```python import os def manage_migration(scriptPath, args, db): if not os.path.isfile(scriptPath): if not args.skip_missing: raise Exception('Missing %s' % scriptPath) else: print('Executing', scriptPath) db.execute_script(open(scriptPath).read().strip()) db.delete_r...
magicoder
python
You are tasked with creating a custom annotation in Java to mark methods that perform a specific type of validation. The annotation should be used to mark methods that take a single String parameter and return a boolean value indicating whether the input string passes the validation criteria. Additionally, you need to ...
```java import java.lang.annotation.*; import java.lang.reflect.Method; @Retention(RetentionPolicy.RUNTIME) @interface ValidationMethod { String value(); } class ValidationProcessor { boolean validate(String input, String validationType, Object obj) { Method[] methods = obj.getClass().getDeclaredMetho...
magicoder
java
You are tasked with creating a Python decorator that measures the execution time of a function and prints the result. Your decorator should take an optional argument `names`, which is a list of names to be included in the printed message. If `names` is not provided, the default behavior is to include all names. Your t...
```python import time from functools import wraps class Clacks: def __init__(self, names=None): self.names = names def clacks(names=None): _names = names def decorator(f): c = Clacks(names=_names) @wraps(f) def wrapper(*args, **kwargs): start_time = time.time(...
magicoder
python
You are tasked with creating a program that extracts the license information from a given text. The license information is embedded within a multi-line comment block, and it follows a specific format. Your program should be able to identify and extract the license details from the input text. Write a function `extract...
```python import re def extract_license_info(text: str) -> str: pattern = r'/\*(.*?)http://.*?\*/' match = re.search(pattern, text, re.DOTALL) if match: return match.group(1).strip() else: return "License information not found" ``` The `extract_license_info` function uses the `re` modu...
magicoder
python
You are tasked with designing a modular game system for a 2D shooter game. The provided code snippet is a part of the game's module system, which organizes various game functionalities into separate modules for better code organization and maintainability. Each module contains specific game features such as player move...
```rust // powerup_system.rs // Define the PowerUp type to represent different power-up effects pub enum PowerUp { SpeedBoost, DamageBoost, HealthRegeneration, } // Define the PowerUpSystem module pub mod powerup_system { use crate::player::Player; // Assuming the existence of a Player module pub...
magicoder
rust
You are tasked with implementing a class for handling SIP (Session Initiation Protocol) communication in a VoIP (Voice over Internet Protocol) application. The provided code snippet is a partial constructor for the SIPHandler class, which initializes some of its member variables. Your task is to complete the implementa...
```java public class SIPHandler { private int localSipPort; private String natIp; private String transport; private boolean fixSdpForNat; private NetworkAddress proxyAddr; public SIPHandler(int _localSipPort, String _natIp, String _transport, boolean fix_sdp_for_nat, String _proxyAddr) { ...
magicoder
java
You are tasked with creating a program that reads a file containing copyright information and extracts the years covered by the copyright. The copyright information is provided in the form of comments within the file. Each comment may contain one or more years in the format "YYYY-YYYY" or "YYYY". Your program should ex...
```java import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CopyrightYearsExtractor { public static void main(String[] args) { if (args.length != 1) { System....
magicoder
java
You are tasked with implementing a Python class method that generates the ARFF (Attribute-Relation File Format) data section for a given dataset. The ARFF format is commonly used for representing datasets in machine learning and data mining. The method should take a list of feature sets (which are represented as dictio...
```python class ARFFGenerator: def data_section(self, tokens, labeled=None): """ Returns the ARFF data section for the given data. :param tokens: a list of featuresets (dicts) or labelled featuresets which are tuples (featureset, label). :param labeled: optional; if True...
magicoder
python
You are tasked with implementing a simple testing framework for a custom logging library. The code snippet provided is a part of the testing framework and includes a function `test_run_all` and a test attribute `#[test]`. Your goal is to complete the testing framework by implementing the missing parts and ensuring that...
```rust use fil_logger::{init, log, LogLevel}; fn run_all() { // Initialize the logger init(); // Test logging messages at different levels log(LogLevel::Info, "This is an info message"); log(LogLevel::Error, "This is an error message"); log(LogLevel::Debug, "This is a debug message"); //...
magicoder
rust
You are tasked with creating a program that simulates a simple inventory management system for a small retail store. The system should allow users to add, remove, and update products in the inventory, as well as display the current inventory status. Your task is to implement a class `Inventory` with the following func...
```python class Inventory: def __init__(self): self.products = {} def add_product(self, name, quantity, price): if name in self.products: self.products[name]['quantity'] += quantity self.products[name]['price'] = price else: self.products[name] = {'qu...
magicoder
python
You are tasked with creating a Python function to process data from a file and extract metadata from the file name. The function should read a CSV file containing numerical data and extract specific information from the file name to populate a metadata dictionary. The file name follows a specific format where the tempe...
```python import ntpath import pandas as pd def process_data_and_extract_metadata(fn_data): # Read data from the CSV file data = pd.read_csv(fn_data, delimiter=',', skiprows=1, header=None).values # Extract metadata from the file name fn_base = ntpath.basename(fn_data) fn_meta = fn_base.split(...
magicoder
python
You are tasked with creating a Java method to generate a random binary file of a specified size. The method should take a file path and the size of the file in kilobytes as input and return the generated binary file as a byte array. You are provided with a code snippet that initializes a file system and creates an outp...
```java import java.io.IOException; import java.nio.file.Path; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FSDataOutputStream; import java.util.Random; public class FileGenerator { private FileSystem cluster; public FileGenerator(FileSystem cluster) { this.cluster = cluster; ...
magicoder
java
You are given a string containing only parentheses, brackets, and braces. Your task is to write a function to determine if the input string has balanced parentheses. A string is considered balanced if every opening parenthesis has a corresponding closing parenthesis and they are properly nested. For example, the string...
```python def isBalanced(s): stack = [] mapping = {")": "(", "}": "{", "]": "["} for ch in s: if ch in mapping.values(): stack.append(ch) else: if len(stack) == 0 or stack.pop() != mapping[ch]: return False return len(stack) == 0 ``` The `isBala...
magicoder
python
You are tasked with creating a Python unit test for a FastAPI endpoint that requires mocking several dependencies. The endpoint is responsible for retrieving a public user's information, including their avatar, and is protected by an authentication dependency. You are provided with the following code snippet as a star...
```python # Import the necessary modules and classes for the test from fastapi.testclient import TestClient from unittest import mock import pytest from fastapi import FastAPI from pol.api.v0.depends.auth import Guest from pol.services.user_service import UserService from pol.services.subject_service import SubjectServ...
magicoder
python
You are tasked with implementing a custom error handling system for a file parser in Swift. The file parser is responsible for reading and processing property list (plist) files. Your goal is to create a custom error type and handle specific error cases that may occur during the parsing process. Your task is to define...
```swift enum ParserError: Error { case invalidFile(path: String, reason: String) case invalidData(description: String) } func parsePlistFile(atPath path: String) -> Result<Any, ParserError> { guard FileManager.default.fileExists(atPath: path) else { return .failure(.invalidFile(path: path, reason:...
magicoder
swift
You are tasked with implementing a Python class that manages the creation and manipulation of graphical user interface (GUI) elements using the PyQt library. The class, named `GUIManager`, should have methods for adding buttons and setting their properties. Specifically, you need to implement the following functionalit...
The `GUIManager` class is implemented with the required methods for adding, updating, and removing buttons from the GUI. The `add_button` method creates a QPushButton with specified properties, the `set_button_icon` method updates the button's icon, and the `remove_button` method removes the button from the GUI. The ex...
magicoder
python
You are tasked with implementing a Bayesian Binary sensor for a home automation system. The Bayesian Binary sensor is a type of sensor that uses Bayesian inference to determine the probability of a binary event, such as motion detection or door opening. The sensor takes into account both prior knowledge and new evidenc...
```python class BayesianBinarySensor: def __init__(self, name, prior_probability, threshold): self.name = name self.prior_probability = prior_probability self.threshold = threshold def update_probability(self, new_evidence): # Implement Bayesian inference algorithm to update pro...
magicoder
python
You are tasked with implementing a text layout algorithm for a custom text rendering engine. The `layout` function takes in a mutable reference to a structure implementing the layout algorithm, a mutable reference to a `LayoutCtx` object, a reference to `BoxConstraints`, and a reference to a `String` containing the tex...
```rust fn layout( &mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &String, ) { // Your implementation of the layout algorithm goes here // Calculate the layout based on the provided constraints and text content // Update the internal state of the layout structure accordingly ...
magicoder
rust
You are tasked with implementing a Singleton design pattern for a shader class in a game engine. The given code snippet is a partial implementation of the Singleton pattern for the `SkinnedNormalMapShader` class. The `SkinnedNormalMapShader` class is responsible for managing and providing access to a shader used for re...
```cpp class SkinnedNormalMapShader { private: static SkinnedNormalMapShader* instance; SkinnedNormalMapShader() { // Private constructor to prevent external instantiation } SkinnedNormalMapShader(const SkinnedNormalMapShader&); // Private copy constructor SkinnedNormalMapShader& operator=...
magicoder
cpp
You are tasked with implementing a custom annotation processor for a Java project. The goal is to create an annotation called `@Validation` that can be applied to fields within a class. When this annotation is present, the processor should generate validation code to ensure that the annotated fields meet certain criter...
```java import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.Modifier; import javax.lan...
magicoder
java
You are tasked with implementing a Python class that loads settings to an etcd server from a YAML file source. The class should be designed to be used as a utility from the command line or for testing purposes. The class should have the following features: - It should be based on a synchronous library. - It should have...
```python import etcd import yaml class EtcdSettingsLoader: def __init__(self, host="127.0.0.1", port=2379, protocol="https", encode=None): self.host = host self.port = port self.protocol = protocol self.encode = encode self.client = etcd.Client(host=self.host, port=self.por...
magicoder
python
You are tasked with creating a Python function that processes a given GitHub repository name and its stars range to generate a list of tuples representing the repository name and its corresponding star count. The function should filter out repositories with star counts falling outside the specified range and return the...
```python def filter_repositories(repositories: list, stars_range: tuple) -> list: filtered_repositories = [] for repo in repositories: repo_name, star_count = repo.rsplit('/', 1) star_count = int(star_count[-1]) # Extract the last character as star count if stars_range[0] <= star_count...
magicoder
python
You are tasked with creating a simple network communication program. Your goal is to write a Python script that acts as a server, listens for incoming connections, and processes commands sent by clients. The server should be able to handle a specific command format and execute corresponding actions based on the receive...
```python import socket def main(): # Create a socket object server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind the socket to a specific port server_socket.bind(('localhost', 9999)) # Listen for incoming connections server_socket.listen(1) print("Server is listening...
magicoder
python
You are tasked with creating a Python function that checks the reputation of a given domain using the Cymru Whois service. The Cymru Whois service provides information about the reputation of a domain, including whether it is associated with malicious activity. Your task is to implement a function that takes a domain n...
```python import socket from cymruwhois import Client def check_domain_reputation(domain): try: ip_address = socket.gethostbyname(domain) cymru_client = Client() result = cymru_client.lookup(ip_address) reputation_info = { "domain": domain, "ip_address": ip_...
magicoder
python
You are given a list of integers, and your task is to reverse each integer and print the reversed integer. Write a function `reverse_integers` that takes a list of integers as input and returns a list of the reversed integers. The function signature is: ```python def reverse_integers(integers: List[int]) -> List[int]...
```python from typing import List def reverse_integers(integers: List[int]) -> List[int]: reversed_integers = [int(str(n)[::-1]) for n in integers] return reversed_integers ``` The `reverse_integers` function takes the list of integers and uses list comprehension to reverse each integer by converting it to a ...
magicoder
python
You are tasked with creating a Python script to automate the extraction and transformation of motion features from a dataset. The script should process motion data using the specified parameters and generate transformed features for further analysis. The script should take the following inputs: - `$py`: The Python int...
```python import subprocess py = "python3" # Replace with the actual Python interpreter executable n = 4 # Replace with the desired number of processes for parallel execution input_directory = "/path/to/input_directory" # Replace with the actual input directory containing motion data param = "expmap" # Specify the...
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 stored. The `UniqueStack` should support the following operations: 1. `push(value)`: Add a new element to the top of the stack if it is not already present in the stack. 2. `pop(...
```python class UniqueStack: def __init__(self): self.stack = [] self.unique_set = set() def push(self, value): if value not in self.unique_set: self.stack.append(value) self.unique_set.add(value) def pop(self): if self.stack: value = sel...
magicoder
python
You are tasked with implementing a geocoding system using Python. Geocoding is the process of converting addresses (like "1600 Amphitheatre Parkway, Mountain View, CA") into geographic coordinates (like latitude 37.423021 and longitude -122.083739), which you can use to place markers on a map, or position the map. You...
```python import pandas as pd from CREDA_tools.geocoding import validators from geopy.geocoders import Nominatim class Geocoder: def __init__(self): self.geolocator = Nominatim(user_agent="geocoder") def geocode_address(self, address): location = self.geolocator.geocode(address) if loc...
magicoder
python
You are tasked with creating a Python function that calculates the total score of a player in a word game. The function should take in two parameters: `hand`, a dictionary representing the letters available to the player, and `totalScore`, an integer representing the current total score. The function should check if th...
```python def calculateTotalScore(hand: dict, totalScore: int) -> None: def calculateHandlen(hand: dict) -> int: return sum(hand.values()) if calculateHandlen(hand) == 0: print('Total score: ' + str(totalScore) + ' points.') ```
magicoder
python
You are tasked with creating a Python script to interact with an Ethereum blockchain using the `web3.py` library. Your script should connect to a local Ethereum test network, retrieve the balance of a specific account, and then send a transaction to transfer a certain amount of Ether to another account. The Ethereum t...
```python from web3 import Web3 # Connect to the local Ethereum test network ganache_url = "http://0.0.0.0:8545" # Assuming the default port for ganache-cli web3 = Web3(Web3.HTTPProvider(ganache_url)) # Retrieve the balance of the initial account initial_account = "0x7c71142c72a019568cf848ac7b805d21f2e0fd8bc341e8314...
magicoder
python
You are tasked with creating a text classification model using Python. Your goal is to implement a function that takes a piece of text as input and returns a JSON string containing the classification label and score. You are provided with a code snippet that demonstrates the usage of a `classify_text` function from a ...
```python import json class TextClassificationResult: def __init__(self, label, score): self.label = label self.score = score class HappyTextClassifier: def classify_text(self, text): # Placeholder implementation for demonstration purposes # Replace this with an actual text cla...
magicoder
python
You are tasked with creating a custom dialect for a compiler using the MLIR (Multi-Level Intermediate Representation) framework. The provided code snippet is a C++ implementation using the MLIR library to define a custom dialect called MaxJDialect. This dialect is used to extend the capabilities of the compiler for a s...
```cpp #include "mlir/Dialect/StandardOps/IR/Ops.h" #include "mlir/Dialect/StandardOps/IR/OpsBase.td" #include "mlir/IR/Builders.h" #include "mlir/IR/OpImplementation.h" #include "mlir/IR/Types.h" using namespace mlir; class CustomOp : public Op<CustomOp, OpTrait::VariadicOperands, OpTrait::OneResult> { public: usi...
magicoder
cpp
You are working on a recommendation system that utilizes embeddings to represent items and labels. The code snippet provided is a part of a TensorFlow implementation for generating embeddings and biases for labels in the recommendation system. Your task is to implement a function that calculates the example embeddings ...
```python import tensorflow as tf def calculate_embeddings(labels_matrix, model, label_size, label_distribution, example_emb, example_idxs, query_vec, label_emb, label_bias, label_idxs): # Generate example embeddings true_classes = labels_matrix num_true = 1 num_sampled = model.negative_sample uniq...
magicoder
python
You are tasked with creating a Java program that manipulates file paths using the `java.nio.file.Path` class. Your program should read a file path from the user, extract the file name from the path, and then print the extracted file name to the console. Your program should perform the following steps: 1. Prompt the us...
```java import java.nio.file.Path; import java.nio.file.Paths; import java.util.Scanner; public class FileNameExtractor { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the file path: "); String filePathString = scanner.nextLine()...
magicoder
java
You are given a list of lists containing integers. Your task is to implement a function `flatten_and_sort` that takes this list of lists as input and returns a new list containing all the integers from the input lists in ascending order. The function signature is: ```python def flatten_and_sort(lst: List[List[int]]) -...
```python from typing import List def flatten_and_sort(lst: List[List[int]]) -> List[int]: flattened = list(chain.from_iterable(lst)) # Flatten the list of lists flattened.sort() # Sort the flattened list return flattened ``` The `flatten_and_sort` function first flattens the list of lists using `chain....
magicoder
python
You are tasked with creating a Java class to manage contact information for a personal address book. The class should include methods to set and retrieve a person's telephone number and address. You are provided with a code snippet that declares private instance variables for the telephone number and address. Your tas...
```java public class ContactInformation { private String telefon; private String adres; // Method to set the telephone number public void setTelefon(String telefon) { if (!telefon.matches("\\d{3}-\\d{3}-\\d{4}")) { throw new IllegalArgumentException("Invalid telephone number format....
magicoder
java
You are tasked with implementing a Python class that performs image classification using a pre-trained deep learning model. The model is initialized and an input tensor is provided for inference. Your task is to complete the implementation of the class by adding a method that processes the input tensor through the mode...
```python import torch class ImageClassifier: def __init__(self, model): self.model = model def classify(self, x): with torch.no_grad(): output = self.model(x) _, predicted_class = output.max(1) return predicted_class.item() ``` In the solution, the `ImageC...
magicoder
python
You are tasked with implementing a Python class that can retrieve and process data from a Naver blog. Naver is a popular South Korean online platform that provides various services, including blogging. Your task is to create a class called `NaverBlog` that can retrieve blog posts from a given Naver blog URL and perform...
```python import requests from bs4 import BeautifulSoup class NaverBlog: def __init__(self, blog_url): self.blog_url = blog_url self.posts = [] def retrieve_posts(self): try: response = requests.get(self.blog_url) if response.status_code == 200: ...
magicoder
python
You are tasked with implementing a simple iterative algorithm to find the maximum value in a given array. The maximum number of iterations allowed for the algorithm is specified by the "max_iterations" parameter. If the algorithm does not find the maximum value within the specified number of iterations, it should retur...
```python from typing import List, Union def findMaxWithinIterations(arr: List[int], max_iterations: int) -> Union[int, str]: max_val = float('-inf') iterations = 0 for num in arr: if num > max_val: max_val = num iterations += 1 if iterations >= max_iterations: ...
magicoder
python
You are working on a time management software project called Kronos Heureka. The project involves handling dates and times using a custom Python module. The code snippet provided imports classes from the custom module for handling dates and times. Your task is to create a Python class that represents a calendar event ...
```python from Kronos_heureka_code.Zeit.Datum.Monat import Monate from Kronos_heureka_code.Zeit.Datum.Jahr import Jahr, Zeitrechnung from Kronos_heureka_code.Zeit.Datum.Tag import Tag class CalendarEvent: def __init__(self, title, start_date, end_date): self.title = title self.start_date = start_da...
magicoder
python
You are tasked with implementing a function that calculates the total number of injuries in a sports team over a given period of time. The function takes in an array of integers representing the number of injuries each day. However, the team has a recovery rate, meaning that the number of injuries on a given day is inf...
```python from typing import List def calculate_total_injuries(injuries: List[int]) -> int: total_injuries = 0 prev_injuries = 0 prev_prev_injuries = 0 for current_injuries in injuries: total_injuries += current_injuries + prev_injuries - prev_prev_injuries prev_prev_injuries = prev_in...
magicoder
python
You are tasked with creating a script to automate the process of checking and updating software versions in a package management system. The script should validate the version of a specific software package and prompt for an update if necessary. Your task is to write a Bash script that performs the following steps: 1....
```bash #!/bin/bash # Check if the environment variable $TERMUX_ON_DEVICE_BUILD is set to true if [[ $TERMUX_ON_DEVICE_BUILD == true ]]; then termux_error_exit "Package '$TERMUX_PKG_NAME' is not safe for on-device builds." fi # Validate that the version of the software package matches a predefined version if ! gr...
magicoder
shell
You are tasked with creating a Python function that processes a list of file paths and performs specific operations based on the file types. The function should take in two arguments: `file_paths` (a list of strings representing file paths) and `static_path` (a string representing the path to a static directory). The f...
```python import os import shutil import csv import json def process_files(file_paths, static_path): if static_path and os.path.exists(static_path): print("Removing old files in the static directory") shutil.rmtree(static_path) for file_path in file_paths: file_type = os.path.splitext(...
magicoder
python
You are tasked with creating a Python function that processes a list of job cards and enhances each card with additional information. The job cards are represented as dictionaries, and the function should retrieve related data from the database and add it to each card. The function should be designed to work within the...
```python import frappe def enhance_job_cards(job_cards): for card in job_cards: card["operation"] = frappe.get_doc("Operation", card["operation"]) card["work_order_image"] = frappe.get_value("Work Order", card["work_order"], "image") return job_cards ``` The `enhance_job_cards` function takes...
magicoder
python
You are working on a data visualization project and need to create a Python function to generate a plot using the `matplotlib` library. The function should take in a set of samples from a Markov Chain Monte Carlo (MCMC) simulation, a prior distribution, and some plot settings, and produce a plot displaying the prior di...
```python import numpy as np import matplotlib.pyplot as plt def generate_mcmc_plot(mcmc_prior_samples, n, b, prior_exp, title, legend_handles, ax, fig, save_filedir): x = np.linspace(np.min(mcmc_prior_samples), np.max(mcmc_prior_samples), n) line = ax.plot(x, mcmc_prior.pdf(x), c=b, label=f'{prior_exp}') ...
magicoder
python
You are tasked with implementing a custom sequence generator that follows a specific pattern. The generator should take two parameters: `return_sequences` and `implementation`. The `return_sequences` parameter is a boolean value indicating whether the generator should return sequences or not. The `implementation` param...
```python class SequenceGenerator: @staticmethod def is_prime(num): if num < 2: return False for i in range(2, int(num ** 0.5) + 1): if num % i == 0: return False return True @staticmethod def generate_sequence(return_sequences, implementa...
magicoder
python
You are tasked with creating a program that simulates a simple banking system. The program should allow users to create accounts, deposit and withdraw funds, and check their balance. Each account should have a unique account number, and the program should be able to handle multiple accounts. Your task is to implement ...
```python from typing import Union class Bank: def __init__(self): self.accounts = {} self.next_account_number = 1 def create_account(self, name: str, initial_balance: float) -> int: account_number = self.next_account_number self.accounts[account_number] = {'name': name, 'balan...
magicoder
python
You are tasked with writing a C++ program to calculate the sum of a series defined by the formula: s = 1^1/1! + 3^3/3! + 5^5/5! + ... Where '^' denotes exponentiation and '!' denotes factorial. The program should prompt the user to enter the number of terms in the series and then calculate and display the sum of the ...
```cpp #include <iostream> using namespace std; int fact(int n) { int f = 1; for (int i = 1; i <= n; i++) { f *= i; } return f; } int main() { int n; double sum = 0; cout << "Enter the number of terms in the series: "; cin >> n; for (int i = 1; i <= n; i++) { ...
magicoder
cpp
You are tasked with creating a program that parses a given HTML file and extracts all the form elements along with their attributes. The HTML file may contain multiple form elements, each with various attributes such as action, method, id, and class. Your program should be able to identify and extract these attributes ...
```python from bs4 import BeautifulSoup def extractFormElements(html): form_elements = [] soup = BeautifulSoup(html, 'html.parser') forms = soup.find_all('form') for form in forms: form_dict = {} form_dict['id'] = form.get('id') form_dict['action'] = form.get('action') f...
magicoder
python
You are tasked with implementing a program to manage a network of overpasses on a highway. The overpasses are represented as a list of tuples, where each tuple contains the start and end points of an overpass. The start and end points are represented as integers. Your program should determine the maximum number of over...
```python from typing import List, Tuple def max_non_overlapping_overpasses(overpasses: List[Tuple[int, int]]) -> int: if not overpasses: return 0 overpasses.sort(key=lambda x: x[1]) # Sort overpasses based on end points count = 1 # Initialize count with 1 for the first overpass end...
magicoder
python
You are tasked with implementing a Java interface for handling HTTP servlet requests related to the BIND specification in WebDAV (Web-based Distributed Authoring and Versioning) protocol. The interface, `BindServletRequest`, includes a method for retrieving `RebindInfo` from the request. Your task is to implement the ...
```java import org.apache.jackrabbit.webdav.DavException; public interface BindServletRequest { /** * Returns the {@link RebindInfo} present with the request * * @return {@link RebindInfo} object * @throws DavException in case of an invalid or missing request body */ RebindInfo getReb...
magicoder
java
You are tasked with creating a function that processes image sharing requests in a web application. The function receives a POST request and handles the editing of image sharing requests based on the user's role and the status of the request. You are given the following information: - The function receives a POST requ...
```python from django.shortcuts import redirect, HttpResponse from django.contrib import messages from .models import ImageShare def process_image_share_request(request): if request.method == "POST": user = request.user post_id = request.POST.get('id', False) if post_id and post_id...
magicoder
python
You are tasked with implementing a method to manipulate a two-dimensional array in a PHP class. The class has a method `getRowNumber()` that returns the number of rows in the array. You need to complete the method `manipulateArray()` that takes in the array and a boolean variable `$isStripe`. If `$isStripe` is true, th...
```php class ArrayManipulator { public function manipulateArray(array $array, bool $isStripe): array { $result = []; foreach ($array as $row) { if ($isStripe) { array_shift($row); // Remove the first element of the row } else { $result[] = ...
magicoder
php
You are tasked with implementing a Python function that performs a specific transformation on a given input array. The transformation involves applying the logistic function to each element of the input array. The logistic function, also known as the sigmoid function, is defined as: \[ f(x) = \frac{1}{1 + e^{-x}} \] ...
```python import numpy as np def apply_logistic_function(input_array: np.ndarray) -> np.ndarray: return 1 / (1 + np.exp(-input_array)) # Test the function with the given example input_array = np.array([0.5, 1.0, 2.0, 3.0, 4.0]) output_array = apply_logistic_function(input_array) print(output_array) # Output: arra...
magicoder
python
You are tasked with implementing a Python class that manages API calls to a backend server. The class, named `APIClient`, has a method `put` to set a configuration parameter and a method `_get_headers` to retrieve the headers for API calls. The `put` method takes two parameters: `team` (optional, defaulting to `None`) ...
```python from typing import Optional class APIClient: def __init__(self, default_team: str): self.default_team = default_team self.config = {} def put(self, datasets_dir: str, team: Optional[str] = None): self.config[f"teams/{team or self.default_team}/datasets_dir"] = datasets_dir ...
magicoder
python
You are tasked with creating a Python function that simulates the process of creating a NAT Gateway in a given subnet and granting internet access to a Lambda function. The function should take in the subnet ID as a parameter and perform the following steps: 1. Create a NAT Gateway in the specified subnet. 2. Modify th...
```python import boto3 from botocore.exceptions import ClientError def create_nat_gateway(subnet_id): ec2_client = boto3.client('ec2') lambda_client = boto3.client('lambda') try: # Create a NAT Gateway in the specified subnet response = ec2_client.create_nat_gateway(SubnetId=subnet_id) ...
magicoder
python
You are tasked with creating a web application for managing recipes. As part of the application, you need to implement a feature that allows users to select the origin of the ingredients used in a particular cuisine. The code snippet provided is a segment of the HTML template for the form used to input this information...
```php function generateIngredientOptions($cuisine) { $options = ''; $ingredientMap = config('base.cuisine_ingredient'); foreach ($ingredientMap as $key => $label) { $selected = ($cuisine->ingredient == $key) ? 'selected' : ''; $options .= "<option value=\"$key\" $selected>$label</optio...
magicoder
php
You are tasked with creating a program that simulates a simple banking system. The program should be able to handle basic banking operations such as account creation, deposit, withdrawal, and balance inquiry. The program should also be able to handle multiple accounts and perform operations on each account independentl...
```python class BankAccount: def __init__(self, account_number, account_holder, initial_balance): self.account_number = account_number self.account_holder = account_holder self.balance = initial_balance def deposit(self, amount): self.balance += amount def withdraw(self, am...
magicoder
python
You are tasked with implementing a custom UICollectionView cell that displays a list of products. Each cell should contain a product image, product name, and product price. You are given a Product struct with properties for the product's name, price, and image URL. Your task is to create a custom UICollectionViewCell s...
```swift import UIKit class ProductCell: UICollectionViewCell { // UI elements for displaying product information private let productImageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit // Add any necessary styling or constraints for the image...
magicoder
swift
You are tasked with implementing a Python class for Gaussian distribution. The Gaussian distribution, also known as the normal distribution, is a continuous probability distribution that is symmetric around the mean, showing that data near the mean are more frequent in occurrence than data far from the mean. Your task ...
```python import math class Gaussian: def __init__(self, mu, sigma): self.mean = mu self.stdev = sigma def calculate_mean(self): return self.mean def calculate_stdev(self, sample=True): if sample: return self.stdev else: return self.stdev * ...
magicoder
python
You are tasked with creating a macro for generating parsers that implement the `FromLexicalLossy` trait. The `FromLexicalLossy` trait is used for parsing and converting lexical representations of numbers into their corresponding types in a lossy manner, meaning that it may not handle all edge cases perfectly, but it sh...
```rust macro_rules! generate_parsers { ( $decimal_name:ident, $partial_decimal_name:ident, $radix_name:ident, $partial_radix_name:ident, $t:ty ) => { macro_rules! $decimal_name { ($input:expr) => { $input.parse::<$t>().ok() }; } m...
magicoder
rust
You are given a Python function that is intended to multiply every object in a given list `q` with each object in the same list `q`. The function is expected to return a unity matrix for an orthonormal system. However, the function is incomplete and needs to be fixed to achieve the desired functionality. Your task is ...
```python def multiply_orthonormal(q): """ Multiplies every object in q with each object in q. Should return a unity matrix for an orthonormal system. Args: q: A list of objects Returns: A 2D list representing the unity matrix for an orthonormal system """ n = len(q) ret = ...
magicoder
python
You are tasked with creating a script to automate the deployment of assets to an S3 bucket for a website. The script should build new assets, publish them to the S3 bucket, and optionally invalidate the CloudFront cache. You are given a code snippet as a starting point, which includes commands to build assets, sync CSS...
```bash #!/bin/bash BUCKET="s3://electionspending.org" PROFILE="tap-in" DISTRIBUTION_ID="E2UUWP43BWKWHW" echo "Building New Assets..." ./build.sh echo "Publishing New Assets..." aws s3 sync assets/css/ $BUCKET/css/ --profile $PROFILE aws s3 cp assets/index.html $BUCKET --profile $PROFILE aws s3 cp assets/elm.min.js ...
magicoder
shell
You are working on a project that involves setting up the environment for a Perl application. As part of this process, you need to understand and manipulate the `PERL5LIB` environment variable. The `PERL5LIB` environment variable is used to specify a list of directories where Perl modules can be found. When a Perl scr...
```perl #!/usr/bin/perl use strict; use warnings; # Define the directory paths my $TRAFFIC_OPS_APP = "/path/to/traffic_ops_app"; my $LOCAL_DIR = "/path/to/local_dir"; # Check if PERL5LIB is already set if ($ENV{'PERL5LIB'}) { $ENV{'PERL5LIB'} .= ":$TRAFFIC_OPS_APP/lib:$LOCAL_DIR:$LOCAL_DIR/perl5/"; } else { ...
magicoder
perl
You are tasked with implementing a custom QuerySet class for a Salesforce backend in a Django application. The provided code snippet includes an import statement and the beginning of a custom QuerySet class. Your task is to complete the implementation of the `SalesforceQuerySet` class by adding necessary methods and at...
```python from salesforce.backend import DJANGO_20_PLUS from django.db import models from salesforce import query class SalesforceQuerySet(query.QuerySet): def __init__(self, model=None, query=None, using=None, hints=None): super().__init__(model, query, using, hints) self.salesforce_backend = True...
magicoder
python
You are tasked with creating a program that analyzes the license information of a given file. The license information is embedded within the file as a comment block, and your program needs to extract and display the license details. The license information is always enclosed within a comment block that starts with a '#...
```python def extract_license_info(file_content: str) -> str: lines = file_content.strip().split('\n') license_info = [] in_license_block = False for line in lines: if line.startswith('#'): if in_license_block: license_info.append(line.lstrip('#').strip()) ...
magicoder
python
You are working on a project that involves translating x86 assembly mnemonics to their corresponding register names. In x86 assembly, mnemonics like "mov", "add", and "sub" are followed by a suffix indicating the size of the operands, such as "_b" for byte, "_w" for word, "_l" for doubleword, and "_q" for quadword. Add...
```python def getRegisterName(mnemonic): mapping = { "mov_b": "al", "mov_w": "ax", "mov_l": "eax", "mov_q": "rax", "add_b": "cl", "add_w": "cx", "add_l": "ecx", "add_q": "rcx", "sub_b": "dl", "sub_w": "dx", "sub_l": "edx", ...
magicoder
python
You are tasked with implementing a function that accumulates values from a channel using a provided closure and returns a future tuple of accumulated completion and success of the channel. The function takes an executor, a cancellation token, and a closure for combining accumulating and update values. The closure is us...
```swift import Foundation func accumulateFromChannel<T, U>( executor: Executor, cancellationToken: CancellationToken = .default, nextPartialResult: @escaping (T, U) -> T ) -> Future<(T, Bool)> { let promise = Promise<(T, Bool)>() executor.execute { var accumulatedValue: T var ...
magicoder
swift
You are tasked with implementing a function that simulates a simple text-based adventure game. The game will involve navigating through different rooms, interacting with objects, and making decisions that affect the outcome of the game. You are provided with a basic structure for the game, including a Room class and a...
```swift class Room { let name: String let description: String var objects: [String] init(name: String, description: String, objects: [String]) { self.name = name self.description = description self.objects = objects } } class Player { let name: String var currentRo...
magicoder
swift
You are tasked with creating a TypeScript class that interacts with a GitHub API to search for users and retrieve their repositories. Your task is to implement the `GitHubService` class with the following requirements: 1. The `GitHubService` class should have a constructor that takes an instance of `HttpClient` as a p...
```typescript import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; interface ApiResponse { avatar_url: any; login: any; location: any; followers: any; following: any; created_at: Date; public_repos: number; } class Users { constructor( public avatar_url: any, p...
magicoder
typescript
You are tasked with implementing a Twitter API client that interacts with the Twitter API to retrieve search metadata and user information. The provided code snippet outlines the structure of two classes: `SearchMetadataObject` and `UserInfoObject`. Your goal is to create a method that utilizes these classes to process...
```csharp using System; using Newtonsoft.Json; public class SearchMetadataObject { public long max_id { get; set; } public string max_id_str { get; set; } public string next_results { get; set; } public int count { get; set; } public long since_id { get; set; } public string since_id_str { get;...
magicoder
csharp
You are tasked with implementing a class to manage IPv6 leases in a DHCP server. The class, `Lease6`, should have the following functionalities: 1. Store the IPv6 address, lease data, lease time, client identifier, and client hostname. 2. Validate the lease state, preferred life, max life, last communication time, and...
```python class Lease6: NON_TEMPORARY = "non-temporary" def __init__(self, ipv6_address, lease_data, lease_time, client_identifier, client_hostname): self.ipv6_address = ipv6_address self.lease_data = lease_data self.lease_time = lease_time self.client_identifier = client_identi...
magicoder
python
You are given a Python code snippet that contains two functions: `compute_computed_constants` and `compute_variables`. The `compute_variables` function takes in a list of variables and an external function `external_variable`. It then assigns values to the variables based on the result of calling the `external_variable...
```python def external_variable(variables, index): if index == 0: return variables[1] + variables[2] elif index == 1: return variables[0] * variables[3] elif index == 2: return variables[0] + variables[1] + variables[3] elif index == 3: return variables[0] * variables[1] ...
magicoder
python
You are tasked with implementing a data structure to manage line breaks in a text editor. The data structure should support adding line breaks and building the final representation of the text with breaks. You are given a partial implementation of the data structure in Rust. The provided code snippet includes methods ...
```rust // Define a struct to represent line breaks struct Breaks { // Define the internal representation of line breaks breaks: Vec<usize>, } // Define a struct to represent a node in the data structure enum Node { Leaf { len: usize, data: Vec<usize> }, Internal { children: Vec<Node> }, } impl Node {...
magicoder
rust
You are tasked with implementing a Python class that facilitates interaction between two plugin instances. The class, named `PluginInteraction`, should allow instances of different plugins to communicate with each other. Each plugin instance is identified by a unique name. The `PluginInteraction` class should have the...
```python class PluginInteraction: def __init__(self): self.plugins = {} def register_plugin(self, plugin_name, plugin_instance): self.plugins[plugin_name] = plugin_instance def send_message(self, recipient_plugin, message): if recipient_plugin in self.plugins: self.plu...
magicoder
python
You are tasked with implementing a function to resolve module information from a crash report. The crash report contains a list of modules, each with an index pointing to the corresponding module entry in the minidump module list. Your goal is to write a function that takes the crash report information and the module l...
```rust struct CrashpadInfo { module_list: Vec<ModuleInfo>, // other fields } struct ModuleInfo { module_index: usize, // other fields } // Function to resolve module entries from crash report information fn resolve_modules(crashpad_info: &CrashpadInfo, module_list: &[ModuleEntry]) -> Vec<Option<&Modu...
magicoder
rust
You are given a list of tuples, where each tuple contains a hexadecimal number and a byte string. Your task is to write a function that processes this list and returns a dictionary where the keys are the hexadecimal numbers and the values are lists of corresponding byte strings. You need to implement the function `pro...
```python from typing import List, Tuple, Dict def process_data(data: List[Tuple[int, bytes]]) -> Dict[int, List[bytes]]: result = {} for hex_num, byte_str in data: decimal_num = int(hex_num) if decimal_num in result: result[decimal_num].append(byte_str) else: re...
magicoder
python
You are tasked with implementing a custom smart pointer in Rust, similar to the built-in `Box` type. The smart pointer should have the ability to store a single character and provide methods to access and modify the stored value. Additionally, you need to handle the error related to the experimental box pattern syntax....
```rust struct MyBox { value: char, } impl MyBox { fn new(value: char) -> MyBox { MyBox { value } } fn get(&self) -> &char { &self.value } fn set(&mut self, new_value: char) { self.value = new_value; } } fn main() { let mut my_box = MyBox::new('c'); printl...
magicoder
rust
You are given a snippet of PHP code that is part of a web application for managing motions and votes. The code is responsible for displaying information about registered and eligible voters, as well as handling the display of motions and their associated voting status. Your task is to write a function that takes an ar...
```php function processMotions($motions) { foreach ($motions as $motion) { $motion->status = ($motion->available_until->getTimestamp() <= time()) ? "closed" : "open"; $positiveVotes = $motion->votes->where('vote_id', '=', '1')->count(); $negativeVotes = $motion->votes->where('vote_i...
magicoder
php
You are tasked with creating a unit test for an Angular component using Jasmine and Karma. The component, `DetailsMessageComponent`, is a part of an Angular application and needs to be tested for its behavior and functionality. The provided code snippet is a part of the test setup for this component. Your task is to w...
```typescript import { ComponentFixture, TestBed } from '@angular/core/testing'; import { DetailsMessageComponent } from 'path-to-details-message-component'; // Replace with the actual path describe('DetailsMessageComponent', () => { let fixture: ComponentFixture<DetailsMessageComponent>; let component: DetailsMes...
magicoder
typescript
You are tasked with implementing a Deep Interest Network (DIN) model for personalized recommendation systems. The given code snippet is a part of the `net` method within the DIN model class. The `net` method takes a set of inputs and initializes various attributes of the model, including historical item sequences, hist...
```python class DINLayer: def __init__(self, item_emb_size, cat_emb_size, act, is_sparse, use_DataLoader, item_count, cat_count): self.item_emb_size = item_emb_size self.cat_emb_size = cat_emb_size self.act = act self.is_sparse = is_sparse self.use_DataLoader = use_DataLoader...
magicoder
python
You are tasked with creating a Python function that processes a CSV file and extracts specific information from it. The CSV file contains data about employees, with each row representing a different employee and the columns containing their details. Your task is to write a function that reads the CSV file, extracts the...
```python import csv def extract_employee_data(csv_file_path): employee_data = {} try: with open(csv_file_path, mode="r", encoding="windows-1252") as csv_file: reader = csv.DictReader(csv_file) for row in reader: employee_id = row['employee_id'] e...
magicoder
python
You are tasked with creating a custom module in AngularJS for handling date and time formatting using Moment.js library. Your module should provide filters for formatting dates and times in various ways. The code snippet provided initializes the AngularJS module named "momentFilters" and injects an empty array as its d...
```javascript // Define the AngularJS module and inject Moment.js as a dependency var app = angular.module('momentFilters', []); // Define the custom filters within the module app.filter('dateFormat', function() { return function(input, format) { return moment(input).format(format); }; }); app.filter('timeAgo...
magicoder
javascript
You are tasked with implementing a NotesRepository class that interacts with a service API to manage notes. The repository should be able to retrieve notes from the service API and save new notes to it. Additionally, the repository should handle caching of notes and invalidate the cache when a new note is saved. Your ...
```java public interface NotesServiceCallback { void onNotesLoaded(List<Note> notes); } public class Note { private String title; private String description; public Note(String title, String description) { this.title = title; this.description = description; } // Getters and se...
magicoder
java
You are working on a code generation framework for a dataflow system. The framework is responsible for generating code objects for specific nodes in a dataflow graph. Each node in the graph represents a computational task, and the framework needs to generate code for these tasks based on certain conditions. The code sn...
```python class CodeGenerationFramework: def __init__(self, frame_codegen, sdfg): self._codeobjects = [] self._cpu_codegen = frame_codegen.dispatcher.get_generic_node_dispatcher() frame_codegen.dispatcher.register_node_dispatcher(self, self.node_dispatch_predicate) def get_generated_cod...
magicoder
python
You are tasked with creating a function to generate boss reward hints for a video game. The function should construct text that will be displayed at the temple of time altar for both child and adult characters. The boss rewards are pulled based on items in a fixed order. The function should take into account the world ...
```python def buildBossRewardHints(world, rom): bossRewardsSpiritualStones = ['Kokiri Emerald', 'Goron Ruby', 'Zora Sapphire'] bossRewardsMedallions = ['Forest Medallion', 'Fire Medallion', 'Water Medallion', 'Shadow Medallion', 'Spirit Medallion', 'Light Medallion'] Block_code = [] Block_code += getBy...
magicoder
python
You are tasked with developing a command-line argument parser for a machine learning training script. The script is used to train a model on a GPU, and it requires several command-line arguments to be set. Your task is to write a Python function that takes in a dictionary of command-line arguments and their values, and...
```python def generate_command_string(args): command_string = "" for key, value in args.items(): if isinstance(value, bool): if value: command_string += f"--{key} " else: command_string += f"--{key} {value} " return command_string.strip() ``` The `gen...
magicoder
python
You are tasked with implementing a function to convert a given string representing a number in a specific base to its integer equivalent. The string may contain digits (0-9) and lowercase letters (a-z) to represent numbers greater than 9. The function should handle bases from 2 to 36, where digits 0-9 represent their r...
```cpp #include <iostream> #include <cctype> #include <string> #include <cstdint> int64_t toInteger(const std::string& s, int n) { int64_t res = 0; for (char c : s) { if (isdigit(c)) { res = res * n + c - '0'; } else if (isalpha(c)) { res = res * n + tolower(c) - 'a' + 10; } } return re...
magicoder
cpp
You are tasked with implementing a data preprocessing function for a computer vision application. The function takes an input image `img` and ground truth bounding boxes `gtboxes`, along with their corresponding labels `gtlabels` and scores `gtscores`. The function performs two operations on the input data before retur...
```python import numpy as np def random_flip(img, gtboxes): # Function to randomly flip the input image and its corresponding bounding boxes horizontally # Implementation not provided as it is specific to the application def shuffle_gtbox(gtboxes, gtlabels, gtscores): # Function to shuffle the ground trut...
magicoder
python
You are tasked with implementing a chess game using TypeScript. The provided code snippet is a part of an abstract class `ChessBoard` that contains some abstract methods. Your task is to create a concrete class `MyChessBoard` that extends `ChessBoard` and implements the abstract methods. The abstract methods in the `C...
```typescript // Define the PieceType enum enum PieceType { Queen, Rook, Bishop, Knight, } // Implement the MyChessBoard class class MyChessBoard extends ChessBoard { async askPromotionType(): Promise<PieceType> { // Implement the logic to prompt the user for piece type selection // and return a prom...
magicoder
typescript