query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with implementing a service for managing infrastructure scans in a software system. The infrastructure scans are stored in a repository, and the service should provide functionality for retrieving and manipulating these scans. You are provided with a partial implementation of the `InfraStructureServiceIm...
```java import com.capitalone.dashboard.repository.InfrastructureScanRepository; import com.capitalone.dashboard.request.InfraStructureRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Collections; import java.util.List; @Service pu...
magicoder
java
You are tasked with implementing a custom `TableWidgetItem` class in C++ that extends the functionality of the `QTableWidgetItem` class and inherits from the `QObject` class. The `TableWidgetItem` class should have constructors to initialize its properties and should support various operations on table items. Your tas...
```cpp #include <QTableWidgetItem> #include <QObject> #include <QString> #include <QIcon> class TableWidgetItem : public QTableWidgetItem, public QObject { public: TableWidgetItem(int ntype, const std::ustring& strName) : QTableWidgetItem(ntype) { // Initialize QTableWidgetItem with ntype } TableW...
magicoder
cpp
You are tasked with implementing a role-based access control system for a web application. The system should allow users to be assigned different roles, and each role should have specific permissions associated with it. You are provided with a code snippet that shows the initialization of a `RoleBusiness` class, which ...
```csharp // Define the Role class to represent a role with its name and associated permissions public class Role { public string Name { get; set; } public List<string> Permissions { get; set; } public Role(string name, List<string> permissions) { Name = name; Permissions = permissions;...
magicoder
csharp
You are tasked with creating a Rust program that processes a given text file and performs various operations on it. The program should utilize the `crossterm`, `lazy_static`, and `minimad` crates to achieve its functionality. Your program should perform the following tasks: 1. Read the contents of a text file named "i...
```rust mod utils; use crossterm::style::{Color, Print, ResetColor, SetForegroundColor}; use lazy_static::lazy_static; use minimad::mad_inline; use std::collections::HashMap; use std::fs; lazy_static! { static ref COLORS: Vec<Color> = vec![Color::Red, Color::Green, Color::Blue]; } fn main() { // Read the con...
magicoder
rust
You are tasked with implementing a search algorithm for a custom data structure. The data structure is represented by a class with a method `search_cf(self, params, args)`. The `search_cf` method takes two parameters: `params`, a dictionary containing search parameters, and `args`, a list of arguments to be used in the...
```python def search_cf(self, params, args): # Assuming the custom data structure is accessible through self.data_structure query = params.get("query", "") filters = params.get("filters", []) limit = params.get("limit", 10) # Perform the search based on the query and filters results = self.data...
magicoder
python
You are given a string representing a sequence of digits. Your task is to calculate the sum of all digits that match the next digit in the sequence. Matching is determined by comparing each digit to the one following it. If the last digit matches the first digit, it should also be included in the sum. For example: - F...
```python def calculate_matching_sum(captcha: str) -> int: captcha = captcha + captcha[0] # Append the first digit to the end to consider circular matching matching_sum = sum(int(captcha[i]) for i in range(1, len(captcha)) if captcha[i] == captcha[i - 1]) return matching_sum ```
magicoder
python
You are tasked with creating a program that simulates a simple banking system. The system should allow users to create accounts, deposit and withdraw funds, and check their balance. Additionally, the system should support the transfer of funds between accounts. You are provided with a partial implementation of the `Ba...
```csharp public void TransferFunds(BankAccount destinationAccount, decimal amount, CancellationToken cancellationToken = default(CancellationToken)) { if (cancellationToken.IsCancellationRequested) { return; // Transfer canceled } // Use a lock to ensure thread safety when transferring funds b...
magicoder
csharp
You are tasked with creating a Python script to process a CSV file containing data on product sales. The script should read the CSV file, perform some data manipulation, and generate a report in HTML format using Jinja2 templating. The CSV file contains the following columns: 'Product', 'Category', 'Quantity', and 'Rev...
```python import os import jinja2 import pandas as pd if __name__ == '__main__': PATH = os.path.dirname(os.path.abspath(__file__)) PATH_OUTPUT = 'output' PATH_DATA = 'load_data.csv' if not os.path.exists(PATH_OUTPUT): os.makedirs(PATH_OUTPUT) # Read the CSV file into a pandas DataFrame ...
magicoder
python
You are tasked with optimizing a data processing system that processes large log files in a distributed environment. The system is designed to distribute the log file processing across multiple nodes in a cloud environment. Your goal is to determine the optimal chunk size for processing the log files based on the total...
```python def calculate_optimal_chunk_size(total_size, cloud_size): size = total_size max_line_length = 0 # Initialize max_line_length # Calculate max_line_length and total_size for line in log_file: size = len(line) total_size = total_size + size if size > max_line_length: ...
magicoder
python
You are tasked with implementing a function to retrieve a specific resource bundle within a given iOS framework. The resource bundle is named "EXDevMenu" and has the file extension ".bundle". Your task is to complete the implementation of the `resourcesBundle` function, which should return the resource bundle if found,...
```swift import Foundation class DevMenuUtils { // ... other methods and properties } class YourClass { static func resourcesBundle() -> Bundle? { let frameworkBundle = Bundle(for: DevMenuUtils.self) guard let resourcesBundleUrl = frameworkBundle.url(forResource: "EXDevMenu", withExtension: "bundle") els...
magicoder
swift
You are tasked with implementing a graph data structure using Python classes. Your task is to create a class `Graph` that represents an undirected graph using an adjacency list. The class should have the following methods: 1. `__init__(self, vertices)`: Initializes the graph with a list of vertices. 2. `add_edge(self, ...
```python class Vertex: def __init__(self, label): self.label = label def get_label(self): return self.label class Graph: def __init__(self, vertices): self.adj_list = {v: [] for v in vertices} def add_edge(self, u, v): self.adj_list[u].append(v) self.adj_list...
magicoder
python
You are tasked with implementing a custom exception handling mechanism for a simple file processing application. The application is expected to read data from a file, perform some operations, and then write the results to another file. Your task is to create a custom exception class and modify the given code snippet to...
```cpp #include <iostream> #include <fstream> #include <string> #include <exception> class FileProcessingException : public std::exception { private: std::string message; public: FileProcessingException(const std::string& msg) : message(msg) {} const char* what() const noexcept override { return ...
magicoder
cpp
You are tasked with creating a Python decorator that tracks the names of test classes and their corresponding test methods within a testing framework. The code snippet provided is a partial implementation of this decorator. Your goal is to complete the implementation of the `wrap` function to achieve the desired functi...
```python def wrap(): global TEST_CLASS_NAME_GAME3 with describe("Game3"): TEST_CLASS_NAME_GAME3 = locals()["test_class"].__name__ @it("hoge") def _(self): # Implement the test method "hoge" functionality here pass # Placeholder for the test method ...
magicoder
python
You are tasked with creating a program that analyzes a given text file to count the occurrences of specific words. The program should read the text file, count the occurrences of each word, and then display the word count for each unique word in the file. Your task is to implement a function `count_word_occurrences(fi...
```python import re def count_word_occurrences(file_path: str) -> dict: word_count = {} with open(file_path, 'r') as file: for line in file: words = re.findall(r'\b\w+\b', line.lower()) for word in words: if word in word_count: word_count[word...
magicoder
python
You are tasked with creating a script to manage and execute multiple training jobs for a deep learning model using the CUDA framework. The script should handle the execution of training jobs on specific GPU devices, manage logging of training output, and support various hyperparameters for each job. Your task is to im...
```python import subprocess from typing import List, Dict, Any import concurrent.futures def execute_training_jobs(job_configs: List[Dict[str, Any]]) -> None: def execute_job(job_config: Dict[str, Any]) -> None: command = "CUDA_VISIBLE_DEVICES={} {} {} >> {}".format( job_config["CUDA_VISIBLE_DE...
magicoder
python
You are tasked with creating a function that processes a given string containing a range of GitHub stars and imports from a specific JavaScript library. Your function should extract the range of GitHub stars and the imported JavaScript library, and then return them as separate values. The input string will be in the f...
```javascript function processImportString(input) { const starsRegex = /<gh_stars>(\d+-\d+)/; const libraryRegex = /import\s*{\s*([^}]*)\s*}\s*from\s*'([^']*)'/; const starsMatch = input.match(starsRegex); const libraryMatch = input.match(libraryRegex); if (starsMatch && libraryMatch) { const stars = st...
magicoder
javascript
You are working on a machine learning project and need to implement a mini-batch gradient descent algorithm for training a neural network. The dataset you are working with is too large to fit into memory all at once, so you decide to use mini-batches to train the model efficiently. The code snippet provided is a part o...
```python def mini_batch_gradient_descent_update(model_params, batch_data, learning_rate, loss_function) -> dict: batch_x, batch_y = batch_data # Forward pass: compute predictions predictions = neural_network_forward_pass(batch_x, model_params) # Compute the gradient of the loss with respect to the...
magicoder
python
You are tasked with implementing a simplified version of a bank account transfer system. The system should allow for the transfer of funds between two accounts while ensuring that the transfer is atomic and thread-safe. You are provided with a basic `Account` class that represents a bank account and a `transfer` method...
```python import threading class Account: def __init__(self, id, balance): self.id = id self.balance = balance self.lock = threading.Lock() # Create a lock for thread safety def transfer(self, account, amount): with self.lock: # Acquire the lock to ensure atomicity ...
magicoder
python
You are tasked with implementing a module loader for a JavaScript application. The module loader should be able to dynamically import and export modules based on the provided code snippet. Your task is to create a function that takes the code snippet as input and returns a list of all the exported modules. Example: I...
```javascript function extractExportedModules(codeSnippet) { const exportRegex = /export \* from '(.*)';/g; const modules = []; let match; while ((match = exportRegex.exec(codeSnippet)) !== null) { modules.push(match[1]); } return modules; } // Test const codeSnippet = ` export * from './Health'; expor...
magicoder
javascript
You are tasked with implementing a custom exception handling mechanism for a distributed application. The application uses Enterprise JavaBeans (EJB) for business logic and remote method invocation. Your goal is to create a custom exception class and modify the given code snippet to handle this custom exception appropr...
```java else { throw e; } } catch (EJBException e) { throw e; } catch (RemoteException e) { throw e; } catch (CustomAppException e) // Added catch block for CustomAppException { System.out.println("CustomAppException caught: " + e.getMessage()); // Log the exception message // Continue execution or ...
magicoder
java
You are given a function `calc_op(l)` that takes a list of integers `l` as input. The function calculates and returns the total number of operations required to transform each element in the list according to the following rules: - If the element is even, divide it by 2. - If the element is odd, add 1 to it and then di...
```python from typing import List def min_operations_to_zero(l: List[int]) -> int: cnt = 0 for i in range(len(l)): if l[i] % 2 == 0: cnt += l[i]//2 else: cnt += l[i]//2+1 return cnt # Test cases print(min_operations_to_zero([4, 7, 5, 8])) # Output: 6 print(min_oper...
magicoder
python
You are tasked with implementing a TypeScript class that represents a generic data publisher. The class should have specific properties and methods to manage and publish data. Your task is to complete the implementation of the `Publisher` class by adding missing properties and methods based on the given code snippet an...
```typescript type FieldProps<T> = {}; // Placeholder for field properties type type SFieldProperties = {}; // Placeholder for field properties class Publisher { public static API_NAME: string = 'Publisher'; public readonly _TYPE_: string = 'Publisher'; private static _fields: { [P in keyof FieldProps<Publ...
magicoder
typescript
You are tasked with creating a Python script that downloads manifest and metadata for a given bundle from the Data Storage System (DSS) and stores them as separate JSON files. The script should accept the bundle UUID as a command-line argument and save the manifest as `$UUID.manifest.json` and the metadata as `$UUID.me...
```python import argparse import json import logging import os import sys from humancellatlas.data.metadata.api import Bundle from humancellatlas.data.metadata.helpers.dss import download_bundle_manifest, download_bundle_metadata def download_and_store_bundle_metadata(bundle_uuid): try: manifest_filename ...
magicoder
python
You are tasked with creating a program that processes escape sequences in a given string. Escape sequences are used to represent characters that are difficult or impossible to represent directly in a string. For example, the escape sequence "\n" represents a newline character. Your program should be able to handle both...
```python import re def process_escape_sequences(input_string): # Replace \xhh sequences input_string = re.sub(r'\\x([0-9a-fA-F]{2})', lambda x: chr(int(x.group(1), 16)), input_string) # Replace \uhhhh sequences input_string = re.sub(r'\\u([0-9a-fA-F]{4})', lambda x: chr(int(x.group(1), 16)), inpu...
magicoder
python
You are tasked with creating a PHP function that parses a given file and extracts the template name and the sections included in the file. The file will contain PHP code for a WordPress template file, and the function should return an array containing the template name and the sections present in the file. The PHP fil...
```php function parseTemplateFile($filename) { $fileContent = file_get_contents($filename); preg_match('/Template Name: (.*)/', $fileContent, $templateNameMatch); $templateName = trim($templateNameMatch[1]); preg_match_all('/get_template_part\(\'template-parts\/(.*?)\'/', $fileContent, $sectionMatches...
magicoder
php
You are tasked with creating a Python program that utilizes the `logging` module to handle and record various levels of messages. Your program should implement a custom logger that writes messages to both the console and a file. Additionally, the program should demonstrate the usage of different logging levels and the ...
```python import logging # Create a custom logger logger = logging.getLogger('custom_logger') logger.setLevel(logging.DEBUG) # Create handlers console_handler = logging.StreamHandler() file_handler = logging.FileHandler('app.log') # Set the log level for handlers console_handler.setLevel(logging.INFO) file_handler.s...
magicoder
python
You are tasked with creating a program that generates a stock spreadsheet file. The program should include functionality to set various metadata properties and version information for the generated file. Your task is to implement a class or module that allows for setting these properties and version information, and th...
```python class StockSpreadsheetGenerator: def __init__(self): self.metadata = {} self.version_info = {"FileVersion": 0 << 48 | 5 << 32 | 1 << 16, "ProductVersion": 0 << 48 | 5 << 32 | 1 << 16} def set_metadata(self, key, value): self.metadata[key] = value def set_version_info(self...
magicoder
python
You are tasked with implementing a Python class that represents a mathematical space. The class should have the following properties and methods: Properties: - `low`: Returns the lower bound of the space. - `high`: Returns the upper bound of the space. - `n`: Returns the dimensionality of the space. Methods: - `__eq_...
```python class Space: def __init__(self, low, high): self.low = low self.high = high self.dimensionality = len(low) if isinstance(low, (list, tuple)) else 1 @property def low(self): return self._low @low.setter def low(self, value): self._low = value @...
magicoder
python
You are tasked with implementing a Python function that interacts with an external API to retrieve information about user subscriptions. The function should handle authentication using OAuth 2.0 and make a GET request to the API endpoint to fetch subscription data. You are provided with a code snippet that sets up the ...
```python import requests def fetch_subscription_data(subscription_id: str) -> dict: client_id = util.maybe_raise_for_env("GEODB_ADMIN_CLIENT_ID") client_secret = util.maybe_raise_for_env("GEODB_ADMIN_CLIENT_SECRET") server_url = util.maybe_raise_for_env("GEODB_SERVER_URL") oauth_token = dict( ...
magicoder
python
You are given a string containing a series of parentheses. Your task is to write a function to determine if the parentheses are balanced. A string of parentheses is considered balanced if every opening parenthesis has a corresponding closing parenthesis and they are properly nested. For example, the string "((()))" is...
```cpp #include <stack> #include <string> bool isBalancedParentheses(std::string s) { std::stack<char> stack; for (char c : s) { if (c == '(') { stack.push(c); } else if (c == ')') { if (stack.empty() || stack.top() != '(') { return false; } ...
magicoder
cpp
You are tasked with implementing a logging utility that supports different log levels and styles. The provided code snippet is a part of a logging function that handles the formatting and output of log messages. The function takes in a log object containing the log level, message, and additional arguments. It then form...
```javascript function loggingFunction(logObj) { const consoleLogFn = console.log.bind(console); const badge = ''; // Define the badge for the log level const style = ''; // Define the style for the log level if (logObj.level === 'info') { badge = '[INFO]'; style = 'color: blue; font-weight: bold;'; ...
magicoder
javascript
You are working on a parallel computing project that involves distributing data to multiple GPUs. The code snippet provided is a part of a larger program and is responsible for copying a matrix `H` to the memory of multiple GPUs. The function `distribute_H` is a method of the class `M` and is used to distribute the mat...
```cpp #include <iostream> #include <vector> class M { public: void distribute_H(const double* H, int ldH) { // Get the number of GPUs int numGPUs = getNumGPUs(); // Calculate the number of rows to be distributed to each GPU int rowsPerGPU = m / numGPUs; int remainingRows =...
magicoder
cpp
You are given a Python code snippet that populates two containers, `val_data` and `test_data`, with values based on certain indices and samplers. Your task is to understand the code and write a function that simulates the behavior of populating these containers based on the given indices and samplers. The code snippet...
```python def populate_containers(task, val_indices, test_indices, all_samplers, task_map, metric_map, results, val_data, test_data): for container, indices in [(val_data, val_indices), (test_data, test_indices)]: for m, sampling_percent in indices: for sampling in all_samplers: ...
magicoder
python
You are given a SHA-256 hash and the size of a file. Your task is to write a program to verify the integrity of the file by calculating its SHA-256 hash and comparing it with the given hash. If the hashes match and the file size is correct, the program should output "File integrity verified", otherwise it should output...
```python import hashlib import os def verify_file_integrity(file_path, given_hash, given_size): # Calculate the SHA-256 hash of the file with open(file_path, 'rb') as file: file_content = file.read() calculated_hash = hashlib.sha256(file_content).hexdigest() # Get the size of the file ...
magicoder
python
You are tasked with creating a Python class for managing data related to sports models. The class, `SpoortakModelsData`, is responsible for handling the data directory, loading models, and performing data integrity checks. Your task is to implement the methods of this class based on the provided test cases. The class ...
```python import os import pandas as pd class SpoortakModelsData: def __init__(self, data_dir): self.data_dir = data_dir self.models = None self.model_changes = None def load_models(self): models_file = os.path.join(self.data_dir, 'models.csv') if os.path.exists(models_...
magicoder
python
You are working on a bioinformatics project that involves analyzing the diversity of microbial communities using Weighted UniFrac distance. Weighted UniFrac is a method for comparing microbial communities that takes into account the phylogenetic relationships between the organisms present. In this problem, you are give...
```python import pandas as pd from skbio.diversity import beta_diversity from skbio import TreeNode import logging def compute_weighted_unifrac(tested_object, tree): tested_object_instance = beta_diversity("weighted_unifrac", tested_object, tree, validate=False) expected_object_instance = beta_diversity("weigh...
magicoder
python
You are tasked with implementing a function that processes a list of tags from a content management system (CMS) and generates a sitemap for search engine optimization (SEO) purposes. The function should take the following parameters: - `$type` (string): A string representing the type of sitemap to generate. If `$type`...
```php function generateSitemap($type, $pagesizeStr, &$list) { if (!$type || $type == 'tags') { $path = "/addons/cms/sitemap/tags/{$pagesizeStr}page/[PAGE]"; $tagsList = \addons\cms\model\Tag::where('status', 'normal')->field('id,name')->paginate($pagesize, false, ['path' => $path]); $lastPa...
magicoder
php
You are tasked with implementing a function to calculate the precision and recall metrics on the entity level, as well as the 'macro' average on well-defined classes. Precision and recall are commonly used metrics in information retrieval and machine learning to evaluate the performance of a classification algorithm. P...
```python def calculate_precision_recall(predictions, labels): """ Calculate precision and recall metrics on the entity level, as well as the 'macro' average on well-defined classes. Args: predictions (list): List of predicted labels for each instance. labels (list): List of true labels for each in...
magicoder
python
You are given a knapsack problem with a twist. You are given a list of items, each with a weight and a value. Additionally, each item has a limit on the number of times it can be included in the knapsack. Your task is to implement a function `max_value_knapsack` that takes in the following parameters: - `weights`: A l...
```python def max_value_knapsack(weights, values, limits, capacity): n = len(weights) dp = [[0] * (capacity + 1) for _ in range(n + 1)] for i in range(1, n + 1): for j in range(1, capacity + 1): for k in range(min(limits[i - 1], j // weights[i - 1]) + 1): dp[i][j] = max(...
magicoder
python
You are tasked with creating a program that analyzes a given text file to count the occurrences of specific words. The program should read the text file, tokenize the words, and then count the occurrences of each word. However, the program should exclude any words that appear in a list of common stop words. The stop wo...
```python import re def count_words(filename, stop_words_file): with open(stop_words_file, 'r') as stop_file: stop_words = stop_file.read().split() with open(filename, 'r') as file: text = file.read().lower() words = re.findall(r'\b\w+\b', text) word_count = {} for wor...
magicoder
python
You are tasked with implementing a file upload endpoint for a web application using Python and Flask. The endpoint should handle the upload of template files, perform validation on the uploaded file, and extract the user ID from the request form data. Your task is to complete the implementation of the `upload_template...
```python from flask import Blueprint, request, jsonify from app import app from app.helper import allowed_file from app.middleware import param_required from app.modules.templates.schema import TemplateUploadSchema from app.services.open_cv import CVImage template_blueprint = Blueprint('template_blueprint', __name__)...
magicoder
python
You are tasked with creating a program that reads a text file and counts the occurrences of each word in the file. Your program should ignore punctuation and consider words with different capitalizations as the same word. For example, "Apple" and "apple" should be considered the same word. Your program should then disp...
```python import re def count_word_frequency(file_name): word_count = {} with open(file_name, 'r') as file: content = file.read().lower() words = re.findall(r'\b\w+\b', content) for word in words: if word in word_count: word_count[word] += 1 else:...
magicoder
python
You are tasked with implementing a custom exception class in C#. The exception class, named `CustomException`, should inherit from the `Exception` class and have two constructors. The first constructor should take a single parameter, `paramName`, representing the name of the parameter that caused the exception. The sec...
```csharp using System; public class CustomException : Exception { // Implement the first constructor public CustomException(string paramName) : base($"Exception caused by parameter: {paramName}") { } // Implement the second constructor public CustomException(string paramName, string message) ...
magicoder
csharp
You are given a file named `passwords.txt`, where each line contains the following information: an acceptable range, a letter, and a password. The acceptable range defines the minimum and maximum number of times the given letter must appear in the password for it to be considered valid. For example, `1-3 a: abcde` mean...
```python def count_valid_passwords(file_name): matches = 0 with open(file_name, 'r') as file: for line in file: acceptable_range, letter, password = line.split(" ") low, high = acceptable_range.split("-") count = password.count(letter[0]) if count in rang...
magicoder
python
You are tasked with implementing a function that inverts a given color and optionally amplifies the inversion to black or white based on a luminance threshold. The function `asRgbArray` takes two parameters: `color` of type `Color` and `bw` of type `BlackWhite` or `boolean`, and returns an RGB array representation of t...
```javascript /** * Represents a color in RGB format. * @typedef {number[]} Color */ /** * Represents a black or white color customization. * @typedef {Object} BlackWhite * @property {Color} black - Custom black color in RGB format. * @property {Color} white - Custom white color in RGB format. */ /** * Repre...
magicoder
javascript
You are working on a tool to deodex Android application files. Deodexing involves converting .odex files back to .dex files, which can then be converted to .smali files for further analysis. Your task is to write a Python function that takes a list of odex file paths as input and performs the necessary deodexing operat...
```python import os import sys def deodex_files(odex_files, tempdir, dirname2): deodexed_files = [] for odex_file in odex_files: basename = os.path.basename(odex_file) archive_file = os.path.join(dirname2, basename + '.jar') if os.path.exists(archive_file): print("Deodexing ...
magicoder
python
You are tasked with creating a Python script to simulate a simple load testing scenario using The Grinder, a popular open-source load testing framework. The Grinder allows you to run multiple instances of your test script in parallel, simulating a large number of users accessing your application simultaneously. In this...
```python # Import necessary modules from The Grinder framework from net.grinder.script.Grinder import grinder from net.grinder.script import Test # Define the test method to send an HTTP request and measure response time class TestRunner: def __init__(self): self.test = Test(1, "HTTP Request test") d...
magicoder
python
You are tasked with implementing a module system for a front-end web application. The application uses a tooltip component to display information when users hover over certain elements. The tooltip component is composed of several sub-components, each responsible for a specific part of the tooltip's content. The code s...
```javascript // Tooltip.js import TooltipTitle from './TooltipTitle'; import TooltipText from './TooltipText'; import TooltipUL from './TooltipUL'; import TooltipListItem from './TooltipListItem'; export const Tooltip = () => { // Tooltip component implementation }; // App.js import { Tooltip, TooltipTitle, Toolti...
magicoder
javascript
You are tasked with implementing a custom metadata reference class for a language compilation system. The provided code snippet is a part of the implementation for the `LanguageCompilationReference` class, which extends a base `CompilationReference` class. Your goal is to complete the implementation of the `LanguageCom...
```csharp using System; using Microsoft.CodeAnalysis; public class LanguageCompilationReference : CompilationReference { public LanguageCompilation Compilation { get; } public LanguageCompilationReference(LanguageCompilation compilation, MetadataReferenceProperties properties) : base(properties) {...
magicoder
csharp
You are tasked with implementing a file management system in Swift. Your goal is to create a class `FileManager` with three methods: `createFile`, `deleteFile`, and `updateFile`. The `createFile` method should create a new file at the specified path, the `deleteFile` method should delete the file at the specified path,...
```swift struct Path { let pathString: String } class FileManager { func createFile(at path: Path) throws { // Implementation to create a new file at the specified path // Example: FileManager.default.createFile(atPath: path.pathString) } func deleteFile(at path: Path) throws { ...
magicoder
swift
You are tasked with creating a Rust program that manages a connection pool to a PostgreSQL database. The program should utilize the `r2d2` and `tokio-postgres` crates to achieve this. The connection pool should be configured with a maximum size and a minimum number of idle connections. Your task is to implement the nec...
```rust use tokio_postgres::NoTls; use r2d2::Pool; use r2d2_postgres::PostgresConnectionManager; #[tokio::main] async fn main() { let max_con = 10; // Maximum size of the connection pool let min_con = 5; // Minimum number of idle connections // Connect to db let manager = PostgresConnectionManager::n...
magicoder
rust
You are tasked with creating a script to automate the compilation process for a project. The project consists of several C source files that need to be compiled with specific compiler flags and options. Your script should be able to compile the source files and generate the executable files with the appropriate optimiz...
```bash #!/bin/sh # Compile denoise.c, kiss_fft.c, pitch.c, and celt_lpc.c gcc -DTRAINING=1 -Wall -W -O3 -g -I../include denoise.c kiss_fft.c pitch.c celt_lpc.c -o dump_data -lm # Compile lpcnet.c, nnet.c, and nnet_data.c gcc -o test_lpcnet -mavx2 -mfma -g -O3 -Wall -W -Wextra lpcnet.c nnet.c nnet_data.c -lm ``` The...
magicoder
shell
You are working on a sentiment analysis tool that processes user comments and extracts aspects, sentiment scores, and opinions associated with each aspect. The code snippet provided is a part of a Python HTTP trigger function that processes a request containing user comments and returns a JSON object containing the asp...
```python from typing import List, Tuple, Dict def process_comments(comments: List[str]) -> Tuple[int, Dict[str, Tuple[int, str, List[str]]]]: reviews = {} total_comments = 0 for comment in comments: # Process each comment to extract aspects, sentiment scores, and opinions # Your implement...
magicoder
python
You are tasked with creating a script to automate the setup process for a new user on a Linux system. The script should perform the following tasks: 1. Add the user to the 'iocard' and 'dialout' groups using the `usermod` command. 2. Update the user's `.bashrc` file to include additional environment variables and sour...
```bash #!/bin/bash # Add user to 'iocard' and 'dialout' groups sudo usermod -a -G iocard $USER sudo usermod -a -G dialout $USER # Update .bashrc file with additional environment variables and source a configuration file echo 'export PYTHONPATH=$PYTHONPATH:$HOME/code/robotics' >> $HOME/.bashrc echo 'export BMI3D=/hom...
magicoder
shell
You are tasked with creating a program that simulates a simple banking system. The program should allow users to create accounts, log in, deposit money, withdraw money, and view their balance. Each account should have a unique account number and a corresponding balance. The program should also store the account informa...
```java import java.util.HashMap; import java.util.Map; import java.util.Random; class Account { private static Map<Integer, Account> accounts = new HashMap<>(); private int accountNumber; private double balance; public Account(double initialBalance) { this.accountNumber = generateAccountNumbe...
magicoder
java
You are tasked with creating a Rust macro that generates code for defining shape systems for icons in a graphics library. The macro should take in parameters for style, strong color, and weak color, and then define the shape system for the icon based on these parameters. Your task is to implement the macro `define_shap...
```rust macro_rules! define_shape_system { (($style:ident: Style, $strong_color:ident: Vector4, $weak_color:ident: Vector4) { $($shapes:tt)* }) => { mod icon_shape_system { use super::*; pub struct $style; pub struct $strong_color; pub struct $weak_color; ...
magicoder
rust
You are tasked with implementing a custom Jupyter magic command that calculates the execution time of a given code cell and prints the result. The magic command should be named `timeit` and should be used as follows: ```python %%timeit # Your code here ``` When the `%%timeit` magic command is used, it should measure ...
```python from IPython.core.magic import register_cell_magic import time @register_cell_magic def timeit(line, cell): start_time = time.time() exec(cell) end_time = time.time() execution_time = (end_time - start_time) * 1000 # Convert to milliseconds print(f"Execution time: {execution_time:.2f} ms...
magicoder
python
You are tasked with implementing a neural network loss function for a reconstruction task. The given code snippet is part of a larger neural network implementation and involves the calculation of a reconstruction loss using the `reconstruction_loss` function. The `zt_bar` variable is obtained by passing `zt_mid` throug...
```python # Import necessary libraries import torch # Define the reconstruction_loss function def reconstruction_loss(zt_, zt_bar, decoder_dist): if decoder_dist == 'gaussian': # Calculate reconstruction loss for Gaussian distribution recon_loss = torch.mean((zt_ - zt_bar)**2) elif decoder_dist...
magicoder
python
You are given a vector of characters representing the movements of children on a playground. Each character in the vector represents the direction in which a child moves: 'R' for right and 'L' for left. The children start at the same point on the playground and move in the specified directions. When two children meet, ...
```cpp #include <vector> #include <algorithm> int maxPairsFormed(const std::vector<char>& input) { int countR = 0, countL = 0; for (char direction : input) { if (direction == 'R') { countR++; } else { countL++; } } return std::min(countR, countL); } ``` ...
magicoder
cpp
You are tasked with creating a class for an online learning platform that allows users to watch courses in different languages and gain skills. Your task is to implement the methods `watch_course` and `change_language` for the `User` class. The `User` class has the following attributes: - `name`: a string representing...
```python class User: def __init__(self, name, language, skills): self.name = name self.language = language self.skills = skills def watch_course(self, course_name, language, skills_earned): if not self.language == language: return f"{self.name} does not know {langua...
magicoder
python
You are tasked with implementing a simplified version of a component mixin system for a game engine. The provided code snippet is a part of a C++ library for entity-component systems (ECS) called "flecs". In ECS, entities are defined by their components, and systems operate on entities based on the components they poss...
```cpp #include <iostream> #include <string> #include <vector> // Simplified Component class representing a component in an ECS template <typename T> struct Component { T value; Component(T val) : value(val) {} }; // Simplified World class representing the ECS world class World { public: // Method to cre...
magicoder
cpp
You are working on a project that involves processing video frames and extracting information from images. You have a video file named "out.mp4" and a set of test images in the "test-images" directory. Your task is to write a script that extracts frames from the video, saves them as individual images in a directory nam...
```python import subprocess import os # Step 1 - Extract frames from the video video_file = "out.mp4" output_directory = "output-images" if not os.path.exists(output_directory): os.makedirs(output_directory) extract_frames_command = f"ffmpeg -i {video_file} -r 1 {output_directory}/%d.png" subprocess.run(extract_f...
magicoder
python
You are tasked with creating a program that retrieves the top GitHub repositories based on the number of stars within a specified range. Your program should utilize the GitHub API to fetch repository data and then display the repository names and their corresponding star counts. Additionally, the program should allow t...
```python import requests def fetch_github_repositories(min_stars, max_stars): url = f"https://api.github.com/search/repositories?q=stars:{min_stars}..{max_stars}&sort=stars&order=desc" response = requests.get(url) if response.status_code == 200: data = response.json() repositories = data['...
magicoder
python
You are tasked with implementing a class that manages user accounts in a web application. The class, named `UserAccount`, should have the following public methods: 1. `getRealm()`: This method should return the realm to which the user account belongs as a string. 2. `getId()`: This method should return the unique ide...
```java public class UserAccount { private String realm; private String id; public UserAccount(String realm, String id) { this.realm = realm; this.id = id; } public String getRealm() { return realm; } public String getId() { return id; } public voi...
magicoder
java
You are working on a project that involves parsing and analyzing JSON objects. Your task is to implement a function that takes a JSON object as input and returns a parsed representation of the object. The parsed representation should include information about the structure of the object and the values it contains. You...
```typescript import { JSONValueType, inferType } from '@jsonhero/json-infer-types'; import { WildcardPathComponent } from '@jsonhero/path/lib/path/wildcard-path-component'; import { ParsedObject, StructureCollection, StructureInfo, ValueCollection, ValueInfo } from './structure'; import { friendlyName } from './naming...
magicoder
typescript
You are tasked with creating a program to process histogram data from a file and generate a JSON representation of the histograms. The histograms are represented as objects with a name and parameters. Each parameter consists of a name and a table mapping different types to their corresponding values. The types include ...
```python import json def generate_histogram_json(filename): all_histograms = {"histograms": []} with open(filename, 'r') as file: lines = file.readlines() histogram_data = [line.strip() for line in lines if line.strip()] i = 0 while i < len(histogram_data): histogram = {"name...
magicoder
python
You are tasked with implementing a custom serialization macro for a Rust struct. The struct, `OneOf`, represents a validation state and contains a path as a string and a list of validation states. The goal is to create a custom serialization implementation for the `OneOf` struct using the `impl_serialize!` macro. Your...
```rust impl_serialize!(OneOf, |err: &OneOf, map: &mut ::serde_json::Map<String, Value>| { let states: Vec<_> = err.states.iter().map(|state| to_value(state).unwrap()).collect(); map.insert("states".to_string(), to_value(states).unwrap()); }); ``` In the solution, the `impl_serialize!` macro is implemented for...
magicoder
rust
You are tasked with implementing a function that parses a given JSON object and returns a list of all the keys present in the object. The JSON object may contain nested objects and arrays, and the function should be able to handle these nested structures to extract all the keys present. You are given a code snippet re...
```python from typing import List def extract_keys(json_obj: dict) -> List[str]: keys = [] for key, value in json_obj.items(): keys.append(key) if isinstance(value, dict): keys.extend(extract_keys(value)) elif isinstance(value, list): for item in value: ...
magicoder
python
You are tasked with creating a script to automate the compilation and encryption of Python files. The script should take a list of directories containing Python files, compile them into bytecode files, and then encrypt the compiled bytecode files. You are given a code snippet that partially accomplishes this task. The...
```bash encrypted_pyc_files="" while IFS= read -r pyc_file; do encrypted_file="${pyc_file%.pyc}.encrypted" openssl enc -aes-256-cbc -salt -in "$pyc_file" -out "$encrypted_file" encrypted_pyc_files+="$(basename "$encrypted_file")"$'\n' done <<< "$to_be_encrypted_pyc_files" echo "$encrypted_pyc_files" ``` In the ...
magicoder
shell
You are tasked with creating a test case for a bot project using TypeScript and the Jest testing framework. The code snippet provided sets up a mock location reference and a bot project instance for testing. Your goal is to write a test case that ensures the proper indexing of the bot project. Write a test case using ...
```typescript import * as Path from 'path'; import { BotProject, LocationRef } from 'botbuilder'; const botDir = '../../mocks/samplebots/bot1'; const mockLocationRef: LocationRef = { storageId: 'default', path: Path.join(__dirname, `${botDir}`), }; const proj = new BotProject(mockLocationRef); beforeEach(async ...
magicoder
typescript
You are tasked with implementing a custom data structure in C# that mimics the behavior of a stack but with an added feature to efficiently retrieve the minimum element in the stack at any given time. You need to design a class `MinStack` that supports the following operations: 1. `Push(int x)`: Add element `x` to the ...
```csharp #nullable enable using System; using System.Collections.Generic; namespace System.Data { public class MinStack { private Stack<int> stack; private Stack<int> minStack; public MinStack() { stack = new Stack<int>(); minStack = new Stack<int>(); ...
magicoder
csharp
You are given a 2D grid represented by a 2D array of characters. The grid contains players denoted by different characters, and each player has a specific direction (up, down, left, or right) denoted by '^', 'v', '<', or '>'. The players can move within the grid in their respective directions. Write a function or meth...
```python def movePlayers(grid, players, movements): directions = {'^': (-1, 0), 'v': (1, 0), '<': (0, -1), '>': (0, 1)} rows, cols = len(grid), len(grid[0]) for i, (player, (x, y), direction) in enumerate(players): dx, dy = directions[direction] for move in movements: if move =...
magicoder
python
You are tasked with creating a Python function to process and update COVID-19 data for the city of Frankfurt. The function is part of a larger system that interacts with Google Sheets to update the data. The provided code snippet contains a part of the function that processes the COVID-19 data and updates the Google Sh...
```python import datetime class NotYetAvailableException(Exception): pass class Task: def __init__(self, *args): self.args = args def force_int(value): try: return int(value.replace("\xa0", "")) except ValueError: return 0 def check_date(date, city, timedelta): # Implemen...
magicoder
python
You are tasked with implementing a function that processes an array of items asynchronously and updates the state with the processed items. The function should follow a specific set of rules for processing the items and updating the state. You are given the following code snippet as a starting point: ```javascript as...
```javascript async function name() { set([]) let items = [] // Simulating asynchronous processing of items for (let item of items) { // Perform a specific asynchronous operation on each item let processedItem = await processItemAsync(item); // Update the state by addin...
magicoder
javascript
You are tasked with implementing a custom error type for a file compression library in Rust. The error type should support various error cases related to file I/O, version compatibility, sync marker mismatch, end of file, and unsupported compression codecs. Your task is to define the custom error type and implement the...
```rust use std::fmt; use std::io; // Define the custom error type #[derive(Debug)] enum CompressionError { IO(io::Error), VersionNotSupported(String), SyncMarkerMismatch, EOF, CompressionTypeUnknown(String), UnsupportedCodec(String), } // Implement the Display trait to provide human-readable ...
magicoder
rust
You are tasked with designing a simplified interface for querying and retrieving documents from a content management system. The interface provides methods for constructing queries, retrieving individual documents by ID or slug, and executing queries to retrieve multiple documents. Your goal is to implement the core fu...
```csharp using System; using System.Threading.Tasks; using System.Globalization; public interface ISanityDocument { // Define properties and methods common to all document types } public interface IQueryBuilder<T> { // Define methods for constructing queries } public class QueryResponse<T> { // Define t...
magicoder
csharp
You are given a simple code snippet that represents a nested structure. The snippet consists of a series of "done" statements, each indented to a certain level. The indentation level indicates the depth of nesting. Your task is to write a program that can determine the maximum depth of nesting in this structure. Write...
```python def maxNestingDepth(s): max_depth = 0 current_depth = 0 for char in s: if char == ' ': current_depth += 1 else: max_depth = max(max_depth, current_depth // 2) current_depth = 0 return max_depth ``` The `maxNestingDepth` function iterates thr...
magicoder
python
You are tasked with implementing a C++ class hierarchy for a board game. The game involves different types of pieces that can be placed on a board. The provided code snippet is a part of the class hierarchy for the game pieces. Your task is to complete the implementation of the `RightQuail` class and its constructor. ...
```cpp #include "StaticDyamicPatternPiece.hpp" class RightQuail : public StaticPatternPiece { public: // ========================================================================== // Construction // ========================================================================== RightQuail(Board* board, int valu...
magicoder
cpp
You are tasked with implementing a temporary file manager in Python. The `TempFileManager` class should provide functionality to create, read, write, and delete temporary files. Additionally, it should support the ability to list all existing temporary files and clear all temporary files from the system. Your task is ...
```python import tempfile import os class TempFileManager: def __init__(self): self.temp_files = [] def create_temp_file(self): temp_file = tempfile.NamedTemporaryFile(delete=False) self.temp_files.append(temp_file.name) return temp_file.name def read_temp_file(self, file_...
magicoder
python
You are tasked with creating a Python function that processes files within a given directory. The function should identify all the text files within the directory and its subdirectories, and then count the total number of lines across all the text files. You are provided with a code snippet that uses the `os` module to...
```python import os def count_text_file_lines(directory_path): total_lines = 0 for root, _, files in os.walk(directory_path): for file in files: file_path = os.path.join(root, file) if file_path.endswith('.txt'): with open(file_path, 'r', encoding='utf-8') as f: ...
magicoder
python
You are tasked with implementing a password dumping utility for a system that stores passwords with a salt. The given code snippet is part of a larger program that is responsible for finding and displaying the salt used for password hashing. Your task is to complete the `dump_password` function, which should extract th...
```python def dump_password(input_string): # Extracting salt and password from the input_string salt_start = input_string.find('Salt:') + len('Salt:') salt_end = input_string.find('Password:') salt = input_string[salt_start:salt_end].strip() password_start = input_string.find('Password:') + len('Pa...
magicoder
python
You are tasked with developing a Python script to parse a label map file and extract relevant information from it. The label map file is in the Protobuf format and contains definitions of object detection labels. Each label has an ID and a display name associated with it. Your task is to write a function that reads the...
```python import re def parse_label_map(label_map_path): label_map = {} with open(label_map_path, 'r') as file: content = file.read() items = re.findall(r'item\s*{\s*id:\s*(\d+)\s*name:\s*\'([^\']+)\'\s*}', content) for item in items: label_map[int(item[0])] = item[1] re...
magicoder
python
You are tasked with implementing a Java class that can parse and manipulate JSON payloads. Your task is to create a class `JsonPayloadParser` with the following requirements: 1. The class should be in the package `com.juliaaano.payload.json`. 2. It should have a method `parsePayload` that takes a JSON payload as a `St...
```java package com.juliaaano.payload.json; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.Map; public class JsonPayloadParser { private final ObjectMapper objectMapper; public JsonPayloadParser() { ...
magicoder
java
You are tasked with creating a program that analyzes a given software license text to extract and display the permissions and conditions specified within it. The license text is structured in a specific format, with permissions and conditions listed in a standardized manner. The license text is structured as follows: ...
```python def extract_permissions_conditions(license_text): permissions = [] conditions = [] current_permission = '' current_condition = '' lines = license_text.split('\n') for line in lines: if line.startswith('# '): if current_permission: permissions.ap...
magicoder
python
You are tasked with implementing a method to perform a 3D translation on a given set of 3D points using a translation matrix. The translation matrix is represented as a 1D array of 16 floating-point numbers. Each group of 4 consecutive elements in the array represents a row of the 4x4 translation matrix. The translatio...
```java public class TranslationHelper { public static float[] translatePoints(float[] points, float[] translateMatrix) { float[] translatedPoints = new float[points.length]; for (int i = 0; i < points.length; i += 3) { float x = points[i]; float y = points[i + 1]; ...
magicoder
java
You are tasked with implementing a custom data sampler for a machine learning model. The sampler is responsible for generating batches of data from a dataset. Your task is to create a class `CustomSampler` that implements the following functionality: - The class should be initialized with the following parameters: -...
```python class CustomSampler: def __init__(self, sampler, batch_size, n_batches=None, store_dataset=False): self.sampler = sampler self.batch_size = batch_size self.n_batches = n_batches self.store_dataset = store_dataset self.current_batch = 0 self.dataset = None ...
magicoder
python
You are tasked with simulating a USB bulk transfer process in Python. You are given a code snippet that uses the `ctypes` library to interact with a USB device. Your goal is to implement a function that simulates the bulk transfer process and handles potential errors. You need to create a Python function `simulate_bul...
```python import ctypes as ct def simulate_bulk_transfer(handle, endpoint_in, buffer, READ_CAPACITY_LENGTH): def err_exit(error_code): # Placeholder for error handling logic return f"Error: {error_code}" size = ct.c_int() r = usb.bulk_transfer(handle, endpoint_in, ct.cast(ct.pointer(buffer...
magicoder
python
You are given a list of intervals, where each interval is represented as a pair of integers `[start, end]`. The intervals are sorted based on their start values. Your task is to merge overlapping intervals and return a new list of non-overlapping intervals. Write a function `merge_intervals(intervals)` that takes in a...
```python def merge_intervals(intervals): if not intervals: return [] intervals.sort(key=lambda x: x[0]) # Sort the intervals based on start values merged = [intervals[0]] # Initialize the merged list with the first interval for interval in intervals[1:]: if interval[0] <= me...
magicoder
python
You are tasked with creating a script to automate the process of running a Java program with the necessary classpath and options. Your script should handle the absence of a required file and construct the classpath dynamically. Given the provided code snippet as a starting point, create a Bash script that accomplishe...
```bash #!/bin/bash # Check if classpath.txt exists if [ ! -f classpath.txt ]; then echo "classpath.txt not found: Run scripts/build.sh first." exit 1 fi # Read classpath.txt and construct the classpath CP=$(cat classpath.txt):$HASHURIJAVADIR/$(ls target/hashuri-*.jar) # Change directory to $DIR cd $DIR # Run t...
magicoder
shell
You are tasked with creating a Python script to manage webhooks for a chat application. The script should be able to add, delete, and list webhooks for a specific chat room using the HipChat API. Your script should have the following functionalities: 1. Add a webhook to a specific chat room. 2. Delete a webhook from a...
```python import requests import json base_url = "https://api.hipchat.com/v2/room/" room_id = "552648" webhook_url = base_url + room_id + "/webhook" auth_token = "<YOUR_AUTH_TOKEN>" def add_webhook(url, data): headers = { "Content-Type": "application/json", "Authorization": "Bearer " + auth_token ...
magicoder
python
You are tasked with implementing a Python class method that processes label data for a machine learning model. The method is responsible for converting azimuth and elevation angles to Cartesian coordinates and handling default values for the Cartesian coordinates. The method receives a 3D array `label` representing th...
```python import numpy as np class LabelProcessor: def __init__(self, azi_only, nb_classes, xyz_def_zero, default_ele): self._azi_only = azi_only self._nb_classes = nb_classes self._xyz_def_zero = xyz_def_zero self._default_ele = default_ele def _split_in_seqs(self, label): ...
magicoder
python
You are tasked with implementing a file management system that involves setting properties for different file types. The system uses a class `FileInfo` to represent file information. The `FileInfo` class has the following methods: - `setDir(boolean isDir)`: Sets whether the file is a directory or not. - `setType(String...
```java import org.apache.commons.io.FilenameUtils; public class FileInfo { private boolean isDir; private String type; private String uid; public void setDir(boolean isDir) { this.isDir = isDir; } public void setType(String name) { this.type = FilenameUtils.getExtension(name)...
magicoder
java
You are tasked with creating a program that analyzes a given text file to determine the frequency of each word in the file. Your program should read the text file, tokenize the words, and then count the occurrences of each word. Additionally, the program should ignore common stop words (e.g., "the", "and", "is") and sh...
```python import re from collections import Counter def analyze_text(file_name, n): with open(file_name, 'r') as file: text = file.read().lower() words = re.findall(r'\b\w+\b', text) stop_words = {'the', 'and', 'is', 'in', 'of', 'to', 'are', 'by', 'or', 'this', 'a', 'an', 'for', 'on', 'with...
magicoder
python
You are tasked with implementing a point system for a user in a gaming application. The user can earn points through various activities such as completing levels, achieving high scores, and participating in special events. The points earned by the user should be tracked and displayed in their profile. Additionally, the...
```javascript class UserPointsSystem { constructor() { this.totalPoints = 0; } addPoints(points) { this.totalPoints += points; } deductPoints(points) { if (this.totalPoints >= points) { this.totalPoints -= points; } else { console.log("Insufficient points for deduction"); } ...
magicoder
javascript
You are tasked with implementing a custom logging system in Java that filters log messages based on their severity level. The system should allow the user to set a minimum severity level, and only log messages with a severity level greater than or equal to the minimum should be displayed. Your task is to implement the...
```java import java.util.logging.Level; import java.util.logging.Logger; public class CustomLogger { private SeverityLevel minSeverityLevel; public CustomLogger(SeverityLevel minSeverityLevel) { this.minSeverityLevel = minSeverityLevel; } public void log(SeverityLevel severity, String message...
magicoder
java
You are tasked with creating a Rust macro that modifies the behavior of a given function. The macro should take a function as input and return a modified version of the function that operates on a mutable reference to a `ByteQue` and returns a `ByteQue`. The `ByteQue` type represents a queue of bytes. Your task is to ...
```rust use proc_macro::TokenStream; use quote::quote; use syn::{parse_macro_input, ItemFn}; #[proc_macro] pub fn format_function(input: TokenStream) -> TokenStream { let input_fn = parse_macro_input!(input as ItemFn); let fn_name = &input_fn.sig.ident; let fn_block = &input_fn.block; let modified_fn...
magicoder
rust
You are tasked with creating a function that determines whether an operand needs brackets when used in an expression with a given order of operations. The function should take into account the order of operations (BODMAS/BIDMAS) and an explicit flag used in the case of multiplication to distinguish between implicit and...
```python def needs_brackets(operand, order, explicit): # Define the precedence of operators based on the given order precedence = {'B': 0, 'O': 1, 'D': 2, 'M': 3, 'A': 4, 'S': 5} # Check if the operand is a single variable or a complex expression if len(operand) == 1: return False # Single va...
magicoder
python
You are tasked with implementing a function that manipulates array subset configurations. An array subset configuration is defined by the following interface: ```typescript interface ArraySubsetConfig { items: Set<any>; maxItems: number; minItems: number; } ``` The function `complementArraySubsetConfig` t...
```typescript const complementArraySubsetConfig = (config: ArraySubsetConfig): ArraySubsetConfig[] => { const allJsonSet: Set<any> = new Set(); // Assume this set is predefined const defaultMinItems: number = 0; // Assume this value is predefined const defaultMaxItems: number = 100; // Assume this value is...
magicoder
typescript
You are working on a project that involves training a neural network for binary classification using PyTorch. You have decided to use the Binary Cross Entropy (BCE) loss function for this task. However, you want to gain a deeper understanding of how the BCE loss is calculated and implemented in PyTorch. Your task is t...
```python import torch def custom_bce_loss(x, y): epsilon = 1e-12 # Small value to prevent numerical instability x = torch.clamp(x, epsilon, 1 - epsilon) # Clamp x to avoid taking the log of 0 or 1 loss = -torch.mean(y * torch.log(x) + (1 - y) * torch.log(1 - x)) # Calculate BCE loss return loss ```...
magicoder
python
You are tasked with implementing a Python function that simulates a simplified version of a task runner. The task runner is responsible for executing shell commands and managing dependencies between tasks. You are given a code snippet that includes a function `shell(args)` and a decorator `@task`. The `shell` function...
```python import shlex import os class TaskRunner: def __init__(self): self.tasks = {} self.executed = set() def run(self): for task in self.tasks: self._execute_task(task) def _execute_task(self, task): if task in self.executed: return depe...
magicoder
python