query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with implementing a Python class that interacts with a bookmaker's API. The provided code snippet includes an incomplete class `Nairabet` that inherits from `BookmakerBaseClass` and imports various modules. Your task is to complete the `Nairabet` class by implementing specific methods and attributes to i...
```python from NaijaBet_Api.utils.normalizer import nairabet_match_normalizer from NaijaBet_Api.utils import jsonpaths from NaijaBet_Api.bookmakers.BaseClass import BookmakerBaseClass class Nairabet(BookmakerBaseClass): bookmaker_name = "Nairabet" def get_match_data(self, match_id): # Implement logic ...
magicoder
python
You are tasked with creating a Python function that extracts the version number of a specified package using the `pkg_resources` module. The function should take the package name as input and return the version number as a string. You should also handle the case where the specified package is not found. Create a funct...
```python import pkg_resources def get_package_version(package_name): try: version = pkg_resources.get_distribution(package_name).version return version except pkg_resources.DistributionNotFound: return "Package not found" # Test the function print(get_package_version("simcore-models-l...
magicoder
python
You are tasked with implementing a simple authentication decorator for a Python web application using the Tornado web framework. The provided code snippet is a simplified version of a Tornado RequestHandler class that handles POST requests for user-related operations. The `@authenticated` decorator is used to restrict ...
```python import functools from tornado.web import RequestHandler def authenticated(method): @functools.wraps(method) def wrapper(self, *args, **kwargs): # Check user authentication status (example: using a boolean flag) if self.current_user: return method(self, *args, **kwargs) ...
magicoder
python
You are tasked with implementing a function that calculates the sum of all prime numbers within a given range. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The function should take two integers, `start` and `end`, as input and return the sum of all prime numbe...
```python def is_prime(n: int) -> bool: if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def sum_of_primes(start: int, end: int) -> int: prime_sum = 0 for num in range(max(2, start), end + 1): if is_prime(num): ...
magicoder
python
You are tasked with implementing a filtering mechanism for MIME types in a Python web application. The MIME type consists of a major type and an optional minor type, separated by a forward slash (e.g., "text/html", "image/jpeg", "application/json"). The code snippet provided is a part of a class method used for filteri...
```python class MimeFilter: @classmethod def filter_mime(cls, value): (major, minor) = value.split('/') cond = sql.and_() cond.append(MimeMajor.name == major) if minor and minor != '*': cond.append(MimeMinor.name == minor) # Condition to match the minor type ...
magicoder
python
You are tasked with creating a Python program that takes in two JSON files containing input data and produces an output JSON file. The program should use the argparse library to handle command-line arguments. The input JSON files contain new and existing values, and the output JSON file will be created based on the com...
```python import argparse import json def compare_json_files(new_file, old_file, output_file): with open(new_file, 'r') as new_input: new_data = json.load(new_input) with open(old_file, 'r') as old_input: old_data = json.load(old_input) output_data = {} # Compare new and existing valu...
magicoder
python
You are tasked with creating a custom plugin for a content management system (CMS) using Django. The CMS allows users to add various types of content to their web pages using plugins. Your goal is to create a custom Spacer plugin that adds empty space to the page for design purposes. The given code snippet shows the b...
```python # Spacer model definition from django.db import models class Spacer(models.Model): # Add any necessary fields for the Spacer model # For example, you can specify the height of the spacer height = models.IntegerField(default=20) def __str__(self): return f'Spacer {self.pk}' # Spacer...
magicoder
python
You are tasked with implementing a cache management system for a web application. The cache is designed to store frequently accessed data to improve performance. The cache has a total cost limit, which is the maximum amount of memory it can consume. The cost of an item in the cache is determined by its size in bytes. W...
```python from collections import OrderedDict class LRUCache: def __init__(self, total_cost_limit): self.total_cost_limit = total_cost_limit self.cache = OrderedDict() self.current_cost = 0 def evict_items(self): while self.current_cost > self.total_cost_limit: key,...
magicoder
python
You are tasked with implementing a method to render a mob in a 3D game environment. The method should take into account the size of the mob and adjust its position accordingly. You are given a code snippet that partially implements the rendering logic, and your task is to complete the method to ensure proper rendering ...
```java private void renderMob(TilePoweredSpawner te, float partialTicks) { Entity entity = te.getCachedEntity(); if (entity != null) { float f = 0.53125F; float f1 = Math.max(entity.width, entity.height); if (f1 > 1.0D) { f /= f1; } GlStateManager.pushMatr...
magicoder
java
You are tasked with creating a program that analyzes CSS code to identify and count the number of unique CSS properties used in a given stylesheet. A CSS property is a key-value pair that defines the style of an HTML element. Each property is defined by a name and a value, separated by a colon. Your program should tak...
```typescript function countUniqueCSSProperties(cssCode: string): number { const propertiesSet = new Set<string>(); const lines = cssCode.split('\n'); for (const line of lines) { const propertyMatch = line.match(/^\s*([a-zA-Z-]+)\s*:/); if (propertyMatch) { propertiesSet.add(propertyMatch[1].trim())...
magicoder
typescript
You are tasked with creating a Python program to perform network scanning using the `scapy` library. The program should iterate through the network routes and extract relevant information about the network, netmask, interface, and address. Additionally, it should allow for the optional specification of a particular net...
```python import scapy.config def network_scanner(interface_to_scan=None): result = [] for network, netmask, _, interface, address, _ in scapy.config.conf.route.routes: if interface_to_scan and interface_to_scan != interface: continue result.append({'network': network, 'netmask': ne...
magicoder
python
You are working on a program to analyze crime data from a file. The code snippet provided reads each line from the file, splits it into words, and then attempts to process the words to identify specific crime types. However, the code contains some errors and lacks the necessary logic to achieve the intended functionali...
```python # Define the crime function to process the crime data def crime(): # Initialize a dictionary to store the counts of each crime type crime_counts = {"ASSAULT": 0, "ROBBERY": 0, "THEFT OF VEHICLE": 0, "BREAK AND ENTER": 0} # Print the header for the crime data print(" Crime Type | Crime ID ...
magicoder
python
You are tasked with implementing a Python program that simulates a simple chat server using sockets. The server should be able to handle incoming connections from multiple clients and broadcast messages from one client to all other connected clients. The provided code snippet is a part of the server's main loop, handli...
```python import socket import threading import logging # Set up the server socket server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind(('localhost', 9999)) server_socket.listen(5) clients = [] def handle_client(client_socket, address): try: while True: message...
magicoder
python
You are tasked with implementing a ConfigService class that manages configuration settings for a server. The ConfigService class interacts with an Authorizer class to ensure that only authorized users can access and modify the configuration settings. Additionally, the ConfigService class interacts with an AlertsService...
```python class ConfigService: def __init__(self, authorizer, config_folder): self.authorizer = authorizer self.config_folder = config_folder def get_config_settings(self, user): if self.authorizer.is_authorized(user): # Logic to retrieve and return configuration settings fo...
magicoder
python
You are tasked with implementing a class that represents a Pet. The class should have the following properties and methods: Properties: - `name` (string): The name of the pet. - `age` (integer): The age of the pet. - `species` (string): The species of the pet. Methods: - `make_sound()`: A method that returns a string...
```python class Pet: def __init__(self, name, age, species): self.name = name self.age = age self.species = species def make_sound(self): return "Some generic sound" class Dog(Pet): def make_sound(self): return "Woof!" class Cat(Pet): def make_sound(self): ...
magicoder
python
You are tasked with creating a function that manages the creation of directories for logging purposes. The function should take in the logs folder path, the application name, and the file manager as input parameters. It should then create a directory for the specified application within the logs folder. If the director...
```swift func configureLogger(logsFolder: URL, appName: String, fileManager: FileManager) throws { let bundleFolder = logsFolder.appendingPathComponent(appName) do { try fileManager.createDirectory(at: bundleFolder, withIntermediateDirectories: true, attributes: nil) } catch { print("Logger....
magicoder
swift
You are tasked with implementing a conditional generative adversarial network (GAN) for generating synthetic data. The GAN consists of a generator and a discriminator, and it uses conditional vectors to guide the generation process. The generator takes random noise as input and produces synthetic data conditioned on th...
```python # Incorporating the generated fakez and condvec into the generator synthetic_data = self.generator(fakez, condvec) # Feeding the synthetic data and corresponding conditional vectors into the discriminator discriminator_output_real = self.discriminator(real_data, condvec) discriminator_output_fake = self.disc...
magicoder
python
You are tasked with creating a Python script to automate the cleanup process for a Docker-based application. The script should stop and remove containers, delete specific volumes, and remove a network using the Docker Compose command-line tool. Your script should perform the following tasks in sequence: 1. Stop all co...
```python import subprocess def execute_command(command): try: subprocess.run(command, check=True, shell=True) print(f"Command '{command}' executed successfully.") except subprocess.CalledProcessError as e: print(f"Error executing command '{command}': {e}") def main(): # Stop all c...
magicoder
python
You are tasked with creating a simple Angular application for a book store. The application should have a landing page component, a menu toggle directive, and should utilize various Angular modules and features. Your goal is to implement the necessary Angular modules and components based on the given code snippet. Giv...
```typescript // LandingPageComponent import { Component } from '@angular/core'; @Component({ selector: 'app-landing-page', template: ` <h1>Welcome to the Book Store</h1> <!-- Add book store content here --> `, styles: [] }) export class LandingPageComponent { // Implement component logic here } // ...
magicoder
typescript
You are tasked with implementing a generic data structure that supports a doubly linked list with the ability to traverse the list in reverse order. The provided code snippet is a part of a C++ class template that defines a method for obtaining the previous entry in the list. Your task is to complete the implementatio...
```cpp template <class Type> class SvTreeList { public: // Other methods and members are not shown for brevity virtual Type Prev(SvListEntry* pEntry, sal_uInt16* pDepth = 0) const { if (pEntry->GetPrev()) { if (pDepth) { (*pDepth)++; } return static_c...
magicoder
cpp
You are tasked with creating a Python function that processes a list of options and returns a dictionary containing various pieces of information. The function should take in a list of options and perform the following tasks: 1. Calculate the count of units using the `compute_count` function and store it in the `unit_c...
```python def compute_count(options): # Function to calculate the count of units # This function is not provided, and its implementation is assumed to exist def describe(options): # Function to describe the changes based on the options # This function is not provided, and its implementation is assumed ...
magicoder
python
You are tasked with implementing a custom training loop for a machine learning model. The training loop consists of several methods that are called at different stages of the training process. Your goal is to implement these methods to perform specific actions before and after each training iteration and epoch. You ar...
```python class CustomTrainingLoop: def __init__(self): self.epoch = 0 def before_train_iter(self): # Perform actions before each training iteration # Example: Reset gradients, update learning rate, etc. pass def after_train_iter(self): # Perform actions after each ...
magicoder
python
You are tasked with implementing a Mean Average Precision (MAP) calculation module for object detection algorithms. The MAP is a popular metric used to evaluate the performance of object detection models. The MAP is calculated based on the precision and recall values obtained from the model's predictions. Your task is...
```python import numpy as np class MAP: def __init__(self, num_classes, iou_threshold, score_threshold): self.num_classes = num_classes self.iou_threshold = iou_threshold self.score_threshold = score_threshold self.true_positives = [0] * self.num_classes self.false_positives...
magicoder
python
You are working on a web application that uses a database to store user information. The application has a testing module that utilizes fixtures to set up test data. The code snippet provided is from a testing module that uses the pytest framework and SQLAlchemy to create a fixture for a superuser for testing purposes....
```python from typing import List def generate_unique_username(first_name: str, last_name: str, existing_usernames: List[str]) -> str: first_initial = first_name[0].lower() base_username = f"{first_initial}{last_name.lower()}" username = base_username count = 1 while username in existing_usernames:...
magicoder
python
You are tasked with implementing a simple CSS-in-JS library that allows users to define styled components using a JavaScript API. Your goal is to create a function that takes a component name and a style object as input and returns a string representing the CSS styles for the component. The function should support the...
```javascript function styled(component, styles) { let css = `${component} {`; for (let key in styles) { if (key.startsWith('$')) { css += `${key.substring(1)}: ${styles[key]};`; } else if (key.startsWith('&')) { css += `${key.substring(1)} {`; for (let nestedKey in styles[key]) { ...
magicoder
javascript
You are tasked with implementing a custom asynchronous task spawner in Rust. The provided code snippet outlines a function `spawn` that takes a spawner and a future, and spawns the future as a task using the spawner. Your goal is to complete the implementation of the `spawn` function by addressing the TODO comments and...
```rust use std::pin::Pin; use std::task::{Context, Poll}; use std::future::Future; use std::sync::Arc; use std::sync::Mutex; // Define a custom error type for the spawn function #[derive(Debug)] pub struct CustomSpawnError; // Define a custom spawner trait trait CustomSpawner { fn spawn<F>(&self, future: F) -> R...
magicoder
rust
You are tasked with implementing a function that calculates the sum of all prime numbers within a given range. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Your function should take two parameters, `start` and `end`, representing the inclusive range within whi...
```javascript function sumOfPrimes(start, end) { function isPrime(num) { if (num <= 1) return false; if (num <= 3) return true; if (num % 2 === 0 || num % 3 === 0) return false; let i = 5; while (i * i <= num) { if (num % i === 0 || num % (i + 2) === 0) return false; i += 6; } ...
magicoder
javascript
You are tasked with implementing a function that processes a given internet location (innetloc) and modifies it according to specific rules. The function should check if the input innetloc contains ".blogspot." but does not end with ".blogspot.com". If this condition is met, the function should extract the prefix befor...
```python def process_innetloc(innetloc: str) -> str: if ".blogspot." in innetloc and not innetloc.endswith(".blogspot.com"): prefix = innetloc.split(".blogspot.")[0] innetloc = prefix + ".blogspot.com" return innetloc ``` The solution defines the function `process_innetloc` that takes a string ...
magicoder
python
You are tasked with creating a script to automate the process of vetting Go modules within a specified directory structure. The script should iterate through all subdirectories within the `./src/` directory and, for each subdirectory containing a `go.mod` file, execute the `go vet` command. The script should be written...
```bash #!/bin/bash echo "Vetting..." # Iterate through subdirectories within ./src/ for d in ./src/*/; do # Check if go.mod file exists in the subdirectory if test -f "$d/go.mod"; then # Execute go vet command within the subdirectory (cd "$d" && go vet) fi done ``` The provided Bash scri...
magicoder
shell
You are tasked with creating a command-line interface (CLI) tool for a data management application called "DataTug." The tool should support various options for serving the application, including the ability to disable optimization and enable source map generation. Your task is to implement a function that parses the ...
```javascript function parseCommandLineArgs(args) { const options = { action: "serve", application: "datatug", optimization: true, sourceMap: false }; for (let i = 0; i < args.length; i++) { if (args[i] === "--optimization=true") { options.optimization = true; } else if (args[i] ===...
magicoder
javascript
You are tasked with creating a Python function that generates a unique identifier for each user in a system. The function should take into account the user's name and age to create the identifier. The identifier should be a combination of the first three letters of the user's name, the last two letters of the user's na...
```python from uuid import uuid4 def generate_user_id(name, age): if len(name) < 3: identifier = name + 'XX' + str(age) + '-' + str(uuid4()) elif len(name) < 5: identifier = name + str(age) + '-' + str(uuid4()) else: identifier = name[:3] + name[-2:] + str(age) + '-' + str(uuid4()) ...
magicoder
python
You are working on a reinforcement learning algorithm for a robotic system that involves controlling the movement of its limbs. The code snippet provided is a part of the scoring mechanism used to evaluate the quality of the robot's actions. The code snippet is written in Python and uses the NumPy library for array ope...
```python import numpy as np def calculate_scores(state, next_state, action): front_foot = state[:, 7] my_range = 0 heading_penalty_factor = 10 scores = np.zeros(len(action)) # Apply penalty based on front foot position scores[front_foot >= my_range] += heading_penalty_factor # Adjust sco...
magicoder
python
You are tasked with creating a Python class that simulates a network query interface. The class, named `NetworkQuery`, should have methods to retrieve a list of Service Provider Interfaces (SPIs), a list of network interfaces, and the Ethernet address of a specific interface. Additionally, you need to write unit tests ...
```python import unittest import six # Assuming the six library is used for compatibility with Python 2 and 3 class NetworkQuery: def get_spi_list(self): # Implement the logic to retrieve the list of Service Provider Interfaces (SPIs) # For example: return ["SPI1", "SPI2"] def get_ifa...
magicoder
python
You are tasked with implementing a class that interfaces with different EEPROM (Electrically Erasable Programmable Read-Only Memory) devices using the I2C (Inter-Integrated Circuit) protocol. The class should support two types of EEPROM devices: 24x256 and 24x512. The class should be able to calculate the maximum addre...
```python class EEPROMInterface: def __init__(self, i2c, i2c_address, EEPROM_device): # Init with the I2C setting self.i2c = i2c self.i2c_address = i2c_address[0] if EEPROM_device == "24x256": self._MAX_ADDRESS = 32767 elif EEPROM_device == "24x512": ...
magicoder
python
You are tasked with creating a Python function that processes historical data for a specific device. The function will interact with a mock database and handle HTTP requests using the Falcon framework. Your goal is to implement the function `STHHistory.on_get` to retrieve historical data based on the provided parameter...
```python import falcon from unittest.mock import MagicMock, patch class STHHistory: @staticmethod def on_get(request, response, device_id, attribute_id, filter_value): # Mocking PyMongo find method mock_pymongo_find = MagicMock() mock_pymongo_find.return_value = [ {"value":...
magicoder
python
You are tasked with implementing a deep learning model for fashion item classification using a subset of a large dataset. The dataset is organized into training, validation, and test sets. The deep learning model uses an embedding network (`emb_net`) for feature extraction and classification. The `emb_net` is then move...
```python import torch import torchvision from torchvision import transforms from torch.utils.data import DataLoader from torchvision.datasets import FashionMNIST def get_data_loaders(deep_fashion_root_dir, subset_size, transform): # Define the transformation for the dataset data_transform = transforms.Compose...
magicoder
python
You are working on a project that involves evaluating the privacy of machine learning models. The `ml_privacy_meter` library provides various utilities for this purpose. In this scenario, you are tasked with using the `attack_data` and `attack_utils` modules from the `ml_privacy_meter` library to assess the vulnerabili...
```python from ml_privacy_meter.utils import attack_data from ml_privacy_meter.utils import attack_utils # Step 1: Generate synthetic attack data attack_data.generate_attack_data(model, dataset, num_samples) # Step 2: Conduct membership inference attack attack_results = attack_utils.membership_inference_attack(model,...
magicoder
python
You are tasked with implementing a function that extracts the default export from a given JavaScript code snippet. The default export is the value that is exported by default from a module. Your function should take a string representing the JavaScript code snippet as input and return the default export value. You are...
```javascript function extractDefaultExport(codeSnippet) { // Remove leading/trailing whitespace and semicolons codeSnippet = codeSnippet.trim().replace(/;$/, ''); // Match the default export statement and extract the exported value const defaultExportMatch = codeSnippet.match(/export default (.+?);/); if (d...
magicoder
javascript
You are tasked with creating a Python program that identifies the type of a given matrix. The program should prompt the user to input the dimensions of the matrix (number of rows and columns) and then input the elements of the matrix. The program should then determine whether the matrix is an identity matrix, symmetric...
```python import numpy as np # Function to check if the matrix is an identity matrix def is_identity_matrix(matrix): return np.array_equal(matrix, np.eye(matrix.shape[0])) # Function to check if the matrix is a symmetric matrix def is_symmetric_matrix(matrix): return np.array_equal(matrix, matrix.T) # Functi...
magicoder
python
You are tasked with creating a class that manages tasks. The class should be able to update the name and description of a task, as well as set its status. Additionally, the class should handle validation of the task name. You are provided with a code snippet that demonstrates the usage of the class. The snippet decode...
```php class Task { private $name; private $description; private $status; public function updateName($name) { $validatedName = self::validateTaskName($name); $this->name = $validatedName; } public function updateDescription($description) { $this->description = $...
magicoder
php
You are tasked with implementing a matrix class in C++ that supports the functionality to set whether to use bias and to resize the matrix to a given size. The matrix class should have the following methods: 1. `setUseBias(bool useBias)`: A method to set whether to use bias in the matrix calculations. If `useBias` is ...
```cpp #include <iostream> #include <vector> class Matrix { private: bool useBias; std::vector<std::vector<int>> data; public: Matrix() : useBias(false) {} void setUseBias(bool useBias) { this->useBias = useBias; } void resize(int rows, int cols) { data.resize(rows, std::vect...
magicoder
cpp
You are tasked with implementing a function that checks whether a given string is a palindrome or not. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward, disregarding spaces, punctuation, and capitalization. You need to implement the function `isPalindrome...
```python def isPalindrome(s: str) -> bool: # Remove spaces and punctuation and convert to lowercase s = ''.join(e for e in s if e.isalnum()).lower() # Check if the string is equal to its reverse return s == s[::-1] ``` The `isPalindrome` function first removes spaces and punctuation from the inpu...
magicoder
python
You are tasked with implementing a file encryption utility that encrypts file paths based on certain criteria. The utility should provide a method `GetEncryptedPath` that takes a file path and a boolean flag indicating whether the file must already exist. The method should return the fully encrypted path if it meets th...
```csharp using System; using System.IO; using System.Text; public class FileEncryptor { private const string EncryptionKey = "MyEncryptionKey"; // Replace with your encryption key /// <summary> /// Encrypts the given file path based on certain criteria. /// </summary> /// <param name="path">The f...
magicoder
csharp
You are tasked with creating a Python class that manages SSL certificates for Cloud SQL instances. Your class should provide methods for creating, deleting, listing, and retrieving information about SSL certificates associated with Cloud SQL instances. The class should be designed to interact with the Google Cloud SDK ...
```python from googlecloudsdk.calliope import base from googlecloudsdk.api_lib.sql import ssl_certs_api class SslCerts(base.Group): """Provide commands for managing SSL certificates of Cloud SQL instances.""" def create_certificate(self, instance_id, common_name): """Create a new SSL certificate for ...
magicoder
python
You are tasked with creating a Python function that processes a list of numbers and returns the count of prime numbers in the list. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. You are given the following code snippet as a starting point: ```python def count...
```python 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 def count_primes(numbers): count = 0 for num in numbers: if is_prime(num): count += 1 return count # Example u...
magicoder
python
You are working on a project that involves analyzing porous materials using image processing techniques. You have been given a Python script that uses the `porespy` and `openpnm` libraries to generate and analyze images of porous materials. The script uses the `numpy` library for numerical operations and the `matplotli...
```python import numpy as np import porespy as ps import matplotlib.pyplot as plt import openpnm as op np.random.seed(0) def analyze_porous_materials(): # Generate binary images using porespy library im1 = ps.generators.blobs(shape=[600, 400], porosity=None, blobiness=1) < 0.4 im2 = ps.generators.blobs(sh...
magicoder
python
You are tasked with creating a program that simulates a simple file system. The file system will consist of directories and files, and you need to implement basic operations such as creating directories, creating files, listing the contents of a directory, and navigating through the file system. Your program should su...
```python class FileSystemNode: def __init__(self, name, is_directory=False): self.name = name self.is_directory = is_directory self.children = {} class SimpleFileSystem: def __init__(self): self.root = FileSystemNode("/", is_directory=True) self.current_directory = self...
magicoder
python
You are tasked with implementing a class that manages configuration sections for a network router. The provided code snippet is a partial implementation of the `RouterSection` class, which is used to represent a section of configuration for a router. Your task is to complete the implementation of the `RouterSection` cl...
```python class RouterSection: defaults = {"mode": "interior"} ignore = ["type", "routerId", "identity", "name"] def __init__(self, id, **kwargs): super(RouterSection, self).__init__("router", RouterSection.defaults, RouterSection.ignore, [], kwargs) self.setEntry("id", id) def setEntr...
magicoder
python
You are tasked with implementing a recommendation system for a polling application. The system should provide recommendations based on user preferences and interactions with the platform. To achieve this, you need to create a class that factors in common behaviors for all recommendation views. Your task is to complete...
```python class PollRecommendationsBaseAPIView(PollScopedViewMixin, ListAPIView): """ A base view used to factorize behaviors common to all recommendation views. """ def get_user_preferences(self, user_id): """ Retrieve the preferences of the specified user. Args: user_...
magicoder
python
You are tasked with implementing a simple drawing application using Python and OpenCV. The application should allow the user to draw either rectangles or circles on a blank canvas using the mouse. The user can switch between drawing rectangles and circles by pressing a specific key. When the left mouse button is presse...
```python import cv2 import numpy as np # Global variables drawing = False # Indicates if drawing mode is active mode = True # Indicates the shape to be drawn (True for rectangle, False for circle) ix, iy = -1, -1 # Initial coordinates for drawing # Mouse event handler function def draw_shape(event, x, y, flags, p...
magicoder
python
You are tasked with implementing a custom hook for tracking the intersection of a target DOM element with the viewport. The hook should provide functionality to determine whether the target element is intersecting with the viewport, calculate the intersection rate, and set the target DOM element to be observed. You ar...
```typescript export default function useIntersection({ threshold = defaultThreshold, }: IUseIntersectionInput = {}): IUseIntersection { const [targetNode, setTargetNode] = React.useState<Element | null>(null) const [isIntersected, setIntersected] = React.useState(false) const [intersectionRate, setIntersection...
magicoder
typescript
You are tasked with implementing a Python function that rounds a given floating-point number to a specified number of decimal places. The function should take two parameters: the floating-point number to be rounded (`num`) and the number of decimal places to round to (`decimal_places`). The function should return the r...
```python def round_to_decimal(num: float, decimal_places: int) -> float: rounded_num = round(num, decimal_places) return rounded_num ``` The `round_to_decimal` function takes the input `num` and `decimal_places` and uses the built-in `round` function in Python to round the number to the specified decimal plac...
magicoder
python
You are tasked with implementing a program that reads a sequence of integers from the standard input and calculates the sum of all the even numbers in the sequence. The program should continue reading integers until a non-positive integer is encountered, at which point it should output the sum of all the even numbers e...
```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class EvenNumberSum { public static void main(String[] args) { System.out.println(calculateEvenSum()); } public static int calculateEvenSum() { int sum = 0; try (BufferedRead...
magicoder
java
You are tasked with implementing a function that validates a given password based on certain criteria. The function should return `true` if the password is valid and `false` otherwise. The criteria for a valid password are as follows: 1. The password must be at least 8 characters long. 2. The password must contain at l...
```java public static boolean isValidPassword(String password) { if (password.length() < 8) { return false; } boolean hasUppercase = false; boolean hasLowercase = false; boolean hasDigit = false; boolean hasSpecialChar = false; for (char ch : password.toCharArray()) { if (C...
magicoder
java
You are tasked with implementing a simple gradient descent algorithm to optimize a linear regression model. Given a set of input features X, corresponding target values y, and initial weights/parameters theta, your goal is to update the weights using gradient descent to minimize the mean squared error (MSE) loss functi...
```python import numpy as np def gradient_descent(X, y, theta, learning_rate, iterations): m = len(y) for _ in range(iterations): # Calculate predictions and error predictions = np.dot(X, theta) error = predictions - y # Calculate gradients gradients = np.dot(X....
magicoder
python
You are tasked with creating a custom decorator in TypeScript to validate whether a given string contains only Kana characters, which are the syllabic Japanese scripts Hiragana and Katakana. The decorator should be implemented using TypeScript decorators and should be able to be used on class methods. Your task is to ...
```typescript // IsKana.ts export function IsKana(target: any, propertyKey: string, descriptor: PropertyDescriptor) { const originalMethod = descriptor.value; descriptor.value = function (...args: any[]) { const inputString = args[0]; const kanaRegex = /^[\u3040-\u309F\u30A0-\u30FF]+$/; // Regex for matchi...
magicoder
typescript
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. Each linked list is represented by a class `ListNode` with the following structure: ``` stru...
```cpp class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode* dummyHead = new ListNode(0); ListNode* p = l1, *q = l2, *curr = dummyHead; int carry = 0; while (p != nullptr || q != nullptr) { int x = (p != nullptr) ? p->val : 0; ...
magicoder
cpp
You are tasked with creating a Vue.js component for a customer portal that handles the registration process for a business internet service called "BiznetWifi". The component is intended to be included in a larger Vue.js application and will be used to facilitate the registration process for customers. The provided co...
```javascript // Vue.js component for BiznetWifi registration form Vue.component('registration-biznetwifi', { props: { url: String, connectlocale: Object }, data() { return { customer: { name: '', email: '', address: '', contactNumber: '' }, registrati...
magicoder
javascript
You are tasked with creating a custom styled component for a mobile navigation item in a React application. The component should be styled using the `styled-components` library and should have specific properties based on the theme provided. The theme properties include breakpoints, palette, and other custom styles. Yo...
```javascript import styled from 'styled-components'; interface ThemePropsType { theme: { breakpoints: { up: (size: string) => string; }; palette: { secondary: { main: string; }; // Add other palette properties as needed ...
magicoder
javascript
You are tasked with implementing a custom weight initialization function for a neural network. The given code snippet shows a Python function `init_func` that initializes the weights of the neural network layers based on the type of initialization specified. The function takes in a module `m` and performs weight initia...
```python import torch import torch.nn as nn import torch.nn.init as init # Define the custom weight initialization function def init_func(m, init_type='normal', gain=0.02): classname = m.__class__.__name__ if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1): if...
magicoder
python
You are tasked with implementing a simple serialization and deserialization library in Rust. The library should provide functionality to serialize and deserialize data structures into a custom binary format. The provided code snippet includes two modules: `serializer` and `util`. The `serializer` module is responsible ...
```rust // serializer.rs use crate::util; #[derive(Debug, PartialEq)] pub struct Person { name: String, age: u32, is_student: bool, } impl Person { pub fn new(name: String, age: u32, is_student: bool) -> Person { Person { name, age, is_student } } } pub fn serialize_person(person: &Person...
magicoder
rust
You are tasked with implementing a simple testing framework for unit tests. The framework provides a function `print_report` to print the results of a test suite. The function takes in the test suite and an optional `printer_mod` argument, which defaults to the result of the `get_default` function. The `get_default` fu...
```python import pyinq.printers.cli def get_default(): return pyinq.printers.cli def print_report(suite, printer_mod=None, **kwargs): def log_fixture(label, fixture): if fixture: printer.log_fixture(label, fixture) printer_mod = printer_mod if printer_mod else get_default() pr...
magicoder
python
You are tasked with implementing a function that calculates the average of a list of numbers, excluding any outliers. An outlier is defined as a number that is either significantly larger or smaller than the rest of the numbers in the list. To identify outliers, you will use the concept of Z-score, which measures how m...
```python import statistics def calculate_average_without_outliers(numbers, z_threshold): mean = statistics.mean(numbers) stdev = statistics.stdev(numbers) if len(numbers) > 1 else 0 # Standard deviation, handling edge case for single element list filtered_numbers = [x for x in numbers if abs((x - mean) /...
magicoder
python
You are given an array `arr` of positive integers in ascending order and an integer `k`. Your task is to find the `k`-th positive integer that is missing from the array. If there are multiple possible answers, return the smallest one. For example, given `arr = [2, 3, 4, 7, 11]` and `k = 5`, the missing positive intege...
```python def findKthPositive(arr: List[int], k: int) -> int: missing_numbers = 0 next_expected = 1 for x in arr: while x != next_expected: missing_numbers += 1 if missing_numbers == k: return next_expected next_expected += 1 next_expected...
magicoder
python
You are tasked with creating a Python function that processes a list of file extensions and returns a filtered list containing only the supported file extensions. The function should utilize the imported modules and their available functions to determine the supported file extensions. Write a function called `filter_s...
```python def filter_supported_extensions(extensions: list) -> list: supported_extensions = [] # Check if the required modules and functions are available if _ipython_module_available() and _pandas_available(): for ext in extensions: if ext.startswith('.'): ext = ext.low...
magicoder
python
You are tasked with creating a program that reads a text file and counts the occurrences of each word in the file. Your program should ignore punctuation and consider words with different capitalizations as the same word. The program should then output the word count for each unique word in alphabetical order. For exa...
```python import string def count_word_occurrences(file_name): word_count = {} with open(file_name, 'r') as file: for line in file: words = line.lower().translate(str.maketrans('', '', string.punctuation)).split() for word in words: if word in word_count: ...
magicoder
python
You are given a class `TreeLinkNode` representing a binary tree with an additional `next` pointer, which is used to connect nodes at the same level in a binary tree. The `connect` method is used to populate the `next` pointer for each node in the tree. Implement the `connect` method to connect the nodes at the same lev...
```java public void connect(TreeLinkNode root) { if (root == null) { return; } TreeLinkNode levelStart = root; while (levelStart != null) { TreeLinkNode curr = levelStart; while (curr != null) { if (curr.left != null) { curr.left.next = curr.right; ...
magicoder
java
You are tasked with creating a Python function that processes stock trading data and generates a report in an Excel file. The function should take a database connection, today's date, and an Excel writer object as input parameters. The function should retrieve information about stocks that have experienced three consec...
```python import pandas as pd import logging class StockProcessor: def __init__(self, dbConnection, excelWriter, logger): self.dbConnection = dbConnection self.excelWriter = excelWriter self.logger = logger self.today = pd.to_datetime('today').date() def Get3LianBan(self, dbCon...
magicoder
python
You are tasked with implementing a Python function that calculates the Lomb-Scargle periodogram for a given time series data. The Lomb-Scargle periodogram is a method used in spectral analysis to find the dominant frequencies in unevenly sampled data. The function should take the time series data, including the time va...
```python import numpy as np from astropy.timeseries import LombScargle def lomb_scargle_periodogram(time, measurements, uncertainties, oversampling, nyquist_factor): ls = LombScargle(time, measurements, dy=uncertainties) frequency, power = ls.autopower(oversampling=oversampling, nyquist_factor=nyquist_factor)...
magicoder
python
You are tasked with implementing a Python function to interact with the European Bioinformatics Institute's (EBI) Ontology Lookup Service (OLS) to retrieve information about Experimental Factor Ontology (EFO) terms. The EFO is used to describe experimental variables in ArrayExpress and other EBI databases. Your task is...
```python import requests class EbiOlsClient: base_url = 'https://www.ebi.ac.uk/ols/api/ontologies/efo/terms' def get_efo_name_from_efo_id(self, efo_id): url = f'{self.base_url}/{efo_id}' response = requests.get(url) if response.status_code == 200: return response.json()['l...
magicoder
python
You are tasked with creating a custom view for a video player in a Swift iOS app. The provided code snippet is a part of the process to embed a SwiftUI view into a UIKit-based app. Your task is to complete the implementation of the `SDKPlayerView` and `sdkPlayerViewModel` to create a functional video player view. The ...
```swift import SwiftUI // Define the ViewModel for the video player class SDKPlayerViewModel: ObservableObject { // Add properties and methods to manage video playback, controls, and data // Example: @Published var isPlaying: Bool = false // Add more properties and methods as needed } // Define the S...
magicoder
swift
You are tasked with creating a feature management system for a software application. The system should allow for the dynamic enabling or disabling of certain features based on configuration settings. To achieve this, you need to implement a feature management worker class that can read configuration options and determi...
```csharp using System; using System.Collections.Generic; using System.IO; using Newtonsoft.Json; namespace FeatureManagementWorkerDemo { public class WorkerOptions { public string Message { get; set; } } public class FeatureManager { private Dictionary<string, bool> featureConfig;...
magicoder
csharp
You are tasked with implementing a class for managing executables on a computing device. The class, named `ExecutableManager`, is responsible for handling the installation of executable files on a specific device. The provided code snippet is a part of the `ExecutableManager` class and demonstrates the installation pro...
```python class ExecutableManager: def __init__(self, device_abi): self.executables = [] # Initialize the list of executables self.device = Device(device_abi) # Create a Device object based on the provided ABI self.device_exe = None # Initialize the currently installed executable to None ...
magicoder
python
You are tasked with creating a Python program that simulates a simple network server for processing incoming data packets. The server will receive serialized data packets, parse them, and then print out specific information from the parsed packets. Your task is to implement the parsing and printing logic for the server...
```python class Foo: def __init__(self, id, bar): self.id = id self.bar = bar # Assuming the existence of a protobuf definition file named foo_pb2 import socket import foo_pb2 def main(): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(('127.0.0.1', 12345)) while Tru...
magicoder
python
You are tasked with implementing a function to find and remove old Docker containers and images based on certain criteria. The code snippet provided is part of a larger system for managing Docker containers and images. Your task is to complete the implementation of the `_find_old_images` function, which is responsible ...
```python def _find_old_images(ctx: BuildContext): old_images = set() for image in _docker_images(): if image['Tag'] != '<none>': # Check if the image's tag is not '<none>' old_images.add(image['ID']) # Add the ID of non-old images to the old_images set return old_images # Return the ...
magicoder
python
You are tasked with implementing a logging system for an educational software application called Kolibri. The application has different types of interactions that need to be logged, such as hints, answers, and errors. The interaction types are defined in a Python file named `interaction_types.py` within the `kolibri/co...
```python import time class InteractionLogger: def __init__(self): self.logged_interactions = [] def log_hint(self, user_id, hint_data): self.logged_interactions.append({ "type": "hint", "timestamp": time.time(), "user_id": user_id, "data": hint_...
magicoder
python
You are tasked with implementing a function that processes polygon data to generate a compressed mask representation. The function should take a list of polygons, scale values, and image dimensions as input, and produce a merged run-length encoded (RLE) mask as output. You are given the following code snippet as a ref...
```python from typing import List, Tuple import mask_util def generate_merged_mask(polygons: List[List[Tuple[int, int]]], scale_value: float, img_h: int, img_w: int) -> dict: rles = [] for poly in polygons: rle = mask_util.frPyObjects(poly, int(float(img_h) * scale_value), int(float(img_w) * scale_valu...
magicoder
python
You are tasked with simulating a series of coin tosses and calculating the probability of obtaining a specific outcome. You are given a function `toss_Coin()` that simulates the tossing of a fair coin and returns either "Success" (representing a head) or "Failure" (representing a tail). The function `toss_Coin()` is ...
```python import random def toss_Coin(): return "Success" if random.random() < 0.5 else "Failure" count_Success = 0 total_tosses = 100000 for i in range(total_tosses): if toss_Coin() == "Success": count_Success += 1 probability = count_Success / total_tosses print("The probability of getting exactly...
magicoder
python
You are tasked with implementing a custom mock class for a managed object context in a Core Data environment. The mock class should mimic the behavior of a real managed object context for testing purposes. Your goal is to create the `MockManagedObjectContext` class with specific functionalities to support testing scena...
```swift import CoreData class MockManagedObjectContext: NSManagedObjectContext { var saveCount: Int = 0 init(concurrencyType: NSManagedObjectContextConcurrencyType) { super.init(concurrencyType: concurrencyType) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been...
magicoder
swift
You are tasked with implementing a basic LZW (Lempel-Ziv-Welch) compression algorithm in Rust. LZW is a lossless data compression algorithm that works by replacing repeated occurrences of substrings with a single code. The algorithm maintains a dictionary of substrings encountered in the input data and assigns a unique...
```rust // lzw.rs use crate::decoder; pub fn compress(input: &str) -> Vec<u16> { let mut dictionary = decoder::create_dictionary(); let mut result = Vec::new(); let mut w = String::new(); for c in input.chars() { let wc = format!("{}{}", w, c); if dictionary.contains(&wc) { ...
magicoder
rust
You are tasked with creating a Python function that processes a Django migration file and extracts information about the migration operations. The migration file is represented as a string, and it contains a series of migration operations that need to be parsed and analyzed. Your task is to implement the function `par...
```python from typing import List import re def parse_migration_operations(migration_file: str) -> List[str]: # Regular expression pattern to match migration operations operation_pattern = r'migrations\.(?:\w+)' # Find all matches of the operation pattern in the migration file operations = re.findall(...
magicoder
python
You are tasked with implementing a method to post messages to a Facebook page using the Facebook Graph API. The provided code snippet is a part of an Android application that aims to facilitate posting messages to a specific Facebook page. The `PostMessages` class extends `AppCompatActivity` and implements the `View.On...
```java import android.os.Bundle; import android.util.Log; import androidx.appcompat.app.AppCompatActivity; import com.facebook.AccessToken; import com.facebook.GraphRequest; import com.facebook.GraphResponse; import org.json.JSONException; import org.json.JSONObject; public class PostMessages extends AppCompatActivit...
magicoder
java
You are tasked with creating a command-line utility for managing a simple file system. The utility should support basic file system operations such as creating, reading, updating, and deleting files. The utility will be invoked using the following command-line syntax: ``` ./sfs -f <file_system_name> <operation> [opera...
```python import sys import os def create_file(file_system_name, file_name): file_path = f"{file_system_name}/{file_name}" if not os.path.exists(file_system_name): os.makedirs(file_system_name) with open(file_path, 'w'): pass def read_file(file_system_name, file_name): file_path = f"{f...
magicoder
python
You are tasked with creating a Python function that simulates a simplified version of a database migration tool similar to Alembic. Your function will receive a list of database migration commands and should process them in the correct order. Each command can be one of the following types: - `op.drop_index(index_name, ...
```python from typing import List, Tuple def process_migration_commands(commands: List[str]) -> List[Tuple[str, str, str]]: processed_commands = [] for command in commands: if "op.drop_index" in command: index_name = command.split("op.f('")[1].split("')")[0] table_name = command...
magicoder
python
You are tasked with implementing a simple alert system for a monitoring application. The system should be able to handle different types of alerts and notify the appropriate recipients based on the severity of the alert. You are given a Python class `AlertSystem` with the following methods: - `add_recipient(recipient...
```python class AlertSystem: def __init__(self): self.recipients = {} def add_recipient(self, recipient_id, email): self.recipients[recipient_id] = email def raise_alert(self, alert_type, severity, message): for recipient_id, recipient_email in self.recipients.items(): ...
magicoder
python
You are tasked with implementing a command-line interface for a teleportation system in a virtual world. The system supports various commands for managing teleporters and player teleportation. Each command is in the format: `tport <teleporter> <action> [parameters]`. The available commands are as follows: - `tport edi...
```python class TeleporterSystem: def __init__(self): self.teleporters = {} # Dictionary to store teleporter data def execute_command(self, command): parts = command.split() if len(parts) < 2: return "Invalid command format" action = parts[1] if action == "...
magicoder
python
You are tasked with creating a custom formatter for a web application using Yii framework. The formatter should be able to convert a given string into a specific format based on certain rules. The rules are as follows: 1. If the input string contains only lowercase letters, it should be converted to uppercase. 2. If th...
```php namespace app\controllers; use Yii; use yii\web\Controller; class FormatterController extends Controller { public function formatString($input) { // Check if the input contains only lowercase letters if (ctype_lower($input)) { return strtoupper($input); // Convert to upperca...
magicoder
php
You are tasked with implementing a memory allocation and management system. The system should support the allocation and deallocation of memory blocks, and it should handle errors such as attempting to allocate memory that has already been allocated. You are given a series of commands in the form of strings, each repr...
To solve this problem, we can use a data structure to keep track of the allocated memory blocks and their states (committed or decommitted). We can use a hash map to store the memory blocks, where the key is the block name and the value is a tuple containing the block size and its state (committed or decommitted). Her...
magicoder
python
You are tasked with implementing a Python class that simulates a simple version of a 64-bit set, called `SimpleSet64`. The set will be based on a seed value and will support basic set operations. Your task is to complete the implementation of the `SimpleSet64` class by adding the necessary methods to support the specif...
```python class SimpleSet64: def __init__(self, seed: int): self.seed = seed self.elements = set() def add(self, value: int) -> None: self.elements.add(value ^ self.seed) def remove(self, value: int) -> None: self.elements.discard(value ^ self.seed) def contains(self, ...
magicoder
python
You are tasked with creating a Python class to manage the operations of various types of vehicles used in a space exploration program. The class should be able to handle rover vehicles and their specific functionalities. Your task is to implement the methods for controlling the rover's movements and actions. You are p...
```python class RoverController: def __init__(self, vehicle_id): self.vehicle_type = 'rover' self.vehicle_id = vehicle_id self.local_pose = None self.target_motion = PositionTarget() self.arm_state = False self.motion_type = 0 self.flight_mode = None s...
magicoder
python
You are working on a network automation project and need to implement a configuration mode for F5 devices. The F5 device has a method `config_mode` which takes a `config_command` as an argument and returns a string. However, the current implementation of `config_mode` simply returns an empty string and does not handle ...
```python class F5Device: def __init__(self): self.config_items = [] def config_mode(self, config_command=""): command_parts = config_command.split() if command_parts[0] == "add": config_item = " ".join(command_parts[1:]) self.config_items.append(config_item) ...
magicoder
python
You are tasked with implementing a cache simulator in Rust. The cache simulator will have a method `misses` that calculates the number of cache misses based on a given memory access pattern. The cache is direct-mapped and uses a simple least recently used (LRU) replacement policy. You are provided with the following c...
```rust pub struct Cache { bits: u64, cache_lines: [Option<u32>; 8], lru_counter: u32, } impl Cache { pub fn new() -> Cache { Cache { bits: 0, cache_lines: [None; 8], lru_counter: 0, } } pub fn access(&mut self, address: u64) { let bl...
magicoder
rust
You are working on a project to develop a neural network library in Python. As part of this project, you are tasked with implementing a function that sets the choice of layers for the neural network. The function takes in the layer number and a list of operations to be performed at each layer. Your task is to implement...
```python def setLayerChoice(layer, operations): # Assuming self.input_dim, self.hidden_dim, and self.output_dim are predefined dimensions updated_choice = [] for op in operations: if isinstance(op, type): # Create an instance of the operation with appropriate input and output dimensions...
magicoder
python
You are tasked with creating a URL routing system for a web application using Django. The given code snippet is a part of the URL configuration for a Django project. The `urlpatterns` list contains several URL patterns, each associated with a specific view function. The `url` function is used to map a URL pattern to a ...
```python def get_view_function(url_pattern: str) -> str: urlpatterns = [ ('auth/$', 'gchatautorespond.apps.autorespond.views.auth_view'), ('oauth2callback/$', 'gchatautorespond.apps.autorespond.views.auth_return_view'), ('worker_status/$', 'gchatautorespond.apps.autorespond.views.worker_sta...
magicoder
python
You are tasked with implementing a simple garbage collection mechanism for a custom programming language. The provided code snippet is a part of a class definition for managing resources and garbage collection. The `_DoKids` function is responsible for invoking a given function on the internal objects `_bvr`, `_notifie...
```cpp #include <iostream> // Define the GCFuncObj interface class GCFuncObj { public: virtual void operator()(Object& obj) = 0; }; // Define the Object class class Object { // Define the members _bvr, _notifier, and _type public: // Implement the _DoKids function void _DoKids(GCFuncObj& proc) { ...
magicoder
cpp
You are tasked with creating a Python package that automates the process of querying the Astrophysics Data System (ADS) and InSPIRE databases to fill a LATEX bibliography. Your package should be able to retrieve relevant bibliographic information and format it in LATEX style for easy inclusion in academic papers. Your...
```python # Import necessary modules from distutils.core import setup # Define the setup parameters for the package setup( name='filltex', version='1.3.1', description='Automatic queries to ADS and InSPIRE databases to fill LATEX bibliography', long_description="See: `github.com/dgerosa/filltex <https:...
magicoder
python
You are tasked with creating a Python function that searches for files with a specific extension within a given directory and its subdirectories. The function should exclude certain files from the search based on a predefined list. Your task is to complete the implementation of the `find_puml` function, which takes a `...
```python import os IGNORE_FILES = ['all.puml', 'all_LARGE.puml', 'test.puml', 'common.puml'] def find_puml(path, ext='.puml'): path = os.path.abspath(path) lpath = len(path) + 1 spriteExt = '-sprite' + ext result = [] for root, dirs, files in os.walk(path): for fname in files: ...
magicoder
python
You are tasked with implementing a simple string class in C++. The class should have the following functionalities: 1. A constructor that takes a C-style string (const char*) as an argument and initializes the internal pointer to point to the same string. 2. A method to return the length of the string. 3. A method to r...
```cpp #include <cstring> class SimpleString { private: const char* p_; public: // Constructor SimpleString(const char* str) : p_(str) {} // Method to return the length of the string size_t length() const { return strlen(p_); } // Method to return the character at a specified...
magicoder
cpp
You are tasked with implementing a custom validation framework in Swift. The `Validation` struct has been provided as a starting point, and you need to extend it with various validation functions. Each validation function should take a value of a specific type and return a boolean indicating whether the value passes th...
```swift public extension Validation { static func isEven(_ value: Int) -> Bool { return value % 2 == 0 } static func isOdd(_ value: Int) -> Bool { return value % 2 != 0 } static func isPrime(_ value: Int) -> Bool { guard value > 1 else { return false } for ...
magicoder
swift
You are given a list of non-negative integers. Your task is to arrange these numbers in such a manner that they form the largest number possible. The result may be very large, so you should return the result in the form of a string. For example, given the numbers [64, 646, 648, 70], you need to arrange them to form th...
```swift func largestNumber(_ nums: [Int]) -> String { let sortedNums = nums.map { String($0) }.sorted { $0 + $1 > $1 + $0 } if sortedNums.first == "0" { return "0" } return sortedNums.joined() } ``` The `largestNumber` function first converts each integer in the input array to a string and the...
magicoder
swift