query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with creating a custom validation constraint in a Symfony application. The goal is to implement a custom constraint that ensures a given property is a prime number. You need to define the custom constraint class, implement the validation logic, and apply the constraint to a sample entity class. Your cus...
```php // PrimeNumber.php use Symfony\Component\Validator\Constraint; /** * @Annotation */ class PrimeNumber extends Constraint { public $message = 'The number {{ value }} is not a prime number.'; public function validatedBy() { return PrimeNumberValidator::class; } } // PrimeNumberVali...
magicoder
php
You are tasked with creating a Swift program that generates a random password based on certain criteria. The password should be a combination of uppercase letters, lowercase letters, numbers, and special characters. The program should allow the user to specify the length of the password and whether to include each of t...
```swift import Foundation func generatePassword(length: Int, includeUppercase: Bool, includeLowercase: Bool, includeNumbers: Bool, includeSpecialChars: Bool) -> String { var passwordCharacters = "" if includeUppercase { passwordCharacters += "ABCDEFGHIJKLMNOPQRSTUVWXYZ" } if includeLowerc...
magicoder
swift
You are tasked with implementing a Python class method that constructs an object from a message (msg) containing specific data. The class, named `SomeClass`, has a method `from_msg` that takes in a dictionary `msg` as input and constructs an instance of `SomeClass` using the data from the dictionary. The dictionary `ms...
```python class PoseStamped: @classmethod def from_msg(cls, msg): return cls(msg['x'], msg['y'], msg['z']) class MoveItErrorCodes: @classmethod def from_msg(cls, msg): return cls(msg['code'], msg['value']) class SomeClass: def __init__(self, pose_stamped, fk_link_names, error_code)...
magicoder
python
You are tasked with implementing a time management system for a microcontroller. The system should handle alarms, timers, and special modes such as power-on-reset override and external clock. Additionally, the system should be able to set the timer to the lowest possible frequency (1/60 Hz) for power saving. Your task ...
```c #include <stdbool.h> bool isLeapYear(int year) { if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) { return true; } return false; } int daysInMonth(int year, int month) { int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; if (month == 2 && isLeapYear(year)) { ...
magicoder
c
You are working on a project to develop a lane detection system for autonomous vehicles. The code snippet provided is a part of the lane detection algorithm. The algorithm processes an image of a road and identifies the left and right lane lines. It then colors the pixels corresponding to the left lane in red and the p...
```python import numpy as np def calculate_search_window_area(out_img, left_line_pts, right_line_pts) -> float: # Calculate the area covered by the left lane search window left_mask = np.zeros_like(out_img[:,:,0]) cv2.fillPoly(left_mask, np.int_([left_line_pts]), 1) left_area = np.sum(left_mask) #...
magicoder
python
You are tasked with implementing a nearest neighbor data retrieval system for a low-resolution to high-resolution dataset. The system should be able to efficiently retrieve the k-nearest high-resolution data points for a given low-resolution data point. You are provided with a Python class `NearestNeighborData` that i...
```python import numpy as np from scipy.spatial import cKDTree class NearestNeighborData(LowResHighResDataset): def __init__(self, dataset: LowResHighResDataset, num_models=None, model_index=None, k=16): super().__init__(dataset.low_res_data, dataset.high_res_data, dataset.region_geometries) self.n...
magicoder
python
You are tasked with creating a Django migration for a user model. The model has a field for the username and another field for the user's avatar. The username field is a CharField with a maximum length of 30 characters, and it is set to be unique. The avatar field is an ImageField that allows for blank and null values,...
```python from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('yourappname', 'previous_migration_number'), # Replace 'yourappname' and 'previous_migration_number' with actual values ] operations = [ migrations.AlterField( model_na...
magicoder
python
You are tasked with creating a validation class for a user registration form in a PHP application. The class should implement validation rules for the following fields: names, lastnames, dni (national identification number), and phone number. The validation rules are as follows: - 'names' and 'lastnames' are required f...
```php class UserValidation { protected $data; public function __construct($data) { $this->data = $data; } public function validate() { $errors = []; if (empty($this->data['names'])) { $errors['names'] = 'Names are required'; } if (empty($t...
magicoder
php
You are tasked with implementing a custom operator in Swift for creating a `Having` clause in a SQL query builder library. The `Having` clause is used to filter the results of an aggregate query based on specified conditions. The custom operator `>=` is to be used to compare a column expression with a predicate. Your ...
```swift /// :nodoc: public func >=(lhs: AggregateColumnExpression, rhs: Predicate<Having,AggregateColumnExpression>) -> Having { return Having(lhs: .columnExpression(lhs), rhs: rhs, condition: .greaterThanOrEqual) } ``` The solution provides the implementation of the custom operator `>=` for creating a `Having` c...
magicoder
swift
You are tasked with implementing a command-line interface for managing contract permissions and status. The provided code snippet contains a list of available commands along with their descriptions. Your goal is to design a program that processes user input to execute the corresponding commands. You need to implement ...
```java import java.util.HashMap; import java.util.Map; public class ContractManager { private Map<String, Boolean> contractWritePermissions = new HashMap<>(); private Map<String, Boolean> contractStatusManagers = new HashMap<>(); private Map<String, Boolean> committeeMembers = new HashMap<>(); private...
magicoder
java
You are tasked with implementing a simplified file system in Rust. The file system consists of directories and files. Each directory can contain multiple files and subdirectories. The provided code snippet is a part of the implementation of the SimpleFileSystem in Rust. Your task is to complete the implementation of t...
```rust use std::ptr; use std::ffi::CStr; use std::ffi::CString; struct FileProtocol { // Implementation details of file protocol } enum Status { Success, // Other possible status codes } struct SimpleFileSystem { // Implementation details of simple file system } impl SimpleFileSystem { pub fn o...
magicoder
rust
You are tasked with creating a custom error type in Rust for a stackable_spark_crd library. The library is used for managing custom resources in a Kubernetes cluster. The provided code snippet shows a custom error type called `InvalidNodeType`, which is used to represent an error when a pod contains an invalid node typ...
```rust use thiserror::Error; #[derive(Error, Debug)] pub enum InvalidNodeType { #[error("Pod contains invalid node type: {source}")] InvalidNodeType { #[from] source: stackable_spark_crd::CrdError, }, } #[derive(Error, Debug)] pub struct InvalidPodError { message: String, } impl Inva...
magicoder
rust
You are working for a data management company that needs to organize and manage various files and directories for different organizations and collections. The company has a specific directory structure for storing shared files and temporary working files, as well as a separate structure for sharing action outputs with ...
```python import os class FileManager: def create_organization(self, organization_id): os.makedirs(f'config.SHARED_FILE_SYSTEM/{organization_id}') def create_collection(self, organization_id, collection_id): os.makedirs(f'config.SHARED_FILE_SYSTEM/{organization_id}/{collection_id}') def c...
magicoder
python
You are tasked with creating a view loader class that loads and renders views for a web application. The view loader accepts a parent view and an array of child view names to be included within the parent view. The child view names are passed as key-value pairs in the array, where the key represents the placeholder in ...
```php class ViewLoader { private $debug; public function __construct($debug) { $this->debug = $debug; } public function load($parentView, $childViews) { $viewContent = $this->loadViewContent($parentView); foreach ($childViews as $placeholder => $childViewName) { $...
magicoder
php
You are given a graph represented as an adjacency list and a start node. Your task is to implement a breadth-first search (BFS) algorithm to find the shortest path from the start node to a target node. Write a function `shortest_path(graph, start, target)` that takes in the following parameters: - `graph`: A dictionar...
```python from collections import deque def shortest_path(graph, start, target): if start not in graph or target not in graph: return [] queue = deque([[start]]) explored = set() while queue: path = queue.popleft() node = path[-1] if node not in explored: ...
magicoder
python
You are tasked with creating a Python decorator that measures the execution time of a function and logs the result. Your decorator should be able to handle both synchronous and asynchronous functions. You should also ensure that the decorator works correctly with functions that return values and functions that raise ex...
```python import time import asyncio def measure_execution_time(func): async def async_wrapper(*args, **kwargs): start_time = time.time() try: result = await func(*args, **kwargs) end_time = time.time() execution_time = (end_time - start_time) * 1000 ...
magicoder
python
You are tasked with creating a simple web server using Python. Your web server should serve a single HTML page with the content "Hello, World!" when accessed through a web browser. Additionally, the server should be able to handle concurrent requests and gracefully shut down when a specific signal is received. Your ta...
```python import http.server import socketserver import threading import signal import sys # Create a simple HTML page with the content "Hello, World!" html_content = """ <!DOCTYPE html> <html> <head> <title>Hello, World!</title> </head> <body> <h1>Hello, World!</h1> </body> </html> """ with open('index.html'...
magicoder
python
You are tasked with implementing a method to load a license key from a given string representation. The method should take a public RSA key and a license string as input and return a LicenseKey object. Additionally, an overloaded version of the method should allow for an expiration timestamp to be specified. You are p...
```java import java.security.KeyFactory; import java.security.PublicKey; import java.security.spec.X509EncodedKeySpec; import java.util.Base64; import java.time.Instant; public class LicenseKey { private String keyData; private boolean isExpired; public LicenseKey(String keyData, boolean isExpired) { ...
magicoder
java
You are tasked with creating a Python script that securely sends an email using the Gmail SMTP server. To achieve this, you need to implement a function that takes in the sender's email address, the recipient's email address, the subject of the email, and the body of the email as input parameters. The function should t...
```python import smtplib from email.message import EmailMessage import os def send_email(sender_email, recipient_email, subject, body): try: # Create a secure connection to the Gmail SMTP server with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: # Login to the Gmail SMTP server using...
magicoder
python
You are working on an image processing application and need to implement a function that can combine a set of grayscale or color images into a single composite image. The function should take a list of images and arrange them in a grid pattern, with the option to specify the number of rows and columns in the grid. If t...
```python import numpy as np def combine_images(images, size): h, w, c = images[0].shape if c == 1: # Grayscale images img = np.zeros((h * size[0], w * size[1])) for idx, image in enumerate(images): i = idx % size[1] j = idx // size[1] img[j * h:j * h + h, i...
magicoder
python
You are tasked with implementing a binary search tree (BST) in Java. A binary search tree is a data structure that allows for efficient searching, insertion, and deletion of elements. Each node in the tree has a value, a left child, and a right child. The left child's value is less than the parent's value, and the righ...
```java public void insert(T value) { root = insertRecursive(root, value); } private Node insertRecursive(Node current, T value) { if (current == null) { return new Node(value); } if (value.compareTo(current.value) < 0) { current.left = insertRecursive(current.left, value); } else ...
magicoder
java
You are tasked with implementing a class to manage a bus route. The route consists of several stops, each identified by a fraction and a string representing the stop name. The fraction represents the distance of the stop from the starting point of the route. Your task is to create a class `BusRoute` with the following ...
```javascript class BusRoute { stops: [number, string][] = []; addStop(fraction: number, stopName: string): void { this.stops.push([fraction, stopName]); this.stops.sort((a, b) => a[0] - b[0]); } removeStop(stopName: string): void { this.stops = this.stops.filter(([_, name]) => name !== stopName);...
magicoder
javascript
You are working on a Python application that interacts with a database using SQLAlchemy. Your task is to create a function that retrieves metadata information and performs operations on a dataset association table. The code snippet provided gives a glimpse of the existing codebase, where the `metadata` object is used t...
```python from sqlalchemy import Table def retrieve_and_operate_on_table(metadata): try: # Step 1: Reflect the database schema using the metadata object metadata.reflect() # Step 2: Attempt to load the table "implicitly_converted_dataset_association" with autoload=True implicitly_c...
magicoder
python
You are tasked with creating a class to represent a student and implementing a method to create a new student instance with default values. Create a class `Student` with the following properties: - `Name` of type `FullName` (a class with `FirstName` and `LastName` properties) - `Type` of type `StudentType` (an enum wi...
```csharp // Define the FullName class public class FullName { public string FirstName { get; set; } public string LastName { get; set; } } // Define the StudentType enum public enum StudentType { Real, Fake } // Define the Student class public class Student { public FullName Name { get; set; } ...
magicoder
csharp
You are tasked with creating a Python script to process image and annotation data for a computer vision project. The script should handle the conversion of human segmentation annotations from a custom format to the COCO dataset format. The input directories for training and validation images and annotations are provide...
```python import os import json def convert_to_coco_format(train_img_dir, train_anno_dir, val_img_dir, val_anno_dir, dataset, json_save_dir, test_img_dir): # Process training, validation, and testing data to generate COCO-style annotations # Your implementation here # Example implementation (replace with ...
magicoder
python
You are tasked with designing a testbench for a video display model that checks the timing of a video display interface. The testbench is written in Python using the `pytest` framework and the `myhdl` library for hardware description and verification. The video display interface is based on the LT24 LCD display and is ...
```python # Import necessary libraries and modules import pytest from myhdl import Signal, intbv, instance, delay, StopSimulation, now from rhea.system import Clock, Reset, Global from rhea.cores.video.lcd import LT24Interface from rhea.models.video import LT24LCDDisplay from rhea.utils.test import run_testbench, tb_ar...
magicoder
python
You are tasked with creating a Python class that simulates a deck of playing cards and provides methods for shuffling and dealing cards. The class should be able to represent a standard 52-card deck and handle the process of shuffling the deck and dealing a specified number of cards to players. Create a class `Deck` w...
```python import random class Deck: def __init__(self): suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades'] ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] self.cards = [{'suit': suit, 'rank': rank} for suit in suits for rank in ranks] def shuffle(self): ...
magicoder
python
You are tasked with implementing a simplified version of a message handling system using C++. The system involves a client-server architecture, where the client sends messages to the server for processing. Your task is to implement a function `handle_output` within the `Client` class that handles sending messages to t...
```cpp int Client::handle_output(ACE_HANDLE) { ACE_Message_Block *mb; ACE_Time_Value nowait(ACE_OS::gettimeofday()); while (-1 != this->getq(mb, &nowait)) { ssize_t send_cnt = this->peer().send(mb->rd_ptr(), mb->length()); if (send_cnt == -1) { ACE_ERROR((LM_ERROR, ACE_TEXT("(%P|%t) %p\n"), ...
magicoder
cpp
You are tasked with creating a Python script to automate the process of killing a specific process by its name. Your script should take the process name as input and terminate all instances of that process running on the system. Write a Python function `kill_process_by_name(process_name)` that takes a string `process_...
```python import subprocess def kill_process_by_name(process_name): try: # Use the ps command to list all processes and filter by the given process name ps_output = subprocess.check_output(['ps', '-ef']).decode('utf-8') processes = [line.split()[1] for line in ps_output.splitlines() if proc...
magicoder
python
You are tasked with implementing a Python class that represents a hierarchical structure. The class should have a method to set the hierarchy level and another method to get the hierarchy level as a string. Implement the class `Hierarchy` with the following specifications: - The class should have a private attribute `...
```python class Hierarchy: def __init__(self): self._hierarchy = "" def set_hierarchy(self, level): self._hierarchy = level def get_hierarchy(self): return self._hierarchy ```
magicoder
python
You are tasked with creating a Python program that uses the OpenCV library to detect objects in an image and identify the number of occurrences of a specific target object. The program should take an input image and a target object name as input and output the count of occurrences of the target object in the image. Yo...
```python def count_target_objects(input_image, target_name): net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg") # Load YOLO model weights and configuration layer_names = net.getLayerNames() output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()] image = cv2.imread(input_imag...
magicoder
python
You are tasked with implementing a module resolution algorithm for a JavaScript module system. The system uses the `export * from "module"` syntax to re-export all named exports from another module. Your goal is to write a function that resolves the exports of a given module, taking into account the `export * from "mod...
```javascript function resolveModuleImports(moduleImports, allExports) { const resolvedImports = []; for (const importStatement of moduleImports) { if (importStatement.startsWith('export * from')) { const modulePath = importStatement.match(/"([^"]+)"/)[1]; const namedExports = allExports[modulePath...
magicoder
javascript
You are tasked with creating a script to automate the versioning of a software project. The script should retrieve the latest commit hash from the Git repository and use it to generate a version string. The version string should follow the format "vX.Y.Z", where X is the major version, Y is the minor version, and Z is ...
```bash #!/bin/bash GYM_HOME=/home/wil/workspace/buflightdev/projects/gymfc cd $GYM_HOME # Retrieve the latest commit hash from the Git repository COMMIT=$(git describe --always) # Retrieve the latest tag from the Git repository LATEST_TAG=$(git describe --tags --abbrev=0) # If there are no tags in the repository, ...
magicoder
shell
You are tasked with creating a Python function that interacts with the LINE Messaging API to check if a specific rich menu is assigned to a user. The function should take a user ID as input and make a GET request to the LINE API to retrieve information about the rich menu assigned to the user. The function should then ...
```python import requests def Check_rich_menu_to_user(userId): Main_rich_menu_id = 'your_rich_menu_id' # Replace with the actual rich menu ID Channel_access_token = 'your_channel_access_token' # Replace with the actual channel access token LINE_API = 'https://api.line.me/v2/bot/user/' + Main_rich_menu_i...
magicoder
python
You are tasked with creating a custom deserialization function for a Rust crate that handles JSON deserialization for a specific error type. The given code snippet is a part of a Rust module that defines a deserialization function for a custom error type called `global_table_not_found_exception`. The function `deser_st...
```rust fn deserialize_global_table_not_found_exception( value: &[u8], mut builder: crate::error::global_table_not_found_exception::Builder, ) -> Result<crate::error::global_table_not_found_exception::Builder, aws_smithy_json::deserialize::Error> { match aws_smithy_json::from_slice(value) { Ok(json_...
magicoder
rust
You are tasked with implementing a Rust function that encodes a given list of assets into the RLP (Recursive Length Prefix) encoding format. RLP is a method of encoding arbitrary nested arrays of binary data, and it is commonly used in Ethereum for serializing data. You are provided with a Rust struct `Asset` and its ...
```rust fn encode_assets(assets: &[Asset]) -> Vec<u8> { let mut stream = RlpStream::new_list(assets.len()); for asset in assets { stream.append(&asset); } stream.out() } ``` In the solution, the `encode_assets` function initializes a new RLP stream with a list of the given assets' length. It th...
magicoder
rust
You are tasked with implementing a function to create temporary schema tables for a database. The function should take the number of temporary tables as input and generate SQL scripts to create these tables. You are given a code snippet that partially implements the function. The snippet defines a shell function `crea...
```bash create_temp_schema() { BASEDIR="/path/to/base/directory" CREATE_SCHEMA_TEMP_SQL="$BASEDIR/create-temp-schema.sql" TEMP__CREATE_TEMP_SCHEMA_SQL="$BASEDIR/_create-temp-schema.sql" NUM_OF_TEMP_TABLES=$1 for i in $(seq 1 $NUM_OF_TEMP_TABLES) do cp $CREATE_SCHEMA_TEMP_SQL "$TEMP__CR...
magicoder
shell
You are tasked with implementing a file generation system for a protocol definition. The system should take an `Endpoint` object as input and generate specific files based on the protocol and role information. The files to be generated are `{protocol}/EFSM.ts` and `{protocol}/{role}.ts`. Your task is to create a Python...
```python from typing import Generator, Tuple from endpoint import Endpoint # Assuming the definition of the Endpoint class is in a separate module def generate(endpoint: Endpoint) -> Generator[Tuple[str, str], None, None]: protocol = endpoint.protocol role = endpoint.role efsm_content = "// Placeholder ...
magicoder
python
You are tasked with implementing a reinforcement learning algorithm for an agent navigating a grid-based environment. The environment consists of cells, and the agent's goal is to reach a specific cell. The agent's state is represented by the current cell it occupies, and it can take actions to move to adjacent cells. ...
```python import random class Agent: def __init__(self, environment): self.environment = environment def select_action(self, state, epsilon=0.1): if random.random() < epsilon: # Random action for exploration return random.choice(['up', 'down', 'left', 'right']) ...
magicoder
python
You are tasked with implementing a function that calculates the duration of an audio file based on the given audio format parameters. The audio format is represented by a structure `WAVEFORMATEX` with the following fields: - `nSamplesPerSec`: The sample rate in samples per second. - `nAvgBytesPerSec`: Average bytes per...
```c #include <stdio.h> typedef struct { unsigned long nSamplesPerSec; unsigned long nAvgBytesPerSec; unsigned short nBlockAlign; unsigned short wBitsPerSample; } WAVEFORMATEX; double calculateAudioDuration(const WAVEFORMATEX* wfx, size_t dataSize) { double duration = (double)dataSize / (wfx->nA...
magicoder
c
You are given a list of names representing attendees at a conference. The list may contain duplicate names. Your task is to write a function that removes all occurrences of a specific name from the list, except for the first occurrence. The function should take the list of names and the name to be removed as input and ...
```python from typing import List def remove_duplicates(names: List[str], name_to_remove: str) -> List[str]: seen = set() result = [] for name in names: if name == name_to_remove and name_to_remove not in seen: seen.add(name_to_remove) result.append(name) elif name !...
magicoder
python
You are tasked with implementing a name validation function in a software system. The function should ensure that the length of the provided name does not exceed a predefined maximum length and throw an exception with a custom message if the validation fails. Write a function `ValidateName` that takes two parameters: ...
```csharp using System; public static class Constants { public const int MaxNameLength = 50; } public static class NameValidator { public static void ValidateName(string name, string message) { if (name.Length > Constants.MaxNameLength) { throw new ArgumentException(message); ...
magicoder
csharp
You are tasked with implementing a TypeScript function that fetches Ethereum events using the `web3-eth-contract` library. The function should take in an Ethereum contract, event name, and event filter, and return a promise that resolves to an array of `EventData` objects. You are provided with the following TypeScrip...
```typescript import { EventData } from 'web3-eth-contract'; import { EventName, EventFilter } from './types'; import { EthereumAdapter } from './ethereum-adapter'; import { Contract } from 'web3-eth-contract'; async function fetchEthereumEvents( contract: Contract, eventName: EventName, eventFilter: EventFilter...
magicoder
typescript
You are tasked with implementing a function that processes a given CSS stylesheet and returns a list of all the selectors and their corresponding properties. Each selector should be paired with a dictionary of its properties and values. You are given a code snippet representing a portion of a CSS stylesheet. The snipp...
```python import re def parse_css(css_snippet): selectors = re.findall(r'([a-zA-Z0-9\s.#]+)\s*{([^}]*)}', css_snippet) result = [] for selector, properties in selectors: properties_dict = {} properties_list = properties.split(';') for prop in properties_list: prop = prop...
magicoder
python
You are tasked with implementing a custom UITableViewCell subclass to display information about campus groups in a university app. The provided code snippet shows the beginning of the `MyGroupsGroupTableCell` class, which is intended to represent a table view cell for displaying information about campus groups. Your t...
```swift class MyGroupsGroupTableCell: UITableViewCell { static let reuseId = "myGroupsCell" var group: CampusGroup! // Assuming CampusGroup is a custom class representing a campus group // Method to configure the cell with the group's data func configure(with group: CampusGroup) { sel...
magicoder
swift
You are tasked with implementing a custom lock mechanism in Rust to manage concurrent access to a shared resource. The lock should support both exclusive and shared access, and it should handle potential errors that may arise from concurrent access. Your task is to implement a custom lock structure `CustomLock` and it...
```rust use std::sync::{Arc, Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard}; use std::sync::atomic::{AtomicUsize, Ordering}; #[derive(Debug)] pub struct CustomLock { mutex: Mutex<()>, rw_lock: RwLock<()>, exclusive_count: AtomicUsize, } impl CustomLock { pub fn new() -> Self { C...
magicoder
rust
You are given a list of neural responses from a set of filters and positions. Each response is represented as a matrix, and the goal is to identify the sparse weight matrix that best represents the neural responses. The weight matrix should capture only a few different filters and positions, ignoring the noise present ...
```python import numpy as np from scipy.optimize import minimize def find_sparse_weight_matrix(responses): num_filters = len(responses) response_size = responses[0].shape[0] def objective_function(weights): weight_matrix = np.reshape(weights, (num_filters, response_size, response_size)) re...
magicoder
python
You are tasked with implementing a Lua binding for a C++ library using the Sol library. The provided code snippet is a part of a C++ namespace `tnt::lua` and declares two functions `loadVector` and `loadRect`. Your task is to complete the implementation of these functions to bind C++ vector and rectangle classes to Lua...
```cpp #include <sol/sol.hpp> #include <vector> namespace tnt::lua { // Bind std::vector to Lua void loadVector(sol::state_view lua_) { lua_.new_usertype<std::vector<int>>("vector", sol::constructors<std::vector<int>(), std::vector<int>(size_t)>(), "size", &std::vector<int>:...
magicoder
cpp
You are tasked with creating a custom React hook to manage the state of a user's staked balance in a decentralized finance (DeFi) application. The hook should interact with the Basis Cash protocol, which is a decentralized stablecoin project. The provided code snippet is a starting point for creating this custom hook. ...
```javascript import { useState, useEffect } from 'react'; import useBasisCash from '../../../hooks/useBasisCash'; import useBoardroomVersion from '../../../hooks/useBoardroomVersion'; import useTokenBalance from '../../../hooks/useTokenBalance'; import useStakedBalanceOnBoardroom from '../../../hooks/useStakedBalanceO...
magicoder
javascript
You are tasked with implementing a simple asynchronous event handling system in Rust. The system should allow registering event handlers and triggering events, and it should support awaiting the completion of an event handler. You are provided with a partial implementation of the event handling system using the `tokio...
```rust use std::sync::Arc; use tokio::sync::oneshot; struct EventHandler { exit_sender: Option<oneshot::Sender<i32>>, } impl EventHandler { async fn on_closed(&mut self) -> Result<(), String> { if let Some(sender) = self.exit_sender.take() { sender.send(0).map_err(|e| format!("failed to s...
magicoder
rust
You are tasked with creating a Python class that dynamically generates methods based on an API specification file. The class should read the API specification from a JSON file, and for each API object in the specification, it should create a method that corresponds to the API endpoint. Additionally, the method should b...
```python import json class APIClient: API_SPEC_PATH = "/path/to/api/specs" def __init__(self, version): self.version = version self.services = {} def _method_factory(self, func_name, uri, http_method): def method_impl(): # Implementation of the method can be added her...
magicoder
python
You are tasked with creating a program that simulates keyboard input based on a given input string. The input string may contain special tokens that represent keyboard keys or actions. Your task is to parse the input string and simulate the corresponding keyboard input. The special tokens are as follows: - `{TAB}`: Re...
```rust use std::time::Duration; use winput::{send, Vk}; static TAB_REGEX: &str = r"\{TAB\}"; static ENTER_REGEX: &str = r"\{ENTER\}"; static SLEEP_REGEX: &str = r"\{SLEEP=(\d+)\}"; static DEFAULT_SLEEP_MILLIS: u64 = 20; fn simulate_keyboard_input(input: &str) { let tokens: Vec<&str> = input.split(|c| c == '{' ||...
magicoder
rust
You are tasked with implementing a doubly linked list in Python. A doubly linked list is a data structure that consists of a sequence of elements, where each element has a reference to the next and previous elements in the sequence. Your task is to create a Python class for a doubly linked list node, along with methods...
```python class DoublyLinkedListNode: def __init__(self, initData, initNext=None, initPrevious=None): self.__data = initData self.__next = initNext self.__previous = initPrevious class DoublyLinkedList: def __init__(self): self.__head = None def insert(self, data): ...
magicoder
python
You are tasked with implementing a function that processes a given CSS style object and returns a new object with specific transformations applied. The input object represents a CSS style with properties and values, and the output object should contain modified properties based on the given rules. You need to implemen...
```javascript function applyTransformations(cssStyleObject, transformations) { const transformedStyle = { ...cssStyleObject }; for (const transformation of transformations) { if (transformation.property in transformedStyle) { if (transformation.transformation === 'invert()') { transformedStyle[tr...
magicoder
javascript
You are tasked with implementing a custom ExcelResult class in C# for an ASP.NET MVC application. The ExcelResult class should inherit from FileResult and also implement the IHttpActionResult interface. Your task is to complete the implementation of the MyExcelResult class by adding the necessary properties and methods...
```csharp using System.Net; using System.Net.Http; using System.Web; using System.Web.Http; using System.Web.Mvc; namespace Never.Web.Mvc.Results { /// <summary> /// ExcelResult /// </summary> public class MyExcelResult : FileResult, IHttpActionResult { #region property /// <summar...
magicoder
csharp
You are tasked with implementing a Python class for a machine learning algorithm. The class, named `FalkonAlgorithm`, inherits from a base class and has several attributes and parameters. Your goal is to complete the implementation of the `FalkonAlgorithm` class by adding a method that performs a specific computation. ...
```python class FalkonAlgorithm(BaseClass): def __init__(self, kernel, M, center_selection, seed, error_fn, penalty, maxiter, use_cuda_=False, error_every: Optional[int] = 1, options=FalkonOptions(), ): super().__init__(kernel, M, center_selection, seed, er...
magicoder
python
You are tasked with creating a Java program that generates a secret key using the AES (Advanced Encryption Standard) algorithm. Your program should take a user-provided password and use it to derive a secret key using the PBKDF2 (Password-Based Key Derivation Function 2) algorithm. The derived key should then be used t...
```java import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; import java.security.spec.KeySpec; import java.util.Base64; import java.util.Scanner; public class SecretKeyGenerator { public static...
magicoder
java
You are tasked with creating a Python function that simulates a simple asynchronous task execution using the `asyncio` library. Your function should take a list of tasks, each represented as a coroutine, and execute them concurrently. However, you need to handle any exceptions that may occur during the execution of the...
```python import asyncio from typing import List async def execute_tasks(tasks: List[asyncio.coroutine]) -> List[Exception]: exceptions = [] results = await asyncio.gather(*tasks, return_exceptions=True) for result in results: if isinstance(result, Exception): exceptions.append(result) ...
magicoder
python
You are tasked with creating a Python program that takes an integer input from the user and then prints the input value, its predecessor, and its successor. The program should prompt the user to enter a number and then display the analyzed values in the specified format. Your task is to write a Python program that acc...
```python # Prompt the user to enter a number n = int(input('Digite um número: ')) # Calculate the predecessor and successor of the input number predecessor = n - 1 successor = n + 1 # Print the analyzed values in the specified format print(f'Analisando o valor \033[33m{n}\033[m, seu antecessor é {predecessor} e o su...
magicoder
python
You are tasked with implementing a custom resizable icon class in Java. The `ImageWrapperResizableIcon` class from the `org.pushingpixels.flamingo.api.common.icon` package provides a foundation for creating resizable icons. Your goal is to extend this class to create a custom resizable icon that can be used in a user i...
```java import org.pushingpixels.flamingo.api.common.icon.ImageWrapperResizableIcon; import org.pushingpixels.flamingo.api.common.icon.ResizableIcon; import java.awt.*; import java.awt.image.BufferedImage; public class CustomResizableIcon extends ImageWrapperResizableIcon { private int width; private int heig...
magicoder
java
You are tasked with implementing a custom annotation processor in Java. The goal is to create an annotation called `CustomAnnotation` that can be used to mark methods within a class. When this annotation is present on a method, the processor should generate a new method in the same class that logs a message before and ...
```java // CustomAnnotation.java import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.SOURCE) @Target(ElementType.METHOD) public @interface CustomAnnotation { String value(); } //...
magicoder
java
You are given two strings, s1 and s2. Your task is to find the minimum window in s1 which will contain all the characters in s2 in complexity O(n). For example, if the input strings are s1 = "ADOBECODEBANC" and s2 = "ABC", then the minimum window is "BANC". Write a function `minWindowSubstring(s1, s2)` that takes in ...
```cpp #include <string> #include <unordered_map> using namespace std; string minWindowSubstring(string s1, string s2) { unordered_map<char, int> target, window; for (char c : s2) target[c]++; int left = 0, right = 0, count = 0, minLen = INT_MAX, minStart = 0; while (right < s1.size()) { char...
magicoder
cpp
You are tasked with creating a Python class that interacts with an API to retrieve various types of school schedules. The class should have methods for fetching different types of schedules, each corresponding to a different endpoint of the API. The methods should be asynchronous and accept parameters to customize the ...
```python # Sample usage of the SchoolScheduleFetcher class import asyncio class MockAPI: async def request(self, method, endpoint, params): # Simulate API request and return dummy data return f"Response for {endpoint} with params: {params}" async def main(): api = MockAPI() schedule_fetch...
magicoder
python
You are tasked with implementing a program that processes a list of transactions and calculates the total amount spent by each customer. Each transaction consists of a customer ID, transaction amount, and transaction date. The program should read the transactions from a file, calculate the total amount spent by each cu...
```python def calculate_total_spent(input_file, output_file): transactions = {} with open(input_file, 'r') as file: for line in file: customer_id, amount, _ = line.strip().split(',') amount = float(amount) if customer_id in transactions: transacti...
magicoder
python
You are tasked with implementing a real estate management system using C++. The system should include a class `realty` that represents a real estate property. The `realty` class should inherit from a class `tree` and have the following functionalities: 1. A constructor that takes a string `d`, a constant reference to ...
```cpp #include <iostream> #include <string> #include <stdexcept> class tree { // Base class with its own members and methods }; class realty : public tree { private: std::string data; std::string name; void data_checker(const std::string &d) { // Example validation criteria: data should not ...
magicoder
cpp
You are tasked with analyzing a dataset containing information about various countries. The dataset is stored in a CSV file named "countries.csv" and includes the following columns: "Country", "Population", "GDP per Capita", and "Life Expectancy". Your goal is to write a Python program to perform the following tasks: 1...
```python import pandas as pd import seaborn as sns # Load the dataset into a pandas DataFrame df = pd.read_csv("countries.csv") # Visualize the relationship between GDP per Capita and Life Expectancy using a scatter plot sns.scatterplot(data=df, x="GDP per Capita", y="Life Expectancy") # Calculate the correlation c...
magicoder
python
You are tasked with implementing a function that processes graphics window properties and returns a new graphics window object. The function takes in various flags and properties to determine if the creation of the graphics window is allowed. The code snippet provided is a part of the function and contains some conditi...
```cpp GraphicsWindow* CreateGraphicsWindow(Engine* engine, const char* name, unsigned int flags, const GraphicsProperties& fb_prop, const WindowProperties& win_prop) { if ((flags & BF_fb_props_optional) == 0) { if ((fb_prop.get_aux_rgba() > 0) || (fb_prop.get_aux_hrgba() > 0) || (fb_prop.get_aux_float() > ...
magicoder
cpp
You are tasked with implementing a function to parse a configuration file in a specific format and extract error messages from it. The configuration file is structured as a Python module and contains a function that returns a dictionary of error messages. The function should read the configuration file, extract the err...
```python from typing import List import ast def parse_error_messages(file_path: str) -> List[str]: with open(file_path, 'r') as file: file_content = file.read() module = ast.parse(file_content) for node in module.body: if isinstance(node, ast.FunctionDef) and node.name == 'get...
magicoder
python
You are given a code snippet that processes a sequence of integers and performs a bitwise operation on each integer. Your task is to complete the code by adding the necessary logic inside the while loop to achieve the desired functionality. The code snippet is as follows: ```c size_t i = 0; uint64_t result = 0; int sh...
```c uint64_t processSequence(const int* sequence, size_t size, int shift) { size_t i = 0; uint64_t result = 0; while (i < size) { uint64_t shiftedValue = (uint64_t)sequence[i] << shift; result |= shiftedValue; i++; } return result; } ``` The provided solution defines ...
magicoder
c
You are given a list of integers representing the scores of a game. Your task is to write a function that calculates the highest possible score by choosing a subset of the scores such that no two chosen scores are adjacent in the original list. Write a function `maxNonAdjacentSum` that takes in a list of integers and ...
```python from typing import List def maxNonAdjacentSum(scores: List[int]) -> int: if not scores: return 0 if len(scores) <= 2: return max(scores) max_sum = [0] * len(scores) max_sum[0] = scores[0] max_sum[1] = max(scores[0], scores[1]) for i in range(2, len(scores)): ...
magicoder
python
You are tasked with creating a route management system for a web application. The application uses the Laravel framework, and the routes are defined in the `web.php` file. Each route is associated with a specific controller method. Your task is to implement a function that will parse the given code snippet and extract ...
```python import re def parseRoutes(code_snippet): routes = {} lines = code_snippet.split('\n') for line in lines: if line.strip().startswith('Route::get') and not line.strip().startswith('//'): route_path = re.search(r"'(.*?)'", line).group(1) controller_method = re.search(...
magicoder
python
You are tasked with creating a script to automate the deployment process for a website using Docker. Your script should perform the following tasks: 1. Build a Docker image for the website with the tag "elliotjreed/www.crescenthr.co.uk" using the provided Dockerfile. 2. Push the built image to a Docker registry with t...
```bash #!/bin/bash # Authenticate with the Docker registry if necessary docker login <registry_url> -u <username> -p <password> # Build the Docker image without using any cached layers docker build -t elliotjreed/www.crescenthr.co.uk . --no-cache # Push the built image to the Docker registry docker push elliotjreed...
magicoder
shell
You are given two strings, `string1` and `string2`, along with match and mismatch scores, and a gap extend penalty. Your task is to implement a function to calculate the optimal alignment score and the aligned strings using the following scoring scheme: - Match: +4 - Mismatch: -2 - Gap extend penalty: -2 The alignmen...
```python from typing import Tuple def optimal_alignment_score(string1: str, string2: str, match: int, mismatch: int, gap_extend_penalty: int) -> Tuple[int, Tuple[str, str]]: n = len(string1) m = len(string2) dp = [[0] * (m + 1) for _ in range(n + 1)] for i in range(1, n + 1): dp[i][0] = dp[i-...
magicoder
python
You are tasked with creating a program to validate and process grade values entered by users. The grade value is expected to be a numerical representation of a student's grade, and it should adhere to specific criteria. The grade value should be a floating-point number within the range of 0.0 to 100.0, inclusive. Add...
```python import re def validate_grade(grade_value: str) -> bool: # Check if the input is a valid floating-point number within the specified range if re.match(r'^\d{1,3}(\.\d+)?$', grade_value): value = float(grade_value) if 0.0 <= value <= 100.0: return True return False ``` T...
magicoder
python
You are tasked with implementing a Java class that manages database connections using JDBC. The class, `JdbcConnection`, has two constructors: one that takes a `DataSource` object and another that takes a `Connection` object. Your task is to implement the `JdbcConnection` class with the following requirements: 1. The ...
```java import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; public class JdbcConnection { private DataSource dataSource; private Connection connection; public JdbcConnection(final DataSource dataSource) { this.setDataSource(dataSource); } public JdbcConn...
magicoder
java
You are tasked with implementing a simple game in Unity where the player controls a character to navigate through a maze. The maze is represented as a 2D grid, where each cell can be either empty or blocked. The player can move up, down, left, or right, but cannot move through blocked cells. The game starts at the top-...
```csharp int Move(int[,] maze) { int rows = maze.GetLength(0); int cols = maze.GetLength(1); int[,] directions = { {0, 1}, {0, -1}, {1, 0}, {-1, 0} }; Queue<(int, int)> queue = new Queue<(int, int)>(); queue.Enqueue((0, 0)); int[,] distance = new int[rows, cols]; for (int i =...
magicoder
csharp
You are tasked with implementing a class that manages a masking view with tap interaction. The class should handle the scenario where the tap handler is set to either perform an action or do nothing. You are given the following code snippet as a starting point: ```swift guard let strongSelf = self else { return } str...
```swift protocol MaskingViewDelegate: AnyObject { func hide(presenter: MaskingView) } class MaskingView { var interactivelyHidden: Bool = false weak var delegate: MaskingViewDelegate? var tappedHandler: (() -> Void)? func handleTap() { if let handler = tappedHandler { if handl...
magicoder
swift
You are tasked with creating a program that processes a given file path and extracts specific information from it. The file path follows a specific structure, and your program needs to parse the path and extract relevant details. Write a function `extractFileInfo` that takes a file path as input and returns the follow...
```python from typing import Tuple def extractFileInfo(file_path: str) -> Tuple[str, str, str, str]: parts = file_path.split('/') filename_with_extension = parts[-1] filename, extension = filename_with_extension.split('.') directory_path = '/'.join(parts[:-1]) package_name = '/'.join(parts[3:-1]) ...
magicoder
python
You are given a binary tree node structure and are required to implement a method to perform an inorder traversal of the tree iteratively using a stack. The inorder traversal should return a list of values in the order they are visited. The binary tree node structure is defined as follows: ```python class TreeNode: ...
```python def inorderTraversal(root: TreeNode) -> List[int]: result = [] stack = [] current = root while current is not None or stack: while current is not None: stack.append(current) current = current.left current = stack.pop() result.append(current.val)...
magicoder
python
You are tasked with implementing a simple stack data structure using C++ and its standard library. The stack should support the following operations: push, pop, and top. Additionally, you need to write a function that checks if a given string of parentheses is balanced or not using the implemented stack. Your task is ...
```cpp #include <iostream> #include <stack> #include <string> #define CATCH_CONFIG_MAIN #include "../catch/catch.hpp" class Stack { private: std::stack<char> data; public: void push(char c) { data.push(c); } void pop() { if (!data.empty()) { data.pop(); } } ...
magicoder
cpp
You are tasked with creating a web form that includes a dropdown menu for selecting a division within a company. The dropdown menu should be populated with options retrieved from a database and should be required for form submission. Your task is to write a PHP function that generates the HTML code for the dropdown men...
```php <?php function generateDivisionDropdown($dd_divisi, $id_divisi) { $dropdown_html = '<select name="id_divisi" required class="form-control select2">'; foreach ($dd_divisi as $key => $value) { $selected = ($key == $id_divisi) ? 'selected' : ''; $dropdown_html .= "<option value='$key' $selec...
magicoder
php
You are tasked with implementing a media streaming system in Swift. The system consists of a `Streamer` class that handles the streaming of media content. The `Streamer` class has three methods: `notifyDownloadProgress`, `notifyDurationUpdate`, and `notifyTimeUpdated`. These methods are responsible for notifying the de...
```swift import Foundation protocol StreamerDelegate: AnyObject { func updatedDownloadProgress(_ streamer: Streamer, progress: Double, forURL url: URL) func updatedDuration(_ streamer: Streamer, duration: TimeInterval) func updatedTime(_ streamer: Streamer) } class Streamer { weak var delegate: Stream...
magicoder
swift
You are tasked with creating a Python function that parses a configuration file and extracts specific information based on a given set of criteria. The configuration file is in a custom format and contains various settings for a service. Each setting is represented by a key-value pair, and some settings may have additi...
```python from typing import Union, Dict, Tuple def parse_config_file(file_path: str, setting_name: str) -> Union[str, Tuple[str, Dict[str, str]]]: with open(file_path, 'r') as file: config_content = file.read() # Find the setting block with the given name start_index = config_content.find(f"CONFI...
magicoder
python
You are tasked with creating a script to automate the build process for a Node.js project. The build process involves transpiling TypeScript files to JavaScript using the TypeScript compiler (`tsc`), and then setting the appropriate permissions for the generated JavaScript file. Your script should perform the followin...
```bash #!/bin/bash # Assign the root and build directories to variables ROOT_DIR="/path/to/root/directory" BUILD_DIR="/path/to/build/directory" # Change the current directory to the parent directory of the root directory cd $ROOT_DIR/.. # Run the TypeScript compiler using npm npm run tsc # Change the current direc...
magicoder
shell
You are tasked with implementing a custom enum type in Rust to represent different states of a task scheduler. The enum should include variants for "Canceled", "Expired", and "Timeout". Additionally, you need to create a function that takes a scheduler state as input and returns a message based on the state. Write a R...
```rust #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] enum SchedulerState { Canceled, Expired, Timeout, } fn get_scheduler_message(state: SchedulerState) -> &'static str { match state { SchedulerState::Canceled => "Task has been canceled", SchedulerState::Expired => "Task h...
magicoder
rust
You are working for a data visualization company that is developing a new feature for their plotting library. The feature involves creating a function to calculate the cumulative purchases over a period of time and then plot the cumulative purchases for different years on a line chart. The code snippet provided is a pa...
```python import matplotlib.pyplot as plt def calculate_cumulative_purchases(purchases): cumulative_purchases = [purchases[0]] for i in range(1, len(purchases)): cumulative_purchases.append(cumulative_purchases[i-1] + purchases[i]) return cumulative_purchases def plot_cumulative_purchases(cumulati...
magicoder
python
You are given a code snippet that appears to be part of a program using a specialized programming language or library. The code involves some mathematical operations and a kernel function. Your task is to understand and implement a function that performs a specific geometric transformation based on the given code snipp...
```python import math def performTransformation(center, polar, h, N, r1, r2): tau = 2 * math.pi # Mathematical constant tau cq1 = (center[0] - polar[0], center[1] - polar[1]) cqh = (center[0] - polar[0] * h, center[1] - polar[1] * h) transformed_points = [] for n in range(N): a = n * tau...
magicoder
python
You are tasked with implementing a function that converts a Python dictionary into a JSON-compatible object. The function should handle various data types and nested structures within the dictionary and convert them into their JSON equivalents. You are provided with a code snippet that demonstrates the conversion of in...
```python def to_json_compatible_object(field): if isinstance(field, (str, int, float, bool)) or field is None: return field elif isinstance(field, list): return [to_json_compatible_object(item) for item in field] elif isinstance(field, dict): return {key: to_json_compatible_object(v...
magicoder
python
You are tasked with creating a Python function to analyze cost summaries for various services in an Azure environment. The function will take in a list of report names, start date, and end date as input parameters. It will then retrieve the cost summaries for the specified reports within the given date range and return...
```python def retrieve_cost_summaries(report_names, start_date, end_date): # Simulate retrieving cost summaries for the specified reports cost_summaries = {} # Placeholder for actual retrieval logic # For demonstration purposes, populate cost summaries with dummy data for report_name in report_names: ...
magicoder
python
You are tasked with implementing a C++ class that simulates a simple leaderboard system for a video game. The leaderboard will store player scores and provide functionality to add new scores, retrieve the top scores, and reset the leaderboard. Your task is to implement the `Leaderboard` class with the following specif...
```cpp #include <iostream> #include <vector> #include <algorithm> class Leaderboard { private: struct PlayerScore { std::string name; int score; }; int capacity; std::vector<PlayerScore> scores; public: Leaderboard(int capacity) : capacity(capacity) {} void AddScore(int score...
magicoder
cpp
You are tasked with creating a program that simulates a simple music player. The program should be able to play notes from a file and also allow the user to play notes using the keyboard. Your task is to implement the function `play_from_file` that plays notes from a given file and the function `play_from_keyboard` tha...
```rust use std::path::PathBuf; use std::thread; use std::sync::mpsc::Sender; use std::time::Duration; fn play_from_file(file_path: &str, tempo: u32) { let notes = std::fs::read_to_string(file_path).expect("Unable to read file"); let notes: Vec<&str> = notes.split_whitespace().collect(); let beat_duration ...
magicoder
rust
You are tasked with implementing a class that manages terminal settings for a text-based user interface. The class should provide methods to modify various terminal settings, such as deleting lines, setting columns, enabling cursor blinking, and more. Your task is to design and implement the class with the given method...
```cpp #include <iostream> class TerminalManager { public: virtual bool DeleteLine(const size_t distance) = 0; // DL virtual bool SetColumns(const size_t columns) = 0; // DECCOLM virtual bool SetCursorKeysMode(const bool applicationMode) = 0; // DECCKM virtual bool SetKeypadMode(const bool applicationM...
magicoder
cpp
You are working on a ticketing system where you need to implement a feature to retrieve user activity logs for auditing purposes. The code snippet provided is a part of the data access layer for this feature. The `IAuditQueries` interface defines a method `GetUserActivity` that takes a nullable `userId` as input and re...
```csharp using System.Collections.Generic; using System.Data; using Dapper; using Microsoft.Data.SqlClient; using Microsoft.Extensions.Configuration; using TicketCore.ViewModels.Audit; namespace TicketCore.Data.Audit.Queries { public class AuditQueries : IAuditQueries { private readonly IConfiguration...
magicoder
csharp
You are tasked with creating a Python function that scrapes a website to extract links for downloading RPG map samples. The function should utilize the Beautiful Soup library to parse the HTML content of the webpage and extract the desired links. Additionally, the function should handle potential exceptions that may oc...
```python import requests from bs4 import BeautifulSoup def get_map_links(url): try: response = requests.get(url) response.raise_for_status() # Raise an HTTPError for bad status codes bs = BeautifulSoup(response.content, 'html.parser') content_images = bs.find_all('figure', {'class...
magicoder
python
You are tasked with implementing a custom data structure that stores data along with its type and expiration time. Your task is to create a class `CustomDataStructure` that inherits from `BaseDataStructure` and adds the functionality to set and check the expiration time of the data. The `BaseDataStructure` class has t...
```python from typing import Union import time class BaseDataStructure: __slots__ = {"data", "type", "expire_at"} def __init__(self, data: Union[str, set]): self.data = data self.type = type(data) self.expire_at = None class CustomDataStructure(BaseDataStructure): def set_expire_t...
magicoder
python
You are tasked with implementing a file system helper class in Python. The class should provide methods for creating, deleting, and listing files and directories, as well as for checking if a given path exists and whether it points to a file or a directory. Your task is to complete the implementation of the `fshelper` ...
```python from typing import List import os class fshelper: def __init__(self): pass def create_file(self, path: str) -> None: if os.path.exists(path): raise FileExistsError(f"File '{path}' already exists") with open(path, 'w'): pass def create_directory(se...
magicoder
python
You are tasked with implementing a notification service that sends push notifications to users based on specified tag expressions. The code snippet provided is part of a larger notification service implementation. The `TrySendAsync` method attempts to send a push notification message to users based on a given tag expre...
```csharp private async Task<bool> TrySendAsync(PushNotificationMessage message, string tagExpression) { try { // Create platform-specific notification properties var notification = PlatformNotificationFactory.CreateTemplateProperties(message); // Send the notification using the tag exp...
magicoder
csharp
You are given a list of integers representing the scores of a game. Your task is to write a function that calculates the average score of the game, excluding the highest and lowest scores. Write a function `calculateAverageScore(scores)` that takes in a list of integers `scores` (2 <= len(scores) <= 100) and returns t...
```python def calculateAverageScore(scores): if len(scores) < 4: return round(sum(scores) / len(scores)) scores.sort() return round(sum(scores[1:-1]) / (len(scores) - 2)) ``` The `calculateAverageScore` function first checks if the length of the input list is less than 4. If so, it calculates t...
magicoder
python
You are tasked with creating a Python function that processes data from a MongoDB database and returns a specific data structure. The function should connect to the database, retrieve all records, and then perform some calculations to generate a specific output. Write a Python function `generate_provider_data` that ta...
```python import pymongo from vanilla.uix.db.database import connect, get_all def generate_provider_data(): conn = connect() all_records = get_all(conn) providers_set = set([prov['provider'] for prov in all_records]) provider_data = [{'count': conn.posts.find({'provider': p}).count(), ...
magicoder
python
You are tasked with creating a Python class that manages configuration settings for a web application. The class should handle the initialization and refreshing of static values from a JSON configuration file. Your task is to implement the `ConfigManager` class with the following requirements: - The class should have ...
```python import os import sys import json class Setting: PORT = None # Static variable to hold the port value class ConfigManager: def __init__(self, log_conf_path, setting_json_path): self.log_conf_path = log_conf_path self.setting_json_path = setting_json_path def log_init(self): ...
magicoder
python