query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with implementing a generic `TaskType` class template in C++. The `TaskType` class template is used to create task objects that can encapsulate a function or functor and its associated data. The `make_TaskType` function is provided to create instances of the `TaskType` class template. The `TaskType` cla...
```cpp #include <type_traits> enum class ExternalFunctorObjectToBeCached { yes, no }; template <typename ReturnType, bool IsConst, ExternalFunctorObjectToBeCached CachePolicy, class Func> class TaskType { public: ReturnType execute() { return func_(); } private: Func func_; }; template <class Fu...
magicoder
cpp
You are tasked with creating a Python script to automate the evaluation of natural language processing systems using paired bootstrap resampling. The paired bootstrap resampling technique is commonly used to compare the performance of two systems on a given task, such as part-of-speech tagging or dependency parsing. Y...
```python import os import subprocess def evaluate_nlp_systems(LEMMA_DATA_DIR, short, RESULTS_DIR, args): gold_file = os.path.join(LEMMA_DATA_DIR, f"{short}.test.gold.conllu") results_dir = os.path.join(RESULTS_DIR, "treebank") # Replace "treebank" with the actual treebank name print(f"Running systems ra...
magicoder
python
You are tasked with creating a Python function that processes a list of dates and generates a payload for querying a repository. The payload should include a search query, sorting criteria, and a date range based on the input dates. Write a function `generate_payload` that takes in two parameters: - `date_list`: a lis...
```python import datetime def generate_payload(date_list, query): repos = [] for date in date_list: yesterday = date - datetime.timedelta(days=7) payload = { 'q': query + " sort:updated" + " created:%d-%02d-%02d..%d-%02d-%02d" % (yesterday.year, yesterday.month, yes...
magicoder
python
You are working on a machine learning project and need to implement a cost computation function for a specific algorithm. The given code snippet is a part of the cost computation method in Python, which is used to calculate the cost associated with a particular class in the algorithm. The method takes in the parameter ...
```python import numpy as np class CostComputation: def __init__(self, m, lambdaRate): self.m = m self.lambdaRate = lambdaRate def compute_distances(self, theta, y): distances = np.abs(np.subtract(theta, y)) return distances def regularize_cost(self, cost, theta): ...
magicoder
python
You are tasked with creating a test case for a reactive programming application. The application uses a state machine and streams to handle inbound and outbound data. Your goal is to write a JUnit test case that ensures the proper termination of execution when an error occurs in the streams. Given the provided code sn...
```java @ParameterizedTest @ValueSource(strings = {"inbound", "outbound"}) public void errorShouldTerminateExecution(String terminationMode) { final TestRequesterResponderSupport activeStreams = TestRequesterResponderSupport.client(); final LeaksTrackingByteBufAllocator allocator = activeStreams.getAllocator();...
magicoder
java
You are tasked with creating a program that processes a list of email addresses and identifies any illegal characters present in the usernames. An illegal character is defined as any character that is not allowed in an email username, with the "@" symbol being a prime example. Your program should take a list of email a...
```python def find_illegal_characters(email_list): illegal_indices = [] for email in email_list: username, domain = email.split('@') for i, char in enumerate(username): if char not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-": illegal_indices...
magicoder
python
You are tasked with implementing a simple class in Swift to manage a list of tasks. The class should allow adding tasks, marking tasks as completed, and listing all tasks. Each task should have a description and a completion status. You need to implement the `TaskManager` class with the following requirements: 1. The ...
```swift import UIKit struct Task { let description: String var isCompleted: Bool } class TaskManager { var tasks: [Task] = [] func addTask(description: String) { let newTask = Task(description: description, isCompleted: false) tasks.append(newTask) } func markTaskAsCompleted...
magicoder
swift
You are working on a build system for a software project and need to write a script to manage the generated images. The script needs to move certain files to a designated directory based on specific conditions. Your task is to implement a function that performs the required file operations based on the given conditions...
```bash #!/bin/bash # Given variables PROJECT="example_project" ARCH="x86_64" IMAGES_DIR="/path/to/images" SVN_REV="1234" # Function to perform file operations perform_file_operations() { for i in "${file_list[@]}"; do if [ -f "/usr/obj/${PROJECT}.${ARCH}/$i" ]; then mv "/usr/obj/${PROJECT}.${...
magicoder
shell
You are tasked with implementing a file synchronization system for a distributed file storage service. The system consists of a client application that interacts with a remote server to upload and download files. The client application uses a `FileSynchronizer` struct, which provides methods for writing files to the se...
```rust impl FileSynchronizer { fn write_file(&self, path: &Path, data: &[u8]) -> Result<()> { debug!("Writing file: {:?}", path); let data_vec: Vec<u8> = data.to_vec(); self.master_interface .upload_file_chunk(&path.to_string_lossy(), 0, data_vec) .chain_err(|| "Er...
magicoder
rust
You are working on a bioinformatics project and need to develop a program to process peptide-spectrum matches (PSMs) from a mass spectrometry experiment. Each PSM represents a match between an observed spectrum and a peptide sequence. Your task is to write a function that reads PSMs from a file and performs validation ...
```csharp using System; using System.Collections.Generic; using System.IO; public class PsmProcessor { public List<string> ReadAndValidatePsmFile(string filePath) { List<string> psms = new List<string>(); List<string> warnings = new List<string>(); try { using (Stre...
magicoder
csharp
You are tasked with creating a function that extracts the text content within the HTML tags of a given string. The function should return a list of all the text content found within the tags. For example, given the following HTML snippet: ``` <div class="container"> <div class="row"> <div class="col-xl-12"...
```python from typing import List import re def extract_text_from_html(html_string: str) -> List[str]: pattern = r">([^<]+)<" matches = re.findall(pattern, html_string) return matches ``` The `extract_text_from_html` function uses the `re.findall` method to search for all occurrences of text content withi...
magicoder
python
You are working on a serverless application using AWS SAM (Serverless Application Model) and need to automate the deployment process using AWS CLI commands. Your task is to create a script that automates the deployment of a serverless application to AWS using the provided code snippet as a reference. The deployment pr...
```bash #!/bin/bash # Step 1: Create an S3 bucket aws s3 mb s3://mateusz-demo-sam-bucket # Step 2: Package CloudFormation template aws cloudformation package --s3-bucket mateusz-demo-sam-bucket --template-file template.yaml --output-template-file gen/template-generated.yaml # Step 3: Deploy CloudFormation stack aws ...
magicoder
shell
You are tasked with implementing a simple neural network model for classifying handwritten digits using the MNIST dataset. The MNIST dataset consists of 28x28 pixel grayscale images of handwritten digits (0-9). Your goal is to create a Python class, `MNISTModel`, that can train on the MNIST dataset and make predictions...
```python import numpy as np import tensorflow as tf class MNISTModel: def __init__(self, input_size=784, hidden_size=128, output_size=10, learning_rate=0.1): self.input_size = input_size self.hidden_size = hidden_size self.output_size = output_size self.learning_rate = learning_rat...
magicoder
python
You are tasked with implementing a function to expand predicates with requirements into concrete lists of predicates. Predicates are defined in a permission map, and some predicates may reference other predicates using the `@requires` annotation. The goal is to convert each predicate clause to include its parent predic...
```python from typing import Dict, List def expand_predicates(permission_map: Dict[str, List[str]]) -> Dict[str, List[str]]: expanded_map = {} def expand_predicate(predicate): if predicate not in expanded_map: expanded_map[predicate] = [] for req_predicate in permission_map[pre...
magicoder
python
You are tasked with implementing a text rendering function for a user interface. The function should conditionally display the name and intensity of a data point based on the zoom level and other settings. The function should also handle multi-line rendering and adapt to the current theme. You are given the following ...
```csharp public string RenderText(bool multiLine, double zoom, string Name, float intensity, bool isDarkTheme) { string renderedText = ""; if (zoom >= Config.ShowNameZoomLevel) { renderedText += Name; } if (multiLine && !string.IsNullOrEmpty(renderedText)) { renderedText += "\...
magicoder
csharp
You are tasked with designing a C++ program that simulates a simple HTTP server request handler. The program should be able to handle incoming HTTP requests and process them based on a predefined configuration. Your task is to implement the `HttpServerRequestHandlerBase` class, which will serve as the base class for h...
```cpp #include "../Container/Container.hpp" #include "../Logging/Logger.hpp" #include "./Handlers/HttpServerRequestHandlerBase.hpp" #include "./HttpServerConfiguration.hpp" class HttpServerRequestHandlerBase { private: HttpServerConfiguration serverConfig; Container requestData; Logger logger; public: ...
magicoder
cpp
You are tasked with creating a custom component for a web application that generates action buttons for different entities. The provided code snippet is a part of a Laravel Blade template, where the `@component` directive is used to include the custom component `admin.partials._action_buttons`. This component takes in ...
```php // Custom component definition in Laravel Blade template (admin/partials/_action_buttons.blade.php) @php $canEdit = auth()->user()->can('edit-' . $permission); $canDelete = auth()->user()->can('delete-' . $permission); $canView = auth()->user()->can('view-' . $permission); @endphp @if($canEdit) ...
magicoder
php
You are tasked with creating a program that will analyze 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 any punctuation marks and consider words in a c...
```python import re from collections import Counter def word_frequency(file_path): with open(file_path, 'r') as file: text = file.read().lower() # Read the file and convert text to lowercase words = re.findall(r'\b\w+\b', text) # Tokenize the words, ignoring punctuation word_counts = Coun...
magicoder
python
You are tasked with implementing a function that takes a string as input and returns the count of each unique word in the string. A word is defined as a sequence of characters separated by spaces. The function should ignore punctuation and treat uppercase and lowercase letters as equivalent. Additionally, the function ...
```python import re def countUniqueWords(inputString): stop_words = {"the", "and", "but", "of", "in", "to", "a", "is", "it", "that", "as", "on", "with", "for", "at", "by", "this", "from", "or", "an", "be", "are"} word_counts = {} # Remove punctuation and convert to lowercase inputString = re.sub(r...
magicoder
python
You are tasked with creating a Python function that takes a list of datetime objects and returns the average time of day across all the datetime objects in the list. The average time of day should be rounded to the nearest minute. The function should have the following signature: ```python def average_time_of_day(date...
```python from typing import List from datetime import datetime, timedelta def average_time_of_day(datetimes: List[datetime]) -> str: total_seconds = sum(dt.hour * 3600 + dt.minute * 60 + dt.second for dt in datetimes) average_seconds = total_seconds // len(datetimes) average_time = str(timedelta(seconds=...
magicoder
python
You are tasked with implementing a data processing algorithm for analyzing animal behavior. The algorithm needs to crop specific time intervals around behavioral bouts detected in the data. The time intervals are defined by the parameters `PRE_INT_BT_S` and `POST_INT_BT_S`, which represent the duration in seconds befor...
```python import math DEF_DT = 0.2 PRE_INT_BT_S = 2 POST_INT_BT_S = 6 def crop_bout_intervals(bout_timestamps): cropped_intervals = [] for bout in bout_timestamps: start_time = math.floor(bout - PRE_INT_BT_S / DEF_DT) * DEF_DT end_time = math.ceil(bout + POST_INT_BT_S / DEF_DT) * DEF_DT ...
magicoder
python
You are working on a large-scale application that uses namespaces and imports various classes from different namespaces. Your task is to create a function that will analyze the given namespace and return the count of imported classes from a specific namespace. You are given a code snippet that represents the namespace...
```php function countImportedClasses(string $namespace, array $importedClasses): int { $count = 0; foreach ($importedClasses as $importedClass) { if (strpos($importedClass, $namespace) === 0) { $count++; } } return $count; } // Test the function $importedClasses = [ 'App...
magicoder
php
You are working on a data processing system that involves mapping identifiers from one study to another. The system uses a function to determine whether an identifier should be modified based on a given mapping. The function takes an identifier object and a dictionary representing the mapping. The identifier object has...
```python class Identifier: def __init__(self, study, values): self.study = study self.values = values def process_identifier(ident, id_map): if 'Study' in id_map and ident.study in id_map['Study'].values(): return ident else: return ident ```
magicoder
python
You are tasked with implementing a function that processes a given JSON object and returns the value associated with a specific key. The JSON object may contain nested objects and arrays, and the key may be present at any level within the JSON structure. Your task is to write a function that can handle this complexity ...
```javascript function getValueFromJSON(json, key) { if (json.hasOwnProperty(key)) { return json[key]; } for (let prop in json) { if (json[prop] !== null && typeof json[prop] === 'object') { const result = getValueFromJSON(json[prop], key); if (result !== undefined) ...
magicoder
javascript
You are tasked with creating a program that parses a given HTML snippet and extracts the contact information present in the "Contact Us" section. The contact information includes the email address, phone number, and any social media links. The HTML snippet is structured as follows: ```html <div> <h4>Contact Us</h4...
```python from bs4 import BeautifulSoup def extractContactInfo(html): contact_info = {} soup = BeautifulSoup(html, 'html.parser') contact_section = soup.find('h4', text='Contact Us').find_next('p') contact_info['email'] = contact_section.text.split(': ')[1] contact_info['phone'] = contact_sect...
magicoder
python
You are tasked with creating a custom Unity Visual Scripting node to calculate the factorial of a given number. The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. For example, the factorial of 5 (denoted as 5!) is 5 * 4 * 3 * 2 * 1 = 120. Your custom node should ...
```csharp using Unity.VisualScripting; namespace Unity.VisualScripting.Community { [UnitCategory("Community")] [UnitTitle("Factorial")] public class FactorialNode : Unit { [DoNotSerialize] public ControlInput input; [DoNotSerialize] public ControlOutput output; ...
magicoder
csharp
You are tasked with implementing a retry policy for error message handling in a message consumer system. The system uses a consumer object with a channel for message processing. The consumer object has pre-defined methods for handling messages, including pre_handle, handle, and post_handle. Additionally, the consumer o...
```python class MaxRetryException(Exception): pass def handle_with_retry(consumer, message, max_retries): for _ in range(max_retries + 1): try: consumer.pre_handle() result = consumer.handle(message) consumer.post_handle() consumer.channel.basic_ack(deliv...
magicoder
python
You are working on a system that involves managing input/output (I/O) ports for a development board. The function `pt_dev_io_port_passthrough` is responsible for handling the passthrough of I/O ports between different components of the system. The function takes three parameters: `board_etree`, `scenario_etree`, and `a...
```python from lxml import etree def pt_dev_io_port_passthrough(board_etree, scenario_etree, allocation_etree): # Parse XML trees board_root = etree.fromstring(board_etree) scenario_root = etree.fromstring(scenario_etree) allocation_root = etree.fromstring(allocation_etree) # Extract port informat...
magicoder
python
You are tasked with implementing a Python function to calculate the semi-major axis of a binary star system and the semi-major axis of a neutron star orbiting the binary system. The function `aNSeq` takes three parameters: `Mbh` (mass of the black hole), `Mns` (mass of the neutron star), and `Pb` (orbital period of the...
```python from math import pi # Gravitational constant G = 6.67430e-11 # in m^3 kg^-1 s^-2 def aNSeq(Mbh, Mns, Pb): aR = ((G * (Mbh + Mns) * (Pb ** 2)) / (4 * (pi ** 2))) ** (1 / 3) aNS = (Mbh / (Mbh + Mns)) * aR return aR, aNS def main(): print('\n Give the parameter values - ') Mbh = float(inp...
magicoder
python
You are tasked with implementing a simple text-based menu system for a restaurant ordering application. The menu system should allow the user to view the menu, add items to their order, view their current order, and place the order. The menu items and their prices are predefined and should be displayed to the user. The...
```java import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.HashMap; import java.util.Map; public class RestaurantMenuApp extends JFrame { private Map<String, Double> menuItems = new HashMap<>(); private Map<String, Integer> orderItems = new HashMap<>...
magicoder
java
You are tasked with implementing a class that manages file I/O operations and provides a callback mechanism upon completion. The class, `FileCallbackTest`, has a virtual method `OnFileIOComplete` that is called when a file I/O operation is finished. Additionally, the class has private member variables `id_`, `helper_`,...
```cpp #include <iostream> class MessageLoopHelper { // Define the MessageLoopHelper class if necessary }; class FileCallbackTest { public: FileCallbackTest(int id, MessageLoopHelper* helper, int* max_id) : id_(id), helper_(helper), max_id_(max_id) {} virtual void OnFileIOComplete(int bytes_copied) { ...
magicoder
cpp
You are tasked with implementing a graph constructor module for a machine learning library. The module should be capable of constructing graphs using various methods such as random walks, percentage-based connections, k-nearest neighbors (KNN), spatial relationships, and threshold-based connections. Each method has its...
To address this problem, we can create a `GraphConstructorInterface` class that acts as a unified interface for the various graph construction methods. This class will provide methods for users to specify the desired construction method and any necessary parameters, while internally delegating the construction process ...
magicoder
python
You are tasked with implementing a custom Mean Squared Error (MSE) loss function in PyTorch. The Mean Squared Error is a common loss function used in regression problems to measure the average of the squares of the errors or residuals. Your task is to create a custom PyTorch module that computes the MSE loss given the ...
```python import torch import torch.nn as nn class MseLoss(nn.Module): def __init__(self): super(MseLoss, self).__init__() def forward(self, predicted, target): # Calculate the mean squared error mse = torch.mean((predicted - target)**2) return mse ``` The `MseLoss` class inhe...
magicoder
python
You are tasked with implementing a token parser for SPDX (Software Package Data Exchange) spreadsheet format. The SPDX format is used to document information on the origin and licensing of software packages. Your task is to create a Python class that can parse tokens from SPDX data and perform assertions on the tokens....
```python class SPDXTokenParser: def __init__(self): self.tokens = [] self.current_token_index = 0 def input(self, data): self.tokens = data.split() # Split SPDX data into tokens def token(self): if self.current_token_index < len(self.tokens): token = self.toke...
magicoder
python
You are tasked with implementing a function to resize images and track the resizing process. The function `ResizeImage._resize_image` is used to resize an image to a specified size and then store the details of the resizing operation in a database. The code snippet provided includes a test case that verifies the correc...
```python def _resize_image(image, image_handler, session, size, after_upload): # Resize the image using the image_handler resized_image = image_handler.resize(image, size) # Store the resizing details in the database resized_height, resized_width = resized_image.height, resized_image.width resize_...
magicoder
python
You are tasked with implementing a Python module that provides functionality for working with IP addresses. The module should include a class called `IP` that allows for the manipulation and validation of IP addresses. The class should support the following operations: 1. Initialization with an IP address in the form o...
```python import ipaddress class IP: def __init__(self, address: str): self.address = address def validate_ip(self) -> bool: try: ipaddress.ip_address(self.address) return True except ValueError: return False def to_binary(self) -> str: ...
magicoder
python
You are tasked with implementing a function to test a class that involves interacting with render frame hosts and render process hosts in a browser environment. The code snippet provided contains partial implementations of two functions: `CreateTab` and `GetMockRenderProcessHost`. Your task is to complete the implement...
```cpp // Creates a new tab in a browser and initializes its render frame host content::WebContents* CreateTab() { // Assuming the existence of a browser object content::WebContents* tab = browser->AddTab(); // AddTab() creates a new tab in the browser content::RenderFrameHostTester::For(tab->GetMainFrame())->In...
magicoder
cpp
You are tasked with creating a custom subclass of a UIView in Swift that incorporates a specific feature. Your custom view should display a series of concentric circles, each with a different color and radius. The number of circles and their properties should be customizable. Additionally, the view should be able to an...
```swift import UIKit class ConcentricCirclesView: UIView { var circleColors: [UIColor] = [] var circleRadii: [CGFloat] = [] var animationDuration: CGFloat = 1.0 private var circleLayers: [CAShapeLayer] = [] override init(frame: CGRect) { super.init(frame: frame) backgroundColor = ...
magicoder
swift
You are tasked with implementing a Python class that performs image segmentation using a Fully Convolutional Network (FCN) with a ResNet backbone. The FCN_ResNet class should inherit from the nn.Module class in the PyTorch library and should have the ability to process input images using the specified ResNet backbone. ...
from torch import nn import torch.nn.functional as F class FCN_ResNet(nn.Module): def __init__(self, backbone, inter_channels=256): super(FCN_ResNet, self).__init__() self.backbone = backbone # Define additional layers for segmentation self.conv1 = nn.Conv2d(in_channels=inter_channe...
magicoder
python
You are tasked with creating a Python program to monitor environmental conditions using sensors. The program should read data from UV, visible light, infrared, temperature, and humidity sensors and display the readings in a specific format. You have access to the following sensor readings and functions: - UV sensor: `...
```python # Import necessary libraries and initialize sensors (si1132 and bme280) # Read sensor data UV_index = si1132.readUV() / 100.0 visible_light = int(si1132.readVisible()) infrared = int(si1132.readIR()) temperature = bme280.read_temperature() humidity = bme280.read_humidity() # Format and print sensor readings...
magicoder
python
You are tasked with implementing a function that processes memory-mapped I/O (MMIO) writes based on a given code snippet. The code snippet provided is a part of a larger program that performs MMIO writes to a hardware device. Your task is to create a function that simulates the behavior of the `dispatchWrite` function ...
```cpp #include <iostream> class Node { public: int idxf_; // Example member variable representing the starting index // Other member variables and methods }; class Range { // Define the Range class with necessary member variables and methods }; class SlicedPathIterator { public: SlicedPathIterator(...
magicoder
cpp
You are tasked with implementing a class method for closing a purchase in an e-commerce system. The `closePurchase` method takes an array of conditions as input and updates the status of the purchase to indicate closure. Your task is to complete the `closePurchase` method in the `Purchase` class. The `closePurchase` m...
```php class Purchase { // Other methods and properties public function closePurchase($conditions) { // Assuming $purchases is the database table for purchases $query = "UPDATE purchases SET status = 'closed' WHERE "; $params = []; foreach ($conditions as $condition) { ...
magicoder
php
You are given a Python code snippet that initializes two variables `i` and `j`. Your task is to write a function that takes in a list of integers `nums` and returns the sum of all the elements in the list from index `i` to index `j-1`. If `i` is greater than or equal to `j`, the function should return 0. If `j` is grea...
```python from typing import List def calculate_sum(nums: List[int]) -> int: i = 1 # Example initialization j = len(nums) # Example initialization if i >= j: return 0 if j > len(nums): j = len(nums) return sum(nums[i:j]) ```
magicoder
python
You are tasked with implementing a function to validate email addresses according to a set of rules. An email address is considered valid if it meets the following criteria: - It is not null. - It may contain alphanumeric characters, dots, and the '@' symbol. - The local part (before the '@' symbol) must contain at lea...
```java public class Email { public static boolean isValidEmail(String email) { if (email == null) { return false; } String[] parts = email.split("@"); if (parts.length != 2) { return false; } String localPart = parts[0]; String domai...
magicoder
java
You are tasked with creating a Rust program that handles file operations using asynchronous I/O. Your program should open a file, read its contents, and then print the contents to the console. You need to implement the necessary code to achieve this functionality. Your program should use the `async-io` feature, which ...
```rust use tokio::fs::File; use tokio::io::AsyncReadExt; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let fpath = "path_to_your_file.txt"; // Replace with the actual file path if #[cfg(feature="async-io")] { let mut file = File::open(&fpath).await?; // Open the file usin...
magicoder
rust
You are tasked with implementing a function to determine legal moves in a game. The game is played on a board of size `BOARD_SIZE` by `BOARD_SIZE`. The function `legalMove` takes in three parameters: `legalMove`, `qiAfterMove`, and `len`. The `legalMove` array stores the indices of legal moves, the `qiAfterMove` array ...
```cpp // The legalMove function populates the legalMove and qiAfterMove arrays with legal moves and their corresponding liberties. void legalMove(int legalMove[], int qiAfterMove[], size_t& len) { // Implement the logic to determine legal moves and their liberties // Populate the legalMove and qiAfterMove arra...
magicoder
cpp
You are tasked with implementing a simple tokenization system for a programming language. The given code snippet represents a mapping of certain character sequences to token types. Each key-value pair in the snippet represents a character sequence and its corresponding token type. The token types are represented by the...
```python from typing import List, Tuple class tt: GREATER_EQUAL = "GREATER_EQUAL" SLASH = "SLASH" EMPTY = "EMPTY" IDENTIFIER = "IDENTIFIER" NUMBER = "NUMBER" def tokenize_code(code: str, token_mapping: dict) -> List[Tuple[str, str]]: tokens = [] i = 0 while i < len(code): foun...
magicoder
python
You are tasked with implementing a simple routing system for a web application using Python and FastAPI. The given code snippet is a part of the main application file and shows the inclusion of two separate routers, `admins_router` and `users_router`, into the main `router`. Each router is prefixed with a specific path...
```python from fastapi import FastAPI, APIRouter app = FastAPI() admins_router = APIRouter() users_router = APIRouter() @app.get("/admins/", tags=["admins"]) async def get_all_admins(): # Implement logic to retrieve all admin users return {"message": "Retrieving all admin users"} @app.get("/admins/{admin_id...
magicoder
python
You are tasked with creating a script that modifies a JavaScript file based on command-line arguments. The script should take in three arguments: service host and port, UI host, and UI port. It should then update a JavaScript file with the provided host and port information. The script should also validate the input ar...
```bash #!/bin/bash # Parse command-line arguments while getopts "s:u:p:" opt; do case $opt in s) service=$OPTARG ;; u) ui=$OPTARG ;; p) port=$OPTARG ;; esac done # Validate input arguments if [ -z "$service" ] || [ -z "$ui" ] || [ -z "$port" ]; then echo "Usage ./update_js.sh -s <service_host:por...
magicoder
shell
You are tasked with implementing a function that calculates the total price of items in a shopping cart, taking into account any discounts that may apply. The function should accept a list of tuples, where each tuple represents an item in the cart. Each tuple contains the item name (a string) and its price (a float). A...
```python def calculate_total_price(cart, discount_code): total_price = sum(item[1] for item in cart) if discount_code == "SAVE20": total_price *= 0.8 # Apply 20% discount return total_price ``` The `calculate_total_price` function first calculates the total price by summing the prices o...
magicoder
python
You are tasked with creating a Python function that processes and uploads a MaxMind DB file to an Amazon S3 bucket. The function receives a filename as input and is responsible for extracting the contents of a .tar.gz file, locating the .mmdb file within it, and then uploading the .mmdb file to the specified S3 bucket....
```python import tarfile import os def process_and_upload_mmdb(filename, s3key_prefix, s3bucket_name, bucket): try: with tarfile.open('/tmp/' + filename + '.tar.gz', 'r:gz') as tf: directory = tf.getmembers()[0].name tf.extractall(path='/tmp/') mmdb = directory + '/' + f...
magicoder
python
You are tasked with implementing a statistical hypothesis test for comparing two receiver operating characteristic (ROC) curves. The null hypothesis is that the two ROC curves are identical, while the alternative hypothesis is that one ROC curve is greater than the other. Your goal is to write a function that performs ...
```python import numpy as np def compare_ROC(roc1, roc2): n = len(roc1) m = len(roc2) AUC1 = 0 AUC2 = 0 for i in range(1, n): AUC1 += (roc1[i][0] - roc1[i-1][0]) * (roc1[i][1] + roc1[i-1][1]) / 2 for i in range(1, m): AUC2 += (roc2[i][0] - roc2[i-1][0]) * (roc2[i][1] + roc2[i-...
magicoder
python
You are tasked with creating a program that processes data from a CSV file containing information about employees. Each row in the CSV file represents an employee and contains the following fields: employee ID, name, department, and salary. Your program needs to handle cases where the department field is empty and perf...
```python import csv from collections import defaultdict def process_employees(csv_file): departments = defaultdict(list) with open(csv_file, 'r') as file: reader = csv.DictReader(file) for row in reader: if row['Department'] == '': row['Department'] = 'Unassigned' ...
magicoder
python
You are tasked with creating a Python script that injects code from a shell script file into a pickle file. The script should take two command-line arguments: the path to the pickle file and the path to the shell script file. The injected code should be appended to the pickle file without altering its existing content....
```python import argparse import pickle def inject_code(pickle_file, code_file): with open(code_file, 'r') as file: code = file.read() with open(pickle_file, 'ab') as file: pickle.dump(code, file) def test_insert_code(): # Implement unit tests here pass def main(): parser = argpa...
magicoder
python
You are tasked with implementing a custom error-handling mechanism for a simple calculator program. The calculator should support addition, subtraction, and multiplication operations on 8-bit signed integers. However, due to the limited range of 8-bit integers, overflow and underflow errors may occur during these opera...
```rust fn main() { // Define the checked methods for 8-bit signed integer operations impl i8 { fn checked_add(self, other: i8) -> Option<i8> { self.checked_add(other) } fn checked_sub(self, other: i8) -> Option<i8> { self.checked_sub(other) } fn...
magicoder
rust
You are tasked with creating a Python function that processes a list of fees and updates their status in a database. The function should take in a list of fees, each represented as a dictionary with the following keys: "name", "company", and "status". The function should update the status of each fee in the database to...
```python from typing import List, Dict import frappe # Assuming frappe library is used for database operations def update_fee_status(fees: List[Dict[str, str]]) -> None: for fee in fees: if fee["status"] == "rejected": query = """UPDATE `tabFees` SET estado_anulacion='Rechazado' WHERE name='{...
magicoder
python
You are tasked with implementing a program to manage different encryption schemes. Each encryption scheme has a unique name and properties associated with it. Your task is to create a Rust program that allows users to add new encryption schemes, retrieve the properties of a specific scheme, and list all available schem...
```rust use std::collections::HashMap; // Define a struct to represent an encryption scheme struct EncryptionScheme { name: String, properties: HashMap<String, String>, } impl EncryptionScheme { // Create a new encryption scheme with a given name and properties fn new(name: String, properties: HashMap...
magicoder
rust
You are tasked with creating a Python class that manages environment variables and provides methods to manipulate and retrieve them. Your task is to implement the `EnvironmentManager` class with the following specifications: - The class should have an `__init__` method that initializes an empty dictionary to store env...
```python class EnvironmentManager: def __init__(self): self.variables = {} def set_variable(self, key, value): self.variables[key] = value def get_variable(self, key): return self.variables.get(key) def remove_variable(self, key): if key in self.variables: ...
magicoder
python
You are tasked with creating a program to analyze the results of a series of AI vs. human games. The program should read a CSV file containing the game results and calculate statistics based on the data. Each row in the CSV file represents a game and contains the following columns: 'AI' (the name of the AI), 'win' (ind...
```python import csv def calculate_stats(csv_file): stats = {} with open(csv_file, 'r') as file: reader = csv.DictReader(file) for row in reader: ai_name = row['AI'] if ai_name not in stats: stats[ai_name] = {'total_games': 0, 'games_won': 0} ...
magicoder
python
You are tasked with creating a program to manage a database of vaccinated individuals. The program should allow users to add new vaccinated individuals, remove existing records, and display the total number of vaccinated individuals. To achieve this, you need to implement a class called `VaccinationDatabase` with the f...
```python class VaccinationDatabase: def __init__(self): self.vaccinated = {} def addVaccinated(self, name, date): self.vaccinated[name] = date def removeVaccinated(self, name): if name in self.vaccinated: del self.vaccinated[name] def totalVaccinated(self): ...
magicoder
python
You are tasked with creating a server monitoring system that updates the state of a server based on the termination status of a ping operation. The termination status is represented by an integer value, and the server state is updated according to the following rules: - If the termination status is 0, the server state ...
```swift func handleTerminationStatus(_ terminationStatus: Int) { switch terminationStatus { case 0: updateServerState(to: .up) case 1: updateServerState(to: .down) case 2: updateServerState(to: .notConnected) default: break } } ```...
magicoder
swift
You are tasked with creating a Python program that simulates a simple game of rock-paper-scissors. The program should prompt the user to input their choice (rock, paper, or scissors), and then randomly generate a choice for the computer. After both choices are made, the program should determine the winner based on the ...
```python import random import time # Simulate a simple game of rock-paper-scissors def rock_paper_scissors_game(): user_choice = input("Enter your choice (rock, paper, or scissors): ").lower() while user_choice not in ['rock', 'paper', 'scissors']: print("Invalid choice. Please enter rock, paper, or s...
magicoder
python
You are tasked with creating a program that compares two files and identifies the differences between them. The program should take two file names as input and output the differences between the files in a human-readable format. Write a function `file_diff` that takes two file names as input and prints the differences...
```python def file_diff(file1, file2): with open(file1, 'r') as f1, open(file2, 'r') as f2: lines1 = f1.readlines() lines2 = f2.readlines() max_lines = max(len(lines1), len(lines2)) for i in range(max_lines): line1 = lines1[i].strip() if i < len(lines1) else "" line2 = line...
magicoder
python
You are tasked with implementing a Python class that generates unique sequential numbers for different categories. The class should allow for the creation of multiple instances, each responsible for numbering a specific category. The numbering should start from 1 for each category and increment by 1 for each subsequent...
```python class Numbering: def __init__(self, category): self.category = category self.counter = 0 self.number = 0 def get_number(self): self.counter += 1 self.number += 1 return self.number ``` The `Numbering` class is initialized with a category name, and it ma...
magicoder
python
You are tasked with creating a Python function that disassembles a given code object and returns a dictionary containing the line numbers for each bytecode instruction. The disassembled code object will be provided as an argument to the function. The bytecode instructions will be represented as strings, and the line nu...
```python def disassemble_code(code_obj): import dis # Disassemble the code object instructions = list(dis.get_instructions(code_obj)) # Create a dictionary to store the line numbers and bytecode instructions disassembled_dict = {} # Iterate through the disassembled instructions a...
magicoder
python
You are given two binary strings, `a` and `b`, which represent non-negative integers. Your task is to write a function to return the sum of these two binary strings as a new binary string. For example, given `a = "11"` and `b = "1"`, the function should return `"100"`, as `11 + 1 = 100` in binary representation. Writ...
```python def addBinary(a: str, b: str) -> str: result = [] carry = 0 i, j = len(a) - 1, len(b) - 1 while i >= 0 or j >= 0 or carry: total = carry if i >= 0: total += int(a[i]) i -= 1 if j >= 0: total += int(b[j]) j -= 1 ...
magicoder
python
You are tasked with designing a URL routing system for a web application using Python's Django framework. The application needs to handle different types of requests for text and audio processing. Your task is to create a set of URL patterns that map to specific views for text analysis, translation, audio analysis, and...
```python from django.urls import path from . import views urlpatterns = [ path('text/analyze', views.TextAnalysisView.as_view(), name='text-analysis'), path('text/translate', views.TranslationView.as_view(), name='text-translation'), path('audio/analyze', views.AudioAnalysisView.as_view(), name='audio-ana...
magicoder
python
You are tasked with implementing a simple coordinator pattern in Swift. The coordinator pattern is commonly used in iOS applications to handle navigation and flow control. A coordinator is responsible for managing the navigation and presentation of view controllers, allowing for better separation of concerns and improv...
```swift import UIKit // Define a concrete coordinator class that conforms to the Coordinator protocol class MainCoordinator: Coordinator { let navigationController: UINavigationController init(navigationController: UINavigationController) { self.navigationController = navigationController } ...
magicoder
swift
You are tasked with writing a program to analyze a given HTML file and count the occurrences of specific HTML tags within it. The HTML file contains a series of nested `div` elements, and you need to count the occurrences of the `div` tags with specific class names. Write a function `countDivOccurrences(html, classNam...
```javascript function countDivOccurrences(html, classNames) { const counts = {}; const divRegex = /<div\s+class="([^"]+)"/g; let match; while ((match = divRegex.exec(html)) !== null) { const className = match[1]; if (classNames.includes(className)) { counts[className] = (co...
magicoder
javascript
You are tasked with implementing a class method to compute the Gamow factor for a nuclear reaction. The Gamow factor is a crucial parameter in nuclear astrophysics, representing the probability of two atomic nuclei overcoming the Coulomb barrier and undergoing a nuclear reaction. The formula for the Gamow factor involv...
```python import math class NuclearReaction: def __init__(self, larger, smaller, kwargs): self.larger = larger self.smaller = smaller self.kwargs = kwargs def value(self): """Compute the Gamow factor.""" screening = self.kwargs.get('screening') or 0 A = self.lar...
magicoder
python
You are tasked with implementing a Python function that processes a given manifest file and performs various operations based on the attributes specified in the manifest. The function should handle attribute validation, database interaction, cleanup operations, and key string processing. Additionally, it should check f...
```python import os class Attributes: def __init__(self, manifest_attributes, database, cleanup, key_string, **global_options): # Initialize attributes based on manifest self.manifest_attributes = manifest_attributes self.database = database self.cleanup = cleanup self.key_s...
magicoder
python
You are given a Python function that takes in two input parameters: `m1` and `m2`. The function is supposed to perform a specific operation and return a result. However, the given code snippet is incomplete and contains a bug. Your task is to understand the intended functionality of the code, identify the bug, and fix ...
The bug in the given code snippet is that the range for the loop is incorrect. It should start from the length of `m2` and go up to the length of `m1` to iterate through the elements of `m1` as intended. Additionally, the method `pylist_to_listnode` is used to convert the list `out` into a linked list. Here's the corr...
magicoder
python
You are tasked with implementing a class that manages intervals and wait periods for a recurring task. The class should provide methods to set the interval and wait period, and handle the execution of the task at regular intervals. The provided code snippet is part of the class and includes a method to set the interval...
```python import threading import time class RecurringTaskManager: def __init__(self): self.interval = 0 self.wait = 0 self.abort = False self.thread = None def set_interval(self, intvl=None, wait_period=None): """ wait interval must be greater than interval ...
magicoder
python
You are tasked with implementing a Python class that manages live game data and timestamps for game patches. The class should provide methods to update the game data and timestamps, as well as retrieve the latest game data and timestamp. You are given a code snippet that initializes two class attributes: `liveGameDiff...
```python # Test the LiveGameManager class live_manager = LiveGameManager(self.liveGameDiffPatchV1, self.liveTimestampv11) # Update game data diff for patch version 2 live_manager.update_game_data_diff(2, "New game data diff for patch 2") # Update timestamp for patch version 12 live_manager.update_timestamp(12, "New ...
magicoder
python
You are working on a project to analyze and visualize waveforms using Python's matplotlib library. As part of this project, you need to create a program that generates and saves a plot comparing two normalized waveforms. The code snippet provided is a part of this program and includes the plotting and saving functional...
```python import os import numpy as np import matplotlib.pyplot as plt def plot_and_save_waveforms(linear_waveform, nonlinear_waveform, output_directory): # Normalize waveforms norm_linear_waveform = linear_waveform / np.max(np.abs(linear_waveform)) norm_nonlinear_waveform = nonlinear_waveform / np.max(np....
magicoder
python
You are tasked with creating a script to automate the installation process of a C++ logging library called g3log. The script should perform the following steps: 1. Remove the directories named "g3log-install" and "g3log" if they exist. 2. Create a new directory named "g3log-install" and navigate into it. 3. Clone the g...
```bash #!/bin/bash # Step 1: Remove existing directories rm -rf g3log-install g3log build # Step 2: Create g3log-install directory and navigate into it mkdir g3log-install && cd g3log-install # Step 3: Clone g3log repository git clone https://github.com/KjellKod/g3log.git # Step 4: Create build_travis directory an...
magicoder
shell
You are tasked with implementing a Python function to perform a merge sort on a given list of integers. Merge sort is a divide-and-conquer algorithm that recursively divides the input list into smaller sublists until each sublist contains only one element. It then merges these sublists in a sorted manner to produce the...
```python from typing import List def merge_sort(items: List[int]) -> None: if len(items) > 1: mid = len(items) // 2 left = items[:mid] right = items[mid:] merge_sort(left) # Sort left sublist in-place merge_sort(right) # Sort right sublist in-place l, r, i = 0, ...
magicoder
python
You are tasked with creating a custom test attribute system for a testing framework. The framework should allow developers to annotate their test classes and methods with custom attributes to provide additional metadata and behavior for the tests. Your task is to implement a custom test attribute called `SystemTestAtt...
```csharp using System; namespace Ion.Testing { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)] public class SystemTestAttribute : Attribute { public string[] Traits { get; } public SystemTestAttribute(params string[] traits) { ...
magicoder
csharp
You are tasked with implementing a subscription management system for a streaming service. The system should allow users to subscribe to various content categories and receive notifications when new content is added to those categories. You are provided with a code snippet for the `SubscriptionManager` class, which inc...
```java class SubscriptionManager { void notifyAddingSubscription(Subscription subscription) { for (User user : getAllUsers()) { if (userSubscribedToCategories(user, subscription.categories)) { sendNotification(user, subscription); } } } private List<...
magicoder
java
You are tasked with implementing a Hierarchical State Machine (HSM) in Python. A Hierarchical State Machine is a design pattern used to model the behavior of an entity that can be in one of a number of distinct states, and can transition between those states based on certain events. The provided code snippet is a part ...
```python class Hsm: # Other methods and attributes of the Hsm class def _perform_init_chain(self, state): if state is not None: self._perform_init_chain(state.superstate) # Recursively initialize superstates if state.initial: # Check if the state has an initial substate ...
magicoder
python
You are working on a compiler optimization tool for a parallel computing framework. One of the optimizations you are implementing is vectorization, which aims to improve the performance of tasklets within a map by aligning memory accesses with the inner-most loop variable. The vectorization matches when all the input a...
```cpp #include <vector> bool isVectorizable(const std::vector<int>& inputMemlets, const std::vector<int>& outputMemlets, int originalStep, int transformedStep) { // Check if the input and output memlets access the inner-most loop variable in their last dimension for (size_t i = 0; i < inputMemlets.size(); ++i...
magicoder
cpp
You are tasked with creating a script that processes a list of GitHub repositories and retrieves their star counts within a specified range. Your script should output the repositories along with their star counts that fall within the given range. Write a Python script that accomplishes the following: 1. Accepts a rang...
```python import requests import sys def get_repositories_with_stars_in_range(min_stars, max_stars): url = 'https://api.github.com/search/repositories' params = { 'q': f'stars:{min_stars}..{max_stars}', 'sort': 'stars', 'order': 'desc' } response = requests.get(url, params=param...
magicoder
python
You are tasked with implementing a simplified version of a Python interpreter for a custom programming language. The given code snippet is part of a larger interpreter implementation and contains methods for converting various operations on objects. Your task is to implement the `convert_method_call` method, which tak...
```python def convert_method_call(self, context, instance, methodname, args, kwargs): dereferenced_instance = self.deref(instance) # Dereference the instance method = getattr(dereferenced_instance, methodname) # Get the method by name result = method(*args, **kwargs) # Call the method with provided argum...
magicoder
python
You are tasked with creating a user interface management system for a software application. The system should handle different states and adjust the visibility and titles of various views accordingly. You are given a code snippet that demonstrates the behavior for three different states: `UserManagement`, `PluginManage...
```csharp public enum UiState { UserManagement, PluginManagement, SourceManagement } public class UIManager { public void UpdateUI(UiState state) { HeaderView.Visibility = Visibility.Visible; HeaderView.UiTitel = GetUiTitle(state); switch (state) { case ...
magicoder
csharp
You are tasked with developing a Python script to automate the computation of coverage in bigWig and/or bedGraph format from an input BAM file. The script should utilize the argparse module to handle command-line arguments and provide flexibility in specifying input parameters. The coverage computation will involve gen...
```python import argparse from datetime import datetime import subprocess # Define the argparse parser parser = argparse.ArgumentParser(description='Computes coverage in bigWig and/or bedGraph format from input BAM.') parser.add_argument('bam_file', help='Input BAM file') parser.add_argument('chr_sizes', help='Chromos...
magicoder
python
You are working on a data processing script that involves writing data to a CSV file. The script uses the `csv` module in Python to write a dictionary of data to a CSV file. However, you notice that the script seems to be taking longer than expected to complete the writing process. You suspect that the `csv.DictWriter`...
To optimize the data writing process, you can utilize the `csv.writer` instead of `csv.DictWriter` to improve the script's performance. The `csv.writer` provides a more efficient way to write data to a CSV file, especially when dealing with large datasets. Here's the optimized code snippet using `csv.writer`: ```pyth...
magicoder
python
You are working on a game development project and need to write a script to handle game level configuration and file management. The game has multiple levels, each with different capabilities and templates. Your task is to create a Python function that performs the following tasks: 1. Iterates through the first 20 gam...
```python import os from shutil import copyfile from lxml import etree def handle_game_levels(game_levels, target_level_path, origin_level_path, level, capability, template, game_level_path, game_config_path): total_template_level_path = [] for game_level in game_levels[:20]: src_path = os.path.join(t...
magicoder
python
You are given a string containing a software license text. Your task is to write a program to extract the URL of the license from the given text. Write a function `extract_license_url` that takes a string `license_text` as input and returns the URL of the license if found, or an empty string if no URL is present. The...
```python import re def extract_license_url(license_text): url_match = re.search(r'(http[s]?:\/\/[^\n]+)', license_text) if url_match: return url_match.group(0) else: return "" ``` The `extract_license_url` function uses the `re` module to search for a URL pattern in the `license_text`. If...
magicoder
python
You are tasked with implementing a Python function that processes a list of test results and aggregates them based on certain criteria. The function should take into account the possibility of reruns for failed tests and should aggregate the results accordingly. You are given a code snippet from a test suite that uses...
```python from typing import List, Dict, Union def aggregate_test_results(test_results: List[Dict[str, Union[str, int]]]) -> List[Dict[str, Union[str, int]]]: aggregated_results = [] for test in test_results: if test["status"] == "failed" and test["reruns"] > 0: rerun_statuses = ["failed" f...
magicoder
python
You are tasked with creating a program that simulates a simple game of rock-paper-scissors. The game should allow a user to input their choice (rock, paper, or scissors), and then randomly generate a choice for the computer. The program should then determine the winner based on the standard rules of rock-paper-scissors...
```python import random def rock_paper_scissors(): choices = ['rock', 'paper', 'scissors'] user_choice = input("Enter your choice (rock, paper, or scissors): ").lower() computer_choice = random.choice(choices) print(f"Computer's choice: {computer_choice}") if user_choice not in choices: pr...
magicoder
python
You are given a string `s` consisting of lowercase English letters. Your task is to write a function `countConsecutiveChars` that counts the number of consecutive characters in the string and returns a list of tuples where each tuple contains a character and its consecutive count. The function signature is: ```python ...
```python from typing import List, Tuple def countConsecutiveChars(s: str) -> List[Tuple[str, int]]: if not s: return [] result = [] count = 1 for i in range(1, len(s)): if s[i] == s[i-1]: count += 1 else: result.append((s[i-1], count)) count...
magicoder
python
You are tasked with implementing a conflict detection algorithm for horizontal line segments in a routing system. The system has a set of parameters that influence the conflict detection process. The conflict penalty for overlapping line segments is defined as CONFLICT_PENALTY = 16. The parameters include: - routingStr...
```python def detect_conflicts(line_segments, routingStrategy, edgeSpacing, conflictThreshold, createdJunctionPoints): total_penalty = 0 for i in range(len(line_segments)): for j in range(i+1, len(line_segments)): seg1 = line_segments[i] seg2 = line_segments[j] if seg...
magicoder
python
You are tasked with implementing a Prolog program to manage a database of people and their ages. The program should allow for the addition of new people and their ages, as well as the ability to query and update the ages of existing people. The program should also provide a way to display the log of all operations perf...
```prolog :- dynamic person/2. :- dynamic log/1. add_person(Name, Age) :- assertz(person(Name, Age)), assertz(log('Added person: ' + Name + ', ' + Age)). update_age(Name, NewAge) :- retract(person(Name, _)), assertz(person(Name, NewAge)), assertz(log('Updated age for ' + Name + ': ' + NewAge)). a...
magicoder
prolog
You are tasked with creating a program that extracts Python method definitions from a given source file and generates a new file based on a set of inclusion and exclusion rules. The program should read a configuration file that specifies which files to include, as well as a whitelist and blacklist for method definition...
```python import re def extract_defs(config_file, source_files): included_methods = set() excluded_methods = set() # Read the configuration file to determine inclusion and exclusion rules with open(config_file, 'r') as config: for line in config: if line.startswith('.include'): ...
magicoder
python
You are tasked with creating a Python script that simulates a simplified version of a file system. Your script should implement a basic web-based file server using the ASGI protocol. The server will allow users to interact with files and directories through web-based Distributed Authoring and Versioning (WebDAV) method...
```python # asgi-webdav.py import uvicorn from fastapi import FastAPI, HTTPException from fastapi.responses import FileResponse from fastapi.middleware.cors import CORSMiddleware app = FastAPI() # Mock file system data file_system = { "file1.txt": "This is the content of file1.txt", "file2.txt": "This is the...
magicoder
python
You are tasked with implementing a downloader program that interacts with a user prompt for solving captchas. The provided code snippet sets up the downloader and registers a signal handler for interrupt signals. Your task is to create a class for the downloader and implement the necessary methods to handle captcha sol...
```python import signal import sys class Downloader: def __init__(self, captcha_solve_fnc): self.captcha_solve_fnc = captcha_solve_fnc signal.signal(signal.SIGINT, self.sigint_handler) def sigint_handler(self, sig, frame): self.terminate() print('Program terminated.') s...
magicoder
python
You are tasked with creating a program that simulates a simple multi-threading scenario. The program should create a specified number of threads, each of which will perform a specific task. Once all the threads have completed their tasks, the main program should print a message indicating that the threads have finished...
```python import threading def task(thread_id): print(f"Thread {thread_id} started task") # Simulate task execution print(f"Thread {thread_id} finished task") def main(): num_threads = 5 # Specify the number of threads threads = [] for i in range(num_threads): thread = threading.Thre...
magicoder
python
You are tasked with creating a Bash script that processes a list of files and performs specific operations on them. Your script should handle potential errors during file processing and provide appropriate error messages. Your script should accept a list of file paths as command-line arguments. For each file, it shoul...
```bash #!/bin/bash # Function to process a file process_file() { local file=$1 # Perform specific operation on the file # Example: Check if the file exists and is readable if [ ! -f "$file" ] || [ ! -r "$file" ]; then exit_error 1 "Error: File $file does not exist or is not readable" fi ...
magicoder
shell
You are tasked with creating a command-line tool for sending test emails to check email templates. The tool should be able to send test emails using different email templates to ensure that they are rendering correctly. Your task is to implement the `TestEmailsCommand` class, which will handle the sending of test email...
```php <?php use Illuminate\Console\Command; class TestEmailsCommand extends Command { /** * The console command description. * * @var string */ protected $description = 'Sends Test Emails to check templates'; /** * Create a new command instance. */ public function __con...
magicoder
php
You are tasked with implementing a custom safe floating-point arithmetic library using C++ and the Boost library. The library should handle various policies for checking addition operations, such as overflow, underflow, inexact results, and invalid results. Your goal is to create a class that encapsulates the safe floa...
```cpp #include <iostream> #include <boost/safe_float.hpp> #include <boost/safe_float/convenience.hpp> #include <boost/safe_float/policy/check_addition_overflow.hpp> #include <boost/safe_float/policy/check_addition_underflow.hpp> #include <boost/safe_float/policy/check_addition_inexact.hpp> #include <boost/safe_float/p...
magicoder
cpp