query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a Python function to convert a given datetime object to a Unix timestamp and then back to a datetime object. Additionally, you need to create a protocol buffer object with a datetime field and convert it to a dictionary, and then back to a protocol buffer object.
You are provided with ... | ```python
import datetime
import time
import sample_pb2 # Assuming sample_pb2 contains the definition of Obj
def datetime_to_timestamp(dt):
return int(dt.timestamp())
def timestamp_to_datetime(timestamp):
return datetime.datetime.fromtimestamp(timestamp)
def pb_convert_to_dict(pb_obj):
return {
... | magicoder | python |
You are tasked with implementing a class that simulates a simple banking system. The class, `BankAccount`, should have the following functionalities:
1. Initialize a bank account with a given `accountNumber` and `balance`.
2. Deposit a specified amount of money into the account.
3. Withdraw a specified amount of money ... | ```csharp
using System;
public class BankAccount
{
public int AccountNumber { get; }
public double Balance { get; private set; }
public BankAccount(int accountNumber, double initialBalance)
{
AccountNumber = accountNumber;
Balance = initialBalance;
}
public void Deposit(double... | magicoder | csharp |
You are tasked with implementing a trajectory simulation for a projectile in a 3D space. You are given a struct `Projectile` representing the projectile's initial state, including its position, velocity, and acceleration. Additionally, you need to implement a method `get_position` for the `Projectile` struct, which cal... | ```rust
impl Projectile {
pub fn get_position(&self, time: f64) -> Vec3 {
let position_x = self.position.x + self.velocity.x * time + 0.5 * self.acceleration.x * time.powi(2);
let position_y = self.position.y + self.velocity.y * time + 0.5 * self.acceleration.y * time.powi(2);
let position_z... | magicoder | rust |
You are tasked with implementing a Python class that can convert a dictionary to an object. Your task is to complete the implementation of the `from_dict` method in the given Python class. The `from_dict` method should take a dictionary as input and create an instance of the class with attributes set according to the k... | ```python
class CustomClass:
def __init__(self):
self.name = ""
self.age = 0
self.gender = ""
@classmethod
def from_dict(cls, d):
obj = cls()
for key, val in d.items():
if hasattr(obj, key):
setattr(obj, key, val)
return obj
... | magicoder | python |
You are tasked with creating a command-line tool similar to the one in the provided code snippet. Your tool should determine which server is serving the current working directory based on a set of predefined rules. The servers in consideration are Apache, Nginx, and Caddy. Each server has a distinct set of configuratio... | ```python
import os
def determine_serving_server(current_directory: str) -> str:
server_configs = {
"Apache": "httpd.conf",
"Nginx": "nginx.conf",
"Caddy": "Caddyfile"
}
closest_server = "Unknown"
closest_distance = float('inf')
while current_directory != '/':
for ... | magicoder | python |
You are tasked with creating a Python class that simulates a security testing tool. The class, named `Exploit`, contains a method `run` that attempts to exploit a vulnerability in a target system. The `run` method first calls the `login` method to authenticate with the target system. If the login is successful, it prin... | ```python
class Exploit:
def run(self):
if self.login():
print_success("Target seems to be vulnerable")
self.info()
print_status("Invoking command loop")
self.shell(architecture="mipsbe", method="wget", location="/tmp")
else:
print_error("E... | magicoder | python |
You are given a code snippet that checks whether two cells on a chessboard have the same color. The code takes the column number of the second cell as input and then determines if the two cells have the same color. However, the code snippet is incomplete and contains errors. Your task is to complete the code and fix an... | ```python
def same_color_cells(row1, col1, row2, col2):
if not (1 <= row1 <= 8 and 1 <= col1 <= 8 and 1 <= row2 <= 8 and 1 <= col2 <= 8):
return "Invalid cell coordinates for a Chessboard!"
if (row1 + col1) % 2 == (row2 + col2) % 2:
return "YES, The two given cells have the SAME color."
els... | magicoder | python |
You are tasked with implementing a class that manages a collection of pointers and provides methods to add and remove pointers from the collection. Your goal is to create a class called `Pointers` with the following specifications:
- The class should have a constructor that takes an integer `capacity` as a parameter a... | ```cpp
#include <iostream>
#include <stdexcept>
#include <vector>
class Pointers {
public:
Pointers(int capacity) : capacity_(capacity) {}
void* Remove(int index) {
if (index < 0 || index >= pointers_.size()) {
throw std::out_of_range("Index out of bounds");
}
void* removed... | magicoder | cpp |
You are tasked with implementing a custom k-nearest neighbors (KNN) classifier from scratch in Python. The KNN algorithm is a simple and effective classification algorithm that works by finding the k nearest neighbors of a given data point and assigning it the majority class among those neighbors.
Your task is to crea... | ```python
import numpy as np
class KNNClassifier:
def __init__(self, k):
self.k = k
self.X_train = None
self.y_train = None
def fit(self, X_train, y_train):
self.X_train = X_train
self.y_train = y_train
def predict(self, X):
distances = np.sqrt(np.sum((self... | magicoder | python |
You are tasked with implementing a sorting function for a given dataset. The function should take in a pandas DataFrame, a column name, and a boolean value indicating whether to sort in ascending or descending order. Your task is to write a Python function that sorts the DataFrame based on the specified column in the s... | ```python
import pandas as pd
def sortValue(data: pd.DataFrame, column: str, ascBoolean: bool) -> pd.DataFrame:
sorted_data = data.sort_values(column, ascending=ascBoolean)
return sorted_data
``` | magicoder | python |
You are tasked with implementing a distributed system that calculates the trace of a matrix using ZeroMQ for inter-process communication. The system consists of a central server and multiple worker nodes. The server distributes matrix data to the worker nodes, and each worker node calculates the trace of the received m... | ```python
import zmq
import numpy as np
context = zmq.Context()
socket_addr = "tcp://localhost:5555"
worker = context.socket(zmq.DEALER)
worker.connect(socket_addr)
print("Worker node started")
while True:
message = worker.recv()
matrix_data = deserialize_matrix(message)
# Calculate the trace of the ma... | magicoder | python |
You are tasked with implementing a URL routing system for a web application using Python's Django framework. The given code snippet represents a part of the URL configuration for a user profile module. Each URL pattern is associated with a specific view function that handles the corresponding HTTP request.
Your task i... | ```python
import re
def find_view_function(url_path: str) -> str:
url_patterns = [
(r'^$', 'index'),
(r'^api_keys/$', 'apikeys'),
(r'^update/$', 'update'),
(r'^password/$', 'password_change'),
(r'^activate/$', 'activation'),
(r'^ssh_key/(?P<action>add|delete)/$', 'ss... | magicoder | python |
You are tasked with implementing a simple hash table data structure in C++. The hash table should support key-value pairs, and it should handle collisions using separate chaining. You need to implement the `HashTable` class with the following functionalities:
1. `insert(key, value)`: Insert a key-value pair into the ha... | ```cpp
#include <iostream>
#include <vector>
#include <list>
class HashTable {
private:
std::vector<std::list<std::pair<int, int>>> table;
int size;
int hash(int key) {
return key % size;
}
public:
HashTable(int tableSize) : size(tableSize), table(tableSize) {}
void insert(int key, i... | magicoder | cpp |
You are tasked with creating a bash script that simulates a countdown timer with a customizable message. Your script should take two arguments: a time in seconds and a message to display while counting down. The script should display the message and then count down from the specified time to 1, updating the countdown o... | ```bash
#!/bin/bash
# SPDX-License-Identifier: Apache-2.0
# Copyright (c) 2021 Intel Corporation
function countdown {
local time=$1
local message=$2
echo "Waiting for $time seconds: $message"
for ((i=$time; i>=1; i--))
do
echo -ne "\r$i seconds remaining "
sleep 1
done
... | magicoder | shell |
You are working on a project to optimize communication costs for a network of cameras sending data to a cloud server. The code snippet provided is a part of a Python script that uses the `matplotlib` library to create a bar chart representing the communication costs for different scenarios. The x-axis represents the to... | ```python
import matplotlib.pyplot as plt
def plot_communication_costs(camera_numbers, video_file_costs, data_to_cloud_costs):
x = range(len(camera_numbers)) # Generate x-coordinates for the bars
width = 0.35 # Width of the bars
plt.xlabel('Total Camera Numbers', fontsize=20)
plt.ylabel('Communicati... | magicoder | python |
You are working on a software tool for processing neuroimaging data using CAT12, a popular toolbox for computational anatomy. The tool has a configuration module that allows users to specify resampling settings for the data. The resampling settings include the resampling type and the internal resampling value. However,... | ```python
def validate_resampling_configuration(resampling_type, internal_resampling_value):
if resampling_type == 'optimal':
if internal_resampling_value != 1:
raise ValueError(INVALID_INTERNAL_RESAMPLING_OPTIMAL)
elif resampling_type == 'fixed':
if internal_resampling_value not in ... | magicoder | python |
You are tasked with implementing a C++ class for 2D points and providing methods to perform various operations on these points. The class should support operations such as calculating the distance between two points, finding the midpoint of two points, and checking if three points are collinear.
You need to create a c... | ```cpp
// geometry.hh
#include <cmath>
class Point {
private:
double x, y;
public:
Point(double x, double y) : x(x), y(y) {}
double distanceTo(const Point& other) {
return sqrt(pow(other.x - x, 2) + pow(other.y - y, 2));
}
Point midpointWith(const Point& other) {
double midX = (... | magicoder | cpp |
You are tasked with implementing a custom asynchronous function in Rust that simulates a simplified version of an HTTP request handler. The function is responsible for making a call to an endpoint and processing the response. Your goal is to complete the implementation of the `handle_request` function, ensuring that it... | ```rust
use std::sync::Arc;
struct AppData {
// Define the structure of AppData
}
struct Request {
// Define the structure of Request
}
struct Params {
// Define the structure of Params
}
struct Endpoint {
// Define the structure of Endpoint
}
impl Endpoint {
async fn call(self, app_data: Arc<A... | magicoder | rust |
You are tasked with implementing a multilayer perceptron (MLP) for a classification task using TensorFlow. An MLP is a type of feedforward artificial neural network that consists of multiple layers of nodes, each connected to the next layer. The task is to complete the implementation of the `multilayer_perceptron` func... | ```python
import tensorflow as tf
STEP = 1
NROFCLASSES = 10
X = tf.placeholder("float", [None, 28*28*1])
Y = tf.placeholder("float", [None, NROFCLASSES])
weights = {
'h1': tf.Variable(tf.random_normal([28*28*1, 256])),
'h2': tf.Variable(tf.random_normal([256, 256])),
'out': tf.Variable(tf.random_normal([2... | magicoder | python |
You are tasked with creating a Python function that processes a dictionary of machine learning model results and returns the best-performing model for each dataset. The function should take in three dictionaries as input: `model_results` (containing the performance metrics of each model on each dataset), `model_types` ... | ```python
def find_best_models(model_results: AllModelResultsDict, model_types: ModelDict, datasets: DfDict) -> ModelDict:
best_models = {}
for dataset, results in model_results.items():
best_model = min(results, key=lambda x: (-results[x], x))
best_model_type = model_types[best_model]
b... | magicoder | python |
You are tasked with implementing a function that calculates the cosine similarity between two vectors using the numpy library. Cosine similarity is a measure of similarity between two non-zero vectors of an inner product space. It is defined to equal the cosine of the angle between them, which is also the same as the i... | ```python
import numpy as np
def calculate_cosine_similarity(vector_a: np.ndarray, vector_b: np.ndarray) -> float:
dot_product = np.dot(vector_a, vector_b)
norm_a = np.linalg.norm(vector_a)
norm_b = np.linalg.norm(vector_b)
cosine_similarity = dot_product / (norm_a * norm_b)
return cosine_similarit... | magicoder | python |
You are given a list of tasks, each represented by a name and a duration. The tasks are divided into multiple sublists, and each sublist represents a specific category of tasks. Your task is to write a function that takes in this list of tasks and returns the total duration for each category.
For example, given the fo... | ```javascript
function calculateCategoryDurations(tasks) {
const categoryDurations = [];
for (const sublist of tasks) {
let totalDuration = 0;
for (const task of sublist) {
totalDuration += task.duration;
}
categoryDurations.push(totalDuration);
}
return categoryDurations;
}
// Test the f... | magicoder | javascript |
You are tasked with creating a Python class that simulates a simple library management system. The library contains books, and patrons can borrow and return books. The system should keep track of the available books, the books currently borrowed by patrons, and the patrons' borrowing history.
Your task is to create a ... | ```python
class Library:
def __init__(self, available_books):
self.available_books = available_books
self.borrowed_books = {}
self.borrowing_history = {}
def borrow_book(self, patron, book):
if book in self.available_books:
self.available_books.remove(book)
... | magicoder | python |
You are tasked with implementing a face tracking algorithm for a video processing application. The provided code snippet initializes some variables and iterates through a list of detected faces to extract their features. Your task is to complete the implementation of the face tracking algorithm by incorporating the fea... | ```python
import numpy as np
import json
# Assume the following variables are initialized:
# in_seq, short_seq, low_confidence, old_frame_id, tracks, faces_len, vid_features
for face_idx in range(faces_len):
curr_face = vid_features[face_idx]
curr_feature = np.array(json.loads(str(curr_face.features)))
#... | magicoder | python |
You are tasked with implementing a logging system for a software platform. The system should support multiple output channels, including syslog, serial communication, and standard error. Additionally, the system should have the capability to include time stamps in the log messages. Your task is to design a logging modu... | To address the logging requirements, a modular logging system can be designed using object-oriented principles. The system can consist of a Logger class with different output handlers and time stamp management. Here's a possible solution using Python as an example:
```python
import time
class Logger:
def __init__... | magicoder | python |
You are tasked with implementing a program to process a tree-like data structure and calculate the sum of metadata entries based on specific rules.
You are given a file `aocDay8.txt` containing a list of numbers representing a tree structure. Each node in the tree is defined by two numbers: the number of child nodes i... | ```rust
use std::fs;
struct Node {
children: Vec<Node>,
metadata: Vec<u32>,
}
impl Node {
fn new() -> Node {
Node {
children: Vec::new(),
metadata: Vec::new(),
}
}
}
fn parse_input(filename: &str) -> Vec<u32> {
let contents = fs::read_to_string(filename).ex... | magicoder | rust |
You are tasked with creating a Python program to perform a simplified version of a network port scanning tool. The program should prompt the user for a target IP address and provide options for different types of scans. For this problem, you will focus on implementing the SYN ACK scan option.
Your program should:
1. P... | ```python
import nmap
# Input & Cast
ip_addr = input("Target IP: ")
# Display Options
resp = input("""\nOptions:
1) SYN ACK Scan
2) Comprehensive Scan\n""")
# Create Nmap scanner object
scanner = nmap.PortScanner()
# SYN ACK Scan
if resp == '1':
print("Nmap Version: ", scanner.nm... | magicoder | python |
You are tasked with creating a Python program to perform port scanning using the `portchecker` function. The `portchecker` function takes two parameters: `port`, an integer representing the port number to be checked, and `timeout`, a float representing the maximum time to wait for a response from the port (default valu... | ```python
import socket
from functools import partial
import time
def check_port(port: int, timeout: float) -> bool:
"""Attempts to connect to the specified port within the given timeout"""
try:
with socket.create_connection(('localhost', port), timeout=timeout) as s:
return True # Port is... | magicoder | python |
You are tasked with creating a Python function that processes and sends data over a network connection. The function should take a result object and send it over the network using the appropriate encoding based on the type of the result. If the result is a string, it should be encoded and sent as is. If the result is n... | ```python
import json
class JsonParser:
@staticmethod
def dump_all_folder(data):
return json.dumps(data)
def send_result_over_network(result, connection):
if isinstance(result, str):
connection.send(result.encode())
else:
json_string = JsonParser.dump_all_folder(result)
... | magicoder | python |
You are tasked with implementing a file processing system for a data analysis application. The system is designed to read and process two types of files: a main data file and a corresponding metadata file. The metadata file contains additional information about the main data file, such as attributes and their values. Y... | ```python
import os
class DataProcessor:
def __init__(self, dir_path, subPath, modelType):
self.dir_path = dir_path
self.subPath = subPath
self.modelType = modelType
def process_files(self):
file = self.subPath+"_D.txt"
file_v = self.subPath+"_V.txt"
fileList = ... | magicoder | python |
You are tasked with creating a Python function that validates a given JWT (JSON Web Token) using the Keycloak authentication service. The code snippet provided initializes a `KeycloakBearerVerifier` object and sets its parameters using the `runtime_config` values. Your task is to implement a function that takes a JWT a... | ```python
def verify_jwt(jwt: str, verifier: KeycloakBearerVerifier) -> bool:
try:
verifier.verify_token(jwt)
return True
except Exception:
return False
```
In the solution, the `verify_jwt` function takes the JWT and the initialized `KeycloakBearerVerifier` object as input. It then att... | magicoder | python |
You are tasked with implementing a function to select a specific region in an image based on a given color. The image is represented as a 3D NumPy array, where the dimensions correspond to the height, width, and color channels. The color of the region to be selected is specified by a 3-element list representing the RGB... | ```python
import numpy
def select_region_by_color(image, color):
matching_pixels = []
for y in range(image.shape[0]):
for x in range(image.shape[1]):
if numpy.array_equal(image[y, x, :], color):
matching_pixels.append((x, y))
return matching_pixels
```
The `select_region... | magicoder | python |
You are tasked with implementing a subscription management system using PHP and Laravel. The provided code snippet is a simplified representation of the `Package` model in Laravel's Eloquent ORM. The `Package` model has a one-to-many relationship with the `Subscription` model, where a package can have multiple subscrip... | ```php
public function calculateTotalRevenue(){
return $this->subscriptions()->sum('amount');
}
```
The `calculateTotalRevenue` method utilizes Laravel's Eloquent ORM to calculate the sum of the `amount` attribute from all associated subscriptions, effectively providing the total revenue generated from the package... | magicoder | php |
You are tasked with creating a command-line utility that generates completions for a given program. The utility should accept a command-line argument specifying the type of completions to generate and then produce the corresponding completions.
You are provided with a Rust code snippet that uses the `structopt` crate ... | ```rust
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
enum Completions {
// Define the possible types of completions
FilePath,
Command,
CustomOption,
}
fn main() {
let completions = Completions::from_args();
match completions {
Completions::FilePath => {
// Logic t... | magicoder | rust |
You are tasked with implementing a custom assertion macro in Rust that compares two instances of a custom vector type. The custom vector type, `FfiVector2_f32`, represents a 2D vector with floating-point components. Your goal is to create a macro, `assert_ne_custom_vector!`, which compares two instances of `FfiVector2_... | ```rust
#[macro_export]
macro_rules! assert_ne_custom_vector {
($left:expr, $right:expr) => {
if $left == $right {
panic!("assertion failed: `(left != right)` (left: `{:?}`, right: `{:?}`)", $left, $right);
}
};
}
#[derive(Default, PartialEq, Debug)]
struct FfiVector2_f32 {
x: f... | magicoder | rust |
You are tasked with creating a simple shopping cart application using SwiftUI and Swift programming language. The application should allow users to add items to their cart, view the items in the cart, and calculate the total cost of the items. You are provided with a basic `Shop` class that manages the items available ... | ```swift
import SwiftUI
class Shop: ObservableObject {
@Published var availableItems: [String] = ["Item 1", "Item 2", "Item 3"]
}
struct ContentView: View {
@EnvironmentObject var shop: Shop
@State private var cartItems: [String] = []
var body: some View {
VStack {
Text("Available... | magicoder | swift |
You are tasked with implementing a simple React component for a Tetris game. The component is responsible for rendering the game interface and managing the game state. The provided code snippet is a part of the component's render method, displaying the current score, number of completed rows, and the game level. Your t... | ```jsx
import React, { useState, useEffect } from 'react';
const TetrisGame = () => {
const [score, setScore] = useState(0);
const [rows, setRows] = useState(0);
const [level, setLevel] = useState(1);
const [gameBoard, setGameBoard] = useState(initializeGameBoard());
const [isGameRunning, setIsGameRunning] =... | magicoder | jsx |
You are tasked with implementing a tone mapping algorithm for a graphics rendering system. The tone mapping algorithm is responsible for converting high dynamic range (HDR) images to low dynamic range (LDR) images for display on standard monitors. The tone mapping process involves adjusting parameters such as gamma, ex... | ```cpp
void ToneMappingMat::Execute(const SPtr<Texture>& source, const SPtr<RenderTarget>& destination, INT32 MSAACount,
float gamma, float exposure, float contrast, float brightness)
{
// Apply tone mapping algorithm to the source texture
// Pseudocode for tone mapping algorithm:
// 1. Retrieve the so... | magicoder | cpp |
You are tasked with implementing a custom authorization handler for a web application. The handler should check if the current user possesses a specific claim and grant access based on the presence of the claim.
You are provided with a code snippet that represents part of the authorization handler logic. The snippet i... | ```csharp
public class CustomAuthorizationHandler : AuthorizationHandler<CustomRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CustomRequirement requirement)
{
var hasClaim = context.User.Claims.Any(x => x.Type == requirement.ClaimType);
if (ha... | magicoder | csharp |
You are tasked with creating a Python function that parses a given Django app configuration file and extracts the number of GitHub stars for the app. The configuration file is in the format of a Python code snippet, and the number of GitHub stars is represented by the placeholder `<gh_stars>`. Your function should take... | ```python
import re
def extract_github_stars(config_file: str) -> int:
# Extract the GitHub stars using regular expression
stars_match = re.search(r'<gh_stars>(\d+)', config_file)
if stars_match:
stars = int(stars_match.group(1))
return stars
else:
raise ValueError("GitHub stars... | magicoder | python |
You are given a snippet of code that processes a text and extracts entities and their corresponding labels. The code snippet is part of a larger program that processes a text and populates a `label_dict` and `data_dict` based on the extracted entities and labels. Your task is to implement a function that takes the `lab... | ```python
def process_data(label_dict: dict, data_dict: dict) -> dict:
for entity, entities in label_dict.items():
if entity == 'extension':
content = ''.join([ent['text'] for ent in entities])
data_dict['content'] = content
# Update start value for duplicate texts
... | magicoder | python |
You are tasked with creating a program that simulates a simple quiz game. The program should present a series of questions to the user and allow them to input their answers. After answering all the questions, the program should display the user's score based on the number of correct answers.
Your task is to complete t... | ```python
def main():
ans = True
score = 0
quiz_questions = {
"What is the capital of France?": "Paris",
"What is the largest planet in our solar system?": "Jupiter",
"What is the powerhouse of the cell?": "Mitochondria"
}
while ans:
for question in quiz_questions:
... | magicoder | python |
You are tasked with creating a memory profiling test for a C# application using the dotMemoryUnit framework. The dotMemoryUnit framework allows for memory profiling and testing in unit tests for .NET applications. The code snippet provided is an example of using the dotMemoryUnit attribute to configure the behavior of ... | ```csharp
using NUnit.Framework;
using JetBrains.dotMemoryUnit;
public class MemoryProfilingTest
{
[Test]
public void MemoryUsageDoesNotExceedThreshold()
{
// Execute the method or code block to be profiled
// For example:
// YourClass yourInstance = new YourClass();
// your... | magicoder | csharp |
You are working on a natural language processing (NLP) project and have been tasked with evaluating the performance of word embeddings at different stages of the training process. The code snippet provided is part of a larger NLP pipeline and involves writing predictions to a file, calculating F1 scores, and visualizin... | ```python
def evaluate_word_embeddings(embeddings, training_condition):
# Write predictions to file at two different stages
write_preds_to_file(embeddings, '10-NN', f'{training_condition}_10-NN_after_stage1')
write_preds_to_file(embeddings, '10-NN', f'{training_condition}_10-NN_after_stage2')
# Calcula... | magicoder | python |
You are tasked with implementing a custom motion curve interpolator for a mobile game development project. The goal is to create a class that can calculate the position of an object over time, using a bounce motion curve. The class should be able to take initial velocity (v) and displacement (d) as input parameters and... | ```java
public class GaiaMotionCurveBounceInterpolator {
private float v; // initial velocity
private float d; // displacement
private static final float g = 9.81f; // acceleration due to gravity
public GaiaMotionCurveBounceInterpolator(float a_v, float a_d) {
v = a_v;
d = a_d;
}
... | magicoder | java |
You are tasked with creating a program to solve a quadratic equation using the quadratic formula, also known as "la chicharronera" in some Spanish-speaking countries. The quadratic formula is used to find the roots of a quadratic equation of the form ax^2 + bx + c = 0. The roots are given by the formula:
x = (-b ± √(b... | ```c
#include <stdio.h>
#include <math.h>
int main() {
float a, b, c;
float discriminant, x1, x2;
printf("Enter the value of coefficient a: ");
scanf("%f", &a);
printf("Enter the value of coefficient b: ");
scanf("%f", &b);
printf("Enter the value of coefficient c: ");
scanf("%f", &c);... | magicoder | c |
You are given an array of integers `arr`. Your task is to write a function `getNextGreaterElement` that takes an array `arr` as input and returns an array of the same length where each element at index `i` represents the next greater element of `arr[i]` in the input array. If there is no greater element for a particula... | ```python
from typing import List
def getNextGreaterElement(arr: List[int]) -> List[int]:
stack = []
result = [-1] * len(arr)
for i in range(len(arr)):
while stack and arr[i] > arr[stack[-1]]:
result[stack.pop()] = arr[i]
stack.append(i)
return result
```
The `getNextGrea... | magicoder | python |
You are tasked with creating a script to validate the usage of certain templates within a directory structure. The script should read through each file in a specified directory and check if the lines in the file match any entries in a template file. If a line in a file does not match any entry in the template file, an ... | ```bash
#!/bin/bash
template_file="template.txt"
check_dir="/path/to/directory"
# Loop through each file in the directory
while IFS= read -r -d '' file; do
# Extract each line from the file and check against the template file
while IFS= read -r line; do
grep -Fw "$line" "$template_file" > /dev/null ||... | magicoder | shell |
You are tasked with implementing a Python function that calculates the length of a line using the line-intersect method. The function takes in an input image, the size of a square mesh, the color of the grid, and a weight parameter. The function should convert the input image to a 3D array if it is not already in that ... | ```python
import numpy as np
def calculate_line_length(image_in, size, color=(255, 0, 0), weight=1):
# Convert 2D grayscale image to 3D if necessary
if len(image_in.shape) == 2:
image_in = np.stack((image_in,)*3, axis=-1)
# Define the line-intersect method to calculate the length of the line
#... | magicoder | python |
You are tasked with implementing a caching mechanism using Python. Your goal is to create a class `Cache` that stores the results of function calls and retrieves them from the cache if the same function is called with the same arguments. The cache should have a limit on the number of entries it can store, and it should... | ```python
class Cache:
def __init__(self, function, limit=1000):
self.function = function
self.limit = limit
self.store = {}
def get(self, key):
value = self.store.get(key)
if value is None:
value = self.function(key)
self.set(key, value)
... | magicoder | python |
You are tasked with implementing a keyboard presenter protocol in Swift. The protocol should handle keyboard notifications and provide methods for configuring and unregistering keyboard notifications. You are given a code snippet that includes a private method for handling the keyboard will hide notification and a prot... | ```swift
// Define the KeyboardPresenterProtocol
protocol KeyboardPresenterProtocol {
func keyboardAboutToHide(keyboardSize: CGRect)
func configureKeyboardPresenter()
func unregisterKeyboardNotifications()
}
// Implement the KeyboardPresentable protocol extension
extension KeyboardPresentable {
func co... | magicoder | swift |
You are tasked with implementing a custom error handling system in C++ using the provided `lunarlady/Error.hpp` library. The `lunarlady/Error.hpp` library provides a set of classes and functions for managing and reporting errors in a C++ program. Your goal is to create a custom error class and demonstrate its usage wit... | ```cpp
#include "lunarlady/Error.hpp"
#include <iostream>
class CustomError : public lunarlady::Error {
public:
CustomError(const std::string& message) : lunarlady::Error(message) {}
const char* what() const noexcept override {
return getMessage().c_str();
}
};
void performOperation() {
// Si... | magicoder | cpp |
You are tasked with testing a function that is responsible for extracting the region from the availability zone. The function `get_region_strips_availability_zone_to_region` takes an availability zone as input and returns the corresponding region after stripping the zone identifier. The function internally uses the `cs... | ```python
from unittest import TestCase
from unittest.mock import patch
from your_module import get_region_strips_availability_zone_to_region
class TestSignalElbHealthcheck(TestCase):
@patch("cseh.get_instance_metadata")
def test_get_region_strips_availability_zone_to_region_valid(self, get_instance_metadata)... | magicoder | python |
You are tasked with implementing a function that extracts the breadcrumb trail from an HTML page. Breadcrumbs are a navigational aid typically displayed horizontally on a webpage, showing the user's current location within the website's hierarchy. The breadcrumb trail is often represented as a series of links or text e... | ```javascript
function extractBreadcrumbs(html) {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const breadcrumbDiv = doc.querySelector('.breadcrumb');
if (breadcrumbDiv) {
const breadcrumbElements = Array.from(breadcrumbDiv.childNodes).filter(node => node.nodeType =... | magicoder | javascript |
You are tasked with creating a custom attribute in a C# ASP.NET Core application that will validate an API key provided in the request header. The API key will be stored in a predefined header field named "gooiosapikey". If the API key is valid, the request should be allowed to proceed; otherwise, it should be rejected... | ```csharp
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Filters;
namespace Gooios.AuthorizationService.Attributes
{
public class ApiKeyAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
... | magicoder | csharp |
You are tasked with implementing a simple stack data structure using Python. A stack is a Last-In-First-Out (LIFO) data structure that supports two main operations: push, which adds an element to the top of the stack, and pop, which removes the top element from the stack. Additionally, we want to implement a method to ... | ```python
class Stack:
def __init__(self):
self.items = []
def push(self, item):
# Add the item to the top of the stack
self.items.append(item)
def pop(self):
# Remove and return the top item from the stack
if not self.is_empty():
return self.items.pop()... | magicoder | python |
You are tasked with implementing a test runner for a system that simulates various events. The provided code snippet is a part of the test runner, which processes a sequence of events and executes corresponding test actions. Your goal is to complete the implementation of the `runSendTest` and `runRecvTest` methods, whi... | ```python
class TestEvent:
send = "send"
recv = "recv"
clear = "clear"
class TestRunner:
def __init__(self):
self.firstTest = False
def runSendTest(self, e, count):
# Implement the send test logic here
# Example: Sending test data and capturing the result
result = "... | magicoder | python |
You are tasked with implementing a simple calculator class in Python. The calculator should be able to perform basic arithmetic operations such as addition, subtraction, multiplication, and division. Additionally, it should have the capability to store and retrieve a memory value, as well as clear the memory.
Your tas... | ```python
import unittest
class Calculator:
def __init__(self):
self.memory = 0
def add(self, x, y):
return x + y
def subtract(self, x, y):
return x - y
def multiply(self, x, y):
return x * y
def divide(self, x, y):
if y == 0:
raise ValueError... | magicoder | python |
You are given a staircase with n steps. You can climb either 1 or 2 steps at a time. Write a function `climb_stairs` to return the distinct number of ways to reach the top of the staircase.
For example, if the staircase has 4 steps, there are 5 distinct ways to climb to the top:
1. 1 step + 1 step + 1 step + 1 step
2.... | ```python
def climb_stairs(n: int) -> int:
if n <= 2:
return n
dp = [0] * (n + 1)
dp[1] = 1
dp[2] = 2
for i in range(3, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
```
The `climb_stairs` function takes an integer `n` as input and returns the distinct number of ways to clim... | magicoder | python |
You are working on a file management system that involves deleting files and directories. Your task is to implement a function that simulates the behavior of a command-line tool for deleting files and directories. The function should take a list of commands as input and return the final state of the file system after e... | ```python
from typing import List
def simulate_file_system(commands: List[str]) -> List[str]:
file_system = {
"file1",
"file2",
"directory1/",
"directory1/file3",
"directory1/file4",
"directory2/",
"directory2/file5"
}
for command in commands:
... | magicoder | python |
You are tasked with simulating the behavior of a hardware interrupt controller in a simplified embedded system. The interrupt controller has two registers: `interrupt_clear_pending_register` and `interrupt_set_enable_register`, each with 32 bits. The provided code snippet is from a method in the interrupt controller's ... | ```python
from typing import List, Tuple
def simulate_interrupt_controller(initial_clear_register: int, initial_enable_register: int, interrupt_numbers: List[int]) -> Tuple[int, int]:
clear_register = initial_clear_register
enable_register = initial_enable_register
for interrupt_number in interrupt_number... | magicoder | python |
You are tasked with implementing a Squeeze-and-Excite block, a component commonly used in convolutional neural networks (CNNs) to improve feature representation. The Squeeze-and-Excite block consists of two main steps: squeezing the spatial dimensions of the input feature maps to obtain channel-wise statistics, and the... | ```python
import torch
import torch.nn as nn
class SqueezeBlock(nn.Module):
def __init__(self, exp_size):
super(SqueezeBlock, self).__init__()
self.exp_size = exp_size
self.squeeze_layer = nn.AdaptiveAvgPool2d(1)
def squeeze(self, x):
# Squeezing step: compute channel-wise stat... | magicoder | python |
You are tasked with implementing a learning rate scheduler for a neural network training process. The learning rate scheduler is responsible for adjusting the learning rate at different epochs to optimize the training process. The provided code snippet outlines a part of the learning rate scheduler function, which take... | ```python
import numpy as np
from typing import List
def learning_rate_scheduler(global_step: int, lr_max: float, decay_epoch_index: List[int]) -> np.ndarray:
lr_each_step = []
for i in range(decay_epoch_index[-1] + 1):
if i < decay_epoch_index[0]:
lr_each_step.append(lr_max)
elif i... | magicoder | python |
You are tasked with creating a Python program that reads data from a JSON file, processes it, and then performs an asynchronous task using the Twisted library. The program should read a JSON file named "data.json" located in the current working directory. The JSON file contains a list of dictionaries, where each dictio... | ```python
import json
import os
from twisted.internet import reactor
from twisted.internet.task import deferLater
def perform_action(action, parameters):
# Implement the logic to perform the specified action with the given parameters
pass
def execute_task(task):
task_id = task["task_id"]
action = task... | magicoder | python |
You are tasked with implementing a function to process and analyze data from a network request. The function will take in an array of `ForwardResponse` objects, each containing information about a network request and its corresponding response. Your goal is to extract and process specific data from these objects to gen... | ```typescript
function generateSummaryReport(responses: ForwardResponse[]): SummaryReport {
const summary: SummaryReport = {
totalRequests: responses.length,
successfulRequests: 0,
failedRequests: 0,
averageResponseTime: 0,
mostCommonTraceID: null,
uniqueTraceIDs: [],
};
const responseTim... | magicoder | typescript |
You are tasked with creating a symbolic regression model to predict housing prices using the Boston housing dataset. The Boston housing dataset contains 13 features such as crime rate, average number of rooms per dwelling, and nitric oxides concentration, and the target variable is the median value of owner-occupied ho... | ```python
from gplearn.genetic import SymbolicRegressor
from sklearn.model_selection import GridSearchCV
def train_symbolic_regression_model(x, y):
param_grid = {
'population_size': [1000, 5000, 10000],
'generations': [10, 20, 50],
'stopping_criteria': [0.9, 0.95, 0.99],
'store': [T... | magicoder | python |
You are tasked with implementing a custom smart pointer class in C++. The smart pointer should mimic the behavior of `std::shared_ptr` and manage the memory of a dynamically allocated object. Your custom smart pointer should support reference counting and automatic memory deallocation when the last reference to the obj... | ```cpp
#include <iostream>
namespace rtt_cdi_analytic {
template <typename T>
class CustomSharedPtr {
public:
// Constructor
CustomSharedPtr(T* ptr) : m_ptr(ptr), m_refCount(new size_t(1)) {}
// Copy constructor
CustomSharedPtr(const CustomSharedPtr<T>& other) : m_ptr(other.m_ptr), m_refCount(other.m... | magicoder | cpp |
You are tasked with implementing a function to parse a byte array and extract query parameters for a database query. The function should handle the extraction of various parameters from the byte array and return a `QueryParameter` object.
The `QueryParameter` class has a private constructor that takes in several param... | ```cpp
QueryParameter QueryParameter::Make(const std::vector<tcp::byte>& body,
std::size_t* offset) {
// Extract values from the body byte array based on the provided offset
// Update the offset if it is provided
// Create a QueryParameter object with the extracted values
// ... | magicoder | cpp |
You are tasked with creating a program that analyzes a given HTML file and counts the occurrences of specific HTML tags within it. Your program should be able to handle nested tags and should ignore any tags within comments or script blocks.
Write a function `countHtmlTags(html, tags)` that takes in two parameters:
- ... | ```python
import re
def countHtmlTags(html, tags):
tag_counts = {tag: 0 for tag in tags}
tag_pattern = re.compile(r'<([a-zA-Z0-9]+)[^>]*>.*?</\1>|<([a-zA-Z0-9]+)[^>]*/?>')
matches = tag_pattern.finditer(html)
for match in matches:
for tag in tags:
if match.group(tag):
... | magicoder | python |
You are tasked with implementing a Java program that utilizes MethodHandles to manipulate a private field within a class. MethodHandles are a powerful feature introduced in Java 7 that allow for low-level access to methods, fields, and constructors, providing a flexible and efficient means of performing operations that... | ```java
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
class Foo {
private int i;
public int getI() {
return i;
}
}
public class Main {
public static void main(final String... args) {
try {
final MethodHandles.Lookup lookup = MethodHandles.lookup... | magicoder | java |
You are tasked with implementing a program that processes a list of software licenses and extracts the type of license for each software. The license type is denoted by the comment lines in the code snippet. Each comment line starts with "//" followed by the license type. Your program should read the input and output t... | ```python
import sys
def extract_license_types(input_lines):
license_types = []
for line in input_lines:
if line.strip() == "END":
break
if line.startswith("//"):
license_type = line[2:].strip()
license_types.append(license_type)
return license_types
def... | magicoder | python |
You are tasked with implementing a function to perform a depth-first search (DFS) traversal on an octree data structure. An octree is a tree data structure in which each internal node has exactly eight children. The octree is represented using the following classes and structures:
```cpp
namespace octomap {
template... | ```cpp
void dfsTraversal(octomap::OcTree* octree) {
se::Node<VoxelT>* node_stack[se::Octree<VoxelT>::max_voxel_depth * 8 + 1];
size_t stack_idx = 0;
se::Node<VoxelT>* node = octree->root();
if (node != nullptr) {
node_stack[stack_idx++] = node;
while (stack_idx > 0) {
se::Node<VoxelT>* current ... | magicoder | cpp |
You are given a file containing a list of words, with each word on a separate line. Your task is to write a Python program to read the file and find the longest word in the list. You should then print the longest word and its length.
Your program should follow these steps:
1. Open the file named `WORDLIST_FILENAME` in... | ```python
# Open the file named WORDLIST_FILENAME in read mode
with open(WORDLIST_FILENAME, 'r') as inFile:
# Initialize variables to store the longest word and its length
longest_word = ""
max_length = 0
# Iterate through each line in the file
for line in inFile:
# Remove any leading o... | magicoder | python |
You are tasked with implementing a class to generate unique IDs for different entities in a system. The class should be able to generate both numeric and alphanumeric IDs, ensuring that each generated ID is unique.
Your task is to create a class `IDGenerator` with the following methods:
1. `generateNumericID()`: This ... | ```php
class IDGenerator {
private $generatedNumericIDs = [];
private $generatedAlphaNumericIDs = [];
public function generateNumericID() {
do {
$numericID = $this->generateRandomNumericID();
} while (in_array($numericID, $this->generatedNumericIDs));
$this->gen... | magicoder | php |
You are tasked with creating a program that simulates a package manager's installation process. The program should take a list of packages to be installed and execute the installation process for each package. Each package installation should be logged, and the program should handle potential errors during the installa... | ```python
from typing import List
import subprocess
def simulate_package_manager(packages: List[str]) -> None:
for package in packages:
print(f"Installing {package}...")
try:
subprocess.run(["brew", "install", package], check=True)
print(f"{package} installed successfully.")... | magicoder | python |
You are given a Python function that takes a list of strings as input and is expected to return the same list after performing a specific operation. The function is defined as follows:
```python
def process_words(words):
"""
This function takes a list of strings as input and is expected to perform a specific o... | ```python
def process_words(words):
"""
This function takes a list of strings as input and sorts the strings based on their lengths in ascending order.
Input:
- words: A list of strings
Output:
- A list of strings after sorting based on their lengths in ascending order
"""
word... | magicoder | python |
You are tasked with creating a Discord bot command that allows users with the "manage_channels" permission to change the slow mode of a specified text channel. The slow mode is the rate limit, in seconds, for how often members can send messages in the channel. The command should have a cooldown of 30 seconds per member... | ```python
import discord
from discord.ext import commands
from datetime import timedelta as t_delta
class YourBot(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.cooldown(rate=1, per=30, type=commands.BucketType.member)
@commands.has_permissions(manage_channels=True)
@commands... | magicoder | python |
You are tasked with implementing a simplified version of a network simulation system. The system consists of nodes that can communicate with each other over a network. Each node has a unique identifier and can be in one of several states. The network is simulated using a custom testing framework that provides utilities... | ```rust
fn service_config_via_client() {
let mut net = btest::SwimNet::new_rhw(2);
net.mesh_mlw_smr();
// Implement service configuration using the client
// Example:
// let client = net.nodes[0].client();
// client.configure_service(/* service configuration parameters */);
}
``` | magicoder | rust |
You are tasked with implementing a breadth-first search algorithm to find the shortest path between two nodes in a graph. The graph is represented using an adjacency list. Your goal is to write a function that takes the graph, start node, and end node as input and returns the shortest path between the start and end nod... | ```cpp
#include <iostream>
#include <queue>
#include <vector>
#include <unordered_map>
#include <algorithm>
std::vector<int> bfsShortestPath(const std::unordered_map<int, std::vector<int>>& graph, int start, int end) {
std::queue<int> q;
std::unordered_map<int, int> parent;
std::unordered_map<int, bool> vi... | magicoder | cpp |
You are given a code snippet that involves manipulating vectors in a 3D space. The code snippet initializes two constant arrays `l` and `r` of size 3 with specific values. It also initializes a variable `dir` with an initial value of 1. The function `subtract_vectors` is called with parameters `coords`, `l`, `x`, and 3... | ```cpp
#include <iostream>
#include <cmath>
void subtract_vectors(const double* v1, const double* v2, double* result, int size) {
for (int i = 0; i < size; i++) {
result[i] = v1[i] - v2[i];
}
}
double vector_norm(const double* v, int size) {
double norm = 0.0;
for (int i = 0; i < size; i++) {
... | magicoder | cpp |
You are tasked with creating a Python function to check the submission frequency of users in a coding contest platform. The function should take in the contest ID and the username as input parameters and return the time difference between the last two submissions of the given user in the specified contest. If there is ... | ```python
import asyncio
from bson import ObjectId
from datetime import datetime
async def _check_submit_frequency(self, contest_id, username):
last_sm = await self.settings["database"]["submission"].find_one({
"username": username, "contest_id": ObjectId(contest_id),
}, sort=[
("submittime", -... | magicoder | python |
You are tasked with implementing a function that generates a calendar component for a scheduling application. The function, `PrestoCalendar`, takes in several parameters to customize the appearance and functionality of the calendar. Your task is to complete the implementation of the `PrestoCalendar` function by adding ... | ```javascript
export default function PrestoCalendar({
headerComponent,
hourRange,
headerComponentStyle,
// Add your implementation here
}) {
return (
<div>
<div style={headerComponentStyle}>{headerComponent}</div>
<div>
{hourRange.map((hour) => (
<div key={hour}>{hour}</div>... | magicoder | javascript |
You are given an array `A` of integers and an integer `K`. You need to find the smallest possible difference between the maximum and minimum values of the array after adding or subtracting `K` from each element in the array. In other words, you need to find the smallest possible range of the modified array.
Write a fu... | ```python
class Solution:
def smallestRangeII(self, A: List[int], K: int) -> int:
A.sort()
ans = A[-1] - A[0]
for x, y in zip(A, A[1:]):
ans = min(ans, max(A[-1]-K, x+K) - min(A[0]+K, y-K))
return ans
```
The `smallestRangeII` function first sorts the input array `A`. It... | magicoder | python |
You are tasked with implementing a retry mechanism for failed network requests in a Swift application. The provided code snippet is part of a networking library and contains a function `retry` that is called when a network request fails. The function takes a `Request` object, a `Session` object, an `Error` object, and ... | ```swift
public func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) {
guard let response = request.task?.response as? HTTPURLResponse, response.statusCode == 401 else {
/// The request did not fail due to a 401 Unauthorized response.
... | magicoder | swift |
You are tasked with creating a script to automate the process of modifying and building a software project. The script should perform the following tasks:
1. Change the source code of two specific files within the project.
2. Build the project after the source code modifications are made.
The code snippet provided de... | ```bash
#!/bin/bash
# Define the directory name as a variable
project_dir="sysklogd-1.5.1"
# Change the working directory to the project directory
cd "$project_dir" || { echo "Error: Directory $project_dir not found"; exit 1; }
# Modify the source files using sed
sed -i '/Error loading kernel symbols/{n;n;d}' ksym_m... | magicoder | shell |
You are given the following problem:
A square spiral is formed by placing the first set of natural numbers in the center and moving in a clockwise direction. The spiral is then filled with the remaining numbers, producing a pattern of numbers arranged in a square grid. For example, the first few elements of the spira... | ```python
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def squareSpiralSideLength():
prime_count = 0
total_count = 1 # Counting the center number as 1
side_length = 1
increment = 2
while ... | magicoder | python |
You are tasked with creating a Python function that processes a list of ProfilePicture objects and returns a dictionary containing the count of profile pictures created each month. Each ProfilePicture object has attributes `id`, `profile_id`, `title`, `path`, `created_at`, and `updated_at`. The `created_at` attribute r... | ```python
from typing import List, Dict
from collections import defaultdict
import datetime
class ProfilePicture:
def __init__(self, id, profile_id, title, path, created_at, updated_at=None):
self.id = id
self.profile_id = profile_id
self.title = title
self.path = path
self.... | magicoder | python |
You are tasked with implementing a custom animation for a JazzyViewPager in an Android application. The provided code snippet is a part of the `Animate` method within a custom `JazzyViewPager` animation class. The `Animate` method is called during the animation process to update the views based on the current animation... | ```csharp
public override void Animate(JazzyViewPager viewPager, View left, View right, float positionOffset, float positionOffsetPixels)
{
if (viewPager.State != JazzyState.Idle)
{
var effectOffset = GetEffectOffset(positionOffset);
if (left != null)
{
var rotation = 30.0f *... | magicoder | csharp |
You are tasked with implementing a function to validate and sanitize user input for sending an email. The function should ensure that the input is safe and properly formatted before sending the email. You are provided with a code snippet that includes a partial implementation of the `send_mail` function, which is part ... | ```php
function send_mail($from, $name, $mail, $sub, $msg)
{
$ci =& get_instance();
// Validate email addresses
if (filter_var($from, FILTER_VALIDATE_EMAIL) === false || filter_var($mail, FILTER_VALIDATE_EMAIL) === false) {
// Handle invalid email addresses
return false;
}
// Sanit... | magicoder | php |
You are tasked with implementing a method to calculate the distance between two points in a 2D grid. The grid is represented by a set of points, and the distance between two points is defined as the Euclidean distance between their coordinates. The points are represented as instances of a `Vector` class, which contains... | ```java
import java.util.List;
class Vector {
private double x;
private double y;
public Vector(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
}
public class DistanceCalculator {
... | magicoder | java |
You are tasked with implementing a function to count the number of graphemes in a given string. Graphemes are the smallest units of a writing system that carry meaning, including letters, diacritics, and other marks. In this problem, we will consider graphemes in the context of Unicode strings.
You are given a code sn... | ```rust
use unicode_segmentation::UnicodeSegmentation;
fn count_graphemes(input: &str) -> usize {
UnicodeSegmentation::graphemes(input, true).count()
}
fn main() {
let input = "a\u{310}e\u{301}o\u{308}\u{332}";
let grapheme_count = count_graphemes(input);
println!("Number of graphemes: {}", grapheme_c... | magicoder | rust |
You are tasked with creating a Python function that visualizes a 3D vector field using matplotlib. The function should take in a set of 3D vectors and plot them as arrows in a 3D coordinate system. The function should also display the coordinate axes with labeled directions.
Write a Python function `plot_3d_vector_fie... | ```python
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
def plot_3d_vector_field(vectors):
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Extract components of vectors
x, y, z = zip(*[(0, 0, 0)] * len(vectors)) # Start all vectors at origi... | magicoder | python |
You are tasked with creating a program that can parse and extract information from a Swift file. The Swift file contains import statements and copyright information. Your program needs to extract the import statements and the copyright notice from the file and present them in a structured format.
Write a function or m... | ```swift
func extractInfo(from swiftFileContent: String) -> (importStatements: [String], copyrightNotice: String) {
var importStatements: [String] = []
var copyrightNotice: String = ""
let lines = swiftFileContent.components(separatedBy: "\n")
var isParsingImports = false
for line in lines... | magicoder | swift |
You are tasked with creating a custom annotation processor for a Java Spring Boot application. The annotation processor should scan for a custom annotation `@CustomValidation` and generate validation logic based on the annotated fields in the target class. The generated validation logic should ensure that the annotated... | ```java
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lan... | magicoder | java |
You are tasked with implementing a simplified version of a class hierarchy system in Python. The given code snippet provides a glimpse of the class creation process. Your goal is to extend this system by implementing a function that can generate a textual representation of the class hierarchy.
You are provided with th... | ```python
class ClassNode:
def __init__(self, name, parent, methods):
self.name = name
self.parent = parent
self.methods = methods
def generate_class_hierarchy(class_node):
def get_class_hierarchy(node, depth=0):
result = " " * depth + node.name + "\n"
if node.parent:
... | magicoder | python |
You are tasked with implementing a configuration manager for a Python application. The configuration manager should be able to handle reading and writing configuration files in the INI format using the configparser module. Additionally, it should support accessing configuration values as dictionary items or as attribut... | ```python
import configparser
class ConfigSubClass:
def __init__(self, config, section):
self._config = config
self._section = section
def __getattr__(self, name):
value = self._config.get(self._section, name)
if isinstance(value, str) and value.replace('.', '', 1).isdigit():
... | magicoder | python |
You are tasked with implementing a debugging macro system in C++ to facilitate conditional debugging output. The given code snippet provides a set of macros for conditional debugging output, which can be enabled by defining the `DEBUG` preprocessor directive. Your task is to create a set of C++ macros that replicate th... | ```cpp
// debug_macros.hpp
#ifndef DEBUG_MACROS_HPP
#define DEBUG_MACROS_HPP
#ifdef DEBUG
#include <iostream>
#define pdbg(...) std::cout << __func__ << "(" << __LINE__ << "): " << __VA_ARGS__ << std::endl
#define pdbg_if(Boolean, ...) if((Boolean)==true){pdbg(__VA_ARGS__);}
#define pdbg_if_exit(Boolean, ...) if((Bool... | magicoder | cpp |
You are tasked with implementing a simple logging system that supports appending log lines and starting/stopping the logging process. The provided code snippet includes a partial class definition for the logging system. Your task is to complete the class implementation by adding the necessary member variables and metho... | ```cpp
#include <mutex>
#include <condition_variable>
#include <iostream>
class Logger {
private:
bool _running;
std::mutex _mutex;
std::condition_variable _cond;
// Add any necessary member variables
public:
Logger() : _running(false) {
// Initialize any member variables
}
void a... | magicoder | cpp |
You are working on a project that involves manipulating geometric data representing curves in a 3D space. The project uses a custom data structure to store the offsets of vertices along these curves. The code snippet provided initializes an empty list of offsets and reserves space for a certain number of vertices per c... | ```cpp
void calculateOffsets(const std::vector<int>& verticesPerCurve, GA_OffsetList& offsets) {
offsets.reserve(verticesPerCurve.size()); // Reserve space for the offsets list
int cumulativeOffset = 0; // Initialize cumulative offset to 0
for (int vertices : verticesPerCurve) {
offsets.append(cum... | magicoder | cpp |
You are tasked with implementing a custom bitset data structure in Rust using the `bitset_const_macros` crate. The bitset should support setting, clearing, and checking individual bits, as well as performing bitwise operations such as AND, OR, XOR, and NOT.
Your task is to create a Rust module `CustomBitset` that prov... | ```rust
use bitset_const_macros::*;
#[derive(Debug, Clone, Copy)]
pub struct CustomBitset {
bits: BitSet,
}
impl CustomBitset {
pub fn new(size: usize) -> CustomBitset {
CustomBitset {
bits: bitset! {0; size},
}
}
pub fn set(&mut self, index: usize) {
self.bits.set... | magicoder | rust |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.