query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with creating a script to manage pool configurations for a system. The script contains a section that handles the modification of pool parameters. Your task is to implement a function that reads the existing pool configuration file and displays the old values for the parameters, or prompts the user to en...
```bash handlePoolConfig() { pool_config="${POOL_FOLDER}/${pool_name}/${POOL_CONFIG_FILENAME}" if [[ -f ${pool_config} ]]; then println "DEBUG" "# Pool Parameters" # Read and display old parameter values from the configuration file # Example: read parameter values from the file and display them #...
magicoder
shell
You are tasked with creating a test automation framework for a mobile application using Appium and Serenity BDD. The provided code snippet is a part of the test automation framework and shows the initialization of the AndroidDriver for interacting with mobile elements. Additionally, it includes the usage of Serenity BD...
```java // NavigateTo class public class NavigateTo { private AndroidDriver<MobileElement> webDriver; public NavigateTo(AndroidDriver<MobileElement> webDriver) { this.webDriver = webDriver; } public void navigateToPage(String pageName) { // Implement the logic to navigate to the specif...
magicoder
java
You are tasked with implementing a scheduling algorithm for a computer system. The system needs to schedule processes for execution based on their priority. You are given a class `GrrProgrammer` with a private member `grrProcedure` of type `writer.GrrProcedure`. Your task is to implement the scheduling algorithm using ...
```java import java.util.LinkedList; import java.util.Queue; public class GrrProgrammer { private writer.GrrProcedure grrProcedure; public GrrProgrammer(writer.GrrProcedure grrProcedure) { this.grrProcedure = grrProcedure; } public void scheduleProcesses() { Queue<writer.GrrProcedure>...
magicoder
java
You are tasked with implementing a file decoding procedure in Python. The `decode_proc` function takes in a file path and an optional parameter `yieldcount`, which specifies the number of decoded items to yield at a time. The file to be decoded contains data in the form of tuples, where each tuple represents a data rec...
```python from typing import List, Any, Tuple, Generator class DataDecoder: def decode_proc(self, filepath: str, yieldcount: int = 1000) -> Generator[Tuple[int, List[Any]], None, None]: with open(filepath, 'r') as file: batch = [] for line in file: try: ...
magicoder
python
You are tasked with creating a program that processes an image to extract numerical data and then performs specific operations on the extracted data. The program should use the Tesseract OCR (Optical Character Recognition) library to extract text from the image, filter out non-numeric characters, and display the proces...
```python import cv2 import pytesseract import numpy as np # Load the input image result = cv2.imread('input_image.jpg') # Use Tesseract OCR to extract text from the image data = pytesseract.image_to_string(result, lang='eng', config='--psm 10') # Filter out non-numeric characters and the decimal point processed_dat...
magicoder
python
You are tasked with implementing a function that processes and updates the state of a collection of items in a mobile app. The app has a feature that allows users to compare different versions of items, and the function needs to handle the logic for selecting and editing these items. You are given a code snippet that ...
```swift enum ComparisonState { case editing case viewing } struct Theme { // Theme properties and methods } struct Item { var revisionID: Int // Other item properties } struct ItemCell { func setEditing(_ editing: Bool) { // Update cell UI for editing state } func enable...
magicoder
swift
You are tasked with implementing a modified precision function for evaluating machine translation hypotheses. The modified precision function takes into account the n-gram matches between a reference translation and a hypothesis translation. An n-gram is a contiguous sequence of n items from a given sample of text or s...
```python from collections import Counter import math def ngrams(tokens, n): return [tuple(tokens[i:i + n]) for i in range(len(tokens) - n + 1)] def modified_precision(reference, hypothesis, n): reference_ngrams = Counter(ngrams(reference, n)) hypothesis_ngrams = Counter(ngrams(hypothesis, n)) clippe...
magicoder
python
You are tasked with creating a Python class that simulates a simple robot controller for a robot operating in a 2D grid environment. The robot can move in four directions: up, down, left, and right. The grid is represented as a 2D array, where each cell can be either empty (0) or occupied (1). The robot cannot move to ...
```python class RobotController: def __init__(self, grid): self.grid = grid self.current_position = self.find_starting_position() def find_starting_position(self): for i in range(len(self.grid)): for j in range(len(self.grid[0])): if self.grid[i][j] == 0: ...
magicoder
python
You are tasked with implementing a metric alias registry system in C#. The system should allow users to register and retrieve alias names for different metrics. To achieve this, you need to create a class that provides methods for registering and retrieving metric alias names. The alias names should be stored in a thre...
```csharp using System.Collections.Concurrent; public enum Metric { Metric1, Metric2, Metric3 } public class MetricAliasRegistry { private static readonly ConcurrentDictionary<Metric, string> MetricAliasNames = new ConcurrentDictionary<Metric, string>(); public void RegisterMetricAlias(Metric met...
magicoder
csharp
You are tasked with implementing a Python class for managing disclosed proofs in a verifiable credential exchange system. The provided code snippet is a part of the `DisclosedProof` class, which includes an asynchronous method `send_proof` for sending a proof to a connection. The `do_call` function is used to make asyn...
```python import json from ctypes import CFUNCTYPE, c_uint32 import asyncio class DisclosedProof: def __init__(self, handle): self.handle = handle self.logger = None # Assume logger is initialized elsewhere async def do_call(self, *args): # Assume implementation of do_call for making ...
magicoder
python
You are tasked with creating a role-based access control system for a web application. The system should allow users with specific permissions to perform actions on certain resources. In this scenario, you need to implement the authorization logic for deleting a question related to a subject. You are given a code snip...
To implement the authorization logic for the `destroy` method, you can use Laravel's built-in authorization features, such as policies and gates. First, define the policies for the `Subject` and `Question` models to specify the authorization rules. 1. Define a policy for the `Subject` model to check if the authenticat...
magicoder
php
You are tasked with implementing a class for managing populations in an evolutionary algorithm framework. The provided code snippet is a part of a method within this class that initializes the population based on different input types. The method first checks if the input is already a population object, and if so, uses...
```python import numpy as np class Individual: def __init__(self, attributes): self.attributes = attributes # Other individual-related methods and attributes can be added as per requirements class Population: def __init__(self, size, individual=None): self.size = size self.indi...
magicoder
python
You are tasked with implementing a Python function that processes a list of dictionaries representing geolocations. Each dictionary contains the keys "latitude" and "longitude" with corresponding numerical values. Your function should calculate the distance between each pair of geolocations and return a list of distanc...
```python from typing import List, Dict import math def calculate_distances(geolocations: List[Dict[str, float]]) -> List[float]: R = 6371 # Earth's radius in kilometers distances = [] for i in range(len(geolocations)): lat1, long1 = math.radians(geolocations[i]['latitude']), math.radians(geolocat...
magicoder
python
You are tasked with creating a program that performs string substitution based on a set of rules provided as command-line arguments. Your program should take a source string and a list of substitution rules, and then apply these rules to the source string to produce the final output. The substitution rules are provide...
```python import re import sys def apply_substitution_rules(source, rules): result = source for rule in rules: pattern = rule.split(' ')[2] # Extract the pattern to find replacement = rule.split(' ')[3] # Extract the replacement string result = re.sub(pattern, replacement, result) # ...
magicoder
python
You are tasked with implementing a custom syntax tree visitor for a programming language. The visitor will traverse the syntax tree and perform specific actions for different types of syntax nodes. Your task is to create a class that inherits from a base visitor class and overrides the necessary methods to handle diffe...
```csharp public class CustomSyntaxTreeVisitor : BaseVisitor { public override void VisitArrayType(ArrayTypeSyntax node) { // Custom logic for visiting ArrayTypeSyntax nodes } public override void VisitBranchInstruction(BranchInstructionSyntax node) { // Custom logic for visiting Br...
magicoder
csharp
You are tasked with implementing a custom data structure in Swift that simulates a queue with the following functionalities: 1. `enqueue`: Add an element to the end of the queue. 2. `dequeue`: Remove and return the element at the front of the queue. 3. `isEmpty`: Return a boolean indicating whether the queue is empty....
```swift import Foundation class Queue<T> { private var elements: [T] = [] private let queueSync = DispatchQueue(label: "com.example.queueSync", attributes: .concurrent) func enqueue(_ element: T) { queueSync.async(flags: .barrier) { self.elements.append(element) } } f...
magicoder
swift
You are tasked with implementing a class for managing user accounts in a system. The class, `Account`, should have the following functionalities: 1. Initialize an account with an ID, profile, wallet, and inventory. 2. Provide methods to retrieve and update the profile, wallet, and inventory associated with the account...
```python from src.Profile import Profile from src.Wallet import Wallet from src.Inventory import Inventory class Account: def __init__(self, id, profile, wallet, inventory): self.__id = id self.__profile = profile self.__wallet = wallet self.__inventory = inventory def get_pr...
magicoder
python
You are tasked with creating a Python class that handles the parsing of a specific XML configuration file for a storage system. The class should include a method to read the XML file, parse its content, and handle any potential errors that may occur during the process. Your task is to implement the `_read_xml` method ...
```python import xml.etree.ElementTree as ET class StorageSystemConfigParser: def __init__(self, configuration): self.configuration = configuration def _read_xml(self): """Open xml file and parse the content.""" filename = self.configuration.manila_nexenta_conf_file print "NEXE...
magicoder
python
You are tasked with implementing a program to analyze the frequency of n-grams in a given text. An n-gram is a contiguous sequence of n items from a given sample of text or speech. In this problem, you are required to write a function that takes a text string and an integer n as input and returns the frequency of each ...
```python def calculateNGramFrequency(text, n): words = text.split() ngrams = [' '.join(words[i:i+n]) for i in range(len(words)-n+1)] frequency = {} for gram in ngrams: if gram in frequency: frequency[gram] += 1 else: frequency[gram] = 1 return frequency ``` ...
magicoder
python
You are tasked with creating a Python program to scrape and process data from a sports news website using the Scrapy framework. The website "Mundodeportivo" is the target for this web scraping task. The code snippet provided is the beginning of a Scrapy spider named "MundodeportivoSpider" for this purpose. Your task is...
```python # -*- coding: utf-8 -*- import scrapy import re import json import urllib.parse import datetime import random class MundodeportivoSpider(scrapy.Spider): name = "md" def start_requests(self): urls = ['https://www.mundodeportivo.com/'] for url in urls: yield scrapy.Requ...
magicoder
python
You are given a code snippet that is part of a function to remove duplicate elements from a singly linked list. The code snippet is responsible for identifying and removing duplicate elements from the list. Your task is to implement the function to remove the duplicate elements from the singly linked list and return th...
```cpp ListNode* removeDuplicates(ListNode* head) { if (head == nullptr || head->next == nullptr) { return head; } ListNode* current = head; while (current != nullptr && current->next != nullptr) { if (current->val == current->next->val) { ListNode* temp = current->next; ...
magicoder
cpp
You are tasked with creating a program to determine the eligibility for military service based on a person's age. In Brazil, military service is mandatory for all male citizens at the age of 18. The provided code snippet is a part of a program that checks the eligibility for military service and provides relevant infor...
```python ano_atual = 2022 # Current year idade = 20 # Person's age if idade == 18: print("É a hora de se alistar no serviço militar, IMEDIATAMENTE!") elif idade < 18: saldo = 18 - idade print(f"Ainda falta {saldo} anos para o seu alistamento!") ano = ano_atual + saldo print(f"Seu alistamento ser...
magicoder
python
You are tasked with creating a Python function that simulates a simple blockchain network. The function will be responsible for running a validator node on a specified host. The validator node can also act as a boot node and can be configured as a validator or non-validator node. Your task is to complete the implement...
```python def run_validator_node(host, is_boot_node, is_validator): print('Run validator node on host', host, 'is_boot_node =', is_boot_node) if not args.with_existing_data: init_node(host) init_keystore(host) docker_command = f"docker run -d {'--name validator' if is_validator else ''} {'--...
magicoder
python
You are tasked with creating a Python function that reads a text file and performs text analysis using the Natural Language Toolkit (nltk) library. Your function should read the contents of a specified file and then tokenize the text, identify named entities, and count the occurrences of specific words. Write a functi...
```python import nltk from nltk import word_tokenize, ne_chunk from collections import Counter nltk.download("punkt") nltk.download('maxent_ne_chunker') nltk.download('averaged_perceptron_tagger') nltk.download("stopwords") def text_analysis(file_path, target_words): with open(file_path, 'r') as file: tex...
magicoder
python
You are tasked with implementing a function that interacts with a web service to place an order. The function takes in a list of root certificates, a data builder function, and a URL. It then makes a POST request to the specified URL using the provided root certificates and data builder function. The response is expect...
```rust use std::error::Error; struct Order { // Define the structure of the Order type } fn place_order<F>( endpoint: &str, root_certs: &[String], data_builder: &F, url: &str, ) -> Result<Order, Error> where F: Fn(&str, &str) -> Result<String, Error>, { // Make a POST request to the speci...
magicoder
rust
You are tasked with implementing a Python program to handle bibliographic data using Digital Object Identifiers (DOIs). The program should prompt the user to input a DOI, retrieve the bibliographic data associated with the DOI, and then display the retrieved data. If the user enters 'q' as the DOI, the program should t...
```python import requests class AbortException(Exception): pass class Work: @staticmethod def from_doi(doi): # Simulate retrieving bibliographic data from a web service response = requests.get(f"https://api.crossref.org/works/{doi}") if response.status_code == 200: retu...
magicoder
python
You are tasked with implementing a simple HTML representation (HRepr) parser that can extract and process specific elements from a given HTML representation string. The HRepr format is a simplified representation of HTML using nested lists and strings. Each HTML tag is represented as a list with the tag name as the fir...
```python from typing import List def extract_elements(hrepr: str, tag_name: str) -> List[str]: stack = [] result = [] i = 0 while i < len(hrepr): if hrepr[i:i+len(tag_name)+3] == f'H.{tag_name}': stack.append(i) elif hrepr[i:i+len(tag_name)+5] == f'H./{tag_name}': ...
magicoder
python
You are tasked with implementing a Python class that simulates a stack data structure. The class should support the following operations: 1. `push(item)`: Add an item to the top of the stack. 2. `pop()`: Remove and return the item at the top of the stack. 3. `peek()`: Return the item at the top of the stack without re...
```python class Stack: def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): if not self.is_empty(): return self.items.pop() else: raise IndexError("Cannot pop from an empty stack") def peek(self): ...
magicoder
python
You are tasked with creating a Python class that implements a QA Trainer for Seq2Seq (Generative + Extractive) models. The class should have the ability to evaluate examples and apply a post-processing function to model outputs. Your task is to implement the `QASeq2SeqTrainer` class with the following specifications: ...
```python from typing import Callable class QASeq2SeqTrainer(BaseClass): # Inherit from the appropriate base class def __init__( self, eval_examples: datasets.Dataset = None, post_process_function: Callable = None, **kwargs ): """ QA Trainer for Seq2Seq(Generative + Ext...
magicoder
python
You are tasked with implementing a Python class decorator that anonymizes the attributes of a given class. The decorator should modify the class such that any attribute access or modification logs the action to the console before performing the actual operation. Additionally, the decorator should ensure that the class ...
```python def anonymize(cls): class AnonymizedClass(cls): def __getattribute__(self, name): print(f"Accessed attribute {name}") return super().__getattribute__(name) def __setattr__(self, name, value): print(f"Modified attribute {name} with value {value}") ...
magicoder
python
You are tasked with creating a program that analyzes and modifies CSS styles for a given HTML document. The program should be able to read an HTML file and identify specific CSS properties within the `<style>` tag. For this problem, you need to focus on extracting and modifying the CSS properties related to button elem...
```javascript function modifyButtonStyles(htmlContent, newFontSize, newMarginTop) { const styleTagRegex = /<style>([\s\S]*?)<\/style>/; const buttonStyleRegex = /button\s*{\s*([\s\S]*?)\s*}/; const styleTagMatch = htmlContent.match(styleTagRegex); if (styleTagMatch) { const styleContent = style...
magicoder
javascript
You are tasked with creating a Python class that simulates a simple banking system. The class should have methods for depositing funds, withdrawing funds, and checking the account balance. Additionally, the class should be able to handle multiple accounts and provide a method for transferring funds between accounts. Y...
```python class BankAccount: def __init__(self, holder_name): self.holder_name = holder_name self.balance = 0 def deposit(self, amount): self.balance += amount def withdraw(self, amount): if amount <= self.balance: self.balance -= amount else: ...
magicoder
python
You are tasked with creating a Python script that extracts metadata information from a given code snippet. The metadata includes the title, description, URL, and version of a Python package. Your script should be able to parse the given code snippet and extract the metadata information. Write a function `extract_metad...
```python import re def extract_metadata(code_snippet: str) -> dict: metadata = {} metadata_pattern = r'__(\w+)__ = "(.*?)"' matches = re.findall(metadata_pattern, code_snippet) for key, value in matches: metadata[key] = value return metadata ``` The `extract_metadata` function us...
magicoder
python
You are tasked with implementing a simplified version of a card game involving animals and coins. The game involves a player's hand, a deck of coins, and different animal types represented by dice values. Your goal is to create a method that adds a specified number of occurrences of a particular animal to the player's ...
```csharp private void AddAnimal(IHand hand, AnimalEnum diceValue, CoinDeck deck, int numberOfOccurrences = 1) { if (numberOfOccurrences <= 0) { throw new ArgumentException("Number of occurrences must be a positive integer."); } if (deck.IsEmpty()) { throw new InvalidOperationExcept...
magicoder
csharp
You are tasked with designing a SQL query to retrieve information about wires located within specific types of tiles in a circuit layout. The database contains two tables: `wire_in_tile` and `selected_tile`. The `wire_in_tile` table has the following columns: - `name`: the name of the wire - `phy_tile_type_pkey`: the ...
```sql SELECT name FROM wire_in_tile WHERE wire_in_tile.phy_tile_type_pkey = ( SELECT tile_type_pkey FROM selected_tile ); ``` In the solution, the SQL query uses the `SELECT` clause to retrieve the `name` column from the `wire_in_tile` table. The `WHERE` clause is used to filter the rows wh...
magicoder
sql
You are tasked with implementing a simple wrapper for a low-level input device in Rust. The provided code snippet contains two functions: `from_ptr` and `as_ptr`. The `from_ptr` function takes a raw pointer to a `wlr_input_device` and returns a `Device` instance, while the `as_ptr` function returns a raw pointer to the...
```rust use std::ptr; struct wlr_input_device { // Define the wlr_input_device struct here } pub(crate) struct Device { device: *mut wlr_input_device, } impl Device { pub(crate) unsafe fn from_ptr(device: *mut wlr_input_device) -> Self { Device { device } } pub(crate) unsafe fn as_ptr(&s...
magicoder
rust
You are working on an image processing project and need to implement a specific thresholding algorithm to segment an image. The given code snippet contains some operations related to thresholding and image manipulation using the OpenCV and NumPy libraries in Python. Your task is to understand the code and implement the...
```python import cv2 import mahotas import numpy as np # Assuming 'temp', 'suave', and 'img' are already defined # Calculate the threshold value T using mahotas.thresholding.rc method T = mahotas.thresholding.rc(suave) # Apply thresholding to the 'temp' image using the calculated threshold value T temp[temp > T] = 2...
magicoder
python
You are tasked with creating a Java class that performs facial detection using a parallel command group. The class should take in a command for recognizing faces and an array of commands that implement the `IStreamInput` interface with type `Integer`. The `RunFacialDetection` class should execute the facial recognition...
```java import frc.stream.InputDataStream; import frc.stream.OutputDataStream; import frc.stream.StreamData; import org.opencv.core.Rect; import javax.annotation.Nonnull; public class RunFacialDetection extends ParallelCommandGroup { /** * @param recognizeFaceCommand command that recognizes faces * @pa...
magicoder
java
You are given a list of strings, each representing a sequence of words. Your task is to create a function `my_solution` that replaces all occurrences of the word "right" with "left" and vice versa in each string, and then concatenates the modified strings with commas. For example: - If the input is `('left', 'right', ...
```python def my_solution(strings): modified_strings = [] for s in strings: modified_s = s.replace('right', 'temp').replace('left', 'right').replace('temp', 'left') modified_strings.append(modified_s) return ','.join(modified_strings) ``` The `my_solution` function iterates through each str...
magicoder
python
You are given a 2D grid representing a chessboard with dimensions `r` rows and `c` columns. Each cell of the grid is either empty or contains an obstacle. You are also given the coordinates of a starting cell `(x1, y1)` and a target cell `(x2, y2)`. Your task is to determine if there exists a sequence of valid knight ...
```cpp #include <vector> #include <queue> using namespace std; bool isValid(int x, int y, int r, int c, vector<vector<int>>& grid) { return x >= 0 && x < r && y >= 0 && y < c && grid[x][y] == 0; } bool canReachTarget(int r, int c, vector<vector<int>>& grid, int x1, int y1, int x2, int y2) { vector<int> dx = {...
magicoder
cpp
You are tasked with implementing a neural network architecture for image classification. The network consists of several layers, each denoted by a specific function call. The input to each layer is the output of the previous layer. Your task is to write the code for the missing layer functions (`b31`, `b32`, `b33`, `b3...
```python import tensorflow as tf class NeuralNetwork: def __init__(self): self.conv1 = tf.keras.layers.Conv2D(64, (3, 3), activation='relu', padding='same') self.conv2 = tf.keras.layers.Conv2D(64, (3, 3), activation='relu', padding='same') self.maxpool1 = tf.keras.layers.MaxPooling2D((2, 2...
magicoder
python
You are tasked with simulating a dart-throwing game using Python. The goal is to create a program that simulates the throwing of darts at a circular target and then visualizes the results using a scatter plot. The program should generate random dart throws within the bounds of the circular target and then plot the resu...
```python import matplotlib.pyplot as plt import numpy as np # Define the circular target radius = 1 center = (0, 0) # Simulate the throwing of darts num_darts = 1000 x = np.random.uniform(-radius, radius, num_darts) y = np.random.uniform(-radius, radius, num_darts) distance = np.sqrt(x**2 + y**2) # Plot the dart th...
magicoder
python
You are tasked with implementing a function that processes a list of hero powers and minion powers in a game. The function should determine the outcome of each power interaction and return the resulting list of powers after the interactions have been resolved. You are given the following information: - The hero powers...
```python from typing import List def processPowers(heroPowers: List[int], minionPowers: List[int]) -> List[int]: result = [] for hero, minion in zip(heroPowers, minionPowers): if hero > minion: result.append(hero - minion) elif minion >= hero: result.append(minion - her...
magicoder
python
You are working on a data preprocessing task for a molecular database using Python and pandas. The given code snippet is part of the data preparation process. The `db` dataframe contains information about molecules, including a column `npl` representing a specific property. The code performs the following operations: 1...
```python import pandas as pd def preprocess_data(db: pd.DataFrame, temp: pd.DataFrame) -> pd.DataFrame: # Concatenate temp to db along the rows db = pd.concat([db, temp], axis=0) # Reset index and drop the previous index db.reset_index(inplace=True, drop=True) # Get indices of molecules with mis...
magicoder
python
You are tasked with creating a Python function that processes and visualizes COVID-19 test result data for a specific county. The function should take a DataFrame containing historical test result data as input and generate a line plot showing the percentage of positive test results over time. Additionally, the functio...
```python import matplotlib.pyplot as plt import matplotlib.dates as mdates import os from datetime import datetime def visualize_covid_data(history): fig, ax = plt.subplots() percentage_positive = history['Positive Test Results'] / (history['Positive Test Results'] + history['Negative Test Results']) * 100 ...
magicoder
python
You are given a Python code snippet that defines a function `n(pos)` and a variable `empty` that is a set. The `n(pos)` function takes a tuple `pos` representing a position and yields neighboring positions based on certain conditions. The code snippet also includes an increment operation on a variable `count` and the a...
```python def find_empty_positions(grid): empty = set() for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 0: for neighbor in n((i, j)): if grid[neighbor[0]][neighbor[1]] == 0: empty.add((i, j)) ...
magicoder
python
You are tasked with creating a mixin system for a JavaScript application. Mixins are a way to mix functionality into a class by including methods from other classes. Your goal is to implement a MixinComponent class that allows other classes to easily incorporate mixins. Your MixinComponent class should have the follow...
```javascript // MixinComponent.js class MixinComponent { constructor() { this.mixins = {}; } registerMixin(name, mixin) { if (this.mixins[name]) { throw new Error(`Mixin with name ${name} is already registered`); } this.mixins[name] = mixin; } applyMixins(targetClass) { for (const...
magicoder
javascript
You are tasked with creating a script to automate the compilation of C++ source files using the `clang++` compiler. The script should compile two separate source files, `main.cpp` and `angelcode.cpp`, and generate executable files named `sdffont` and `angelcode2font` respectively. The compilation should include debuggi...
```bash #!/bin/bash set -e # Compile main.cpp clang++ -o sdffont -g -O3 -m64 -Wall -Isource source/main.cpp || { echo "Compilation of main.cpp failed"; exit 1; } # Compile angelcode.cpp clang++ -o angelcode2font -g -O3 -m64 -Wall source/angelcode.cpp || { echo "Compilation of angelcode.cpp failed"; exit 1; } echo "C...
magicoder
shell
You are tasked with developing a program to process a text file containing data records. Each record is represented by a series of lines, with an empty line indicating the end of a record. Your program should read the file, process the records, and perform specific operations on the data within each record. Your task ...
```python def process_records(file_path): averages = [] with open(file_path, 'r') as file: record_number = 1 record_values = [] for line in file: if line == "\n": if record_values: average = sum(record_values) / len(record_values) ...
magicoder
python
You are tasked with creating a script to automate the execution of a series of R scripts for analyzing genomic data. The script should handle the execution of the R scripts in the background and capture the output and errors in log files. Your task is to write a Bash script that accomplishes this automation. Your Bash...
```bash #!/bin/bash # Check if the correct number of arguments are provided if [ "$#" -ne 3 ]; then echo "Usage: $0 <path_to_R_executable> <path_to_R_script> <log_file_name>" exit 1 fi # Assign input parameters to variables R_executable="$1" R_script="$2" log_file="$3" # Execute the R script in the backgroun...
magicoder
shell
You are tasked with implementing a mesh refinement algorithm for a 2D finite element analysis program. The mesh refinement process involves dividing each element in the mesh into smaller sub-elements to improve the accuracy of the analysis. Your task is to design a class `MeshRefiner` that can refine the mesh based on ...
```python class MeshRefiner: def __init__(self, mesh: Mesh): self.mesh = mesh def refine(self, criteria: Callable[[Element], bool]) -> Mesh: refined_elements = [] for element in self.mesh.elements: if criteria(element): refined_elements.extend(self._refine_el...
magicoder
python
You are given a square matrix `a` of size `n x n` and an integer `k`. Your task is to write a program to extract specific elements from the matrix and print them in a specific order. You need to perform the following steps: 1. Extract elements from the matrix `a` based on the following rules: - Take the elements fr...
```cpp #include <iostream> #include <fstream> using namespace std; int main() { int n, k; cin >> n; int a[n+1][n+1]; for(int i=1; i<=n; i++) for(int j=1; j<=n; j++) cin >> a[i][j]; int x = 0; int v[n*n+1]; for(int i=1; i<=n/2; i++) { x++; v[x] = a[i]...
magicoder
cpp
You are tasked with creating a Rust program that simulates a simple inventory management system for a small store. The program should allow users to add, remove, and update the quantity of items in the inventory. Additionally, it should provide the ability to display the current inventory and calculate the total value ...
```rust struct Item { name: String, price: f64, quantity: i32, } impl Item { fn new(name: String, price: f64, quantity: i32) -> Item { Item { name, price, quantity } } } fn add_item(inventory: &mut Vec<Item>, name: String, price: f64, quantity: i32) { let item = Item::new(name, price, ...
magicoder
rust
You are tasked with implementing a function that determines whether editing a cell in a grid is allowed based on the column index and certain rules. The grid is represented as a 2D array, and the rules for allowing cell editing are as follows: - If the column index is less than 0 or greater than or equal to the number ...
```python def isCellEditingAllowed(grid, column): num_columns = len(grid[0]) if column < 0 or column >= num_columns: return False return column % 2 == 0 ``` The `isCellEditingAllowed` function first checks if the column index is out of range, returning `False` if it is. Otherwise, it returns `True` ...
magicoder
python
You are tasked with implementing a function that simulates a simple job scheduling system in Swift. The function `waitThenRunOnMain` takes two parameters: `delay`, a `Double` representing the time delay in seconds, and `closure`, a closure that represents the task to be executed after the delay. The function schedules ...
```swift import Foundation func waitThenRunOnMain(delay: Double, closure: () -> Void) { let dispatchTime = DispatchTime.now() + delay DispatchQueue.main.asyncAfter(deadline: dispatchTime, execute: closure) } ``` In the solution, we import the `Foundation` framework to access the `DispatchQueue` and `DispatchT...
magicoder
swift
You are tasked with implementing a custom dataset class for a machine learning project. The dataset consists of audio files, where each audio file is a mixture of multiple sound sources, and the corresponding target file contains the individual sound sources separated from the mixture. Your goal is to create a custom d...
```python import torch from torch.utils.data import Dataset import librosa import numpy as np class InstanceDataset(Dataset): def __init__(self, mix_file_path, target_file_path): self.mix_file_path = mix_file_path self.target_file_path = target_file_path # Add any additional initialization ...
magicoder
python
You are tasked with creating a simple iOS app that allows users to rate items using a star-based rating system. The app should display a list of items, and when a user taps on an item, a new screen should appear with the item details and a star rating component. The user can then tap on the stars to rate the item, and ...
```swift import UIKit protocol StarRatingViewDelegate: AnyObject { func didChangeRating(_ rating: Int) } class StarRatingView: UIView { weak var delegate: StarRatingViewDelegate? private var rating: Int = 0 private var starButtons: [UIButton] = [] override init(frame: CGRect) { super.init...
magicoder
swift
You are tasked with implementing a Python class that represents a 3D point in spherical coordinates. The class should provide methods for converting between spherical and Cartesian coordinates, as well as for calculating the distance between two points in spherical coordinates. You are given the following code snippet...
```python from math import sin, cos, sqrt, atan2, hypot from typing import NamedTuple, Tuple class Spherical(NamedTuple): rot_x: float # Rotation around the X-axis, in radians rot_y: float # Rotation around the Y-axis, in radians def to_cartesian(self) -> Tuple[float, float, float]: r = cos(sel...
magicoder
python
You are tasked with implementing a function to verify the authenticity of a digital signature using the secp256k1 elliptic curve cryptography library in JavaScript. You are given the following code snippet as a reference: ```javascript const sig = new secp.Signature(r, s); deepStrictEqual(secp.verify(sig, msg, pub), ...
```javascript const secp = require('secp256k1'); function verifySignature(r, s, msg, pub) { const sig = new secp.Signature(r, s); return secp.verify(sig, Buffer.from(msg, 'utf8'), Buffer.from(pub, 'hex')); } ``` The `verifySignature` function uses the `secp` library to create a signature object from the component...
magicoder
javascript
You are tasked with implementing a function to manage the creation of execution engines for a blockchain system. The function, `create_execution_engine`, takes three input parameters: `ee_lmdb_path`, `default_max_db_size`, and `manual_sync_enabled`. The `ee_lmdb_path` parameter represents the path to the LMDB (Lightnin...
```rust use std::path::Path; use std::sync::Arc; use log::info; use anyhow::Error; use engine_state::EngineState; use lmdb::LmdbEnvironment; /// Creates a new execution engine. pub fn create_execution_engine( ee_lmdb_path: impl AsRef<Path>, default_max_db_size: usize, manual_sync_enabled: bool, ) -> Result...
magicoder
rust
You are working on a computer vision project and need to implement a custom layer for local response normalization (LRN) in a convolutional neural network (CNN). The LRN layer is a common component in CNN architectures and is used to normalize the responses across channels to improve generalization and reduce overfitti...
```python import torch import torch.nn as nn import torch.nn.functional as F class CustomLRN(nn.Module): def __init__(self, size=1, alpha=1.0, beta=0.5, k=1.0): super(CustomLRN, self).__init__() self.size = size self.alpha = alpha self.beta = beta self.k = k def forward...
magicoder
python
You are tasked with simulating a race between two rabbits, "大白兔" (Big White Rabbit) and "小肥兔" (Little Fat Rabbit). Each rabbit is represented by a separate thread in Java. The rabbits will move forward in a race, and the first rabbit to reach the finish line will be declared the winner. You are provided with the follo...
```java public class RabbitRunnable implements Runnable { private static int distance = 100; // The distance to the finish line @Override public void run() { while (distance > 0) { int move = (int) (Math.random() * 10); // Each step is a random distance between 0 and 10 sync...
magicoder
java
You are tasked with implementing a Python class that represents a data structure for storing key-value pairs. The class should support adding, updating, and retrieving key-value pairs, as well as deleting key-value pairs. Additionally, the class should provide a method to return a list of all keys in the data structure...
```python class KeyValueStore: def __init__(self): self.data = {} def add(self, key, value): self.data[key] = value def update(self, key, value): if key in self.data: self.data[key] = value else: raise KeyError("Key not found") def get(self, key...
magicoder
python
You are tasked with implementing a program to parse and analyze HTML table data. Given a snippet of HTML code representing a table, your program should extract the table data and calculate the average value of a specific column. You are provided with a snippet of HTML code representing a table. The table contains rows...
```javascript function calculateAverageFromHTML(htmlSnippet, columnIndex) { const parser = new DOMParser(); const doc = parser.parseFromString(htmlSnippet, 'text/html'); const table = doc.querySelector('table'); const rows = table.querySelectorAll('tr'); let sum = 0; let count = 0; for (let i = 1; i < r...
magicoder
javascript
You are tasked with creating a Python function that validates and formats URLs according to a specific format. The function should take a URL and a format string as input and return the formatted URL if it matches the specified format. If the URL does not match the format, the function should raise a ValueError with a ...
```python def validate_and_format_url(url: str, format: str) -> str: placeholders = [p.strip('{}') for p in format.split('}')[:-1]] components = url.split('/') format_components = format.split('/') for i in range(len(format_components)): if '{' in format_components[i] and '}' in format_comp...
magicoder
python
You are tasked with implementing a C++ class that demonstrates the concept of function overloading with ref-qualifiers. Ref-qualifiers were introduced in C++11 to specify whether a member function can be called on an lvalue, rvalue, or both. Your task is to create a class `OverloadedFunctions` with two member functions...
```cpp #include <iostream> class OverloadedFunctions { private: int data; public: OverloadedFunctions() : data(0) {} void process(int& value) & { data += value; } void process(int&& value) && { data -= value; } int getData() const { return data; } }; int mai...
magicoder
cpp
You are tasked with implementing a Graph Object-Relational Mapping (ORM) system in Python. An ORM system is a programming technique for converting data between incompatible type systems using object-oriented programming languages. In this problem, you will create a simplified version of a Graph ORM system that allows u...
```python class GraphORM: def __init__(self): self.graph = {} # Initialize an empty graph def register_node(self, node_class): if not isinstance(node_class, type): raise TypeError("Argument should be a class") # Add the node class to the graph self.graph[node_class....
magicoder
python
You are tasked with creating a Python function that parses a given module file and extracts the names of unit operations for size reduction. The module file contains documentation in reStructuredText format, and the unit operations are listed under the "Unit operations" section. Write a function called `extract_unit_o...
```python import re def extract_unit_operations(file_path): with open(file_path, 'r') as file: content = file.read() unit_operations = re.findall(r'\.\. autoclass:: (.+)', content) return unit_operations ``` The `extract_unit_operations` function opens the specified file, reads its content, and t...
magicoder
python
You are tasked with creating a Bash script that automates the process of updating version numbers in a given file. The script should take in a message, old version number, and new version number as command-line arguments and then update the version number in the specified file. If the file contains the old version numb...
```bash #!/usr/bin/env bash if [ $# -lt 3 ]; then echo "usage: $0 message <old-version> <new-version>" exit 1 fi message=$1 old_version=$2 new_version=$3 file_path="path/to/your/file" # Replace with the actual file path if grep -q "$old_version" "$file_path"; then sed -i "s/$old_version/$new_version/g" "$file...
magicoder
shell
You are tasked with creating a Python script that utilizes the PyBullet physics engine and OpenAI Gym to simulate a simple robotic arm picking up and stacking blocks in a 3D environment. The goal is to implement the logic for the robotic arm to successfully pick up a block and place it on top of another block. Your ta...
```python import pybullet as p import pybullet_data import gym def pick_and_stack_blocks(env, joint_angles): # Load the URDF file for the robotic arm arm_urdf_path = "path_to_arm_urdf_file.urdf" arm_id = p.loadURDF(arm_urdf_path, [0, 0, 0]) # Load the block URDF file block_urdf_path = "path_to_blo...
magicoder
python
You are tasked with implementing a module resolution system for a JavaScript project. The project has a file structure with multiple modules and interfaces. Your goal is to create a function that resolves and exports all the interfaces from a specific module. You are given a code snippet from the project's entry file:...
```javascript function resolveModuleInterfaces(moduleName) { const modulePath = `./${moduleName}/`; const moduleInterfaces = require(modulePath); const interfaces = {}; for (const key in moduleInterfaces) { if (Object.prototype.hasOwnProperty.call(moduleInterfaces, key)) { interfaces[key] = moduleInt...
magicoder
javascript
You are tasked with creating a Python function that evaluates the fitness of a supervised model using a given training data set loader. The function should be able to handle random seed generation, optional model seed, silent mode, input collection, and CUDA support. Your task is to implement the `supervised_eval` func...
```python import torch import random def supervised_eval(model, train_loader, random_seed, mseed=None, silent=False, collect_inputs=False, do_cuda=False, **kwargs): # Set random seed for reproducibility random.seed(random_seed) if mseed is not None: torch.manual_seed(mseed) # Set model seed f...
magicoder
python
You are tasked with implementing a generic interface for managing sites in a cloud infrastructure management system. The interface, `ISiteOperations<T>`, provides methods for retrieving site information asynchronously. The `Site` class is a base class for different types of sites in the system. Your task is to create ...
```csharp using System; using System.Collections.Generic; using System.Threading.Tasks; namespace UKFast.API.Client.ECloud.Operations { // Base class for different types of sites public class Site { // Properties and methods common to all types of sites } // Concrete implementation of ISit...
magicoder
csharp
You are tasked with creating a Python function that simulates the behavior of a test case runner for a unit testing framework. The function should take a list of test case numbers and a test class as input, and then execute the test methods associated with each test case number in the given test class. The test methods...
```python def run_test_cases(test_class, case_numbers): import unittest # Dynamically create a test suite suite = unittest.TestSuite() # Iterate through the case numbers and add corresponding test methods to the suite for case_num in case_numbers: test_method_name = f"test_parse_time_case{...
magicoder
python
You are tasked with implementing a Python function that processes a list of entries, each representing a word and its associated part of speech tag. The function should organize the entries into a dictionary where the keys are the part of speech tags and the values are lists of words corresponding to each tag. Addition...
```python def organize_entries(entries: list) -> dict: organized_dict = {} for entry in entries: tag = entry['tag'] word = entry['word'] synonyms = [syn.replace('_', ' ') for syn in entry['synonyms']] if tag in organized_dict: organized_dict[tag].append(word) ...
magicoder
python
You are tasked with implementing a custom annotation processor for a Java project. The annotation processor should generate code to validate the format of a specific field in a class. The validation format is specified using a regular expression provided as a parameter to the custom annotation. Your task is to create ...
```java // Define the custom annotation @FormatValidation import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.SOURCE) @Target(ElementType.FIELD) public @interface FormatValidation { ...
magicoder
java
You are tasked with implementing a custom project management service that handles the storage and retrieval of project information. The service should support the hashing of project objects based on their name, SHA hash, and certification type. Additionally, the service should provide methods for adding, retrieving, an...
```python class Project: def __init__(self, name, sha_hash, cert_type): self.name = name self.sha_hash = sha_hash self.cert_type = cert_type def __hash__(self): return hash((self.name, self.sha_hash, self.cert_type)) class _ProjectManagementService: def __init__(self): ...
magicoder
python
You are tasked with implementing a Python class method that truncates a string if its length exceeds a certain limit. If the string is longer than the limit, it should be truncated and appended with an ellipsis ("..."). If the string is within the limit, it should be returned as is. You need to implement the `truncate...
```python class TextTruncator: def __init__(self, content): self.content = content def truncate_string(self): if len(str(self.content)) > 40: return '{}…'.format(str(self.content)[0:40]) # Truncate the string and append an ellipsis else: return str(self.content)...
magicoder
python
You are tasked with implementing a simple hierarchical data structure in Rust. The structure consists of nodes, each of which can have zero or more child nodes. Each node has an `on_assemble` method that needs to be called when the node is assembled. Your task is to implement the `Node` struct and its associated method...
```rust struct Node { children: Vec<Node>, } impl Node { fn new() -> Self { Node { children: Vec::new() } } fn add_child(&mut self, child: Node) { self.children.push(child); } fn on_assemble(&mut self) { // Perform the on_assemble operation for the current node ...
magicoder
rust
You are tasked with creating a program that can analyze and modify ASCII art representations of text. The program should be able to perform two operations: "colorize" and "replace". The "colorize" operation involves changing the color of a specific word in the ASCII art, while the "replace" operation involves replacing...
```rust fn modify_ascii_art(ascii_art: &str, operation: &str, params: &str) -> String { let mut modified_art = String::new(); match operation { "colorize" => { let parts: Vec<&str> = params.split(':').collect(); let word_to_colorize = parts[0]; let color = parts[1]; ...
magicoder
rust
You are tasked with implementing a circular buffer data structure in Rust. The circular buffer has a fixed capacity and supports the following operations: 1. `push`: Adds an element to the buffer. If the buffer is full, it returns an error. 2. `pop`: Removes and returns an element from the buffer. If the buffer is empt...
```rust fn main() { let mut buffer: CircularBuffer<i32> = CircularBuffer::new(3); assert_eq!(buffer.push(1), Ok(())); assert_eq!(buffer.push(2), Ok(())); assert_eq!(buffer.push(3), Ok(())); assert_eq!(buffer.push(4), Err("Buffer full")); assert_eq!(buffer.pop(), Ok(1)); assert_eq!(buffer.pop...
magicoder
rust
You are tasked with implementing a function to analyze a package graph and identify any errors that may have occurred during the loading process. The package graph is represented as a directed graph, where each node represents a package and each edge represents a dependency relationship between packages. The function s...
```go func FindErrorPackages(graph PackageGraph) []string { var errorPackages []string if graph.diags.hasErrors { for pkg := range graph.nodes { errorPackages = append(errorPackages, pkg) } } return errorPackages } ``` The `FindErrorPackages` function checks if the `hasError...
magicoder
go
You are tasked with implementing a visitor pattern for a simple bytecode instruction set used in a virtual machine. The bytecode instructions are represented by different classes, each corresponding to a specific operation. The visitor pattern allows you to define new operations to be performed on these bytecode instru...
```java // Visitor interface defining visit methods for each bytecode instruction interface InstructionVisitor { void visitPushInstruction(PushInstruction instruction); void visitTypedInstruction(TypedInstruction instruction); void visitACONST_NULL(ACONST_NULL instruction); // Add visit methods for othe...
magicoder
java
You are tasked with implementing a method to parse a JSON configuration file and extract specific information from it. The configuration file is in a specific format and contains settings for a language server. Your goal is to extract the language setting from the configuration file and return it as a string. You are ...
```java import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.JsonNode; import java.io.File; import java.io.IOException; public class ConfigurationParser { public String getLanguageFromConfigurationFile() { File configFile = new File("src/test/resources/LSConfiguration...
magicoder
java
You are tasked with implementing a simple iOS application for controlling a home entertainment system. The application has a user interface with the following elements: - `vwConnectionControl`: A view representing the connection control section. - `vwVolumeControl`: A view representing the volume control section. - `b...
```swift import UIKit class EntertainmentViewController: UIViewController { @IBOutlet weak var vwConnectionControl: UIView! @IBOutlet weak var vwVolumeControl: UIView! @IBOutlet weak var btnMuteOnOff: UIButton! @IBOutlet weak var btnPowerOff: UIButton! @IBOutlet weak var btnAVOnOff: UIButton! @...
magicoder
swift
You are tasked with creating a Python class to manage products in an e-commerce system. The class should include methods to add, update, and delete products, as well as retrieve product information. Additionally, you need to implement a method to calculate the total value of all products in the system. Your task is to...
```python class Product: def __init__(self, product_code, name, price): self.product_code = product_code self.name = name self.price = price class ProductManager: def __init__(self): self.products = [] def add_product(self, product_code, name, price): new_product = ...
magicoder
python
You are tasked with creating a Python function that analyzes the configuration of an application server and suggests modifications to the WebContainer thread pool settings. The function should take the server configuration ID as input and identify the WebContainer thread pool within the server's configuration. It shoul...
```python def app_server_tuning(server_confid): server_name = AdminConfig.showAttribute(server_confid, "name") threadpool_list = AdminConfig.list('ThreadPool', server_confid).split("\n") for tp in threadpool_list: if tp.count('WebContainer') == 1: min_size = int(AdminConfig.showAttribute...
magicoder
python
You are working on a system that manages workflows and their states. The system uses a custom data structure called `snapshot` to represent the current state of the workflows. The `snapshot` contains a `core` attribute, which in turn contains `states` and `aliases` attributes. The `states` attribute is a dictionary whe...
```python class WorkflowUpdate: def __init__(self, changes, deletions, additions): self.changes = changes self.deletions = deletions self.additions = additions def apply(self, snapshot, workflow_id): # Apply changes to the snapshot if workflow_id in self.changes: ...
magicoder
python
You are given a partial implementation of a class that is used to test a stack of XML elements. The class contains a method `test` that takes a `Stack<XmlElement>` and an `Element` as input and returns a boolean value. Additionally, there is an overridden method `test` that takes only a `Stack<XmlElement>` as input and...
```java public boolean test(Stack<XmlElement> xmlElements, Element element) { return test(xmlElements); } @Override public boolean test(Stack<XmlElement> xmlElements) { int pos = namesFromTopAncestorToParent.length; ListIterator<XmlElement> it = xmlElements.listIterator(xmlElements.size()); while (it.h...
magicoder
java
You are tasked with creating a Python function that interacts with a monitoring service to retrieve and process metrics data. The function should be able to handle dynamic tags and perform specific actions based on the received data. Write a Python function `process_metrics_data` that takes in three parameters: 1. `ag...
```python def process_metrics_data(aggregator, dd_run_check, mock_http_response): metrics_data = mock_http_response.__closure__[0].cell_contents.strip().split('\n') processed_metrics = {} for line in metrics_data: if line.startswith("# HELP"): metric_name = line.split()[2] else: ...
magicoder
python
You are tasked with creating a Python function that simulates a simple game of rock-paper-scissors. The function should take a single argument representing the player's choice and return the outcome of the game. The game rules are as follows: - Rock beats scissors - Scissors beats paper - Paper beats rock - If both the...
```python import time import random def rock_paper_scissors(player_choice): time.sleep(1) # Simulate computer's decision-making time choices = ['rock', 'paper', 'scissors'] computer_choice = random.choice(choices) if player_choice == computer_choice: return "It's a tie!" elif (player_choi...
magicoder
python
You are tasked with implementing a robust method for estimating a homography matrix between two images using the RANSAC (Random Sample Consensus) algorithm. The RANSAC algorithm is commonly used in computer vision to estimate model parameters from noisy data containing outliers. In this problem, you will focus on imple...
```python import numpy as np from .RANSAC_homography import * def estimate_homography_ransac(src_points, dst_points, num_iterations, threshold): best_homography = None max_inliers = 0 for _ in range(num_iterations): # Randomly sample minimal set of points sample_indices = np.random.choice(...
magicoder
python
You are tasked with creating a Python class that processes a dictionary containing fields and their corresponding data. Your class should be able to validate and manipulate the data based on the specified field types. The field types are defined by separate classes, and the data dictionary may contain multiple fields o...
```python class FieldProcessor: def __init__(self, data: dict, FieldClass: object): self.data = data self.FieldClass = FieldClass def validate_data(self) -> bool: for field, value in self.data.items(): if not self.FieldClass.validate(field, value): return Fal...
magicoder
python
You are tasked with implementing a collate function for data processing in a natural language visual reasoning (NLVR) system. The NLVR system processes paired and triplet data for evaluation and training. The collate function is responsible for processing and organizing the input data into a format suitable for trainin...
```python def nlvr2_paired_collate(batch): # Process paired data for training # Implement the logic to organize the paired image and sentence data for training # Return the processed data in a suitable format for training def nlvr2_paired_eval_collate(batch): # Process paired data for evaluation # ...
magicoder
python
You are tasked with creating a JavaScript function that will animate the opacity of certain elements on a web page. The function should take in two parameters: a jQuery selector for the elements to be animated, and a speed at which the animation should occur. The function should set the initial opacity of the selected ...
```javascript function animateOpacity(selector, speed) { $(selector).css('opacity', 0).fadeTo(speed, 1); } // Example usage animateOpacity('.elgg-page .elgg-menu-filter-default, .ideas-list', 'slow'); ``` In this solution, the `animateOpacity` function takes in the `selector` and `speed` parameters. It uses the jQu...
magicoder
javascript
You are tasked with creating a Python function that extracts unique links from a given HTML content using the BeautifulSoup library. The function should take the HTML content as input and return a set of unique links found within the content. Function Signature: `def extract_unique_links(html_content: str) -> set` Fo...
```python from bs4 import BeautifulSoup def extract_unique_links(html_content: str) -> set: soup = BeautifulSoup(html_content, 'html.parser') anchors = soup.find_all('a') all_links = set() for link in anchors: href = link.get('href') if href: all_links.add(href) return...
magicoder
python
You are tasked with implementing a function to generate random points on a circle in a given number of dimensions. The circle is defined by a radius and is parametrized by an angle, theta. The function should return an array of points on the circle in the specified number of dimensions. You are given the following cod...
```python import numpy as np def make_orthonormal_vector(v, ndim): '''Given a vector v, returns an orthonormal vector''' if ndim == 1: return np.array([-v[0]]) elif ndim == 2: return np.array([v[1], -v[0]]) else: raise ValueError("Unsupported number of dimensions") def random_c...
magicoder
python
You are tasked with creating a Java program to validate and extract the client's IP address from an HTTP request header. The program should handle various scenarios and provide a reliable method for obtaining the client's IP address. Write a Java method `getClientIPAddress` that takes an `HttpServletRequest` object as...
```java import javax.servlet.http.HttpServletRequest; public class ClientIPAddressExtractor { public String getClientIPAddress(HttpServletRequest request) { String clientIP = request.getHeader("X-Forwarded-For"); if (clientIP != null && clientIP.length() > 0) { // The "X-Forwar...
magicoder
java
You are tasked with creating a real-time web application that utilizes the `streamlit` and `streamlit_webrtc` libraries to capture and display a live video stream. Your goal is to implement a simple web application that allows users to access their webcam and view the live video feed within the application interface. ...
```python # Import necessary libraries import streamlit as st from streamlit_webrtc import webrtc_streamer # Create a streamlit web application st.title("Live Video Stream from Webcam") # Define the main function to set up the live video streamer def main(): # Use webrtc_streamer to create a live video streamer w...
magicoder
python
You are tasked with designing a multithreaded Java program to manage a shared resource in a concurrent environment. The shared resource is a simple counter that starts at 0 and can be incremented or decremented by multiple threads simultaneously. However, to ensure data consistency, the counter should never go below 0....
```java import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Counter { private int value; private final Lock lock = new ReentrantLock(); public Counter() { this.value = 0; } public void increment() { lock.lock(); try { ...
magicoder
java