query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with implementing a function to check if two integers are coprime using the Extended Euclidean Algorithm (EEA). The Extended Euclidean Algorithm is an efficient method for finding the greatest common divisor (GCD) of two numbers and expressing it as a linear combination of the two numbers. Two integers a...
```rust fn check_eea<T: std::ops::Add<Output = T> + std::ops::Sub<Output = T> + std::ops::Mul<Output = T> + std::cmp::PartialEq + std::clone::Clone + std::marker::Copy>(a: T, b: T) -> bool where T: std::cmp::PartialOrd + std::ops::Div<Output = T> + std::ops::Rem<Output = T> + std::ops::Neg<Output = T> + std::fmt::D...
magicoder
rust
You are tasked with implementing a function to validate a specific syntax for defining local variable usage in a programming language. The syntax consists of comma-separated strings, where each string represents a variable name preceded by an optional exclamation mark to indicate negation. The function should return Tr...
```python def _check_use_local_syntax_valid(use_local_list): for item in use_local_list: if item.startswith('!'): if len(item) < 2 or not item[1:].isidentifier(): return False else: if not item.isidentifier(): return False return True ``` ...
magicoder
python
You are working for a social media advertising company, and you are tasked with analyzing the viral spread of an ad campaign. The ad is initially shown to 5 people on the first day. Each day, half of the people who saw the ad like it and share it with 3 of their friends. These friends then see the ad the next day. You ...
```python def viralAdvertising(n: int) -> int: shared = 5 liked = 0 cumulative_likes = 0 for _ in range(n): liked = shared // 2 cumulative_likes += liked shared = liked * 3 return cumulative_likes ``` The `viralAdvertising` function initializes the number of people who initi...
magicoder
python
You are tasked with implementing a function that checks if a given user follows a specific channel on a social media platform. The function will take in the user's name and the channel name as input and should return a boolean value indicating whether the user follows the channel. You are provided with a code snippet ...
```javascript /** * Checks if a user follows a specific channel. * @param {string} userName - The name of the user. * @param {string} channelName - The name of the channel. * @returns {boolean} - True if the user follows the channel, false otherwise. */ async function checkFollowsChannel(userName, channelName) { ...
magicoder
javascript
You are tasked with implementing a class for managing weather states in a virtual world simulation. The provided code snippet is a partial definition of the `worldWeatherState` class in C#. The class inherits from `CVariable` and contains several properties annotated with attributes for serialization and data binding. ...
```csharp using System; public class worldWeatherState : CVariable { [Ordinal(0)] [RED("effect")] public raRef<worldEffect> Effect { get; set; } [Ordinal(1)] [RED("environmentAreaParameters")] public rRef<worldEnvironmentAreaParameters> EnvironmentAreaParameters { get; set; } [Ordinal(2)] [RED("maxDurat...
magicoder
csharp
You are tasked with implementing a function to calculate the age of a person based on their birthdate. You are given a code snippet that imports various modules and libraries, including `chrono` for date and time handling, and `proptest` for property-based testing. Your task is to write a function `calculate_age` that...
```rust use chrono::{DateTime, Utc, Duration}; use proptest::prelude::*; fn calculate_age(birthdate: DateTime<Utc>) -> i32 { let current_date = Utc::now(); let age = current_date.year() - birthdate.year(); if current_date.month() < birthdate.month() || (current_date.month() == birthdate.month() &&...
magicoder
rust
You are tasked with implementing a simple VIPER (View, Interactor, Presenter, Entity, Router) architecture for a basic note-taking application. The VIPER architecture is a design pattern used to separate the concerns of an application into distinct layers, promoting better organization and maintainability. Your task is...
```swift import Foundation protocol Note { var id: String { get } var content: String { get } } protocol NoteViewInput: AnyObject { func displayNotes(_ notes: [Note]) func noteCreationSuccess() func noteDeletionSuccess() } protocol NoteInteractorInput { func retrieveNotes() func createNot...
magicoder
swift
You are tasked with implementing a Python class that manages user information for a version control platform. The class should have attributes for the user's Gitee ID, Gitee login, Gitee name, phone number, avatar URL, CLA (Contributor License Agreement) email, and roles. Additionally, the class should have a method to...
```python class User: def __init__(self, gitee_id, gitee_login, gitee_name, phone, avatar_url, cla_email, roles): self.gitee_id = gitee_id self.gitee_login = gitee_login self.gitee_name = gitee_name self.phone = phone self.avatar_url = avatar_url self.cla_email = cla_...
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 from typing import List class FileSystem: def __init__(self): self.root = {} def create_directory(self, path: str) -> None: current = self.root for dir_name in path.split("/")[1:]: if dir_name not in current: current[dir_name] = {} curr...
magicoder
python
You are tasked with creating a Python function that simulates a simple card game. The game involves drawing cards from a standard deck and comparing their values to determine the winner. Your task is to implement the `play_card_game` function, which takes two lists of integers representing the drawn cards for two playe...
```python from typing import List def play_card_game(player1_cards: List[int], player2_cards: List[int]) -> str: player1_wins = 0 player2_wins = 0 for card1, card2 in zip(player1_cards, player2_cards): if card1 > card2: player1_wins += 1 elif card2 > card1: player2_...
magicoder
python
You are tasked with implementing a custom exception handling mechanism for a rule evaluation system. The system processes rule expressions and throws exceptions when encountering errors. Your goal is to create a custom exception class and modify the existing code to use it. You are provided with a code snippet that at...
```csharp public class RuleExpressionParseException : Exception { public RuleExpressionParseException(string message, Exception innerException) : base(message, innerException) { } } public class RuleProcessor { public void ProcessRuleExpression(string expression) { try { ...
magicoder
csharp
You are tasked with implementing a class hierarchy for geographical data representation. The provided code snippet shows the beginning of a class `GeoData` that extends the `Location` class and implements the `IGeoData` interface. Your task is to complete the implementation of the `GeoData` class and its associated int...
```java import java.lang.Math; interface IGeoData { double calculateDistance(Location loc); boolean isSameLocation(Location loc); } class Location { double latitude; double longitude; double altitude; public Location(double latitude, double longitude, double altitude) { this.latitude ...
magicoder
java
You are tasked with implementing a Python class that calculates the weighted average and standard deviation of a given set of values and their corresponding weights. The class should be able to handle these calculations efficiently and accurately. Your task is to complete the implementation of the `weighted_avg_and_st...
```python import numpy as np from features_infra.feature_calculators import NodeFeatureCalculator, FeatureMeta class BfsMomentsCalculator(NodeFeatureCalculator): def is_relevant(self): return True def weighted_avg_and_std(self, values, weights): if not values or not weights: rais...
magicoder
python
You are given a code snippet from a Minecraft mod that deals with the positioning and state of a "DoomTree" in the game. The code snippet contains a method that takes the position of a player ("pos") and the position of a "heart" of the tree ("heartPos") as input. The method calculates the vertical distance between the...
```java public class DoomTreeSimulator { public static final int MAX_HEIGHT = 10; public static final int TERMINAL_HEIGHT = 5; public static final Object TERMINAL_STATE = new Object(); // Define the TERMINAL_STATE object public Object calculateTreeState(Position pos, Position heartPos, int dy) { ...
magicoder
java
You are working on a PHP application that involves handling authorization for different actions. The code snippet provided is a part of a method in a class. The method is responsible for checking authorization before performing a specific action. The `getActionMethod` method is used to retrieve the action method from t...
```php class AuthorizationHandler { private $excludedAuthorization = ['publicAction']; public function getActionMethod($request) { // Implement the logic to retrieve the action method from the request // For example, if the action method is specified in the request parameters return...
magicoder
php
You are working on a project that involves managing a set of files and directories. Your task is to write a Python function that simulates the behavior of the `cp` command in Unix-based systems. The `cp` command is used to copy files and directories from a source location to a destination location. Your function should...
```python def copy_files(source, destination): try: if os.path.isdir(source): if not os.path.exists(destination): os.makedirs(destination) for item in os.listdir(source): s = os.path.join(source, item) d = os.path.join(destination, item...
magicoder
python
You are tasked with implementing a logging plugin for a software application. The plugin is responsible for handling various commands related to logging. The provided code snippet includes the definition of the plugin and a class for command-line arguments. Your task is to create a class that extends the `TestLogPlugi...
```python import logging class CustomLogPlugin(TestLogPlugin): def initialize_plugin(self): logging.basicConfig(filename='app.log', level=logging.INFO) def start_logging(self, filename): self.log_file = open(filename, 'a') def stop_logging(self): self.log_file.close() ``` In the ...
magicoder
python
You are tasked with implementing a function to convert a given integer into its Roman numeral representation. Roman numerals are represented by seven different symbols: I, V, X, L, C, D, and M, which correspond to the decimal values 1, 5, 10, 50, 100, 500, and 1000, respectively. The conversion should follow the standa...
```python def int_to_roman(num): tbl = { 1: 'I', 4: 'IV', 5: 'V', 9: 'IX', 10: 'X', 40: 'XL', 50: 'L', 90: 'XC', 100: 'C', 400: 'CD', 500: 'D', 900: 'CM', 1000: 'M' } res = '' for k in sorted(tbl.keys(), reverse=True): while num >= k: res += tbl[k] ...
magicoder
python
You are tasked with implementing a function that expands the tilde (~) in a file path to the user's home directory. The tilde is a shorthand notation commonly used in Unix-like systems to represent the home directory of the current user. Your task is to create a function that takes a file path as input and expands any ...
```swift import Foundation // MARK: - Path Expansion func expandTildeInFilePath(_ filePath: String) -> String { var expandedPath = filePath if filePath.hasPrefix("~") { if filePath == "~" { expandedPath = FileManager.default.homeDirectoryForCurrentUser.path } else { let...
magicoder
swift
You are tasked with implementing a token parser for a regular expression engine. The regular expression engine will use a set of tokens to represent different components of a regular expression. Your task is to write a function that takes a string representing a regular expression and returns an array of tokens extract...
```javascript function parseTokens(regex) { const tokens = []; let index = 0; while (index < regex.length) { if (regex[index] === '[') { const endIndex = regex.indexOf(']', index); if (endIndex !== -1) { tokens.push({ type: 'CharacterClass', value: regex.substring(index, endIndex + 1) });...
magicoder
javascript
You are tasked with creating a program that simulates the auto-alignment of components in glyphs that cannot be auto-aligned. Each glyph is represented as a 2D grid of characters, where each character represents a component. The goal is to align all components in each glyph by shifting them to the left as much as possi...
```python from typing import List def alignComponents(glyphs: List[List[str]]) -> List[List[str]]: aligned_glyphs = [] for glyph in glyphs: max_width = max(len(row) for row in glyph) aligned_glyph = [row.ljust(max_width) for row in glyph] aligned_glyphs.append(aligned_glyph) return ...
magicoder
python
You are tasked with implementing a method to handle HTTP requests in a web application. The method should retrieve a timeout value from an event listener, generate a list of parameter name-value pairs, and then create an HTTP request data object to be used for processing the request. Additionally, the method should han...
```java public void handleHttpRequest() { long timeout = evtListener.getTimeout(); List<NameValue> paramList = evt.genParamURL(); ItsNatDocItsNatImpl itsNatDoc = getItsNatDocItsNatImpl(); PageImpl page = itsNatDoc.getPageImpl(); HttpRequestData httpRequestData = new HttpRequestData(page); int ...
magicoder
java
You are tasked with implementing a caching system for a public transportation application. The application has two main components: stops and buses. Each stop represents a location where buses pick up and drop off passengers, and each bus represents a specific route that it follows, stopping at various stops along the ...
```python class StopCache: def __init__(self): self.cache = {} def get_stop(self, stop_id): return self.cache.get(stop_id, None) def set_stop(self, stop_id, stop_info): self.cache[stop_id] = stop_info def delete_stop(self, stop_id): if stop_id in self.cache: ...
magicoder
python
You are tasked with creating a program that processes a given license text to extract specific information from it. The license text follows a specific format and contains various fields such as the copyright holder, year, and license type. Your program should be able to parse the license text and extract the followin...
```python import re def extract_license_info(license_text): pattern = r'Copyright (\d{4}-present) (.+?)\.\n//\n// Licensed under the (.+?)\.$' match = re.search(pattern, license_text) if match: year = match.group(1) holder = match.group(2) license_type = match.group(3) ...
magicoder
python
You are tasked with implementing a Time class in C++ to represent time in hours, minutes, and seconds. The class should have the following functionalities: 1. Set the time using the `setTime` method, which takes three integer parameters representing hours, minutes, and seconds. 2. Get the time in 24-hour format using t...
```cpp #include <iostream> #include <string> class Time { private: int hour; int minute; int second; public: void setTime(int h, int m, int s) { hour = h; minute = m; second = s; } std::string getTime() { return std::to_string(hour) + ":" + std::to_string(minut...
magicoder
cpp
You are tasked with implementing a state machine that processes a sequence of input elements and maintains a set of states based on the input. Each state transition is determined by the current state and the input element. Your goal is to implement the `add_state` method, which adds a new state to the state machine bas...
```rust impl<T: TracebackColumn> YourType<T> { #[inline] fn add_state(&self, source: &Self::TracebackColumn, pos: usize, states: &mut [State<T, usize>]) { let new_state = State::derive_from_source(source, pos); // Assuming a method to derive a new state from the source states[pos] = new_state; ...
magicoder
rust
You are tasked with implementing a Python function that optimizes a given mathematical expression using a custom optimization library. However, the optimization process may not always succeed, and you need to handle such cases appropriately. Additionally, you are required to write unit tests to ensure the correctness o...
```python import optimization_library as opt import unittest def optimize_expression(expr): optimized = opt.optimize(expr) if optimized is None: return "Optimization failed" return optimized class TestOptimization(unittest.TestCase): def test_successful_optimization(self): expr = "2 * ...
magicoder
python
You are working on a program to manage book requests and fulfillments in a library. The code snippet provided is a part of the program that handles the fulfillment of book requests. The snippet seems to be updating the status of fulfilled requests and remaining requests after fulfillment. Your task is to implement a f...
```python def update_requests(num_books, request_list): fulfilled_requests = [0] * len(request_list) remaining_requests = request_list.copy() for i in range(len(request_list)): if num_books >= request_list[i]: fulfilled_requests[i] = 1 remaining_requests[i] = 0 n...
magicoder
python
You are tasked with creating a Django model for a music streaming service. The model should represent an audio file that can be either a song or a podcast. Each audio file has a title, duration, and an associated artist or host. Additionally, songs have an album they belong to, while podcasts have an episode number and...
```python from django.db import models class Artist(models.Model): name = models.CharField(max_length=100) class Album(models.Model): title = models.CharField(max_length=100) artist = models.ForeignKey(Artist, on_delete=models.CASCADE) class Series(models.Model): title = models.CharField(max_length=1...
magicoder
python
You are tasked with designing a Python decorator that will automatically expose methods from different modules of an application. The decorator should take a list of module names as input and dynamically expose all the methods from those modules. Your task is to implement the `expose_methods` decorator function, which...
```python def expose_methods(modules): exposed_methods = {} def decorator(func): nonlocal exposed_methods for module_name in modules: module = globals()[module_name] exposed_methods[module_name] = [method for method in dir(module) if callable(getattr(module, method)) and...
magicoder
python
You are tasked with implementing a class for managing the export of test data in various formats. The class, named `TestExporter`, contains methods for exporting test data to different file formats such as text, LaTeX, CSV, and XML. The class also handles the generation of XML files specifically for the "eva" format. T...
```python import csv class TestExporter: def __init__(self, nombre, instancias): self.nombre = nombre self.instancias = instancias def export_tests(self, tipo_exportacion, directorio): if tipo_exportacion in ['texto', 'latex']: planilla_respuestas = [] for prueb...
magicoder
python
You are tasked with creating a Python class that simulates a simple banking system. The class should have methods for creating a new account, depositing funds, withdrawing funds, and checking the balance. Each account should have a unique account number, and the class should be able to handle multiple accounts. Your t...
```python from typing import Dict, Union class Bank: def __init__(self): self.accounts: Dict[int, Dict[str, float]] = {} def create_account(self, account_holder: str, initial_deposit: float) -> int: account_number = len(self.accounts) + 1 self.accounts[account_number] = {'holder': acco...
magicoder
python
You are tasked with creating a Python function that reads configuration settings from a file and generates an Ansible inventory list. The function should read the configuration settings using the `oslo_config` library and then build an Ansible inventory list based on the configuration data. The configuration settings ...
```python from oslo_config import cfg from oslo_log import log as logging CONF = cfg.CONF LOG = logging.getLogger(__name__) def build_ansible_inventory(config_file_path): """Get inventory list from config files Args: config_file_path (str): The path to the configuration file. Returns: dict: A di...
magicoder
python
You are tasked with creating a Rust function that processes a collection of items and performs a specific operation on each item. The function should be generic and capable of handling any type that can be converted from a `Reference` and deserialized. Your task is to implement the function and ensure that it satisfies...
```rust use serde::de::DeserializeOwned; fn process_items<T, F, R>(items: &[T], closure: F) -> Vec<R> where T: From<Reference> + DeserializeOwned, F: Fn(&T) -> R, { items.iter().map(|item| closure(item)).collect() } ``` In the solution, the `process_items` function takes a slice of items and a closure as ...
magicoder
rust
You are tasked with implementing a class that handles alert triggers in a distributed system. The provided code snippet is a partial implementation of the `AlertTrigger` class, which is responsible for sending alerts to a specified port and display topic. Your task is to complete the implementation of the `AlertTrigger...
```java public class AlertTrigger { private final String displayTopic; private final static Logger logger = LoggerFactory.getLogger(AlertTrigger.class); private final MsgCommandChannel commandChannel; private final Port port; public AlertTrigger(FogRuntime runtime, Port alertPort, String displayTop...
magicoder
java
You are given a code snippet that represents the beginning of a software license agreement. The snippet is as follows: ``` // Permission is hereby granted, free of charge, to any person obtaining a copy of ``` Your task is to write a program that can automatically generate the full software license agreement based ...
```python def generate_license_agreement(): title = input("Enter the title of the software: ") license_type = input("Enter the type of license (e.g., MIT, Apache, GPL): ") copyright_holder = input("Enter the name of the copyright holder: ") year = input("Enter the year of the license agreement: ") a...
magicoder
python
You are tasked with implementing a function that extracts values from a SCIP column using the given code snippet as a reference. SCIP (Solving Constraint Integer Programs) is a framework for solving constraint integer programs and mixed-integer linear programs. The `get_vals` function is expected to return a non-modifi...
```cpp #include <span> #include "scip/scip.h" std::span<SCIP_Real> getVals(const SCIP_COL* col) { int num_nonz = SCIPcolGetNNonz(col); const SCIP_Real* vals = SCIPcolGetVals(col); return std::span<SCIP_Real>(vals, num_nonz); } ``` In the solution, we use the SCIP API functions to retrieve the number of no...
magicoder
cpp
You are tasked with creating a custom badge view in a SwiftUI application. The badge view should display a title and a count, and it should have a customizable style. Your goal is to implement the `BadgeView` struct and the `BadgeViewStyle` protocol to achieve this functionality. The `BadgeView` struct should have the...
```swift // Define the BadgeViewStyle protocol protocol BadgeViewStyle { associatedtype Configuration: BadgeViewStyleConfiguration func makeBody(configuration: Configuration) -> some View } // Define the BadgeViewStyleConfiguration struct struct BadgeViewStyleConfiguration { var title: String var count...
magicoder
swift
You are tasked with implementing a Python function that filters a list of projects based on certain criteria. The function should take in a list of projects and a set of filters, and return a filtered list of projects based on the given filters. Each project is represented as a dictionary with various attributes. The ...
```python def filter_projects(projects, filters): filtered_projects = projects.copy() for f in filters: exclude = False if f.startswith('-'): exclude = True f = f[1:] key, value = f.split(':') filtered_projects = [p for p in filtered_projects if (p.get(k...
magicoder
python
You are tasked with developing a Python script to automate the deployment of a Dataflow job on Google Cloud Platform. The script should accept various parameters and generate the necessary command to submit the job to Dataflow. Below is a simplified version of the script with placeholders for variables: ```python impo...
```python import argparse def main(): parser = argparse.ArgumentParser(description='Submit Dataflow job') parser.add_argument('--project', required=True, help='GCP project ID') parser.add_argument('--runner', required=True, help='Dataflow runner type') parser.add_argument('--staging_location', required...
magicoder
python
You are tasked with implementing a Python class that interacts with a blockchain-based service contract. The provided code snippet is a simplified version of the `Service` class, which inherits from `ts4.BaseContract` and contains several methods for interacting with the service contract. Your task is to complete the ...
```python class Service(ts4.BaseContract): def __init__(self, address: ts4.Address): super().__init__('Service', {}, nickname='Service', address=address) def get_subscription_plans(self) -> list[ts4.Address]: return self.call_getter('getSubscriptionPlans', {'_answer_id': 0}) def get_balan...
magicoder
python
You are working on a software system that deals with product definitions and formations. The system uses a specific syntax and set of operations to manipulate and compare these definitions. Your task is to implement a function that takes a reference to a product definition and performs a comparison operation on its rel...
```swift // Definition of the SDAI type and its associated operations enum SDAI { case UNKNOWN case FORCE_OPTIONAL(Any) // Represents a forced optional value // Custom comparison operation for SDAI values static func .===. (lhs: SDAI, rhs: SDAI) -> Bool { switch (lhs, rhs) { case (...
magicoder
swift
You are tasked with implementing a function that processes search terms and interacts with a web service to perform asynchronous searches. The function should handle encoding the search term, making a connection to the search service, and handling potential errors. The provided code snippet is a part of a larger progra...
```python import suds class SearchServiceClient: def __init__(self, service, token): self.searchclient = service self.token = token self.transaction_id = '' self.errorstatus = None def perform_search(self, searchterm): # Decode searchterm from 'utf8' to 'ascii' encoding...
magicoder
python
You are tasked with implementing a custom pairwise distance metric function for sparse matrices using Python and Scipy. The pairwise distance metric calculates the distance between each pair of vectors in a given dataset. Your task is to create a function that computes the pairwise distance for sparse matrices using a ...
```python import numpy as np from scipy.spatial import distance from scipy.sparse import csr_matrix def pairwise_distance_sparse_my_own_metric(X, my_own_metric_func): n = X.shape[0] distances = np.zeros((n, n)) for i in range(n): for j in range(i, n): dist = my_own_metric_func(X[i]...
magicoder
python
You are tasked with creating a program that analyzes the given software license text and extracts specific information from it. The license text follows the format of the Apache License, Version 2.0, and contains copyright information, licensing terms, and a link to obtain the full license. Your program should extract...
```python import re def extract_license_info(license_text): info = {} # Extract version version_match = re.search(r'Version\s\d+\.\d+', license_text) if version_match: info["version"] = version_match.group(0) # Extract copyright year year_match = re.search(r'Copyright\s(\d+\s-...
magicoder
python
You are tasked with creating a Flask web application that serves a static HTML file and handles a specific API endpoint. Your goal is to implement the missing code to achieve the desired functionality. You are provided with a partial code snippet for a Flask application: ```python from flask import Flask, send_from_d...
```python from flask import Flask, send_from_directory, jsonify import os app = Flask(__name__) app.config['DEBUG'] = True here = os.getcwd() @app.route('/') def serve_static_html(): return send_from_directory('static', 'index.html') @app.route('/api/data') def get_api_data(): data = { "message": "He...
magicoder
python
You are working on a data analysis project and need to write a Python function to calculate the frequency of scores in a given dataset. The dataset is represented as a pandas DataFrame named `b`, and it contains a column named 'score' which holds numerical values representing scores. Your task is to write a function `c...
```python import pandas as pd def calculate_score_frequency(b): score_counts = b['score'].value_counts().to_dict() return score_counts ``` The `calculate_score_frequency` function takes a DataFrame `b` as input and uses the `value_counts` method to count the occurrences of each unique score in the 'score' colu...
magicoder
python
You are tasked with implementing a genetic algorithm to optimize the architecture of a convolutional neural network (CNN) for image classification. The genetic algorithm will be used to evolve the structure of the CNN by modifying the number of convolutional layers, dense layers, and the number of filters in each layer...
```python # Import necessary libraries import numpy as np from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense from keras.optimizers import Adam from keras.utils import to_categorical # Define the fitness function to evaluate the performance of a CNN architecture def evalua...
magicoder
python
You are tasked with implementing a function to group an array of strings based on their frequency of occurrence. You are given a function `makeKey` that takes a string `s` as input and returns a key based on the frequency of characters in the string. The function should return a hashmap where the keys are the frequency...
```cpp #include <iostream> #include <unordered_map> #include <vector> std::string makeKey(const std::string& s) { std::unordered_map<char, int> freq; for (char c : s) { freq[c]++; } std::string key; for (const auto& p : freq) { key += std::to_string(p.second) + p.first; } re...
magicoder
cpp
You are tasked with implementing a program that processes a given fragment shader source code to extract and count the number of comments present in the code. A comment is defined as any text enclosed within `/*` and `*/` or preceded by `//`. The program should ignore any comments that are within a string literal or a ...
```python import re def countComments(shaderSource: str) -> int: in_string_literal = False in_comment = False comment_count = 0 for i in range(len(shaderSource)): if shaderSource[i] == '"' and (i == 0 or shaderSource[i-1] != '\\'): in_string_literal = not in_string_literal ...
magicoder
python
You are tasked with creating a script that simulates a simple testing process for a software project. The script should execute a test command using a package manager (in this case, "yarn test"), capture the result of the test execution, and then exit with the same result code. Your task is to write a bash script that ...
```bash #!/bin/bash # Execute the "yarn test" command yarn test # Capture the result code of the test execution RESULT="$?" # Exit the script with the captured result code exit "$RESULT" ``` In the solution, the bash script "run_test.sh" is created to execute the "yarn test" command, capture the result code of the t...
magicoder
shell
You are given a grid of size n x m, where n represents the number of rows and m represents the number of columns. Each cell in the grid contains a non-negative integer value. Your task is to find the maximum sum of integers that can be obtained by traversing from the top-left cell to the bottom-right cell, moving only ...
```python from typing import List def maxSumPath(grid: List[List[int]]) -> int: n = len(grid) m = len(grid[0]) # Initialize the first row for j in range(1, m): grid[0][j] += grid[0][j-1] # Initialize the first column for i in range(1, n): grid[i][0] += grid[i-1][0] # Calc...
magicoder
python
You are tasked with creating a script to automate the process of setting up a ramdisk for development purposes. A ramdisk is a portion of the computer's primary storage that is used as if it were a disk drive. The provided code snippet is a starting point for this task. Your script should perform the following steps: ...
```bash #!/bin/bash # Define the ramdisk device and mount point ramdisk_device="/dev/sda3" ramdisk_mount_point="/media/user-backups" # Step 1: Create the directory if it does not exist if [ ! -d "$ramdisk_mount_point" ]; then sudo mkdir -p "$ramdisk_mount_point" fi # Step 2: Add entry to /etc/fstab if not already ...
magicoder
shell
You are tasked with creating a Python function that generates a migration script for a hypothetical database migration tool. The migration script should take in a list of database table names and generate a migration file in the format used by Django's migration system. The migration file should include the necessary c...
```python def generate_migration_script(table_names): migration_script = f"# Generated by Django 2.2.1 on 2019-05-08 14:56\n\n" migration_script += "from django.db import migrations, models\n\n" migration_script += "class Migration(migrations.Migration):\n" migration_script += " dependencies = []\n\n...
magicoder
python
You are tasked with implementing a custom mathematical function using JAX (a numerical computing library for Python that automatically differentiates native Python and NumPy code). Your function will calculate the value of a special trigonometric expression based on the given input. The function you need to implement ...
```python import jax.numpy as jnp def custom_trig_function(x, y): result = jnp.tan(x) * jnp.cos(y) + jnp.arccos(x) / jnp.arctan(y) return result ``` The `custom_trig_function` takes two input parameters `x` and `y`, and calculates the value of the given mathematical expression using the JAX library functions ...
magicoder
python
You are tasked with creating a Java program that simulates a simple inventory management system for a small retail store. The store sells various items, each with a unique identifier, name, price, and quantity in stock. Your program should allow the user to perform the following operations: 1. Add a new item to the in...
```java class InventoryItem { private int id; private String name; private double price; private int quantity; public InventoryItem(int id, String name, double price, int quantity) { this.id = id; this.name = name; this.price = price; this.quantity = quantity; } ...
magicoder
java
You are tasked with implementing a generic stack data structure in C#. The stack should support the standard operations of push, pop, and peek, as well as a method to check if the stack is empty. Additionally, the stack should have a method that returns the minimum element in the stack in constant time. Your task is t...
```csharp public class MinStack { private Stack<int> stack; private Stack<int> minStack; public MinStack() { stack = new Stack<int>(); minStack = new Stack<int>(); } public void Push(int x) { stack.Push(x); if (minStack.Count == 0 || x <= minStack.Peek()) ...
magicoder
csharp
You are tasked with implementing a Python function that performs a specific transformation on a given input matrix. The transformation involves applying a sigmoid function to a subset of the input matrix and then combining the result with another subset of the input matrix. Your task is to write a function that accompl...
```python import torch import torch.nn as nn class Sigmoid(nn.Module): def __init__(self): super(Sigmoid, self).__init__() def apply_transformation(inputs: torch.Tensor, h: int) -> torch.Tensor: m, a = Sigmoid().trunk(h).chunk(2, 1) x = torch.empty_like(inputs) for i_col in range(inputs.size(1...
magicoder
python
You are tasked with simulating a simple network configuration using Python. Your goal is to create a program that sets up a virtual network interface, assigns IP addresses to the interfaces, and adds a default route within a network namespace. Your program should perform the following steps: 1. Create a network namesp...
```python import subprocess # Step 1: Create a network namespace named "vpn" subprocess.run(["ip", "netns", "add", "vpn"]) # Step 2: Set the network interface "eth0" into the "vpn" network namespace subprocess.run(["ip", "link", "set", "eth0", "netns", "vpn"]) # Step 3: Assign the IP address 10.0.0.1/24 to a virtual...
magicoder
python
You are tasked with implementing a method to convert a given `FileTime` object to an `Instant` object, following specific formatting rules. The `FileTime` class represents a time in the file system and the `Instant` class represents a moment on the time-line. The method should handle exceptions and return the converted...
```java import java.nio.file.attribute.FileTime; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.Instant; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; public class FileTimeConverter { private static final DateTimeFormatter rfc3339 = DateTimeF...
magicoder
java
You are tasked with creating a program to manage travel itineraries for a travel agency. The agency has a database containing various destinations, and each destination has multiple itineraries associated with it. Your task is to write a function that takes the destination as input and returns all the itineraries for t...
```python def get_itineraries(destination): # Assume data.sicily is a dictionary containing itineraries for Sicily # Replace this with actual data retrieval logic from the database itineraries = data.sicily.get(destination, []) return itineraries ``` The `get_itineraries` function takes a destination as...
magicoder
python
You are tasked with implementing a function that processes messages in a messaging app. The function receives a message list and an index path, and it is expected to handle different types of messages, such as quick reply buttons. The code snippet provided is a part of the implementation of this function. Your task is ...
```swift func processMessage(messageList: [Message], indexPath: IndexPath, messagesDataSource: MessagesDataSource, messagesCollectionView: MessagesCollectionView, button: UIButton) { guard let messagesDataSource = messagesDataSource else { fatalError("Ouch. nil data source for messages") } guar...
magicoder
swift
You are tasked with implementing a Vector class in Python that supports various operations. The class should represent a mathematical vector and provide functionality for scalar multiplication, absolute value calculation, and item retrieval. Your task is to complete the implementation of the Vector class by adding the...
```python import math import numbers class Vector: def __init__(self, *components): self.components = components def __rmul__(self, number): return Vector(*(number * component for component in self.components)) def __abs__(self): return math.sqrt(sum(i * i for i in self.components...
magicoder
python
You are tasked with creating a Java class that represents a character in a role-playing game. The class should have a field to store the character's armor value. Additionally, you need to implement a method to calculate the character's total defense value, which is the sum of the armor value and a base defense value of...
```java public class Character { private int armor; public Character(int armor) { this.armor = armor; } public int calculateTotalDefense() { return armor + 10; } // Additional methods and fields can be added as per the requirements of the game. } ```
magicoder
java
You are tasked with implementing a function that takes a list of integers and two integer parameters, `start` and `end`. The function should return a list of strings representing ranges of numbers within the given list, based on the following rules: - If a single number is missing between `start` and the first element ...
```python def find_ranges(nums, start, end): result = [] if start < nums[0]: if start + 1 == nums[0]: result.append(str(start)) else: result.append(f"{start}->{nums[0]-1}") for i in range(len(nums) - 1): if nums[i] + 1 < nums[i + 1]: if nums[i] + 2...
magicoder
python
You are tasked with creating a Python package version comparator. Your task is to implement a function that compares two version strings and determines which one is greater. The version strings follow the Semantic Versioning (SemVer) format, which consists of three non-negative integers separated by periods (e.g., "1.2...
```python def compare_versions(version1: str, version2: str) -> int: v1_parts = version1.split('.') v2_parts = version2.split('.') for i in range(3): # Compare major, minor, and patch versions if int(v1_parts[i]) > int(v2_parts[i]): return 1 elif int(v1_parts[i]) < int(v2_p...
magicoder
python
You are working on a project to design a digital clock signal generator for a custom system-on-chip (SoC) using Verilog. The code snippet provided sets the clock signal options and specifies the Verilog top module file. Your task is to implement a Verilog module for the clock signal generator that can produce different...
```verilog module clock_generator( input wire clk_opt, output reg clk ); always @ (posedge clk_opt) begin if (clk_opt == 1'b1) begin // Generate 50MHz clock signal for "-clk v.clk" clk <= ~clk; end else begin // Generate 25MHz clock signal for "-clk v.clk_...
magicoder
verilog
You are tasked with creating a custom validator for a Symfony application that ensures the attributes of a group meet certain criteria. The `GroupAttributesValidatorTest` class extends `ConstraintValidatorTestCase` and is used to test the custom validator for group attributes. The `attributeManager` property is initial...
```php use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; class GroupAttributesValidator extends ConstraintValidator { private $attributeManager; public function __construct(AttributeManager $attributeManager) { $this->attributeManager = $attributeMana...
magicoder
php
You are tasked with implementing a simple text editor in Python. Your text editor should support the following operations: 1. Insert a character at the current cursor position. 2. Delete the character at the current cursor position. 3. Move the cursor left or right. 4. Get the current text content. To achieve this, yo...
```python class TextEditor: def __init__(self, text: str): self.text = list(text) self.cursor_position = len(text) def insert(self, char: str): self.text.insert(self.cursor_position, char) self.cursor_position += 1 def delete(self): if self.cursor_position < len(sel...
magicoder
python
You are tasked with implementing a class that loads assets from a file and returns a shared pointer to the loaded asset. The class, `PlyAssetLoader`, contains a method `loadBasicAsset` which takes a file path and a boolean flag as input and returns a shared pointer to a `ColoredAsset`. The `ColoredAsset` represents an ...
```cpp #include <iostream> #include <memory> #include <fstream> #include <string> #include <stdexcept> class ColoredAsset { public: // Constructor to initialize the colored asset ColoredAsset(/* Parameters for initialization */) { // Implementation for asset initialization } // Other methods a...
magicoder
cpp
You are tasked with implementing a program to analyze the frequency of words in a given text. Your program should read a text file and output the frequency of each word in the file. For the purpose of this problem, a word is defined as a sequence of characters separated by spaces or punctuation marks. Your program sho...
```python import re def word_frequency(text_file): word_freq = {} with open(text_file, 'r') as file: text = file.read().lower() words = re.findall(r'\b\w+\b', text) for word in words: if word in word_freq: word_freq[word] += 1 else: ...
magicoder
python
You are tasked with creating a web application that displays a table of employees along with their department and status. The status is represented by a boolean value, where 1 indicates "Active" and 0 indicates "Inactive". You need to implement a function that takes an array of employee objects and generates the HTML t...
```javascript function generateEmployeeTable(employees, departments) { let tableHTML = '<table>'; tableHTML += '<tr><th>Name</th><th>Department</th><th>Status</th></tr>'; employees.forEach(employee => { const department = departments.find(dep => dep.id === employee.department_id); const...
magicoder
javascript
You are tasked with implementing a Python class that manages a queue of services. Each service can be started, stopped, and restarted. Your task is to complete the implementation of the `ServiceManager` class by adding the necessary methods to control the services. You are provided with a partial implementation of the...
```python class Service: def __init__(self, name): self.name = name self.is_running = False def start(self, *args, **kwargs): """Starts a service.""" self.is_running = True def stop(self, *args, **kwargs): """Stops a service.""" self.is_running = False clas...
magicoder
python
You are working on a note management system that involves importing and adding notes to a collection. The system has an `Importer` class responsible for importing notes, and a `Collection` class responsible for managing the collection of notes. Additionally, there are test cases written using a testing framework, where...
```python class Importer: def __init__(self, collection): self.collection = collection def import_note(self, note): if not self.collection.noteExists(note): self.collection.addNote(note) class Collection: def __init__(self): self.notes = [] def addNote(self, note)...
magicoder
python
You are tasked with implementing a C++ template class that manages a collection of unique elements. The class should support adding elements, removing elements, checking for the presence of elements, and retrieving the number of elements in the collection. Your task is to complete the implementation of the `UniqueColl...
```cpp #include <unordered_set> template <typename T> class UniqueCollection { public: void add(const T& element) { elements.insert(element); } void remove(const T& element) { elements.erase(element); } bool contains(const T& element) const { return elements.find(element) ...
magicoder
cpp
You are tasked with creating a tax calculation system for a government agency. The system needs to process tax return information for the year 2018. You are given a Java bean object with various properties related to tax return data. Your task is to write a method that calculates the total tax refund amount for the yea...
```java import java.math.BigDecimal; import java.time.LocalDate; public class TaxCalculator { public Money calculateTaxRefundAmount(TaxReturnBean bean) { if (bean.getReasonForTaxReturnPartYear() == 1) { return bean.getTaxPayment2018(); } else if (bean.getReasonForTaxReturnPartYear() == ...
magicoder
java
You are tasked with implementing a system to track and manage enemy units within a game environment. The game contains living units, and the system should be able to detect when an enemy unit enters or leaves the sight of a living unit. You are provided with a partial code snippet from the `ALivingUnit` class, which in...
```cpp class ALivingUnit { public: // Other methods and members are not shown for brevity. void OnEnemyLeaveSight(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex) { AUnit* OtherUnit = Cast<AUnit>(OtherActor); if (OtherUnit) ...
magicoder
cpp
You are tasked with implementing a menu permission system for a documentation website. The code snippet provided includes a function that generates menu items based on use cases and actions, as well as the definition of two menu permission objects. Your task is to create a class that manages menu permissions and implem...
```javascript // Define the MenuPermission type type MenuPermission = { type: "allow" } | { type: "role"; role: string } // Define the MenuPermissionManager class class MenuPermissionManager { menuPermissions: Record<string, MenuPermission> constructor(menuPermissions: Record<string, MenuPermission>) { ...
magicoder
javascript
You are tasked with creating a Python function that sends a notification through Telegram when a command is executed. The function should take the command to be executed as an argument and should send a notification with the command's output to a specified Telegram channel. You are provided with a Python script `tg.py`...
```python import subprocess def send_notification(command: str, message: str) -> None: try: result = subprocess.run(command, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) output = result.stdout.strip() error_code = result.returncode ...
magicoder
python
You are tasked with implementing a command-line tool for managing extras in a software development environment. The tool, called `CTAGS`, allows developers to list, enable, and disable various extras related to different programming languages. The extras are specified using a syntax like `--extras-LANG=EXTRA`, where `L...
```python def process_ctags_commands(commands): extras_state = {} for command in commands: parts = command.split() lang_extra = parts[2].split('=')[1].strip('-\'') if lang_extra: extras_state[lang_extra] = [] return extras_state ```
magicoder
python
You are tasked with implementing a Python class for a sequential camera runner that captures images from multiple camera handlers. The class should allow for setting a wait duration and provide a method to retrieve a specified number of images from each camera handler. Your task is to complete the implementation of th...
```python def get_images(self, n_per_camera, verbose=False): self._result.clear() for handler in self.cam_handlers: images = [] for _ in range(n_per_camera): image = self.capture_image(handler) images.append(image) if verbose: print(f"Captured ...
magicoder
python
You are tasked with creating a Python class that manages authentication specifications for different appliance configurations. The class, `AuthSpec`, is responsible for storing and validating authentication details for various appliances. The `AuthSpec` class takes an `ApplianceConfigSpec` object and an `appliance_conf...
```python import random import string class ApplianceConfigSpec: def __init__(self, profile, endpoint, access_token, serial_id): self.profile = profile self.endpoint = endpoint self.access_token = access_token self.serial_id = serial_id class AuthSpec: def __init__(self, applia...
magicoder
python
You are tasked with implementing a function to add a watermark to a collection of images. The function should take the path to the images, the watermark image, and two alpha values as input. The watermark should be added to each image in the specified path, and the resulting images should be saved with the watermark ap...
```python import cv2 import glob def AddWatermark(str_imgname, str_watermarkname, alpha1=1.0, alpha2=0.2): # Load the image to be watermarked img = cv2.imread(str_imgname) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Load the watermark waterimg = cv2.imread(str_watermarkname, cv2.IMREAD_UNCHAN...
magicoder
python
You are tasked with implementing a context manager in Python to handle database connections. The context manager should ensure that the database connection is properly closed, even in the event of an exception. Additionally, you need to create a fixture for a nested database connection. Your task is to complete the im...
```python from contextlib import contextmanager class DatabaseConnection: def __init__(self, database_url): self.database_url = database_url self.connection = None @contextmanager def __call__(self): try: self.connection = self.connect_to_database() yield se...
magicoder
python
You are tasked with creating a program that processes a given Java source file and extracts information about the package declaration and the license under which the file is distributed. Write a Java program that takes a string representing the content of a Java source file as input and extracts the following informat...
```java import java.util.regex.Matcher; import java.util.regex.Pattern; public class JavaSourceFileProcessor { public static void main(String[] args) { String sourceCode = "/*\n" + " * This file was automatically generated by com.microsoft.tfs.core.ws.generator.Generator\n" + ...
magicoder
java
You are tasked with creating a custom plugin for a Minecraft server using the Denizen scripting language. The plugin should allow players to create and manage custom quests. One of the requirements is to implement a command that allows players to set the rewards for completing a quest. The rewards can include items, ex...
```yaml # Custom command to set rewards for a quest SetQuestRewards: type: script script: - define quest_name <[quest_name].as_element> - define items_to_give <[items].as_list> - define experience_reward <[experience].as_int> - define money_reward <[money].as_double> - if <[quest_name].is_null>:...
magicoder
yaml
You are given a sorted array of integers. Your task is to write a function to remove the duplicates in-place such that each element appears only once and return the new length of the array. Do not allocate extra space for another array; you must do this by modifying the input array in-place with O(1) extra memory. For...
```python from typing import List class Solution: def removeDuplicates(self, nums: List[int]) -> int: if not nums: return 0 # Initialize the pointer for the new length new_length = 1 # Iterate through the array for i in range(1, len(nums)): ...
magicoder
python
You are tasked with creating a Python program that interacts with Docker to manage networks. Your program should have the following functionalities: 1. List all the existing Docker networks. 2. Create a new Docker network with a specified name and driver. 3. Remove an existing Docker network by its name. Your program ...
```python import docker def list_networks(client): networks = client.networks.list() if networks: print("Existing Docker Networks:") for network in networks: print(network.name) else: print("No Docker networks found.") def create_network(client, name, driver): try: ...
magicoder
python
You are tasked with implementing a class that represents a group of people and provides functionality to perform operations on the group. The class should have the following specifications: Class Name: Group Attributes: - `people`: a list to store instances of the `Person` class (defined below) Methods: 1. `add_perso...
```python class Person: def __init__(self, name, age): self.name = name self.age = age class Group: def __init__(self): self.people = [] def add_person(self, person): self.people.append(person) def get_average_age(self): if not self.people: return 0...
magicoder
python
You are working on a project that involves processing and analyzing geographical data. One of the tasks involves determining whether a given point lies inside a polygon. To achieve this, you need to implement a function that takes in the coordinates of a polygon's vertices, the number of vertices, and the coordinates o...
```python def is_inside_polygon(polygon, N, point): x, y = point inside = False p1x, p1y = polygon[0] for i in range(N+1): p2x, p2y = polygon[i % N] if y > min(p1y, p2y): if y <= max(p1y, p2y): if x <= max(p1x, p2x): if p1y != p2y: ...
magicoder
python
You are tasked with implementing a function to determine the request type based on the input JSON data. The request type can be one of the following: NODES_POST, NODES_DELETE, NODES_GET, NODES_PUT_START, or NODES_PUT_END. The input JSON data is represented as an array of JSON objects, where each object contains informa...
```cpp #include <array> #include <string> #include <json_lib> enum req_type { NODES_POST, NODES_DELETE, NODES_GET, NODES_PUT_START, NODES_PUT_END, EDGES_POST, EDGES_DELETE, EDGES_GET, EDGES_PUT_START, EDGES_PUT_END }; req_type make_req_type(const json_object& obj) { if (obj.contains("action")) { std::stri...
magicoder
cpp
You are tasked with implementing a basic calculator that evaluates a given arithmetic expression in the form of a string. The expression consists of non-negative integers and the four basic arithmetic operators: addition (+), subtraction (-), multiplication (*), and division (/). The expression may also contain parenth...
```java import java.util.Stack; public class BasicCalculator { public String calculate(String s) { Stack<Integer> stack = new Stack<>(); int num = 0; char sign = '+'; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (Character.isDigit(c)) { ...
magicoder
java
You are tasked with implementing a session management system in PHP. The system should include a class `Session` with methods to start, retrieve, and save sessions. The `start` method should create a new session if one does not exist, or retrieve an existing session if it does. The `retrieve` method should return the s...
```php class Session { private $id; private $last_activity; private $data; public function start() { if (isset($_SESSION['id'])) { $this->id = $_SESSION['id']; $this->last_activity = $_SESSION['last_activity']; $this->data = $_SESSION['data']; } else ...
magicoder
php
You are tasked with creating a script to automate the build process for a software project. The script should be able to handle the compilation and installation of the project's components. Your task is to write a shell script that performs the necessary build and installation steps for a specific project. Your script...
```bash #!/bin/sh # Change directory to the project build directory cd /Users/lbajo/ros2_mod_ws/build/rosidl_generator_objc # Execute the make command to build all components make -f /Users/lbajo/ros2_mod_ws/build/rosidl_generator_objc/CMakeScripts/install_postBuildPhase.make$CONFIGURATION all ``` The provided shell...
magicoder
shell
You are tasked with creating a program that simulates a forest hunt game. In this game, the player navigates through a forest, encountering various animals and obstacles. The player's goal is to hunt specific animals while avoiding others and overcoming obstacles. The game is controlled through a command-line interface...
```c #include <stdio.h> #include <stdbool.h> // Define the size of the forest grid #define ROWS 5 #define COLS 5 // Define the symbols for different elements in the forest #define EMPTY_CELL '.' #define PLAYER_CELL 'P' #define DEER_CELL 'D' #define BEAR_CELL 'B' #define TREE_CELL 'T' // Define the initial position o...
magicoder
c
You are tasked with implementing a file watcher and reloader in Python. Your goal is to create a function that monitors a specified directory for any changes to its contents and automatically triggers a reload process when a change is detected. The reload process should restart the Python script, effectively updating i...
```python import os import sys import asyncio import watchdog.events import watchdog.observers import logging _startup_cwd = os.getcwd() def restart_script(): args = sys.argv[:] logging.debug("Restarting: %s" % " ".join(args)) args.insert(0, sys.executable) if sys.platform == "win32": args = [...
magicoder
python
You are tasked with creating a Python fixture for a testing framework that sets up a MinIO server using Docker. MinIO is an open-source object storage server that is compatible with Amazon S3 cloud storage service. The fixture should be designed to be used within a testing environment and should handle the setup and te...
```python import pytest from docker import DockerClient from typing import Iterator from urllib.parse import urlunsplit @pytest.fixture(scope="session") def _minio_server( docker_client: DockerClient, in_docker: bool, reuse_docker: bool, minio_container_image: str, minio_container_name: str, ) -> I...
magicoder
python
You are tasked with implementing a simple rendering engine that supports face culling. Face culling is a technique used in 3D computer graphics to improve rendering performance by discarding the rendering of certain polygons based on their orientation with respect to the viewer. In this problem, you will need to implem...
```python class FaceCulling: def __init__(self): self.culling_enabled = True self.culling_mode = 'back' def disable_culling(self): self.culling_enabled = False def enable_back_culling(self): self.culling_enabled = True self.culling_mode = 'back' def enable_fron...
magicoder
python
You are tasked with implementing a context manager for a custom file-like object. The context manager should ensure that any buffered data is flushed when exiting the context. You need to implement the `CustomFile` class with the necessary methods to act as a context manager and handle writing data to a buffer. Your t...
```python from typing import Any class CustomFile: def __init__(self): self.buf = [] def __enter__(self): return self def __exit__(self, exc_type, exc_value, exc_traceback): self.flush() def write(self, msg: Any) -> None: self.buf.append(self._write(msg)) def flu...
magicoder
python
You are tasked with implementing a thread-safe singleton pattern using the Boost C++ library. The provided code snippet demonstrates the use of `boost::call_once` and `boost::once_flag` to ensure that certain functions are only called once, even in a multi-threaded environment. Your task is to create a class `Singleto...
```cpp #include <boost/thread.hpp> class Singleton { private: static Singleton* instance; static boost::once_flag onceFlag; size_t uniqueId; Singleton() { // Private constructor to prevent instantiation uniqueId = generateUniqueId(); } static void createInstance() { in...
magicoder
cpp