query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a function that extracts the title from an HTML snippet. The title is enclosed within an HTML tag and has the following structure:
```html
<div class="card shadow">
<div class="card-header ">
<br>
<div class="row">
<div class="col-md-12"><h5 class="m-0 font-weight-b... | ```javascript
function extractTitle(html) {
const regex = /<h5 class="m-0 font-weight-bold ">(.*?)<\/h5>/;
const match = html.match(regex);
return match ? match[1] : "Title Not Found";
}
// Test the function
const htmlSnippet = `
<div class="card shadow">
<div class="card-header ">
<br>
<div cl... | magicoder | javascript |
You are given a string `code_tag` that represents a hexadecimal number. Your task is to write a function `convert_hex_to_int` to convert the hexadecimal number into its decimal equivalent.
The function should take the string `code_tag` as input and return the decimal equivalent of the hexadecimal number.
For example,... | ```python
def convert_hex_to_int(code_tag):
decimal_value = int(code_tag, 16)
return decimal_value
```
The `int` function in Python with base 16 converts the given hexadecimal number represented as a string into its decimal equivalent. The function `convert_hex_to_int` simply uses this built-in functionality t... | magicoder | python |
You are tasked with implementing a binary search tree (BST) in Python. A binary search tree is a data structure that allows for efficient searching, insertion, and deletion of values. Each node in the BST has at most two child nodes, referred to as the left child and the right child. The value of all nodes in the left ... | ```python
class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(root, value):
if root is None:
return TreeNode(value)
if value < root.value:
root.left = insert(root.left, value)
else:
root.right = inse... | magicoder | python |
You are tasked with creating a Java program that simulates a simple banking system. The program should allow users to create accounts, deposit and withdraw funds, and check their balance. Additionally, the program should be able to transfer funds between accounts.
Your task is to implement the `Bank` class, which will... | ```java
import java.util.HashMap;
class Account {
private static int nextAccountNumber = 1;
private int accountNumber;
private String accountHolderName;
private double balance;
public Account(String accountHolderName, double initialBalance) {
this.accountNumber = nextAccountNumber++;
... | magicoder | java |
You are tasked with creating a JavaScript function that simulates the behavior of the `export` keyword in ES6 modules. The function should take an object representing a module and return the default export of that module. If the module does not have a default export, the function should return `undefined`.
The input o... | ```javascript
function simulateExport(module) {
return module.default;
}
``` | magicoder | javascript |
You are tasked with creating a Python function that processes a response from a server and extracts specific information from it. The response is in the form of a text string containing XML-like tags. Your function should extract the purchase order number and the URL of a PDF file from the response and then update a da... | ```python
import re
def process_response(response_text):
po_number = re.search(r'<po-number>(.*?)</po-number>', response_text).group(1)
pdf_url = re.search(r'<link rel="artifact" href="(.*?)"', response_text).group(1)
# Construct dictionary
result = {"po_number": po_number, "pdf_url": pdf_url}
... | magicoder | python |
You are given a Python dictionary containing lowercase letters as keys and their corresponding numerical values as values. Your task is to write a function that takes this dictionary as input and returns a new dictionary with the keys and values swapped.
For example, given the input dictionary:
```python
input_dict = ... | ```python
def swap_keys_values(input_dict: dict) -> dict:
return {v: k for k, v in input_dict.items()}
```
The `swap_keys_values` function takes the input dictionary and uses a dictionary comprehension to create a new dictionary with the keys and values swapped. For each key-value pair in the input dictionary, it ... | magicoder | python |
You are tasked with implementing a Logger class in Python that supports adding different types of loggers, such as stream logger and file logger. The Logger class should have the following methods:
1. `add_stream_logger()`: This method adds a stream logger to the Logger instance.
2. `add_file_logger(folder, file)`: Th... | ```python
import logging
class Logger:
def __init__(self):
self.logger = logging.getLogger()
self.logger.setLevel(logging.DEBUG)
def add_stream_logger(self):
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%... | magicoder | python |
You are tasked with implementing a utility function to filter and prepare payload data for insertion into a database, as well as a method to delete a user from the database. You are provided with a code snippet that includes a partial implementation of a Python class. Your task is to complete the implementation of the ... | ```python
import typing
class Model:
pass
def filter_payload(payload: dict) -> dict:
# Filter out any non-essential or sensitive data from the payload
filtered_payload = {k: v for k, v in payload.items() if v is not None}
return filtered_payload
class DatabaseManager:
async def _insert(self, **kw... | magicoder | python |
You are tasked with implementing a function that processes a sequence of tokens representing a nested map structure. Each token in the sequence can be one of the following: `MapStart`, `MapEnd`, `String`. The `MapStart` token indicates the beginning of a new map, the `MapEnd` token indicates the end of the current map,... | ```python
from typing import List, Dict, Union
class Token:
MapStart = "MapStart"
MapEnd = "MapEnd"
String = "String"
def processTokens(tokens: List[Token]) -> Dict[str, Union[str, Dict[str, Union[str, Dict[str, Union[str, ...]]]]]]:
stack = []
current_map = {}
stack.append(current_map)
f... | magicoder | python |
You are working on a project that involves writing images to the file system using TypeScript. The project utilizes a function called `writeImage` which is declared as follows:
```typescript
export declare function writeImage(file: FileSystemNode, args: ISharpGatsbyImageArgs, pathPrefix: string, reporter: Reporter, ca... | ```typescript
import { FileSystemNode, ISharpGatsbyImageArgs, Reporter, GatsbyCache } from 'your-module'; // Import necessary types from your module
export async function writeImage(file: FileSystemNode, args: ISharpGatsbyImageArgs, pathPrefix: string, reporter: Reporter, cache: GatsbyCache, filename: string): Promise... | magicoder | typescript |
You are tasked with implementing a Python function that checks the internet connectivity status of a device. The function should handle various scenarios and return a dictionary containing the cause of the connectivity issue.
You are provided with the following code snippet as a starting point:
```python
def check_int... | ```python
import socket
def check_internet_connectivity():
try:
# Attempt to connect to a well-known website to check internet connectivity
socket.create_connection(("www.google.com", 80))
return {"cause": "Internet connection is active."}
except socket.gaierror:
return {"cause"... | magicoder | python |
You are tasked with implementing a ShardingRepository class that will manage sharded data storage. The ShardingRepository class should be responsible for distributing data across multiple repositories, each handling a subset of the data based on a sharding key. Your goal is to implement the ShardingRepository class and... | ```csharp
public class ShardingRepository
{
private Dictionary<int, IRepository> repositories;
public ShardingRepository(IRepository repository)
{
repositories = new Dictionary<int, IRepository>();
// Initialize repositories based on sharding logic
// For example, using consistent h... | magicoder | csharp |
You are working on a bioinformatics project and need to develop a program to align DNA sequences using the `alignlib_lite` library and process input sequences from a FASTA file using the `CGAT.FastaIterator` module. Your task is to write a Python function that takes a FASTA file containing DNA sequences and performs pa... | ```python
from typing import Tuple
import alignlib_lite
import CGAT.FastaIterator as FastaIterator
def align_sequences(filename: str) -> Tuple[int, Tuple[str, str]]:
sequences = []
for header, sequence in FastaIterator.iterate(open(filename)):
sequences.append(sequence)
aligner = alignlib_lite.py_... | magicoder | python |
You are tasked with implementing a class that manages a unique identifier and a corresponding string representation. The class should ensure that the string representation is always in sync with the unique identifier and the name property. You are provided with a code snippet that demonstrates the structure of the clas... | ```csharp
using System;
public class UniqueIdentifier
{
private Guid id;
public Guid Id { get { return id; } private set { setIfChanged(ref id, value, "Id", "IdStr"); } }
public string IdStr { get { return $"{Id.ToString().Substring(0, 6)} {Name}"; } }
private string name;
public string Name { get... | magicoder | csharp |
You are tasked with implementing a blockchain validation algorithm for a simplified blockchain system. The blockchain consists of a series of blocks, each containing a header and a reference to the previous block's hash. The goal is to identify and handle a specific scenario in the blockchain validation process.
Given... | ```rust
// Define a data structure to represent a block in the blockchain
struct Block {
number: u64,
hash: String,
// Other block data fields
}
impl Block {
// Implement a method to create a new block
fn new(number: u64, hash: String) -> Block {
Block {
number,
hash... | magicoder | rust |
You are tasked with implementing a function to replace certain values within a nested dictionary with unique keys and store the original values in a separate mapping. The function should take a JSON-like nested dictionary as input and replace non-dictionary values with unique keys, while storing the original values in ... | ```python
import json
reps_index = 0 # Global index for generating unique keys
reps_map = {} # Global mapping to store original values with unique keys
def has_sub_map_items(json_dict):
for value in json_dict.values():
if isinstance(value, dict):
return True
return False
def replace_me... | magicoder | python |
You are tasked with creating a Python script to automate the process of web browsing using the Selenium library. Your script should perform the following tasks:
1. Open a web browser.
2. Navigate to a specific website.
3. Perform a series of interactions on the website.
4. Close the web browser.
Your script should uti... | ```python
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
# Set up the web driver
driver = webdriver.Chrome()
# Navigate to a specific website
driver.get("https://www.example.com")
# Perform interactions on the website
search_box = driver.find_element_by_name("q")
search_bo... | magicoder | python |
You are tasked with implementing a function that processes a given array of 3D points to determine the distance between each pair of points. The points are represented as instances of the `SCNVector3` struct, which contains `x`, `y`, and `z` coordinates. The function should return a 2D array representing the distances ... | ```swift
func calculateDistancesBetweenPoints(_ points: [SCNVector3]) -> [[Float]] {
let n = points.count
var distances = Array(repeating: Array(repeating: Float(0.0), count: n), count: n)
for i in 0..<n {
for j in 0..<n {
let point1 = points[i]
let point2 = points[j]
... | magicoder | swift |
You are tasked with creating a Python program to control a robot's movements using the `rosebot` library. The robot is equipped with a camera and can perform various actions based on the data it captures. Your goal is to implement a program that utilizes the robot's capabilities to perform specific movements and action... | ```python
import rosebot
import time
# Initialize a RoseBot object
robot = rosebot.RoseBot()
# Display the camera data
robot.drive_system.display_camera_data()
# Spin counterclockwise until an object is detected within 500 units
robot.drive_system.spin_counterclockwise_until_sees_object(100, 500)
# Pause for 5 seco... | magicoder | python |
You are given a scenario where a voting system needs to identify candidates who can potentially gain an advantage through manipulative votes. Your task is to implement a function that determines the distinguished candidates who can become stronger than a dropped candidate by adding manipulative votes, based on the stre... | ```python
def get_distinguished_cand(c, r, l, non_manip_rankmaps, strength_order):
# Create a dictionary to store the strength of each candidate
candidate_strength = {candidate: 0 for candidate in strength_order}
# Iterate through the non-manipulative voter rankings to calculate the strength of each candid... | magicoder | python |
You are tasked with implementing a simplified version of a Promise library in Swift. A Promise represents a proxy for a value not necessarily known when the promise is created, allowing you to associate handlers with an asynchronous action's eventual success value or failure reason. The provided code snippet is a part ... | ```swift
enum Resolution<T> {
case Fulfilled(T)
case Rejected(ErrorType, ErrorConsumptionToken)
}
class ErrorConsumptionToken {
let error: ErrorType
init(_ error: ErrorType) {
self.error = error
}
}
class UnsealedState<T> {
var resolver: ((Resolution<T>) -> Void)!
init(resolver: in... | magicoder | swift |
You are given a string `s` containing a series of characters. Your task is to write a function that takes the string `s` as input and returns the longest substring of `s` that contains at most two distinct characters.
For example, given the input string `s = "abaccc"`, the function should return `"abac"` as the longes... | ```javascript
function longestSubstringWithTwoDistinct(s) {
let start = 0;
let maxLen = 0;
let charMap = new Map();
for (let end = 0; end < s.length; end++) {
charMap.set(s[end], (charMap.get(s[end]) || 0) + 1);
while (charMap.size > 2) {
charMap.set(s[start], charMap.get(s[start]) - 1);
i... | magicoder | javascript |
You are tasked with implementing a simple stack data structure using Rust. The stack should support the following operations:
1. `push`: Add an element to the top of the stack.
2. `pop`: Remove and return the element at the top of the stack.
3. `peek`: Return the element at the top of the stack without removing it.
4. ... | ```rust
// Define the Stack struct
pub struct Stack<T> {
data: Vec<T>,
}
impl<T> Stack<T> {
// Create a new empty stack
pub fn new() -> Self {
Stack { data: Vec::new() }
}
// Add an element to the top of the stack
pub fn push(&mut self, item: T) {
self.data.push(item);
}
... | magicoder | rust |
You are tasked with creating a program to optimize hyperparameters for a machine learning model using a genetic algorithm. The genetic algorithm will be used to find the best combination of hyperparameters for an XGBoost classifier.
You are given a Python code snippet that sets up an XGBoost classifier with various hy... | ```python
import numpy as np
from xgboost import XGBClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# Define the fitness function to evaluate the performance of hyperparameters
def fitness_function(hyperparameters, X_train, X_test, y_train, y_test):
model ... | magicoder | python |
You are given a TypeScript code snippet that defines constants `one`, `two`, and `three`, and a function `getTotal` that takes two parameters and returns their sum. The function is then called with arguments `1` and `2`, and the result is stored in the constant `total`.
Your task is to write a TypeScript function that... | ```typescript
// Define constants
const one: number = 1;
const two: number = 2;
const three: number = one + two;
// Function to get total
function getTotal(one: number, two: number): number {
return one + two;
}
// Call getTotal function with arguments 1 and 2
const total: number = getTotal(1, 2);
// Function to... | magicoder | typescript |
You are tasked with creating a Python function that retrieves the last commit date for a given file in a Git repository. The function should use the `git log` command to obtain the timestamp of the last commit that modified the specified file. However, there is a caveat: in some cases, multiple versions of the file are... | ```python
import subprocess
def last_commit_date(file):
# Run the git log command to retrieve the timestamp of the last commit for the specified file
p = subprocess.run(f'git log -1 --format=%ct {file}', shell=True, capture_output=True)
return p.stdout.decode().strip()
```
The `last_commit_date` function ... | magicoder | python |
You are tasked with creating a Python function that processes a given text and extracts all the comments within the text. Comments are defined as any text enclosed within triple double quotes (`""" ... """`). The function should return a list of all the comments found in the input text.
Create a function `extract_comm... | ```python
from typing import List
def extract_comments(text: str) -> List[str]:
comments = []
start = 0
while True:
start = text.find('"""', start)
if start == -1:
break
end = text.find('"""', start + 3)
if end == -1:
break
comments.append(tex... | magicoder | python |
You are working on a machine learning project and need to compare the performance of different classifiers on a given dataset. You have imported several modules from the `sklearn` library and are planning to use the `RandomForestClassifier`, `DecisionTreeClassifier`, and `SVM` classifiers. Additionally, you have import... | ```python
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn import svm, preprocessing
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
import matplotlib.pyplot as plt
import numpy as np
def compare_clas... | magicoder | python |
You are tasked with creating a Python function that processes and visualizes data from a predictive model. The function should take in various parameters and generate a line plot based on the input data. The code snippet provided gives a glimpse of the visualization process, but it lacks the complete function and neces... | ```python
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
def visualize_prediction(x_col, spec_thresh_col, hue_col, use_palette, use_hue_order, pred, ci, cumsum_col=None):
"""
Visualizes the predictive model data using a line plot.
Parameters:
x_col (str): Name of the column ... | magicoder | python |
You are tasked with implementing a function that performs resampling operations on a given input array using a specified background strategy and stream. The function takes in the following parameters:
- `a_o`: The output array where the resampled data will be stored.
- `a_i`: The input array that needs to be resampled.... | ```cpp
// Implementation of Opers::Resample function
void Opers::Resample(ArrayType& a_o, const ArrayType& a_i, BackgroundStrategy bg, bool rescaleVector, StreamT stream) {
// Check if the background strategy is valid
MK_CHECK_VFIELD_BACKGROUND(bg);
// Perform resampling based on the background strategy
... | magicoder | cpp |
You are tasked with implementing a Timer class in Python. The class should have the following methods:
1. `start`: Start the timer initially or resume after pause.
2. `pause`: Pause the timer.
3. `toggle_pause`: Toggle the pause state of the timer.
4. `stop`: Stop the timer and return the elapsed time in seconds and m... | ```python
from typing import Tuple
import time
class Timer:
def __init__(self):
self.start_time = 0
self.pause_time = 0
self.paused = False
def start(self):
if not self.paused:
self.start_time = time.time()
else:
self.start_time += time.time() - ... | magicoder | python |
You are tasked with implementing a function that calculates the cosine similarity between two vectors using NumPy. The cosine similarity between two vectors A and B is defined as the dot product of A and B divided by the product of their magnitudes.
Write a function `cosine_similarity(A, B)` that takes two 1D NumPy a... | ```python
import numpy as np
def cosine_similarity(A, B):
dot_product = np.dot(A, B)
magnitude_A = np.linalg.norm(A)
magnitude_B = np.linalg.norm(B)
similarity = dot_product / (magnitude_A * magnitude_B)
return round(similarity, 4)
```
The `cosine_similarity` function first calculates the dot produ... | magicoder | python |
You are tasked with creating a ticketing system for a Discord bot. The given code snippet is a part of the implementation for creating a new ticket. The code snippet includes the creation of a new ticket entry in a database, setting up the ticket details, and obtaining mentionable roles for ticket agents.
Your task is... | ```typescript
function filterMentionableRoles(guildRoles: Role[], permission: string): string[] {
return guildRoles
.filter(role => role.perms.includes(permission))
.map(role => role.toString());
}
```
The `filterMentionableRoles` function filters the `guildRoles` array based on the specified `permission` an... | magicoder | typescript |
You are tasked with creating a script to automate the process of minimizing test cases for a fuzz testing tool. Fuzz testing involves providing random or invalid inputs to a program to uncover vulnerabilities. The given code snippet is a part of a script that takes a test case file as input, extracts the base name of t... | ```bash
#!/bin/bash
minimize_test_case() {
if [ ! -f "$1" ]; then
echo "Error: Input file does not exist" >&2
exit 1
fi
local input_file="$1"
local base_name=$(basename "$input_file")
local output_dir="${base_name}.out"
mkdir "$output_dir"
afl-cmin -i "$input_file" -o "$ou... | magicoder | shell |
You are tasked with implementing a class that manages open orders in a trading system. The class, `OpenOrders`, is designed to store a list of open orders and provide functionality to manage these orders. The open orders are represented as instances of the `LimitOrder` class, which is a subclass of the `Order` class. T... | ```java
import java.util.ArrayList;
import java.util.List;
public class OpenOrders {
private final List<LimitOrder> openOrders;
/**
* Constructor
*
* @param openOrders The list of open orders
*/
public OpenOrders(List<LimitOrder> openOrders) {
this.openOrders = new ArrayList<>(... | magicoder | java |
You are tasked with creating a convolutional neural network (CNN) model using the Keras library to classify images from the CIFAR-10 dataset. The CIFAR-10 dataset consists of 60,000 32x32 color images in 10 classes, with 6,000 images per class. The task is to build a CNN model to classify these images into their respec... | ```python
from __future__ import print_function
import keras
from keras.datasets import cifar10
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.optimizers import RMSprop
from keras.utils import to_categorical
batc... | magicoder | python |
You are given a Python function that performs batch 2D Inverse Discrete Cosine-Sine Transformation without normalization to coefficients. Your task is to implement the inverse function that computes idct(idxst(x)).
The function signature is as follows:
```python
def idct_idxst(x, expk_0=None, expk_1=None):
'''
... | ```python
import torch
def idct_idxst(x, expk_0=None, expk_1=None):
'''
Batch 2D Inverse Discrete Cosine-Sine Transformation without normalization to coefficients.
Compute idct(idxst(x)).
@param x batch tensor, the 2D part is MxN
@param expk_0 with length M, 2*exp(-1j*pi*k/(2M))
@param expk_1 w... | magicoder | python |
You are working on a simulation program for wave propagation. The given code snippet is a part of the program that simulates the propagation of a wave through a medium. The program uses a mesh to represent the medium, and it calculates the propagated amplitude at different points on the mesh.
Your task is to complete ... | ```python
import numpy
# Given context
p_Y = wavefront.get_mesh_y()
det_X = p_X
det_Y = p_Y
amplitude_propagated = numpy.zeros_like(amplitude, dtype='complex')
wavenumber = 2 * numpy.pi / wavelength
# Complete the propagation of wave amplitude
for i in range(det_X.size):
for j in range(det_Y.size):
if not... | magicoder | python |
You are tasked with implementing a shopping bag feature in a React application. The shopping bag component is responsible for displaying the items added to the bag and providing functionality to remove items. You are provided with a code snippet that sets up the initial structure of the shopping bag component using Rea... | ```javascript
import React, { useContext } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import { AddShoppingCart as EmptyBag } from '@material-ui/icons/';
import { ShoppingBagContext } from '../../context/ShoppingBag';
import { withRouter } from 'react-router-dom';
const useStyles = makeStyles(... | magicoder | javascript |
You are tasked with implementing a function that can determine whether a given range in a HTML document contains a table cell boundary. The function should take in the start and end positions of the range and return a boolean value indicating whether the range contains a table cell boundary.
You are provided with the ... | ```javascript
function rangeContainsTableCellBoundary(start, end) {
// Get the common ancestor container of the start and end positions
const commonAncestor = start.commonAncestorContainer;
// Check if the common ancestor is a table cell or contains a table cell
if (commonAncestor.tagName === 'TD' || commonAnc... | magicoder | javascript |
You are tasked with creating a Python program that simulates a simple web server using the `wsgiref` module. Your program should accept command-line arguments for the server address and port, and it should serve a static file using the WSGI server.
Your program should perform the following tasks:
1. Parse command-line... | ```python
import argparse
import logging
from wsgiref import simple_server
# Parse command-line arguments
parser = argparse.ArgumentParser(description='Simple WSGI Web Server')
parser.add_argument('--addr', default='localhost', help='Server address')
parser.add_argument('--port', type=int, default=8080, help='Server p... | magicoder | python |
You are tasked with creating a program to manage and analyze geographical map data. The program should be able to serialize and deserialize map data using the `pickle` module in Python. The map data includes the dimension of the map, the range of the map, and the actual map data itself.
Your task is to implement a Pyt... | ```python
import pickle
class MapManager:
def serialize_map(self, filename, dimension, map_range, map_data):
with open(filename, 'wb') as pickle_file:
pickle.dump(dimension, pickle_file)
pickle.dump(map_range, pickle_file)
pickle.dump(map_data, pickle_file)
def dese... | magicoder | python |
You are tasked with creating a Python program to scrape data from a university course registration portal and store it in a structured format. The program should utilize the Scrapy library to crawl the website, extract relevant information, and save it to a JSON file. Additionally, the program should handle file paths ... | ```python
# Import the necessary libraries and modules
from abc import ABC
from pathlib import Path
import pandas as pd
import scrapy
from src.crawl.utils import cleanup
from settings import YEAR, CRAWLING_OUTPUT_FOLDER
# Define the base URL for crawling
BASE_URL = 'https://ku-portal.kyushu-u.ac.jp/campusweb/slbssb... | magicoder | python |
You are tasked with creating a program to display search results for movies and TV shows. The program should construct a user interface to show the title, release/air date, and poster image for each search result. The search results can be either for a movie or a TV show, and the information to be displayed varies base... | ```java
public class SearchResults {
private Result result;
private VerticalLayout vlInfo;
private Image imgPoster;
private Html lblTitle;
public SearchResults(Result result) {
this.result = result;
vlInfo = new VerticalLayout();
}
public void displaySearchResult() {
... | magicoder | java |
You are working on a web development project and need to extract information from HTML code. Your task is to write a program that can parse HTML comments and extract the URLs from anchor tags within those comments.
You are given a string representing an HTML comment containing anchor tags. Each anchor tag has an `href... | ```python
import re
def extract_urls_from_html_comment(html_comment):
anchor_tags = re.findall(r'<a\s+href="([^"]+)"', html_comment)
return anchor_tags
html_comment = '<!-- <a href="http://www.example.com" class="wl-project-link" style="background-image:url(\'images/example-icon.png\')" target="_blank"></a><a... | magicoder | python |
You are tasked with creating a program to analyze a given text and count the occurrences of each unique word. The program should ignore punctuation, capitalization, and consider words with different cases as the same word. Additionally, the program should exclude common stop words such as "the", "and", "of", etc. The o... | ```python
from collections import Counter
import re
from typing import List, Dict
def word_frequency_counter(text: str, stop_words: List[str]) -> Dict[str, int]:
text = re.sub(r'[^\w\s]', '', text) # Remove punctuation
words = text.lower().split() # Convert to lowercase and split into words
words = [word... | magicoder | python |
You are tasked with implementing a function to calculate the length of a slider curve based on its type and control points. The slider curve can be of three types: LINEAR, BEZIER, or CIRCLE. The control points for the curve are provided as a vector of 2D points. The length of the curve is defined as the sum of the dist... | ```cpp
#include <vector>
#include <cmath>
#include <iostream>
namespace framework {
template <typename T>
struct Vector2 {
T x, y;
};
}
enum class SliderCurveType {
LINEAR = 0,
BEZIER = 1,
CIRCLE = 2
};
struct SliderInfo {
SliderCurveType curve_type;
std::vector<framework::Vec... | magicoder | cpp |
You are tasked with implementing a function to extract a target polygon from a list of polygons based on a given bounding box. The function should take the bounding box and a list of polygons as input and return the target polygon that lies within the bounding box.
The input parameters are defined as follows:
- `bbox`... | ```python
def extract_target_polygon(bbox, polygons):
min_x, min_y, max_x, max_y = bbox
for polygon in polygons:
x_coords = [vertex[0] for vertex in polygon]
y_coords = [vertex[1] for vertex in polygon]
if all(min_x <= x <= max_x and min_y <= y <= max_y for x, y in polygon):
... | magicoder | python |
You are tasked with implementing a function to process a list of posts retrieved from a client. Each post is represented as a dictionary with attributes such as title, author, date, and content. The function should sort the list of posts based on a specified attribute and order.
You are given the following code snippe... | ```python
async def sort_posts(posts: List[Dict[str, Any]], order: Dict[str, str]) -> List[Dict[str, Any]]:
sorted_posts = posts
for key, value in order.items():
sorted_posts = sorted(sorted_posts, key=lambda x: x[key], reverse=(value == 'desc'))
return sorted_posts
```
The `sort_posts` function ta... | magicoder | python |
You are tasked with creating a Python package that calculates the nth Fibonacci number using a recursive approach. Your package should include a setup.py file that properly configures the package for distribution using setuptools.
Your package structure should be as follows:
```
fibonacci_package/
├── fibonacci/
... | ```python
# fibonacci_package/fibonacci/fibonacci.py
def calculate_fibonacci(n):
if n <= 0:
return "Invalid input"
elif n == 1:
return 0
elif n == 2:
return 1
else:
return calculate_fibonacci(n-1) + calculate_fibonacci(n-2)
```
```python
# fibonacci_package/tests/test_f... | magicoder | python |
You are tasked with implementing a function to determine whether a given time interval has been processed before. The time interval is represented by the day of the week (fromDay and toDay) and the hour of the day (fromHour and toHour). The function should return true if the time interval has been processed before, bas... | ```java
public boolean hasBeenProcessed(int fromDay, int toDay, int fromHour, int toHour, int processed) {
if (fromDay != toDay || (fromDay == toDay && fromHour < toHour) ||
(fromDay == toDay && fromHour > toHour && processed > 0)) {
return true;
}
return false;
}
```
The solution implements... | magicoder | java |
You are tasked with implementing a class for handling decimal numbers in a specific format. The class should be able to convert decimal numbers to and from a custom byte representation. Additionally, the class should be able to handle invalid input gracefully by throwing exceptions.
Your task is to implement the `Deci... | ```cpp
#include <iostream>
#include <string>
#include <stdexcept>
class Decimal {
private:
std::string bytes;
public:
Decimal(const std::string& bytes) : bytes(bytes) {}
std::string to_bytes() const {
return bytes;
}
std::string str() const {
// Implement conversion from byte rep... | magicoder | cpp |
You are tasked with creating a Python function that generates a density plot of celestial objects' Right Ascension (RA) and Declination (DEC) using Gaia data. The function should also overlay a sample of objects on the density plot. The function should have the following signature:
```python
def plot_gaia_density(
... | ```python
import numpy as np
import matplotlib.pyplot as plt
from astropy.coordinates import SkyCoord
from astropy import units as u
from astroquery.gaia import Gaia
def plot_gaia_density(
title: Optional[str] = None,
save: Optional[Union[str, pathlib.Path]] = None,
):
"""Plot the RA/DEC Gaia density plot ... | magicoder | python |
You are tasked with implementing a logging system for a web application. The system should allow logging different types of messages and storing them in a database. You are provided with a C# code snippet that defines a `Log` class and a `LogType` enum. The `Log` class has two properties: `LogType` and `LogContent`. Th... | ```csharp
// Method to save the Log object to the database
public void SaveLogToDatabase(Log log)
{
// Assuming the existence of a database connection and a method to execute SQL commands
// SQL command to insert the log into the database
string insertCommand = "INSERT INTO LogTable (LogType, LogContent) V... | magicoder | csharp |
You are tasked with creating a Python class that represents a basic bank account. The class should have methods to deposit funds, withdraw funds, and check the current balance. Additionally, the class should have a property to store the account holder's name.
Your task is to complete the implementation of the `BankAcc... | ```python
class BankAccount:
def __init__(self, account_holder):
self.account_holder = account_holder
self.balance = 0
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if self.balance >= amount:
self.balance -= amount
else:
... | magicoder | python |
You are tasked with implementing a circular queue data structure in Python. A circular queue is a data structure that follows the FIFO (First In First Out) principle, but with a fixed size. When the queue is full and a new element is enqueued, it overwrites the oldest element. The circular queue also has a cursor that ... | ```python
class CircularQueue:
def __init__(self, size):
self.size = size
self.queue = [None] * size
self.cursor = -1
def enqueue(self, element):
self.cursor = (self.cursor + 1) % self.size
self.queue[self.cursor] = element
def dequeue(self):
oldest_element ... | magicoder | python |
You are tasked with implementing a function that takes in an array of integers and returns the maximum difference between any two numbers in the array. If no such difference exists, the function should return 0. You are not allowed to use any built-in sorting functions.
The function signature is:
```java
public static... | ```java
public static int maxDifference(int[] nums) {
if (nums == null || nums.length < 2) {
return 0;
}
int minNum = nums[0];
int maxDiff = 0;
for (int i = 1; i < nums.length; i++) {
if (nums[i] > minNum) {
int diff = nums[i] - minNum;
if (diff > maxDiff) {... | magicoder | java |
You are tasked with creating a custom Django admin action to update the status of multiple orders at once. The `Order` model has a field `status` which can have values 'pending', 'shipped', or 'delivered'. Your task is to create a custom admin action that will change the status of selected orders to 'shipped' when trig... | To implement the `mark_as_shipped` custom admin action for the `Order` model in Django, you can follow the steps below:
```python
# In admin.py
from django.contrib import admin
from .models import Order
def mark_as_shipped(modeladmin, request, queryset):
updated_count = queryset.update(status='shipped')
messa... | magicoder | python |
You are tasked with implementing a learning rate scheduler for a neural network training process. The provided code snippet is a part of a Python script for training a neural network using PyTorch. The script uses a learning rate scheduler to adjust the learning rate during training. The `print` statement in the code s... | ```python
import torch.optim as optim
def custom_lr_scheduler(optimizer, validation_loss, patience):
if not hasattr(custom_lr_scheduler, 'counter'):
custom_lr_scheduler.counter = 0
custom_lr_scheduler.best_loss = validation_loss
else:
if validation_loss > custom_lr_scheduler.best_loss:
... | magicoder | python |
You are tasked with implementing a settings loader for a Python application. The settings are stored in JSON files and can be loaded into a Python dictionary. The settings can be overridden by environment variables and can have nested structures. Your task is to implement the `load` function that loads the settings fro... | ```python
import os
import json
def load(settings: dict, filename: str, env: str = None) -> None:
# Load base settings from the JSON file
with open(filename, 'r') as file:
base_settings = json.load(file)
# Override with environment-specific settings if provided
if env:
env_filename = f... | magicoder | python |
You are tasked with creating a script to monitor the availability of a web application by periodically attempting to connect to its homepage. The script should attempt to connect to the application's homepage at regular intervals and should stop after a certain number of unsuccessful attempts. The script should also st... | ```bash
#!/bin/bash
APP_HOMEPAGE="http://localhost:8080/api/MyApi?success=true"
SECONDS_BETWEEN_CONNECT_ATTEMPTS="2"
MAX_ATTEMPTS="5"
app_available=1
start_webserver()
{
echo "Starting the miniature web app with xsp4 ..."
original_dir="$(pwd)"
cd "./${WEB_APP_HOME}/"
xsp4 &
cd "$original_dir"
}
attempt_co... | magicoder | shell |
You are tasked with implementing a simple cursor management system for a graphical user interface (GUI) library. The provided code snippet is a partial implementation of a `Cursor` struct and its associated methods using the SDL library for handling mouse cursors.
Your task is to complete the implementation of the `Cu... | ```rust
use std::ffi::CString;
use std::ptr;
use sdl2::image::LoadTexture;
use sdl2::mouse::SystemCursor;
use sdl2::video::WindowContext;
pub struct Cursor {
pub(in crate::mouse) ptr: *mut SDL_Cursor,
}
impl Drop for Cursor {
fn drop(&mut self) {
unsafe {
SDL_FreeCursor(self.ptr);
... | magicoder | rust |
You are tasked with implementing a simplified version of a code dumping mechanism for a programming language. The provided code snippet is a part of a hypothetical compiler or interpreter for a programming language. The `WhileStmt` class represents a while loop statement in the language. The `dump` method is used to pr... | ```cpp
#include <iostream>
#include <vector>
// Forward declaration for the Expression class
class Expression;
// Forward declaration for the Statement class
class Statement;
class WhileStmt {
private:
std::vector<Statement*> inits;
Expression* cond;
Statement* stmt;
public:
// Constructor to initia... | magicoder | cpp |
You are tasked with implementing a middleware to handle token authentication and expiration in a PHP application. The given code snippet is a part of a Laravel application's exception handling mechanism. The `render` method is responsible for handling exceptions and returning appropriate HTTP responses. The code checks... | ```php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
class TokenAuthenticationMiddleware
{
public function handle(Request $request, Closure... | magicoder | php |
You are tasked with implementing a weighted directed graph in C++. The graph will consist of nodes representing items, and directed edges representing links between the items, each with an associated weight. Your goal is to create a class that can represent this graph and provide functionality to add links between item... | ```cpp
#include <iostream>
#include <vector>
#include <algorithm>
class WeightedDirectedGraph {
private:
struct Item {
std::vector<std::pair<Item*, int>> children;
};
std::vector<Item*> items;
public:
void add_item() {
items.push_back(new Item());
}
void add_link(Item* from, I... | magicoder | cpp |
You are tasked with creating a Python function that extracts the author and version information from a comment block in a source code file. The comment block follows a specific format, as shown in the code snippet below:
```python
"""
@author John Doe
@detail Automatically generated by make_anlpy_project.sh 1.0.0
"""
... | ```python
import re
def extract_info(source_code: str) -> dict:
pattern = r'/\*\*\s*@author\s+(.*?)\s+@detail\s+Automatically generated by\s+(\S+)\s+(\d+\.\d+\.\d+)\s+\*/'
match = re.search(pattern, source_code, re.DOTALL)
if match:
author = match.group(1)
tool = match.group(2)
vers... | magicoder | python |
You are working on a Python library for managing and recording timeline events. The library provides a `Timeline` class that allows users to record requests, mark specific events, and manage expectations. The code snippet provided is a part of the library's `Timeline` class, which includes methods for sending requests,... | ```python
import contextlib
class Request:
def __init__(self, command, arguments):
self.command = command
self.arguments = arguments
self.sent = None
class Timeline:
def __init__(self, channel):
self.channel = channel
self.timeline = []
def record_request(self, com... | magicoder | python |
You are given a set of data structures representing a 3D model in a computer graphics application. The model is defined using vertices, normals, and texture coordinates. Your task is to implement a function that merges these separate data structures into a single data structure, which can be used to render the 3D model... | ```rust
fn merge_data(vertex: &Vec<f32>, v_index: &Vec<u32>, normals: &Vec<f32>, n_index: &Vec<u32>, texture: &Vec<f32>, t_index: &Vec<u32>) -> Vec<f32> {
let mut merged_data: Vec<f32> = Vec::new();
for i in 0..v_index.len() {
let v_idx = v_index[i] as usize * 3;
let n_idx = n_index[i] as usize... | magicoder | rust |
You are tasked with implementing a desugaring function for a custom programming language. The language supports `and` expressions, but these need to be transformed into nested `if` statements for the language's internal representation. The desugaring function takes a sequence of expressions and converts the `and` expre... | ```rust
/// Desugar an `and` expression into nested `if` statements
fn desugar_and(mut body: Sequence) -> Expr {
if !body.is_empty() {
Expr::If(
Box::new(desugar(body.remove(0))),
Box::new(desugar_and(body)),
Some(Box::new(Expr::Val(Value::Bool(false))),
)
} e... | magicoder | rust |
You are tasked with creating a program that analyzes the sentiment of a given text. The sentiment analysis will involve counting the occurrences of positive, negative, and neutral words in the text and then determining the overall sentiment based on the counts.
Your task is to implement a function `sentiment_analysis(... | ```python
from typing import List
def sentiment_analysis(text: str, positive_words: List[str], negative_words: List[str]) -> str:
positive_count = sum(1 for word in text.split() if word in positive_words)
negative_count = sum(1 for word in text.split() if word in negative_words)
if positive_count > negati... | magicoder | python |
You are tasked with creating a Rust function that interacts with the LastPass command-line interface (CLI) to perform various operations. LastPass is a password manager that allows users to store and retrieve sensitive information securely. The provided code snippet contains two functions related to executing LastPass ... | ```rust
use std::process::{Command, Stdio};
use std::error::Error;
use std::fmt;
#[derive(Debug)]
struct LPassError {
message: String,
source: Option<Box<dyn Error>>,
}
impl LPassError {
fn new(message: &str, source: Option<Box<dyn Error>>) -> LPassError {
LPassError {
message: message... | magicoder | rust |
You are tasked with creating a Swift function that processes a given JSON file and extracts specific information from it. The JSON file contains data about different programming languages and their features. Your function should load the JSON file, parse its contents, and return a list of programming languages that mee... | ```swift
import Foundation
struct Language: Codable {
let name: String
let year: Int
let paradigm: [String]
}
func extractLanguages(from filePath: String) -> [String] {
guard let fileURL = URL(string: filePath) else {
fatalError("Invalid file path")
}
do {
let data = try D... | magicoder | swift |
You are given a maze represented as a grid of size N x N. Each cell in the grid is either empty (denoted by 0) or blocked (denoted by 1). You are also given a starting cell (x, y) and a target cell (p, q). Your task is to find the shortest path from the starting cell to the target cell by moving only in the four cardin... | ```cpp
#include <iostream>
#include <queue>
#include <vector>
#include <cstring>
using namespace std;
const int MAX_N = 100;
int visited[MAX_N][MAX_N];
int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, 1, -1};
vector<int> track;
bool isValid(int x, int y, int N, const vector<vector<int>>& maze) {
return (x >= 0 && x <... | magicoder | cpp |
You are tasked with creating a Discord bot command that allows users to play a simple number guessing game. The bot should generate a random number between 1 and 100, and the user will have to guess the number. The bot should provide hints such as "Too high" or "Too low" after each guess until the user correctly guesse... | ```python
import discord
import random
from discord.ext import commands
bot = commands.Bot(command_prefix='!')
@bot.event
async def on_ready():
print(f'We have logged in as {bot.user}')
@bot.command(name='guess', help='Play a number guessing game')
async def guess(ctx):
number_to_guess = random.randint(1, 10... | magicoder | python |
You are tasked with creating a SwiftUI view in Swift that displays text along the circumference of a circle. Your task is to implement the `CircleText` view, which takes in the radius of the circle and the text to be displayed along its circumference. The text should be evenly distributed along the circle's perimeter.
... | ```swift
import Foundation
import SwiftUI
struct CircleText: View {
let radius: CGFloat
let text: String
var body: some View {
GeometryReader { geometry in
ZStack {
ForEach(0..<text.count, id: \.self) { index in
let angle = -Double(index) * 2 * .pi /... | magicoder | swift |
You are tasked with creating a program to analyze and categorize document page sizes based on their width. The program should identify whether a given page width corresponds to standard paper sizes such as A4 or Letter, or if it is an unknown size. Additionally, the program should extract and categorize references and ... | ```python
import re
from typing import Tuple, List
def analyze_page(width: float, document_content: str) -> Tuple[str, List[str], List[str]]:
if width == round(210, -4):
page_size = 'A4'
elif width == round(8.5 * 25.4, -4): # Convert inches to mm for comparison
page_size = 'Letter'
else:
... | magicoder | python |
You are tasked with implementing a method to extract and process VXLAN (Virtual eXtensible Local Area Network) data from a given UDP packet. VXLAN is a network virtualization technology that encapsulates Layer 2 Ethernet frames within Layer 4 UDP packets, allowing for the creation of virtualized overlay networks. The p... | ```java
public void processVxlanPacket(IPacket udpPacket) {
IPacket udpData = udpPacket.getPayload(); // Extract the payload from the UDP packet
byte[] udpPayload = udpData.serialize(); // Serialize the payload to a byte array
ByteBuffer vxlanDataBB = ByteBuffer.wrap(udpPayload); // Wrap the payload in a By... | magicoder | java |
You are tasked with creating a program that reads a text file and counts the occurrences of each word in the file. Your program should ignore punctuation and consider words with different capitalization as the same word. The program should then output the unique words along with their respective counts in alphabetical ... | ```python
import string
def count_word_occurrences(file_name):
word_count = {}
with open(file_name, 'r') as file:
for line in file:
line = line.lower()
for word in line.split():
word = word.strip(string.punctuation)
if word:
wo... | magicoder | python |
You are working on a Python project that involves importing various modules from different files. Your project structure includes the following files: `buyback_metrics.py`, `fei_metrics.py`, `fei_volume_metrics.py`, and `pcv_metrics.py`. Each of these files contains relevant functions and classes for calculating specif... | ```python
# Import necessary modules from the provided files
from .buyback_metrics import *
from .fei_metrics import *
from .fei_volume_metrics import *
from .pcv_metrics import *
# Utilize the functions and classes from the imported modules to calculate financial metrics
def calculate_combined_metrics():
buyback_... | magicoder | python |
You are tasked with implementing a function to convert an amount of money from one currency to another. You are given an interface `Money` which represents a monetary amount in a specific currency. The interface has two properties: `cents`, which represents the amount in cents, and `currency`, which represents the curr... | ```typescript
function convertCurrency(amount: number, fromCurrency: Currency, toCurrency: Currency): number {
const exchangeRates: { [key in Currency]: number } = {
USD: 1,
EUR: 0.85,
GBP: 0.73,
JPY: 110.17,
AUD: 1.31
};
const amountInUSD = amount / exchangeRates[fromCurrency];
return amou... | magicoder | typescript |
You are tasked with implementing a custom function `_reduce` that mimics the behavior of Python's built-in `reduce` function. The `_reduce` function takes two parameters: `x`, which is a list of elements, and `reduction`, which is a function used to reduce the list to a single value. The `reduction` function takes two ... | ```python
def _reduce(x, reduction):
result = x[0]
for i in range(1, len(x)):
result = reduction(result, x[i])
return result
# Example usage
input_list = [1, 2, 3, 4]
custom_reduction = lambda a, b: a + b
output = _reduce(input_list, custom_reduction)
print(output) # Output: 10
``` | magicoder | python |
You are tasked with creating a Python program to visualize and analyze data from a hypothetical experiment. The experiment involves measuring the growth of three different plant species under varying light conditions. To accomplish this, you will need to generate a plot that displays the growth data for each plant spec... | ```python
import pandas as pd
import matplotlib.pyplot as plt
# Load the growth data from the CSV file
data = pd.read_csv('plant_growth_data.csv')
# Extract data for each plant species
species1_data = data[data['species'] == 'Species1']
species2_data = data[data['species'] == 'Species2']
species3_data = data[data['sp... | magicoder | python |
You are tasked with creating a program to convert Roman numerals to their corresponding decimal values. Your program should include a class `ConvertRomanButtonListener` that listens for user input and performs the conversion. The class should have a constructor that takes two `JTextField` objects as parameters: `result... | ```java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextField;
public class ConvertRomanButtonListener implements ActionListener {
private JTextField valueTextField;
private JTextField resultTextField;
public ConvertRomanButtonListener(JTextField resultTarg... | magicoder | java |
You are tasked with implementing a custom EntryDialog class in Python, which is a variation of the MessageDialog class. The EntryDialog should have the ability to take all the arguments of the MessageDialog constructor, along with an optional named argument "default_value" to specify the initial contents of the entry.
... | ```python
class MessageDialog:
def __init__(self, title, message):
self.title = title
self.message = message
class EntryDialog(MessageDialog):
def __init__(self, title, message, **kwargs):
super().__init__(title, message)
if 'default_value' in kwargs:
self.default_va... | magicoder | python |
You are tasked with implementing a simplified version of a resource management system. The system consists of a resource that needs to be opened before it can be used and closed after it has been used. Your task is to write a class that manages the opening and closing of the resource.
You are provided with a code snip... | ```java
public class ResourceManager {
private boolean isOpen;
public ResourceManager() {
this.isOpen = false;
}
public void open() {
if (!isOpen) {
System.out.println("Opening the resource");
isOpen = true;
} else {
System.out.println("Resou... | magicoder | java |
You are tasked with creating a Python program to monitor the temperature and humidity of a room using a Xiaomi Mi Bluetooth Temperature and Humidity Sensor. The sensor can be accessed using the `mitemp_bt` library, which provides a `MiTempBtPoller` class for interacting with the sensor. The `MiTempBtPoller` class has m... | ```python
from mitemp_bt.mitemp_bt_poller import MiTempBtPoller, MI_TEMPERATURE, MI_HUMIDITY, MI_BATTERY
import time
import csv
from datetime import datetime
# Replace 'XX:XX:XX:XX:XX:XX' with the actual MAC address of your Xiaomi Mi Bluetooth Temperature and Humidity Sensor
sensor_mac_address = 'XX:XX:XX:XX:XX:XX'
d... | magicoder | python |
You are given a class `RightTriangle` with a method `triangleCount` that takes five integers: `places`, `points`, `a`, `b`, and `c`. The method aims to count the number of right-angled triangles that can be formed using the given points on a grid.
The grid has `places` number of points, and `points` represents the num... | ```cpp
#include <set>
#include <vector>
#include <algorithm>
using namespace std;
class RightTriangle {
public:
long long triangleCount(int places, int points, int a, int b, int c) {
if (places & 1) {
return 0;
}
set<long long> S;
for (int i = 0; i < places; ++i) {
... | magicoder | cpp |
You are tasked with implementing a Java class that manages a list of domain parameters. The `DominiosImports` class contains a private list of `DominioParams` objects and provides methods to get and set this list. Your task is to complete the implementation of the `DominiosImports` class by adding a method to find and ... | ```java
public DominioParams findMaxAttributeValue(String attribute) {
if (dominios == null || dominios.isEmpty()) {
return null;
}
DominioParams maxAttributeDominio = dominios.get(0);
int maxAttributeValue = maxAttributeDominio.getAttributeValue(attribute);
for (DominioParams dominio : do... | magicoder | java |
You are tasked with implementing a function to calculate the overlap area between two given images represented by their physical points and sizes. The physical points and sizes are obtained from the largest possible regions of the images. The function should take the physical points and sizes of the two images as input... | ```python
import numpy as np
def calculate_overlap_area(a1, b1, a2, b2):
# Calculate the minimum of the maximum x and y coordinates to find the top-right corner of the overlap
top_right = np.minimum(a1 + b1, a2 + b2)
# Calculate the maximum of the minimum x and y coordinates to find the bottom-left co... | magicoder | python |
You are given a list of integers `nums`. Your task is to write a function `helper` that takes four parameters: `start`, `current`, `count`, and `visited`. The function should recursively determine if it's possible to reach the end of the list by jumping from the current index to a new index based on the value at the cu... | ```python
from typing import List
def helper(start, current, count, visited):
if current == len(nums) - 1:
return True
if current < 0 or current >= len(nums) or current in visited:
return False
visited.add(current)
return helper(start, current + nums[current], count + 1, visited) or hel... | magicoder | python |
You are tasked with creating a Python function that loads configuration data from YAML files and performs validation on the loaded data. The configuration data consists of two types: `GlobalConfig` and `CameraConfigSection`. The `GlobalConfig` is loaded from the file "src/config/config.yaml", while the `CameraConfigSec... | ```python
import yaml
import typing as tp
class GlobalConfig(tp.TypedDict):
app_name: str
version: str
max_users: int
class CameraConfigSection(tp.TypedDict):
camera_id: int
camera_name: str
resolution: str
def load_and_validate_config() -> tp.Tuple[GlobalConfig, tp.List[CameraConfigSection]]... | magicoder | python |
You are tasked with implementing a function that processes a JSON response containing an array of `SampleItem` objects and returns the sum of the `id` values for all the items in the response.
You are given the following code snippet as a reference for the structure of the `SampleItem` and `SampleItemResponse`:
```sw... | ```swift
import Foundation
func sumOfIdsInResponse(jsonData: Data) -> Int {
do {
let decoder = JSONDecoder()
let response = try decoder.decode(SampleItemResponse.self, from: jsonData)
let sum = response.data.reduce(0) { $0 + $1.id }
return sum
} catch {
print("Error deco... | magicoder | swift |
You are working on a project that involves processing data from astronomical observations. The code snippet provided is part of a Python script used to load and process visibility data from a specific astronomical target. The script uses a custom module called `mdldictionary` and the `numpy` library for numerical opera... | ```python
import sys
import numpy as np
from mdldictionary import ImportMS
def calculate_average_visibility_amplitude(target: str) -> float:
# Load model and residual visibilities into MS format
ms_data = ImportMS('data/' + target + '.ms')
# Extract visibility amplitudes from the loaded data
visibilit... | magicoder | python |
You are tasked with implementing a Vector2 class in TypeScript to perform various operations on 2D vectors. The class should support normalization, addition, and subtraction of vectors. You need to implement the static methods `_normalize`, `_add`, and `_subtract` within the Vector2 class.
The `_normalize` method shou... | ```typescript
interface IVector2 {
v: number[];
length(): number;
}
type TypedArrayConstructor = Int8ArrayConstructor | Uint8ArrayConstructor | Int16ArrayConstructor | Uint16ArrayConstructor | Int32ArrayConstructor | Uint32ArrayConstructor | Float32ArrayConstructor | Float64ArrayConstructor;
class Vector2 {
sta... | magicoder | typescript |
You are tasked with implementing a simplified version of a factory pattern for creating lowered cell objects for different backends in a neuron simulation framework. The provided code snippet is a part of the implementation of this factory pattern. The `make_fvm_lowered_cell` function takes a backend kind and an execut... | ```cpp
#include "backends/multicore/fvm.hpp"
#include "backends/gpu/fvm.hpp"
#include "fvm_lowered_cell_impl.hpp"
namespace arb {
// Define the fvm_lowered_cell_impl class for the multicore backend
template <typename Backend>
class fvm_lowered_cell_impl {
public:
fvm_lowered_cell_impl(const execution_context& ctx... | magicoder | cpp |
You are tasked with implementing a simplified version of a timeout manager in Rust. The timeout manager should allow users to set a timeout for a specific task and then clear that timeout if the task completes before the timeout duration elapses.
You are provided with a partial implementation of the `TimeoutManager` s... | ```rust
use std::time::{Duration, Instant};
use std::collections::HashMap;
struct TimeoutManager {
id_counter: u64,
timeouts: HashMap<u64, Instant>,
}
impl TimeoutManager {
fn new() -> TimeoutManager {
TimeoutManager {
id_counter: 0,
timeouts: HashMap::new(),
}
... | magicoder | rust |
You are tasked with implementing a Python class that performs a specific computation on a given dataset. The class contains a method `compute` that processes the data and returns a list of results. Your task is to complete the implementation of the `compute` method based on the provided code snippet and additional cont... | ```python
def compute(self):
results = []
to_process = [(self.data, 1, [self.data])]
for i in range(self._max_depth):
new_results = []
for data_tuple in to_process:
data, prior_w, prior_rules = data_tuple
# Perform computation on the da... | magicoder | python |
You are given a code snippet that appears to be part of a program to find the minimum spanning tree (MST) of a weighted graph using Kruskal's algorithm. Your task is to complete the implementation of the KruskalMST method and ensure that it correctly finds the total weight of the minimum spanning tree.
The KruskalMST ... | ```java
import java.util.*;
class Edge implements Comparable<Edge> {
int src, dest, weight;
public int compareTo(Edge compareEdge) {
return this.weight - compareEdge.weight;
}
}
class Graph {
int V, E;
Edge edge[];
Graph(int v, int e) {
V = v;
E = e;
edge = ne... | magicoder | java |
You are tasked with implementing a custom React component that allows users to input and manipulate strings. The component, `ControlledStringInput`, should support drag-and-drop functionality for text input. The provided code snippet shows the beginning of the component's implementation, including the use of a `ref` fo... | ```jsx
import React, { useState } from 'react';
const ControlledStringInput = React.forwardRef((props, ref) => {
const [inputValue, setInputValue] = useState('');
const handleDrop = (event) => {
event.preventDefault();
const droppedText = event.dataTransfer.getData('text/plain');
setInputValue(dropped... | magicoder | jsx |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.