query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with implementing a simple string calculator that can evaluate arithmetic expressions in a given string. The calculator should support addition, subtraction, multiplication, and division operations, as well as parentheses for grouping expressions. The input string will consist of numbers, arithmetic oper...
```rust use std::collections::VecDeque; fn evaluate(expression: &str) -> i32 { let tokens = tokenize(expression); let postfix = infix_to_postfix(tokens); evaluate_postfix(postfix) } fn tokenize(expression: &str) -> Vec<String> { // Implement tokenization logic to split the expression into individual t...
magicoder
rust
You are tasked with implementing a simple thread scheduling algorithm for a concurrent program. The provided code snippet includes a function `thread_yield` and a function `mutator_resume`. The `thread_yield` function is responsible for yielding the current thread's execution, while the `mutator_resume` function is use...
```rust use std::sync::{Arc, Mutex}; use std::thread; use std::sync::atomic::{AtomicUsize, Ordering}; static GC_INSIDE_COLLECT: AtomicUsize = AtomicUsize::new(0); struct ThreadData { id: usize, attempts: usize, } fn thread_yield(data: &Arc<Mutex<ThreadData>>) { let mut thread_data = data.lock().unwrap();...
magicoder
rust
You are tasked with creating a script to automate the process of adding a new X display authorization entry. The script should take the current display information, modify it, and then merge it back into the X authority file. Your script should perform the following steps: 1. Use the `xauth` command to retrieve the cu...
```bash #!/bin/bash # Step 1: Retrieve current authorization information current_auth=$(xauth nlist $DISPLAY) # Step 2: Modify the retrieved authorization information modified_auth=$(echo "$current_auth" | sed -e 's/^..../ffff/') # Step 3: Merge the modified authorization information into the X authority file echo "...
magicoder
shell
You are tasked with creating a function that retrieves a specified number of entries from the Qiita API and processes the data to extract relevant information. The Qiita API returns an array of objects, each representing an entry with properties such as name, private, updated_at, and url_name. Your task is to implement...
```javascript async function getProcessedQiitaEntries(limit = 100) { try { const response = await fetch(`https://qiita.com/api/v2/items?per_page=${limit}`); const data = await response.json(); const processedEntries = data.map(entry => { return { name: entry.name, updated_at: en...
magicoder
javascript
You are tasked with implementing a function that parses a given input representing a data structure and extracts specific information from it. The input is in the form of a JavaScript object, and the goal is to extract all the keys and their corresponding data types from the object. You need to write a function `extra...
```javascript function extractDataTypes(input) { const result = {}; for (const key in input) { if (input.hasOwnProperty(key)) { const value = input[key]; if (typeof value === "object") { if (Array.isArray(value)) { result[key] = "array"; } else { result[key] = "ob...
magicoder
javascript
You are tasked with creating a program to validate properties of definitions in a software system. Each definition has a set of expected properties, and the program needs to compare these expected properties with the actual properties of the definition. The code snippet provided is a part of the validation process and ...
```java import org.assertj.core.api.SoftAssertions; import java.util.Map; public class DefinitionValidator { public void validateDefinitionProperties(String definitionName, Map<String, Property> expectedDefinitionProperties, Map<String, Property> actualDefinitionProperties) { SoftAssertions softAssertions...
magicoder
java
You are tasked with implementing a data retrieval system for a SQL database. The system should support filtering of data based on a set of filter statements and retrieval of annotations associated with specific indices. You are provided with a Python abstract class `SqlDataRetriever` which defines two abstract methods...
```python import abc from typing import List, Any, Dict from galleries.annotations_filtering.filter import FilterStatement import sqlite3 class ConcreteDataRetriever(SqlDataRetriever): def __init__(self, db_path: str): self.db_path = db_path def get_indices(self, cursor, filters: List[List[FilterStat...
magicoder
python
You are tasked with creating a function that parses a given Swift package manifest file and extracts the names of the libraries and their corresponding targets. The Swift package manifest file is written in Swift Package Manager's Package.swift format, which contains information about the package's name, products, depe...
```swift func parsePackageManifest(_ packageSwiftContent: String) -> [String: [String]] { var libraryTargets: [String: [String]] = [:] // Extracting products section from the package.swift content if let productsRange = packageSwiftContent.range(of: "products: [") { let productsSubstring = packageS...
magicoder
swift
You are tasked with creating a syntax highlighting feature for a code editor. The editor should be able to recognize and colorize different elements of a programming language, such as keywords, comments, and punctuation. Your task is to implement a function that takes a code snippet as input and returns a list of tuple...
```python from typing import List, Tuple import re def syntax_highlight(code: str) -> List[Tuple[str, str]]: tokens = [] # Define regular expressions and token types for different elements rules = [ (r'[()\[\]\{\},.;<>@]', 'Punctuation'), (r'(\n|\s)+', 'Text'), (r'/\*.*?\*/', 'Comme...
magicoder
python
You are tasked with creating a Python script that simulates a simple banking system. The script should be able to handle basic banking operations such as account creation, deposit, withdrawal, and balance inquiry. Your task is to implement a Python class called `BankAccount` that represents a bank account. The class s...
```python class BankAccount: def __init__(self, account_number, account_holder, initial_balance): self.account_number = account_number self.account_holder = account_holder self.balance = initial_balance def deposit(self, amount): if amount > 0: self.balance += amount...
magicoder
python
You are tasked with implementing a function to calculate the aberration terms for a given wavelength in a simulated detector system. The aberration terms are approximated for wavelengths falling outside the specified range. Your task is to create a Python function that accurately handles out-of-bound wavelengths by app...
```python def get_aberration_terms(wavelength): available_wavelengths = [2e-6, 3e-6, 4e-6, 5e-6] # Available wavelengths for aberration terms aberration_terms = { 2e-6: [0.01, 0.02, 0.01], 3e-6: [0.015, 0.025, 0.012], 4e-6: [0.018, 0.03, 0.014], 5e-6: [0.02, 0.03, 0.015] } ...
magicoder
python
You are tasked with implementing a logging system for a software application. The system should support different levels of logging, such as INFO, WARNING, and ERROR. Additionally, the system should allow for the use of proxies to handle the logging process. The code snippet provided demonstrates the usage of a proxy t...
```python class Proxy: def log_message(self, message): # Implementation of logging message using the proxy pass class LoggingSystem: def __init__(self): self.proxy = None def set_proxy(self, proxy): self.proxy = proxy def info(self, message): if self.proxy: ...
magicoder
python
You are tasked with creating a program that validates the licensing terms for a software package. The licensing terms are provided in a text file, and your program needs to check if the terms meet the specified conditions. The conditions are as follows: 1. The copyright notice must be present and should contain the phr...
```python def validateLicenseTerms(file_path): with open(file_path, 'r') as file: content = file.read() if "All rights reserved" in content: if "Redistribution and use in source and binary forms" in content: if "modification, are permitted provided that the following cond...
magicoder
python
You are tasked with implementing a custom view controller method in Swift that sets accessibility identifiers for various views within the view controller. The method should take a dictionary of view identifiers and corresponding views, and then set the accessibility identifiers for the views based on the provided iden...
```swift // Define the AccessibilitySettable protocol protocol AccessibilitySettable { func setIdentifier(_ identifier: String) } // Create a custom view class conforming to the AccessibilitySettable protocol class CustomView: UIView, AccessibilitySettable { func setIdentifier(_ identifier: String) { s...
magicoder
swift
You are tasked with creating a program that simulates a simplified file operation system. The program should implement a function to delete a file using the Windows Shell API and handle potential errors that may occur during the deletion process. Your task is to implement a function `deleteFile` that takes a file path...
```rust use winapi::um::shellapi::{SHFileOperationW, FOF_ALLOWUNDO, FOF_SILENT, FOF_WANTNUKEWARNING, FO_DELETE}; use winapi::shared::winerror::S_OK; use std::ptr; use std::ffi::OsStr; use std::os::windows::ffi::OsStrExt; fn delete_file(file_path: &str) -> Result<String, String> { let mut file_op = winapi::um::shel...
magicoder
rust
You are tasked with creating a database schema for a social media platform's "group" feature using Knex.js, a popular SQL query builder for Node.js. The schema should include the necessary fields to store information about groups, such as their unique identifier, name, type (public or private), and other relevant detai...
```javascript exports.up = function(knex) { return knex.schema.createTable('group', table => { table.increments('id').primary(); table.string('uuid').notNullable(); table.string('name').notNullable(); table.integer('creator_id').notNullable(); table.string('cover'); table.string('avatar'); ...
magicoder
javascript
You are tasked with creating a Python class that simulates a simple task management system. The class should have the ability to define read-only fields for certain attributes. Your task is to implement the `ReadOnlyMeta` metaclass that will enforce read-only fields for specified attributes in the class. You should im...
```python # Define the custom exception for read-only errors class ReadOnlyError(Exception): pass # Implement the ReadOnlyMeta metaclass class ReadOnlyMeta(type): def __new__(cls, name, bases, dct): read_only_fields = dct.get('read_only_fields', ()) for field in read_only_fields: # ...
magicoder
python
You are tasked with implementing a Python function that simulates a simple boids flocking behavior. Boids are artificial life programs that simulate the flocking behavior of birds. The function should take in the current positions and velocities of a group of boids, and then update their velocities based on three simpl...
```python import math def update_boids(boids_positions, boids_velocities): separation_distance = 100.0 alignment_distance = 10000.0 cohesion_distance = 10000.0 max_speed = 10.0 max_rule_velocity = 0.02 new_velocities = [] for i in range(len(boids_positions)): separation = [0.0, 0....
magicoder
python
You are tasked with implementing a plugin system for a software application. The `PluginHelper` class is provided to manage the loading and execution of plugins. Your goal is to complete the `PluginHelper` class by implementing the following methods: 1. `loadPlugin`: This method should take the name of a plugin class ...
```java import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; public class PluginHelper { private List<Object> loadedPlugins; public PluginHelper() { loadedPlugins = new ArrayList<>(); } public void loadPlugin(S...
magicoder
java
You are working on a Django project that involves managing subscription plans and quotas. The given code snippet is from a migration file that alters certain fields in the database schema. The `models.BooleanField` and `models.PositiveIntegerField` are used to define fields in the Django models. Your task is to create...
```python # models.py from django.db import models class SubscriptionPlan(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=10, decimal_places=2) automatic_renewal = models.BooleanField(default=False, verbose_name='has automatic renewal') class Quota(models.Mode...
magicoder
python
You are tasked with creating a program that simulates the FizzBuzz game. In this game, players take turns counting up from 1, replacing any number divisible by 3 with the word "Fizz," any number divisible by 5 with the word "Buzz," and any number divisible by both 3 and 5 with "FizzBuzz." Your program should take a pos...
```python def fizz_buzz_game(): while True: in_val = input("Please enter a positive integer (enter 'q' to quit).\n > ") if in_val.lower() == 'q': break elif in_val.isdigit() and int(in_val) > 0: num = int(in_val) if num % 3 == 0 and num % 5 == 0: ...
magicoder
python
You are tasked with implementing a Python function to calculate the total value of assets (denoted as K) based on a given set of prices and transition probabilities. The function should utilize a Discrete Dynamic Programming (DDP) approach to solve for the optimal policy and then compute the stationary distribution to ...
```python import numpy as np from quantecon.markov import DiscreteDP def calculate_total_assets_value(am, β): # Set prices for assets and labor am.set_prices(r, w) # Create a Discrete Dynamic Program aiyagari_ddp = DiscreteDP(am.R, am.Q, β) # Compute the optimal policy using policy iterat...
magicoder
python
You are tasked with implementing a custom logging system in C#. The system should allow for logging messages with different severity levels and should support the ability to filter and retrieve logs based on their severity. You are provided with a partial implementation of the `Logger` class, which includes the `Log` m...
```csharp public List<LogEntry> GetLogs(LogLevel minLevel) { List<LogEntry> filteredLogs = new List<LogEntry>(); foreach (var log in logEntries) { if (log.Level >= minLevel) { filteredLogs.Add(log); } } return filteredLogs; } ``` In the `GetLogs` method, we itera...
magicoder
csharp
You are working on a streaming data processing application that allows users to add conditions to data streams. The application provides a method `add_condition` that takes a stream and a condition as input and adds the condition to the stream. Conditions are typically added through methods like `tuple_count`, `content...
```python class Condition: def evaluate(self, stream): raise NotImplementedError("Subclasses must implement evaluate method") class TupleCountCondition(Condition): def __init__(self, count): self.count = count def evaluate(self, stream): return len(stream) == self.count class Co...
magicoder
python
You are tasked with creating a Bash script that processes input and returns a specific output based on the input value. The script should take a single argument and use a function to determine a post-padding word based on the input. Depending on the post-padding word, the script should output a corresponding file syste...
```bash #!/bin/bash # Define the function to get the post-padding word get_post_padding_word() { # Logic to determine the post-padding word based on the input argument # For this problem, let's assume a simple logic to return a post-padding word if [[ $1 == "input1" ]]; then echo "deadc0de" els...
magicoder
shell
You are given a dataset `breast_cancer_data` containing information about breast cancer patients. The dataset has several features such as age, tumor size, tumor type, and more. The variable `X` contains the data of the features for all the patients. Your task is to write a Python function to perform feature selection ...
```python from sklearn.feature_selection import chi2 import numpy as np def feature_selection_chi_squared(X, y, k): chi2_scores, _ = chi2(X, y) indices = np.argsort(chi2_scores)[::-1][:k] return indices ``` The `feature_selection_chi_squared` function first calculates the chi-squared scores for all feature...
magicoder
python
You are tasked with implementing a type checking system for dictionaries in Python. The system should allow for different levels of strictness in checking the types of values in the dictionary. To achieve this, you need to create a CheckerFactory class that can produce different types of type checkers based on the stri...
```python class CheckerFactory: def __init__(self, checker_mapping): self.checker_mapping = checker_mapping def create_checker(self, strictness_level): if strictness_level in self.checker_mapping: return self.checker_mapping[strictness_level]() else: raise ValueE...
magicoder
python
You are tasked with implementing a class that handles the state of a button. The class should track whether the button has been pressed or released since the last time its state was checked. The class should also provide a method to reset the state of the button. You are given the following code snippet as a starting ...
```cpp class ButtonHandler { public: ButtonHandler(const Gpio &button) : button_(button), was_pressed_(false), was_released_(false) {} void Update() { bool current_state = button_.Read(); // Assuming Gpio has a Read method to get the current state if (current_state && !was_pressed_) { was_pressed_ ...
magicoder
cpp
You are tasked with implementing a function that simulates the drawing of a sprite with a rotozoom effect. The function takes in various parameters to determine the position, size, rotation, and zoom level of the sprite. Your goal is to write a function that accurately performs the rotozoom effect on the given sprite. ...
```cpp void DrawSpriteRotozoom(VertexBuffer vertexBuffer, int xpos, int ypos, int pivotX, int pivotY, float sprX, float sprY, int width, int height, VertexBuffer vertexC, UVCoordinates uvC, int spriteSheetID) { // Calculate the center of the sprite int centerX = xpos + pivotX; int centerY = ypos + pivotY; ...
magicoder
cpp
You are tasked with implementing a non-maximum suppression (NMS) algorithm to filter out redundant bounding boxes in object detection. The provided code snippet is a function signature for performing NMS on a set of bounding boxes. Your task is to write a function that takes in a list of bounding boxes and performs NMS...
```c void nms(int* keep_out, int* num_out, const float* boxes_host, int boxes_num, int boxes_dim, float nms_overlap_thresh, int device_id) { // Initialize an array to keep track of selected bounding boxes bool* selected = new bool[boxes_num]; for (int i = 0; i < boxes_num; i++) { selected[i...
magicoder
c
You are tasked with implementing a command-line argument parser for a Python script. The parser should handle both positional and optional arguments, and provide a user-friendly interface for the script's configuration. Your task is to create a function that takes in a list of argument specifications and returns a dict...
```python import argparse def parse_arguments(args_spec): parser = argparse.ArgumentParser(description="Argument Parser") for arg_spec in args_spec: if arg_spec[0].startswith("--"): arg_name = arg_spec[0][2:] arg_type = arg_spec[1] help_msg = arg_spec[2] ...
magicoder
python
You are tasked with implementing a function that processes arguments for a Rust function with the "rust-call" ABI. The function takes two arguments: `args`, a vector of operands, and `fx`, a code generation context. The goal is to extract and process the arguments to prepare them for a function call. The `args` vector...
```rust struct CodegenContext; struct Operand { // Define the fields of Operand } struct CallArgument { value: Operand, is_owned: bool, } impl Operand { fn layout(&self) -> Layout { // Define the layout method } fn value_field(&self, fx: &CodegenContext, field: Field) -> Operand { ...
magicoder
rust
You are working on a machine learning project and need to implement a Gaussian Naive Bayes classifier from scratch. To achieve this, you decide to create a Python class that encapsulates the functionality of the classifier. The Gaussian Naive Bayes classifier assumes that the features are independent and have a Gaussia...
```python from IMLearn.learners import UnivariateGaussian, MultivariateGaussian import numpy as np class GaussianNaiveBayes: def __init__(self): self.class_labels = None self.class_priors = None self.class_feature_stats = None def fit(self, X, y): self.class_labels = np.unique(...
magicoder
python
You are tasked with creating a Python function that validates and processes a JSON object representing gate model simulator device parameters. The function should use the `pydantic` library to validate the input JSON against a predefined schema and then extract specific parameters for further processing. The schema fo...
```python import json from pydantic import ValidationError from braket.device_schema.simulators.gate_model_simulator_device_parameters_v1 import GateModelSimulatorDeviceParameters def validate_and_process_device_parameters(device_params_json: str) -> dict: try: device_params = json.loads(device_params_json...
magicoder
python
You are tasked with creating a function that processes a collection of database query results and performs a specific operation on the data. Given a PHP code snippet that iterates through the result set of a database query and retrieves a property called `delete_at` from each row, your task is to implement a function t...
```php function processDeleteAt(array $queryResults): array { $processedResults = []; foreach ($queryResults as $row) { $processedRow = new stdClass(); if (isset($row->delete_at) && !empty($row->delete_at)) { $processedRow->delete_at = date('Y-m-d H:i:s', strtotime($row->delete_at));...
magicoder
php
You are tasked with creating a function that filters and maps an array of tray objects to render images based on certain conditions. The tray objects represent items in a collection tray, and each object contains information about the item, such as count and collection status. The function should iterate through the tr...
```javascript function renderTrayImages(trayObjects, onTrayObjectSelect, traySelectionType, wrapperRef) { return ( <div> {trayObjects.map((trayObject, index) => { return ( trayObject.count > 0 && !trayObject.collected && ( <TrayImage key={`animal-image-${index}`} ...
magicoder
javascript
You are tasked with implementing a modality predictor for a biological dataset. Modality refers to the distinct patterns of gene expression within a cell population. The provided code snippet includes a class `ModishTestResult` that is used to store the original data, an estimator, and modality assignments. Your task i...
```python class ModalityPredictor: def __init__(self): self.trained = False # Initialize any necessary attributes def train(self, training_data): # Implement training logic using the provided training data # Update the necessary attributes and set self.trained = True def pr...
magicoder
python
You are tasked with implementing a circular queue data structure using an array in Python. A circular queue is a data structure that follows the FIFO (First In First Out) principle, but the last element is connected to the first element to form a circle. The queue has a fixed size and when it reaches its maximum capaci...
```python # Circular Queue Implementation class CircularQueue: def __init__(self, size): self.size = size self.queue = [None] * size self.front = self.rear = -1 def enqueue(self, item): if (self.rear + 1) % self.size == self.front: self.queue[self.front] = item ...
magicoder
python
You are tasked with simulating a control system for a series of operations. The control system consists of nested control blocks, each with its own set of rules and behaviors. Your goal is to implement a function that can execute a sequence of operations within this control system and handle any potential failures that...
```python from enum import Enum class Propagation(Enum): FAILURE_TO_UNSTABLE = 1 FAILURE_TO_STABLE = 2 FAILURE_TO_CRITICAL = 3 class ControlBlock: def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): pass def serial(self, propagation=None): ...
magicoder
python
You are tasked with implementing a simplified version of an EXI (Efficient XML Interchange) stream encoder in Java. The EXI format is designed to efficiently encode and decode XML data for transmission or storage. Your task is to complete the implementation of the `EXIStreamEncoderImpl` class, which is responsible for ...
```java import java.io.OutputStream; public class EXIStreamEncoderImpl { private EXIFactory exiFactory; private EXIHeaderEncoder exiHeader; private EXIBodyEncoder exiBody; public EXIStreamEncoderImpl(EXIFactory exiFactory) throws EXIException { this.exiFactory = exiFactory; exiHeader =...
magicoder
java
You are tasked with implementing a data acquisition system for a scientific experiment. The system will be responsible for reading and processing data from a sensor, and then stopping the data acquisition process when required. The provided code snippet is a part of the data acquisition system, and it includes a method...
```python import numpy as np class DataAcquisitionSystem: def __init__(self, sensor_type): self.sensor_type = sensor_type # Initialize the data acquisition controller and other necessary components here def start_acquisition(self): # Start the data acquisition process and read data fro...
magicoder
python
You are tasked with creating a function that handles user registration and image upload in a mobile application. The function should take in user registration data, including email, password, and a profile image, and then perform the registration process using Firebase Authentication. Upon successful registration, the ...
```swift import Firebase func registerUserAndUploadImage(email: String, password: String, imageData: Data) { Auth.auth().createUser(withEmail: email, password: password) { authResult, error in if let error = error { print("Registration Auth Error", error.localizedDescription) } ...
magicoder
swift
You are tasked with implementing a custom table view cell for a social media app that allows users to share comments. The provided code snippet includes the definition of a `ShareCommentCell` class, which is a subclass of `UITableViewCell`. This cell contains a `commentTextView` property, representing a `UITextView` wh...
```swift import UIKit class ShareCommentCell: UITableViewCell, UITextViewDelegate { @IBOutlet weak var commentTextView: UITextView! @IBOutlet weak var characterCountLabel: UILabel! // New property for character count static let reuseIdentifier = "ShareCommentCell" override func awakeFromNib()...
magicoder
swift
You are given the definition of a Node class used in a tree structure. Each node in the tree has a value and a list of its children. The code snippet provided below is a Python function that takes the root node of a tree as input and returns a list of values obtained by performing a post-order traversal of the tree. T...
```python from typing import List class Node: def __init__(self, val, children): self.val = val self.children = children def post_order_reverse(root: Node) -> List[int]: stack = root and [root] vals = [] while stack: node = stack.pop() vals.append(node.val) stac...
magicoder
python
You are tasked with creating a Python function that generates a surface of section for a given orbit. A surface of section is a 2D projection of a higher-dimensional phase space onto a lower-dimensional space, which can reveal important dynamical information about the system. The function takes an input orbit and a con...
```python import numpy as np import pandas as pd def generate_surface_of_section(orbit, constant_idx): # Extract phase space coordinates at the constant index phase_space_coords = orbit.get_phase_space_coords_at_constant(constant_idx) # Create a DataFrame to store the surface of section surface_of_sec...
magicoder
python
You are tasked with implementing a text layout algorithm for a word processor. The algorithm needs to handle line breaking and text overflow. The provided code snippet is part of a larger text layout algorithm and is responsible for handling the logic when a line of text overflows. The `self.state` object contains the...
```rust fn commit_line( layout: &Layout, lines: &mut Vec<Line>, line: &mut LineState, ) { if line.x == 0. { // If we're at the start of the line, this particular // cluster will never fit, so consume it and accept // the overflow. line.runs.end = line.i + 1; line....
magicoder
rust
You are tasked with implementing a custom interrupt handling mechanism in a low-level programming language. The provided code snippet is a simplified representation of interrupt handling in a hypothetical system. The `interrupt_stack!` macro is used to define interrupt handlers for specific types of interrupts. When an...
The `handle_interrupt` function takes the interrupt type, interrupt context (`stack`), and a closure representing the interrupt handler as parameters. It then matches the interrupt type to invoke the appropriate handler. For the "simd" interrupt type, it prints the fault message, dumps the interrupt context stack, call...
magicoder
python
You are working on a bioinformatics pipeline for processing RNA-seq data. The given code snippet is part of a configuration file for the pipeline. The pipeline is defined using a domain-specific language (DSL) that allows specifying the steps and their dependencies. Each step represents a specific task in the data proc...
```python import re def parse_pipeline_config(config_file): step_info = {} with open(config_file, 'r') as file: config_content = file.read() step_calls = re.findall(r"D.step\('(\w+)',\s*outfile='(\w*.csv)?',\s*propname='(\w+)?',\s*delay=(True|False)\)", config_content) for step_call in ...
magicoder
python
You are tasked with creating a program that decodes a string of emoji codes into their corresponding emoji characters. Each emoji code is represented as a hexadecimal string, and the program should convert each code into its respective emoji character using the `chr` function in Python. Write a function `decode_emojis...
```python def decode_emojis(emoji_codes): decoded_emojis = [] for emojicode in emoji_codes: try: emoji = chr(int(emojicode, 16)) decoded_emojis.append(emoji) except ValueError: pass return ''.join(decoded_emojis) ``` The `decode_emojis` function iterates ...
magicoder
python
You are tasked with implementing a sorting algorithm for a custom data structure called `BlockStack`. The `BlockStack` is a stack-like structure that contains blocks, where each block has a color represented by a string. Your goal is to sort the blocks within the `BlockStack` based on their colors in a specific order. ...
```java public class BlockStackSorterUtil { public static void sortBlockStack(BlockStack blockStack) { Map<String, Integer> colorOrder = new HashMap<>(); colorOrder.put("red", 0); colorOrder.put("green", 1); colorOrder.put("blue", 2); colorOrder.put("yellow", 3); colo...
magicoder
java
You are tasked with implementing a custom namespace management system in C++. Your goal is to create a class that allows users to add, remove, and list namespaces and their contents. A namespace can contain other namespaces and variables. Each variable has a name and a value. The system should support the ability to re...
```cpp #include <iostream> #include <unordered_map> #include <string> #include <vector> class NamespaceManager { private: struct Variable { std::string name; int value; }; std::unordered_map<std::string, std::vector<Variable>> namespaces; public: void addNamespace(const std::string& n...
magicoder
cpp
You are tasked with creating a program that converts a given color in hexadecimal format to its corresponding RGB (Red, Green, Blue) values. The input will be a string representing the color in the format "#RRGGBB", where RR, GG, and BB are two-digit hexadecimal numbers representing the intensity of red, green, and blu...
```python def hex_to_rgb(color): # Remove the '#' symbol from the input color color = color.lstrip('#') # Convert the hexadecimal color values to decimal red = int(color[0:2], 16) green = int(color[2:4], 16) blue = int(color[4:6], 16) # Return the RGB values as a formatted string ...
magicoder
python
You are given a series of mathematical operations involving exponentiation. Your task is to write a function that determines the result of each operation and returns a list of the results. The operations are as follows: 1. Calculate the value of `b` which is equal to 2 raised to the power of 63. 2. Calculate the value...
```python def calculate_exponentiation_results(): b = 2 ** 63 c = 0 ** 0 d = 0 ** 1 e = 1 ** 999999999 f = 1 ** 999999999999999999999999999 g = 1 ** (-1) h = 0 ** (-1) i = 999999999999999 ** 99999999999999999999999999999 j = 2 ** 10 return [b, c, d, e, f, g, h, i, j] ``` The fun...
magicoder
python
You are tasked with implementing a commission calculation system for a sales company. The system should utilize a Business Object Layer (BOL) and a DataAccess layer to handle the storage and retrieval of sales data. The DataAccess layer is responsible for interacting with the database, while the BOL contains the busine...
```csharp public class CommissionBOL { private DataAccess dataAccess; public CommissionBOL(DataAccess dataAccess) { this.dataAccess = dataAccess; } public decimal CalculateCommissionForSalesperson(string salespersonId) { decimal totalSalesAmount = dataAccess.GetTotalSalesAmount...
magicoder
csharp
You are tasked with creating a function that processes a list of keyboard shortcuts and generates a user-friendly display of these shortcuts. The function should take an array of shortcut objects as input and return a formatted string representing the shortcuts. Each shortcut object will have the following structure: ...
```javascript function formatShortcuts(shortcuts) { return shortcuts.map(shortcut => `${shortcut.action}: ${shortcut.keys.join(" + ")}`).join("\n"); } ``` The `formatShortcuts` function takes an array of shortcut objects as input. It uses the `map` function to transform each shortcut object into a formatted string, ...
magicoder
javascript
You are tasked with implementing a function that validates a PESEL number, a national identification number used in Poland. The PESEL number consists of 11 digits and is used to identify individuals for official purposes. Your task is to create a function that takes a PESEL number as input and determines whether it is ...
```python def validatePESEL(pesel: str) -> bool: if not pesel.isdigit() or len(pesel) != 11: return False weights = [1, 3, 7, 9, 1, 3, 7, 9, 1, 3] checksum = sum(int(pesel[i]) * weights[i] for i in range(10)) % 10 if checksum == 0: control = 0 else: control = 10 - checksum ...
magicoder
python
You are given a snippet of C++ code that is part of a larger program for analyzing survey data. The code snippet involves calculations related to survey volume, normalization, and shot noise. Your task is to implement a function that performs similar calculations based on the given context. You are provided with the f...
```cpp #include <iostream> #include <cmath> namespace utils { // Define utility functions invsum, sqsum_wei, sqsum_div, zweight double invsum(int nden, int np) { // Implementation of invsum function } double sqsum_wei(double* w, int nden, int np) { // Implementation of sqsum_wei functi...
magicoder
cpp
You are tasked with creating a script to automate the process of merging two single-header files in a C++ project. The script needs to copy checks from a specific GitHub repository and then create a new single-header file. The script should be able to handle the merging of the two single-header files and incorporate th...
```bash #!/bin/bash STARTER_PATH_OLD_SINGLE_HEADER="$STARTER_PROJECT_DIR/lib/$OLD_SINGLE_HEADER" STARTER_PATH_NEW_SINGLE_HEADER="$STARTER_PROJECT_DIR/lib/$NEW_SINGLE_HEADER" # Copy checks from the GitHub repository curl -o checks.sh https://raw.githubusercontent.com/pages-themes/minimal/master/script/release # Merge...
magicoder
shell
You are tasked with implementing a file search function that will traverse a directory structure and return a list of file paths that match a given file name. The function should also exclude certain directories from the search based on the provided exclusion list. You are given the following function signature as a s...
```python import os from typing import Iterable, List def find( file_name: str, base_dir: str, excluded_dirs: Iterable[str] = () ) -> List[str]: """Return a list containing the paths of the files found.""" result = [] for root, dirs, files in os.walk(base_dir): dirs[:] = [d for d in dirs if d n...
magicoder
python
You are tasked with creating a function that processes a list of book sequences based on a given book ID. Each book sequence is represented by a tuple containing the book ID and the sequence number. The function should filter the sequences based on the given book ID and then sort them in ascending order based on their ...
```python def filterAndSortSequences(bookId, sequences): filtered_sequences = [sequence[1] for sequence in sequences if sequence[0] == bookId] filtered_sequences.sort() return filtered_sequences # Test the function bookId = 3 sequences = [(1, 3), (2, 1), (3, 2), (3, 1), (4, 4), (3, 3)] print(filterAndSortS...
magicoder
python
You are tasked with implementing a function to optimize a given objective function using the golden section search method. The objective function is provided as `func`, and the initial bracketing interval `[xa, xb, xc]` is given. The optimization process involves iteratively updating the interval and function evaluatio...
```python import numpy def golden_section_search(func, bracket, maxiter=100, tol=1e-6): xa, xb, xc = bracket _verysmall_num = 1e-21 # Small number to avoid division by zero grow_limit = 2.0 # Limit for interval growth def evaluate_function(x): return func(*((x,) + args)) args = () # Ad...
magicoder
python
You are tasked with implementing a code coverage tool that tracks the coverage of specific code targets in a given codebase. The code snippet provided is a configuration setting for the code coverage tool. The `codeCoverageTargets` array is used to specify the code targets that need to be covered. Each code target is r...
```javascript function calculateCoverage(codeCoverageTargets, executedCodeTargets) { const totalTargets = codeCoverageTargets.length; const executedTargets = executedCodeTargets.filter(target => codeCoverageTargets.includes(target)).length; const coveragePercentage = (executedTargets / totalTargets) * 100; retu...
magicoder
javascript
You are tasked with implementing a function that processes a series of lines of text and extracts specific information based on a given pattern. The function should identify the starting positions of lines that match the pattern and store these positions in a list. Additionally, it should count the number of matching l...
```python import re def process_lines(lines, pattern, limit): start = [] hand_cnt = 0 limit_flg = False pat = re.compile(pattern) for i, line in enumerate(lines): if pat.match(line): start.append(i) hand_cnt += 1 if hand_cnt == limit: lim...
magicoder
python
You are tasked with implementing a Python class method that retrieves and processes data from an external API. The class `EMStockhkRecorder` is a subclass of `Recorder` and is responsible for fetching tradable stock data for the Hong Kong market from the EM (Entity-Model) API. The `run` method of this class should retr...
```python from zvt.contract.recorder import Recorder from zvt.domain.meta.stockhk_meta import Stockhk from zvt.recorders.em import em_api class EMStockhkRecorder(Recorder): provider = "em" data_schema = Stockhk def run(self): # Fetch tradable stock list for the Hong Kong market, focusing on stock...
magicoder
python
You are tasked with implementing a directed acyclic graph (DAG) framework in Python. A DAG is a finite directed graph with no directed cycles. The framework should allow the creation of tasks and their dependencies, and provide a mechanism for executing these tasks in a way that respects their dependencies. Your task ...
```python class DagMeta(type): def __new__(cls, name, bases, dct): tasks = [value for key, value in dct.items() if isinstance(value, Task)] for task in tasks: if task.n not in dct: raise ValueError(f"Task {task.fn.__name__} depends on non-existent task {task.n}") ...
magicoder
python
You are tasked with creating a program that analyzes and optimizes CSS code. Your program should be able to identify and remove redundant CSS properties to improve the efficiency of the code. You are given a CSS code snippet as input. The CSS code snippet contains various CSS properties and their corresponding values....
```python def optimizeCSS(cssCode: str) -> str: # Split the CSS code into individual lines lines = cssCode.split('\n') # Dictionary to store CSS properties for each selector properties = {} # Iterate through each line of the CSS code for line in lines: line = line.strip() ...
magicoder
python
You are tasked with creating a program that processes a given text and splits it into individual words and numbers. The program should use regular expressions to handle various delimiters, including spaces, commas, and periods. The input text may contain words, numbers, and punctuation, and the program should correctly...
```python import re def split_text(text, delimiters): regex = r'\s|(?<!\d)[' + re.escape(delimiters) + r'](?!\d)' return re.split(regex, text) # Example usage input_text = "The price is $12,500.50, and the item is in stock." result = split_text(input_text, " ,.") print(result) ``` The `split_text` function u...
magicoder
python
You are tasked with creating a Python program that generates and saves AR markers using the OpenCV library. AR markers are visual markers used in augmented reality applications to identify and track objects. The code snippet provided initializes the number of GitHub stars as 0 and then uses the OpenCV library to genera...
```python import cv2 def generate_ar_markers(num_markers): aruco = cv2.aruco dictionary = aruco.getPredefinedDictionary(aruco.DICT_4X4_50) for i in range(num_markers): marker = aruco.drawMarker(dictionary, i + 1, 100) cv2.imwrite('ar_marker' + str(i + 1) + '.png', marker) ``` The `generate...
magicoder
python
You are tasked with creating a command-line interface (CLI) for managing Vless Websocket accounts. The snippet provided is a part of the CLI menu display, which shows the available options for managing Vless accounts. Each option is associated with a number, a description, and a command to execute the corresponding act...
```python import re def create_vless_account(): print("Creating Vless Websocket Account") username = input("Enter username: ") password = input("Enter password: ") expiration_date = input("Enter expiration date (YYYY-MM-DD): ") # Validate input data if not re.match(r'^[a-zA-Z0-9_]+$', username...
magicoder
python
You are tasked with creating a Python program to automate the process of sending emails using the `smtplib` library. Your program should prompt the user to input their email address, password, recipient's email address, subject, and the body of the email. The program should then establish a connection with the email se...
```python import smtplib from email.message import EmailMessage def send_email(): email = input("Enter your email address: ") password = input("Enter your email password: ") recipient = input("Enter recipient's email address: ") subject = input("Enter the email subject: ") body = input("Enter the e...
magicoder
python
You are tasked with implementing a keyframe transformation algorithm for a multimedia application. The keyframes represent snapshots of an animation at specific points in time, and the transformation involves evaluating variables and applying transformations to the body elements of the keyframes. You are given a Java ...
```java protected void transformBodyElements(Keyframes keyframes, Keyframes transformed, EvaluationContext context) { EvaluationContext mediaContext = new EvaluationContext(); // Iterate through the body elements of the keyframes for (BodyElement element : keyframes.getBodyElements()) { // Apply tr...
magicoder
java
You are tasked with creating a Python program to simulate a simple banking system. The program should allow users to create accounts, deposit and withdraw funds, and check their balance. Each account should have a unique account number, and the program should support multiple accounts. Your program should include the ...
```python class Bank: def __init__(self): self.accounts = {} self.account_number = 1000 # Initial account number def create_account(self, name, initial_deposit): self.account_number += 1 self.accounts[self.account_number] = {'name': name, 'balance': initial_deposit} ret...
magicoder
python
You are tasked with implementing a function that dereferences a configuration object by replacing references with the actual values they point to. The configuration object contains references to other parts of the configuration, and your goal is to resolve these references and return a fully dereferenced configuration ...
```python def dereference_config(cfg): def resolve_reference(ref, config): parts = ref.split('.') value = config for part in parts: value = value[part] return value def replace_references(obj, config): if isinstance(obj, dict): for key, value in o...
magicoder
python
You are tasked with implementing a sequence-to-sequence model for a machine translation system. The model consists of an encoder and a decoder, and it is trained using teacher forcing, a technique where the target output from the training data is fed as input to the decoder during training. The provided code snippet is...
To solve this problem, you would need to implement the encoder and decoder components of the sequence-to-sequence model and understand the impact of a teacher forcing ratio of 0.0 during training. Here's a high-level overview of the solution: 1. Implement the Encoder: - The encoder takes the input sequence and pro...
magicoder
python
You are tasked with implementing a class method for an underwater rendering system. The provided code snippet is a part of the implementation of the `cUnderWater` class. Your task is to complete the implementation of the `RenderUnderWater` method within the `cUnderWater` class. The method should handle the rendering of...
```cpp void cUnderWater::RenderUnderWater() { // Set rendering states for underwater scene glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); // Render the underwater scene // Assuming there are additional rendering functions for underwater scene // Example: renderUnderwaterScene(); // Clear...
magicoder
cpp
You are tasked with implementing a default player list screen for a mobile gaming application. The screen should display a list of players along with their basic information. Each player's information should include their username, level, and score. Additionally, the screen should allow the user to sort the player list...
```java import java.util.Collections; import java.util.Comparator; import java.util.List; public class DefaultPlayerListScreen { public void displayPlayerList(List<Player> players) { for (Player player : players) { System.out.println("Username: " + player.getUsername() + ", Level: " + player.ge...
magicoder
java
You are tasked with implementing a function to load language data into a system. The function `load_language` takes three parameters: `ldata`, `languages`, and `families`. The `ldata` parameter represents the data of a language, while `languages` and `families` are collections of language and family data, respectively....
```python class LanguageFamily: def __init__(self, family_id, data): self.family_id = family_id self.data = data def load_language(ldata, languages, families): # get or create the language family: # Note: If the related languoid is an isolate or a top-level family, we create a # Languag...
magicoder
python
You are tasked with implementing a Python function that handles the forwarding database (FDB) for a networking application. The function interacts with a WireGuard client and uses the `IPRoute` class to manage the FDB entries. The `bridge_fdb_handler` function takes a `WireGuardClient` object as input and returns a dic...
```python from typing import Dict from pyroute2 import IPRoute from dataclasses import dataclass @dataclass class WireGuardClient: remove: bool # Indicates whether to remove FDB entries def bridge_fdb_handler(client: WireGuardClient) -> Dict: with IPRoute() as ip: operation = "del" if client.remove e...
magicoder
python
You are tasked with implementing a function to determine whether a given undirected graph is bipartite. A graph is bipartite if its vertices can be divided into two disjoint sets such that every edge connects a vertex from one set to a vertex in the other set. Your task is to write a Python function `is_bipartite(graph...
```python import networkx as nx def is_bipartite(graph): color = {} queue = [] start_node = next(iter(graph.nodes())) color[start_node] = 0 queue.append(start_node) while queue: current_node = queue.pop(0) for neighbor in graph.neighbors(current_node): if neighbor ...
magicoder
python
You are working for a company that manages sales data using a pandas DataFrame in Python. The DataFrame `df` contains the following columns: `product_id`, `quantity_sold`, and `unit_price`. Your task is to calculate the total amount earned for each product and add this information as a new column called `total_earned` ...
```python import pandas as pd def total_earned(row): return row['quantity_sold'] * row['unit_price'] def calculate_total_earned(df): df['total_earned'] = df.apply(total_earned, axis=1) return df # Example usage data = {'product_id': [1, 2], 'quantity_sold': [5, 3], 'unit_price': [10, 15]}...
magicoder
python
You are tasked with creating a Python class that can serialize geometric regions into different formats. The class should provide a method to serialize the regions into various formats and another method to retrieve the available formats for serialization. Your task is to implement the `Regions` class with the followi...
```python class Regions: def __init__(self, regions): self.regions = regions def serialize(self, format): if format == 'crtf': return self._serialize_crtf() elif format == 'fits': return self._serialize_fits() else: raise ValueError("Unsupport...
magicoder
python
You are tasked with implementing a custom annotation processor for the `AutoMerge` annotation. The `AutoMerge` annotation is used to mark classes for automatic merging of their fields. The annotation has one attribute `excludes`, which is an array of strings representing the fields that should be excluded from the auto...
```java import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.lang.model.element.Element; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lan...
magicoder
java
You are tasked with implementing a Django view for a user's order history. The view should retrieve the user's orders from the database and display them in a paginated manner. The URL pattern for accessing this view is `/user/order/(page)`, where `(page)` is the page number for pagination. Your task is to complete the...
```python from django.views import View from django.shortcuts import render, redirect from django.core.paginator import Paginator from django.urls import reverse from .models import Order class OrderHistoryView(View): def get(self, request, page): if not request.user.is_authenticated: next_url ...
magicoder
python
You are tasked with implementing a file upload system that generates a unique directory for each user and sets an expiration time for the uploaded files. The system should use the `user_upload_dir` function to create the directory structure and set the expiration time based on certain conditions. The `user_upload_dir`...
```python import os from django.conf import settings # Assuming Django framework is being used def get_current_user_id(): # Implement the logic to retrieve the ID of the current user pass def user_upload_dir(instance, filename): name_struct = os.path.splitext(filename) current_user_id = get_current_u...
magicoder
python
You are tasked with implementing a file encryption class in Python. The class should use the Advanced Encryption Standard (AES) algorithm in Cipher Block Chaining (CBC) mode to encrypt a given file. The class should have the following properties and methods: Properties: - `filesize`: An integer representing the size o...
```python import os from Crypto.Cipher import AES from Crypto.Random import get_random_bytes class FileEncryptor: def __init__(self, stage2_image): self.stage2_image = stage2_image self.filesize = len(stage2_image) self.iv = os.urandom(32) def encrypt_file(self, file_path, key): ...
magicoder
python
You are tasked with implementing a custom TCP status tracking system using C++. The provided code snippet outlines the initial structure for the system, including the definition of an enum `TcpStatus` and a class `TCPStatusFlowData`. Your task is to extend this code to create a TCP status tracking system that can store...
```cpp #include <vector> #include <click/flow/flow.hh> #include <click/flow/flowelement.hh> CLICK_DECLS enum TcpStatus {TCP_FIRSTSEEN = 0, TCP_DROP}; class TCPStatusFlowData { public: enum TcpStatus status; TCPStatusFlowData() : status(TCP_FIRSTSEEN) {} // Initialize status to TCP_FIRSTSEEN }; class TCPSta...
magicoder
cpp
You are tasked with implementing a Python class to parse and extract information from the output of a network device. The output contains MAC address table entries for a specific device. Your task is to create a class method that can parse this output and return a list of dictionaries, where each dictionary represents ...
```python import re from typing import List, Dict, Union class Script: rx_line = re.compile( r"^\s*(?P<vlan_id>\d+)\s+(?P<interfaces>\S+)\s+" r"(?P<mac>[\.0-9a-f]+)\s+\S+\s+(?P<type>\w+)\s*\n", re.MULTILINE, ) @staticmethod def parse_mac_address_table_output(output: str) -> Lis...
magicoder
python
You are tasked with implementing a data structure that maintains the last 25 elements added to it. You should create a class `Last25Queue` that utilizes the `deque` data structure from the Python `collections` module to achieve this functionality. The class should have the following methods: - `add(element)`: Adds the ...
```python from collections import deque class Last25Queue: def __init__(self): self.last_25 = deque() def add(self, element): if len(self.last_25) == 25: self.last_25.popleft() self.last_25.append(element) def get_last_25(self): return list(self.last_25) ``` Th...
magicoder
python
You are tasked with developing a ROS (Robot Operating System) node for a robotic classifier system. The node is responsible for subscribing to various topics and performing specific actions based on the received data. Your goal is to implement the callback functions for the subscribed topics and ensure that the main lo...
```python import rospy from std_msgs.msg import String, StdString from std_msgs.msg import Float32MultiArray import scipy.io as io memory = {} # Initialize memory data structure def label_callback(data): # Process the received String message for 'label' pass # Add your processing logic here def labelstd_ca...
magicoder
python
You are tasked with implementing a class method for simulating the propagation of an electromagnetic field through a medium. The method, `single_step`, takes in the current propagation distance `z_curr` and the frequency domain representation of the field `Ew` at that distance. It then advances the field by a single `z...
```python import numpy as np class FieldPropagationSimulator: def __init__(self, medium_params): self.medium_params = medium_params def single_step(self, z_curr, Ew): """ Advance field by a single z-slice Args: z_curr (float): Current propagation distance. ...
magicoder
python
You are tasked with creating a Rust function that manages actions within a GUI application. The function should take in two parameters: `action_map` and `actionptr`, both of which are pointers to foreign functions or data structures. The function should extract necessary information from these pointers and then add the...
```rust fn manage_action<T>(action_map: *mut ffi::GActionMap, actionptr: *mut ffi::GAction) { // Convert action_map and actionptr to Rust types let action_map_ref = unsafe { &mut *action_map }; let actionptr_ref = unsafe { &mut *actionptr }; // Extract necessary information from the pointers and perfor...
magicoder
rust
You are tasked with implementing a caching mechanism for asynchronous function calls in Python. You need to create a decorator that wraps asynchronous functions and caches their results to improve performance. Your task is to implement the `call_or_get_from_cache` function, which takes a cache, a wrapped function, its...
```python import functools async def call_or_get_from_cache(cache, func, *args, **kwargs): key = (func.__name__, args, frozenset(kwargs.items())) if key in cache: return cache[key] result = await func(*args, **kwargs) cache[key] = result return result def outer(wrapped): @functools.wra...
magicoder
python
You are tasked with implementing a function that downloads a file from a given URL using the libcurl library in C. The function should take the download URL as input and return the downloaded file's content along with its size. You are provided with a partial code snippet that sets up the libcurl context and initialize...
```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <curl/curl.h> struct WriteBuffer { char *data; size_t size; }; size_t writeCallback(void *ptr, size_t size, size_t nmemb, void *data) { size_t realsize = size * nmemb; struct WriteBuffer *mem = (struct WriteBuffer *)data; me...
magicoder
c
You are tasked with implementing a custom sorting algorithm for a list of employees based on their department, position, and full name. The sorting should follow a specific order: first, employees should be sorted in descending order based on their department; then, within each department, employees should be sorted in...
```python def custom_sort_employees(employees): sorted_employees = sorted(employees, key=lambda emp: (-emp['department'], emp['position'], emp['full_name'])) return sorted_employees # Test the function with the given example employees = [ {'full_name': 'Alice', 'position': 'Manager', 'department': 2}, ...
magicoder
python
You are given a list of distinct integers representing candidates for a combination sum and a target integer. Write a function `combinationSum(candidates, target)` that returns all unique combinations of candidates where the chosen numbers sum to the target. Each number in candidates may be used an unlimited number of ...
```python def combinationSum(candidates, target): def backtrack(candidates, start, target, path, result): if target < 0: return if target == 0: result.append(path) return for i in range(start, len(candidates)): backtrack(candidates, i, target -...
magicoder
python
You are given an array of integers `nums` and an integer `target`. Your task is to find the sum of three integers in the array that is closest to the target. Return the sum of the three integers. Write a function `threeSumClosest(nums, target)` that takes in an array of integers `nums` and an integer `target` as input...
```python class Solution: def threeSumClosest(self, nums, target): nums.sort() # Sort the array closest_sum = float('inf') # Initialize closest sum to positive infinity for i in range(len(nums) - 2): left, right = i + 1, len(nums) - 1 # Two pointers approach while ...
magicoder
python
You are tasked with creating a Python function that simulates a simplified training process for a machine learning model. The function will take in three parameters: `data_batch` (a list of input data), `labels_batch` (a list of corresponding labels), and `steps` (an integer representing the number of training steps to...
```python from typing import List def simulate_training(data_batch: List, labels_batch: List, steps: int, device_iterations: int, batch_size: int, replicas: int) -> None: total_items = device_iterations * batch_size * replicas training_model.compile(data_batch, labels_batch) print(f"Evaluating: {steps} ste...
magicoder
python
You are tasked with implementing a Python class that generates test cases for a block-level diagram problem. The block-level diagram consists of a series of blocks connected by arrows, where each block has a unique identifier and may have multiple input and output arrows. Your task is to implement the `generate` method...
```python import sys import random from test_base import * class TestBlockLD(TestBase): def generate(self): # Generate random block-level diagram num_blocks = random.randint(3, 5) block_level_diagram = [] block_ids = list(range(1, num_blocks + 1)) for block_id in block_ids: num_connect...
magicoder
python
You are tasked with creating a program that analyzes a Ruby file and identifies the number of occurrences of a specific constant type within the file. In Ruby, constants are defined using uppercase letters and can be used to store values that are not meant to change during the program's execution. Your program should b...
```python import re def count_constant_occurrences(file_path, constant_type): try: with open(file_path, 'r') as file: content = file.read() occurrences = re.findall(r'\b{}\b'.format(constant_type), content) return len(occurrences) except FileNotFoundError: re...
magicoder
python
You are tasked with implementing a custom data structure called `AnyEntry` that can store any type of data. The `AnyEntry` should support operations to add an entry, retrieve an entry, and check if the data structure is empty. Additionally, you need to implement a method to check if a specific type of entry exists in t...
```python class AnyEntry: def __init__(self): self.entries = [] def add_entry(self, entry): self.entries.append(entry) def get_entry(self, index): if 0 <= index < len(self.entries): return self.entries[index] return None def is_empty(self): return l...
magicoder
python