query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a custom React component called `Tag` that allows users to create and display tags with customizable text. The `Tag` component should be able to render the provided text and match a predefined snapshot.
Your task is to complete the implementation of the `Tag` component and ensure that ... | ```jsx
import React from "react";
import PropTypes from "prop-types";
const Tag = ({ text }) => {
return <div className="tag">{text}</div>;
};
Tag.propTypes = {
text: PropTypes.string.isRequired,
};
export default Tag;
```
In the solution, the `Tag` component is implemented as a simple functional component that... | magicoder | jsx |
You are tasked with creating a program to perform multilingual named entity recognition using XLM-RoBERTa models. Named entity recognition (NER) is a natural language processing task that involves identifying and classifying named entities in text into predefined categories such as names of persons, organizations, loca... | ```python
# Import necessary libraries
from transformers import XLMRobertaTokenizer, XLMRobertaForTokenClassification
import torch
# Load pre-trained XLM-RoBERTa model and tokenizer
model_name = 'xlm-roberta-base'
tokenizer = XLMRobertaTokenizer.from_pretrained(model_name)
model = XLMRobertaForTokenClassification.from... | magicoder | python |
You are tasked with implementing a genetic algorithm for evolving neural networks. In this scenario, the genetic algorithm is used to create new neural networks by combining the weights and biases of two parent networks. The crossover operation is performed on the weights and biases of the neural network layers to prod... | ```python
def crossover(weights1, weights2):
crossover_point = len(weights1) // 2 # Determine the crossover point
children = [weights1[:crossover_point] + weights2[crossover_point:],
weights2[:crossover_point] + weights1[crossover_point:]] # Perform crossover
return children
def biasCros... | magicoder | python |
You are tasked with creating a Python function that simulates a simple game of rock-paper-scissors. The function should take two arguments, representing the choices of two players, and return the result of the game based on the standard rules:
- Rock beats scissors
- Scissors beats paper
- Paper beats rock
The functi... | ```python
def rock_paper_scissors(player1, player2):
valid_inputs = {'rock', 'paper', 'scissors'}
player1 = player1.lower()
player2 = player2.lower()
if player1 not in valid_inputs or player2 not in valid_inputs:
return "Invalid input, please enter 'rock', 'paper', or 'scissors'."
if playe... | magicoder | python |
You are tasked with creating a program that organizes a list of file paths into a hierarchical structure based on their directory paths. Each file path is represented as a string, and the directory structure is delimited by forward slashes ("/"). Your program should group the file paths based on their directory structu... | ```python
def organize_files(file_paths):
file_structure = {}
for path in file_paths:
components = path.split('/')
current_level = file_structure
for component in components:
if component not in current_level:
current_level[component] = {}
curren... | magicoder | python |
You are working on a backup script that is designed to run on a Linux system. The script is responsible for configuring the AWS CLI and setting up a scheduled backup using cron jobs. Your task is to write a Bash script that automates this process.
Your script should perform the following tasks:
1. Check if the environ... | ```bash
#!/bin/bash
set -e
if [ "${S3_S3V4}" = "yes" ]; then
aws configure set default.s3.signature_version s3v4
fi
if [ "${SCHEDULE}" = "**None**" ]; then
sh backup.sh
else
echo "$SCHEDULE /bin/sh $(pwd)/backup.sh" > crontab-fragment.txt
crontab -l | cat - crontab-fragment.txt > crontab.txt && crontab cro... | magicoder | shell |
You are tasked with implementing a class for autoregressive (AR) sequence modeling in C++. The autoregressive sequence is defined by a set of lag coefficients and a bias term. The class should support updating the sequence with new values and predicting the next value based on the current sequence.
You are given a cod... | ```cpp
#include <iostream>
#include <vector>
#include <map>
using my_float = double;
class ARSeq {
private:
std::map<int, my_float> lag_coeff;
std::vector<my_float> prev_val;
my_float bias;
public:
ARSeq(std::map<int, my_float> mp, my_float bias) : lag_coeff{mp}, bias{bias} {
for (auto i = 0;... | magicoder | cpp |
You are tasked with implementing a function to calculate the integration of angular velocities using quaternions. Quaternions are a mathematical concept used to represent rotations in 3D space. The function `quaternion_integrate` takes in a list of angular velocities and a time step `dt`, and returns a list of quaterni... | ```python
# Define the quaternion integration function
def quaternion_integrate(angular_velocities, dt):
# Initialize the list to store the integrated quaternions
integrated_quaternions = []
# Initialize the quaternion as the identity quaternion
current_quaternion = [1, 0, 0, 0]
# Integrate the ang... | magicoder | python |
You are tasked with implementing a PHP trait that provides functionality for interacting with the filesystem using the Laravel framework's filesystem abstraction layer. The trait should encapsulate methods for performing common filesystem operations such as reading, writing, and deleting files.
Your task is to complet... | ```php
use Illuminate\Contracts\Filesystem\Filesystem;
use Illuminate\Filesystem\FilesystemAdapter;
use League\Flysystem\Adapter\Local;
use League\Flysystem\Filesystem as Flysystem;
trait UsesFilesystem
{
protected $filesystem;
public function __construct(Filesystem $filesystem)
{
$this->filesyste... | magicoder | php |
You are tasked with implementing a circular buffer data structure in Python. A circular buffer is a fixed-size buffer that overwrites the oldest data with new data when the buffer is full. Your task is to create a class `CircularBuffer` that supports the following operations:
1. `__init__(self, size: int)`: Initialize... | ```python
from typing import Any
class CircularBuffer:
def __init__(self, size: int):
self.size = size
self.buffer = [None] * size
self.head = 0
self.tail = 0
self.count = 0
def write(self, data: Any) -> None:
if self.is_full:
self.tail = (self.tail ... | magicoder | python |
You are tasked with implementing a game of Connect Four. The game is played on a 6x7 grid, where two players take turns dropping colored discs into the grid. The discs fall straight down, occupying the lowest available space within the chosen column. The objective of the game is to be the first to form a horizontal, ve... | ```swift
enum Player {
case player1
case player2
}
enum GameOutcome {
case nextTurn
case won(Player)
case draw
}
class ConnectFourGame {
var board: [[Player?]] = Array(repeating: Array(repeating: nil, count: 7), count: 6)
var currentPlayer: Player = .player1
func throwChip(player: Pla... | magicoder | swift |
You are tasked with creating a Python function that generates an HTML report for a specific employee based on their ID. The function should retrieve data from a MySQL database and use a Jinja2 template to format the report. Your task is to complete the implementation of the `print_report` function by writing the necess... | ```python
import webbrowser
import MySQLdb
from jinja2 import Environment, FileSystemLoader
def print_report(id):
# Connect to the MySQL database
db = MySQLdb.connect(host="localhost", user="username", passwd="password", db="employees_db")
# Create a Jinja2 environment and load the template
env = Envi... | magicoder | python |
You are tasked with implementing a password validation function for a user authentication system. The function should validate the user's password based on a set of predefined rules and return a boolean value indicating whether the password is valid or not.
You are given the following rules for password validation:
1.... | ```python
import re
def validate_password(password: str) -> bool:
# Rule 1: The password must be at least 8 characters long.
if len(password) < 8:
return False
# Rule 2: The password must contain at least one uppercase letter, one lowercase letter, and one digit.
if not any(char.isupper() for ... | magicoder | python |
You are tasked with creating a Python function that parses a given text file to extract the license information and the module name. The license information is denoted by the comment block containing the license text, and the module name is the first non-comment line after the license block. Your function should return... | ```python
import re
def extract_license_info(file_path: str) -> dict:
with open(file_path, 'r') as file:
content = file.read()
license_match = re.search(r'(?s)(?<=^#.*?\n).*?(?=\n\n|\"\"\"|\'\'\')', content)
module_name_match = re.search(r'(?<=\n\n|\"\"\"|\'\'\'\n).*', content)
if license_mat... | magicoder | python |
You are tasked with implementing a simplified task management system using Rust. The system should allow users to create, retrieve, update, and delete tasks. To achieve this, you need to define a `TaskManager` struct and implement several methods for task management.
You are provided with a code snippet that defines a... | ```rust
use metrohash::MetroHashMap;
type TaskId = u64;
struct Task {
id: TaskId,
description: String,
}
struct TaskManager {
tasks: MetroHashMap<TaskId, Task>,
}
impl TaskManager {
fn new() -> Self {
TaskManager {
tasks: MetroHashMap::new(),
}
}
fn create_task(&... | magicoder | rust |
You are tasked with implementing a configuration manager for network settings in a Python application. The configuration manager should provide default values for network settings and allow users to override these defaults. The network settings include the number of retry times for network requests, proxy enablement, p... | ```python
class NetworkConfigManager:
def __init__(self):
self.retry_times = NETWORK_RETRY_TIMES_DEFAULT
self.proxy_enable = NETWORK_PROXY_ENABLE_DEFAULT
self.proxy_type = NETWORK_PROXY_TYPE_DEFAULT
self.proxy_host = NETWORK_PROXY_HOST_DEFAULT
self.proxy_port = NETWORK_PROXY_... | magicoder | python |
You are tasked with creating a program that counts the occurrences of specific characters in a given string. Your program should take a string and a list of characters as input and return the count of each character in the string. The program should ignore case sensitivity, meaning 'A' and 'a' should be considered the ... | ```python
from collections import defaultdict
from typing import List, Dict
def count_characters(string: str, characters: List[str]) -> Dict[str, int]:
# Convert the string to lowercase to ignore case sensitivity
string = string.lower()
# Initialize a dictionary to store the count of characters
ch... | magicoder | python |
You are tasked with implementing a Python class that represents a 2D grid. The grid will be used to store and manipulate data in a two-dimensional space. Your task is to create a class called `Grid` with the following functionalities:
- Initialize the grid with a specified size or a default size of 50x50.
- Set a value... | ```python
class Grid:
def __init__(self, grid_size=50):
self.grid = [[None for _ in range(grid_size)] for _ in range(grid_size)]
def set_value(self, x, y, value):
if 0 <= x < len(self.grid) and 0 <= y < len(self.grid[0]):
self.grid[x][y] = value
else:
print("Inva... | magicoder | python |
You are tasked with implementing a function to parse and process POST request data in a Python web application. The function should handle cases where the request data is a dictionary with empty string values.
Write a Python function `parse_post_data(request_data: dict) -> dict` that takes a dictionary `request_data`... | ```python
def parse_post_data(request_data: dict) -> dict:
return {key: value for key, value in request_data.items() if value != ''}
```
The `parse_post_data` function iterates through the key-value pairs in the input `request_data` dictionary and constructs a new dictionary with non-empty string values. The dicti... | magicoder | python |
You are tasked with implementing a Python function that calculates the coefficients for a family of embedded Runge-Kutta formulae based on the research paper "A family of embedded Runge-Kutta formulae" by <NAME> and <NAME> (1980). The coefficients are used for solving ordinary differential equations numerically. The fa... | ```python
import numpy as np
def calculate_runge_kutta_coefficients(order):
# Initialize the Butcher tableau coefficients
A = np.zeros((order, order))
b = np.zeros(order)
b_star = np.zeros(order)
c = np.zeros(order)
# Define the coefficients based on the order of the Runge-Kutta method
if ... | magicoder | python |
You are tasked with implementing a custom data loader class for the CIFAR-10 dataset using PyTorch. The CIFAR-10 dataset consists of 60,000 32x32 color images in 10 classes, with 6,000 images per class. The dataset is divided into 50,000 training images and 10,000 testing images. Your custom data loader class should in... | ```python
import torch
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
class CifarDataloader(DataLoader):
def __init__(self, root, batch_size, shuffle=True, num_workers=1):
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normal... | magicoder | python |
You are tasked with implementing a function that checks whether a given string is a valid palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward, disregarding spaces, punctuation, and capitalization. For example, "A man, a plan, a canal, Panama" is a... | ```java
public boolean isPalindrome(String s) {
s = s.replaceAll("[^a-zA-Z0-9]", "").toLowerCase(); // Remove non-alphanumeric characters and convert to lowercase
int left = 0, right = s.length() - 1;
while (left < right) {
if (s.charAt(left) != s.charAt(right)) {
return false; // Not a... | magicoder | java |
You are working on a 2D texture mapping system for a game engine. The code snippet provided is a part of the texture mapping process. The `textureMapper` object contains a mapping of texture IDs to texture maps. Each texture map contains information about the front face of the texture, including UV coordinates for mapp... | ```java
public Rect calculateUVCoordinates(int textureId, TextureMapper textureMapper) {
TextureMapper.TextureMap textureMap = textureMapper.map[(byte)textureId];
TextureMapper.TextureMap.Face face = textureMap.front;
float left = 1.0f / 128 * face.bl.x * 16;
float top = 1 - (1.0f / 128 * face.bl.y... | magicoder | java |
You are tasked with implementing a function that takes in a string representing a mathematical expression and evaluates it. The expression will consist of integers, the four basic arithmetic operators (+, -, *, /), and parentheses. The expression will be properly formatted and will not contain any spaces.
Your task is... | ```python
def evaluateExpression(expression):
def apply_operator(operands, operator):
b, a = operands.pop(), operands.pop()
if operator == '+':
operands.append(a + b)
elif operator == '-':
operands.append(a - b)
elif operator == '*':
operands.appen... | magicoder | python |
You are tasked with implementing a function that converts a given color in hexadecimal format to a UIColor object in Swift. The function should take into account the red, green, blue, and alpha components of the color and return the corresponding UIColor object.
The function signature is as follows:
```swift
func hexT... | ```swift
func hexToUIColor(hex: String, alpha: CGFloat) -> UIColor {
var formattedHex = hex
if hex.hasPrefix("#") {
formattedHex.remove(at: formattedHex.startIndex)
}
let scanner = Scanner(string: formattedHex)
var hexNumber: UInt64 = 0
if scanner.scanHexInt64(&hexNumber) {
... | magicoder | swift |
You are tasked with implementing a simple task scheduler in Rust. The scheduler should allow users to schedule tasks to run at specific times and execute them in a concurrent manner. Your task is to implement the `Scheduler` struct and its associated methods to achieve this functionality.
The `Scheduler` struct should... | ```rust
use std::sync::{Arc, Mutex};
use std::thread;
pub struct Scheduler {
tasks: Arc<Mutex<Vec<Box<dyn Fn() + Send>>>>,
}
impl Scheduler {
pub fn new() -> Self {
Scheduler {
tasks: Arc::new(Mutex::new(Vec::new())),
}
}
pub fn schedule_task(&self, task: Box<dyn Fn() + Se... | magicoder | rust |
You are given a list of integers representing the daily stock prices of a company. Your task is to write a function to calculate the maximum profit that can be obtained by buying and selling the stock at most once. If it is not possible to make any profit, the function should return 0.
Write a function `maxProfit(pric... | ```python
def maxProfit(prices: List[int]) -> int:
if not prices:
return 0
max_profit = 0
min_price = prices[0]
for price in prices:
if price < min_price:
min_price = price
else:
max_profit = max(max_profit, price - min_price)
return max... | magicoder | python |
You are tasked with implementing a rendering system for a particle simulation. The simulation consists of different types of particles that need to be rendered in a specific order to achieve the desired visual effect. The rendering order is determined by the "pass" number associated with each particle type.
Each parti... | To solve this problem, you can create a rendering system that maintains a list of particles to be rendered and sorts them based on their pass numbers. Additionally, for particles with the same pass number, a secondary ordering based on their specific rendering order can be applied.
Here's a Python solution that demons... | magicoder | python |
You are tasked with creating a Python decorator that logs the execution time of a function and prints it to the console. Your decorator should also have an option to include the function's docstring in the log output.
Your task is to implement the `log_execution_time` decorator with the following specifications:
- Th... | ```python
import time
from functools import wraps
def log_execution_time(include_docstring=False):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
execution... | magicoder | python |
You are tasked with implementing a Python function that takes in a list of geographical coordinates and their corresponding values, and returns a smoothed interpolation of the values using the Inverse Distance Weighting (IDW) method. The IDW method calculates the value at any location by averaging the values of the sur... | ```python
def interpolate_values(coordinates, values, target_coords, power):
interpolated_values = []
for target_coord in target_coords:
numerator = 0
denominator = 0
for i in range(len(coordinates)):
distance = np.sqrt((target_coord[0] - coordinates[i][0])**2 + (target_coord... | magicoder | python |
You are tasked with implementing a custom asynchronous command execution framework in C#. The framework should allow the execution of commands in a non-blocking manner, enabling the system to continue processing other tasks while the commands are being executed. Your task is to create a class that encapsulates the func... | ```csharp
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace CoreCommand.Command.Function
{
public class AsyncCommandExecutor
{
private readonly Dictionary<Guid, Task> _commandTasks = new Dictionary<Guid, Task>();
private readonly Dic... | magicoder | csharp |
You are tasked with implementing a custom animation transition in an iOS app. The given code snippet is a part of an animation transition implementation using the UIKit framework in Swift. The `fromView` is a reference to the view being transitioned from, and the code sets its alpha value to 1.0. The `transitionContext... | ```swift
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let fromView = transitionContext.view(forKey: .from) else {
return
}
let containerView = transitionContext.containerView
// Assuming toView is the view being transitioned to
guard let ... | magicoder | swift |
You are tasked with analyzing the performance of a Python program using the `pstats` module. The `pstats` module provides a convenient interface for retrieving and analyzing statistics from Python's `cProfile` module, which is used for profiling Python programs. Your goal is to write a program that reads a profile data... | ```python
import pstats
def analyze_profile_data(profile_file):
stats = pstats.Stats(profile_file)
stats.strip_dirs()
stats.sort_stats('cumulative')
stats.calc_callees()
total_time = stats.total_tt
function_stats = {}
for func, (cc, nc, tt, ct, callers) in stats.stats.items():
... | magicoder | python |
You are tasked with implementing a dependency graph data structure in JavaScript. The graph should support adding dependencies between nodes and detecting circular dependencies.
You need to implement the `DependencyGraph` class with the following methods:
1. `addNode(id)`: Adds a node with the given id to the graph.
2... | ```javascript
class DependencyGraph {
constructor() {
this.nodes = new Map();
}
addNode(id) {
if (this.nodes.has(id)) {
throw new Error(`Node with id ${id} already exists in the graph`);
}
this.nodes.set(id, { dependsOn: new Set(), dependedOnBy: new Set() });
}
addDependency(subjectId,... | magicoder | javascript |
You are tasked with creating a Python program to parse a given text file and extract specific information from it. The text file contains a list of contacts in the following format:
```
Name: John Doe
Email: johndoe@example.com
Phone: (123)4567890
Name: Jane Smith
Email: janesmith@example.com
Phone: (987)6543210
```
... | ```python
import re
class Contact:
def __init__(self, name, email, phone):
self.name = name
self.email = email
self.phone = phone
def parse_contacts(file_path):
contacts = []
try:
with open(file_path, 'r') as file:
data = file.read()
contact_info = r... | magicoder | python |
You are tasked with simulating a text-based adventure game where the player navigates through a cave system, encountering various hazards and creatures. The game is driven by a series of events and actions, and the player's objective is to survive and reach the end of the cave.
The game is represented by a series of i... | ```cpp
// Define the Room and Cave classes to represent the game world
class Room {
// Define properties and methods for the Room class
};
class Cave {
// Define properties and methods for the Cave class
};
// Define the Player class to represent the player in the game
class Player {
public:
bool MoveTo(Room* r... | magicoder | cpp |
You are tasked with implementing a function that generates a unique class identifier (ClassId) based on the level and primitive type provided. The ClassId is constructed by concatenating a prefix derived from the primitive type and a sequence of array brackets based on the level.
You are given the following Rust code ... | ```rust
pub fn gcid_from_level_array_of_primitives(
&mut self,
level: NonZeroUsize,
prim: PrimitiveType,
) -> ClassId {
let prefix = prim.as_desc_prefix();
let class_path = std::iter::repeat(b"[" as &[u8]).take(level.get()).collect::<Vec<_>>();
let class_id = [&prefix, &class_path.concat()].conc... | magicoder | rust |
You are tasked with implementing a C++ template structure that handles the end directive for a parser. The given code snippet provides a partial implementation of the `end_director_base` template structure. Your task is to complete the implementation by defining the `attribute` structure within the `end_director_base` ... | ```cpp
template <typename Parser>
struct end_director_base<Parser, mpl::true_>
{
typedef mpl::true_ stores_iterator;
template <typename Component, typename Context, typename Iterator>
struct attribute
{
// Define the nested type 'type' representing the attribute type associated with the parser
... | magicoder | cpp |
You are working on a data management system that involves renaming dataset files and dumping data into fixtures. Your task is to implement a Python function that renames dataset files and then dumps the data into fixtures using the Django framework.
You are given a partial code snippet from the data management system:... | ```python
import os
import sys
from django.core.management import call_command
from datetime import datetime
class DatasetManager:
def __enter__(self):
self.old_stdout = sys.stdout
sys.stdout = open(os.devnull, 'w')
return self
def __exit__(self, exc_type, exc_value, traceback):
... | magicoder | python |
You are tasked with creating a program that processes a list of layout data for different GUI components. Each layout data entry consists of a group name, layout type, and parent component. The layout type can be one of the following: `SWT.SHADOW_NONE`, `SWT.SHADOW_IN`, or `SWT.SHADOW_OUT`. Your goal is to write a func... | ```python
def organize_layout_data(layout_data):
organized_data = {}
for entry in layout_data:
group_name, layout_type, parent_component = entry
if parent_component not in organized_data:
organized_data[parent_component] = {layout_type: [group_name]}
else:
if layo... | magicoder | python |
You are tasked with implementing a custom control system for a virtual machine using C#. The virtual machine has a set of control instructions that need to be executed based on the control signals received. Your task is to implement the control system using the provided code snippet as a starting point.
The `Jsm` clas... | ```csharp
public static partial class Jsm
{
#region Classes
public static partial class Control
{
public static void HandleControlSignal(string signal)
{
switch (signal)
{
case "Start":
StartExecution();
break;
... | magicoder | csharp |
You are tasked with creating a Python class that simulates a simple banking system. The class should have methods for depositing funds, withdrawing funds, and checking the current balance. Additionally, the class should log all transactions using a logger instance.
Your task is to implement the `BankAccount` class wit... | ```python
import sims4
logger = sims4.log.Logger('BankAccount', default_owner='msundaram')
class BankAccount:
def __init__(self):
self.balance = 0
def deposit(self, amount):
self.balance += amount
logger.info('Deposited {} units. Current balance: {}'.format(amount, self.balance))
... | magicoder | python |
You are tasked with creating a Python class that manages a library of API views for a web application. The class should handle the registration and retrieval of different types of API views, such as base views, generic views, and mixins.
Your task is to implement the `APIViewManager` class with the following requireme... | ```python
class APIViewManager:
def __init__(self):
self.views = {
'base': [],
'generic': [],
'mixins': []
}
def register_view(self, view, view_type):
if view_type in self.views:
self.views[view_type].append(view)
else:
... | magicoder | python |
You are tasked with implementing a function that performs a specific mathematical operation on a list of values and returns the result. Additionally, you need to write tests to ensure that the function behaves as expected.
You are given the following code snippet as a reference:
```python
test_values = get_standard_v... | ```python
import numpy as np
def f(values):
# Assuming the mathematical operation is to take the absolute values of the input list
result = [abs(val) for val in values]
return result
def test_f():
# Test case using the provided code snippet
test_values = get_standard_values()
result = f([test_... | magicoder | python |
You are tasked with creating a program to manage a robot's movements and Easter egg actions using Python's tkinter library. The program should include functionality for setting the target position of the robot's body and triggering various Easter egg actions. Additionally, the program should display the robot's statist... | ```python
import tkinter as tk
from tkinter import ttk
def reset_body_position():
# Implement the logic to reset the robot's body position
pass
def egg_wave():
# Implement the logic for the wave Easter egg action
pass
def egg_shake():
# Implement the logic for the shake Easter egg action
pass... | magicoder | python |
You are tasked with implementing a function to calculate the refund contributions for a group of individuals. The function `get_refund_contribs` takes no parameters and is a method of a class. The class maintains a list of individual contributions made towards a refund. The contributions are represented as a list of po... | ```python
class RefundCalculator:
def __init__(self, contributions):
self.contributions = contributions
def get_refund_contribs(self):
total_contributions = sum(self.contributions)
num_contributors = len(self.contributions)
if total_contributions < 100:
retu... | magicoder | python |
You are tasked with creating a Python class that utilizes the provided code snippet to interact with the Sherlock and LCBuilder libraries. Your class should be able to perform the following functionalities:
1. Initialize an object with the necessary input parameters.
2. Retrieve information about a celestial object usi... | ```python
from timeit import default_timer
from sherlockpipe.sherlock import Sherlock
from lcbuilder.objectinfo.InputObjectInfo import InputObjectInfo
from lcbuilder.objectinfo.MissionFfiCoordsObjectInfo import MissionFfiCoordsObjectInfo
from lcbuilder.objectinfo.MissionFfiIdObjectInfo import MissionFfiIdObjectInfo
fro... | magicoder | python |
You are tasked with writing a Python function to validate a JSON payload received from an API. The payload contains information about streaming data and must adhere to specific criteria. Your function should assert the presence of certain keys and their corresponding values within the JSON payload. Additionally, it sho... | ```python
class ValidationException(Exception):
pass
def validate_stream_payload(payload):
try:
assert "streams" in payload and isinstance(payload["streams"], list) and len(payload["streams"]) > 0, "Invalid 'streams' key or value"
stream = payload["streams"][0].get("stream", {})
assert ... | magicoder | python |
You are tasked with implementing a user authentication system for a web application. The system should allow users to register, login, and obtain an access token for subsequent authenticated requests. You are provided with a code snippet from a test suite for the authentication system, written in Python using the Djang... | ```python
def get_access_token_and_user_id(REGISTER_URL, LOGIN_URL, user_data, client):
registration_response = client.post(REGISTER_URL, user_data, format="json")
login_response = client.post(LOGIN_URL, user_data, format="json")
access_token = "Bearer " + eval(login_response.data['tokens'])['access']
u... | magicoder | python |
You are working on a project management system that involves storing and managing various project-related data in a relational database. The given code snippet represents a part of the database schema using SQLAlchemy, a popular Python ORM (Object-Relational Mapping) library.
Your task is to create a Python class that... | ```python
from sqlalchemy import Column, Integer, String, Boolean, DateTime, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class Result(Base):
__table... | magicoder | python |
You are tasked with implementing a function that processes a list of clusters and returns a modified version of the list based on certain criteria. Each cluster is represented as a DOM element with the class structure `.body .clusters .cluster.selector.option`. Your task is to filter the clusters based on specific cond... | ```javascript
function filterClusters(clusters) {
// Remove clusters with class '.hidden'
const filteredClusters = clusters.filter(cluster => !cluster.classList.contains('hidden'));
// Sort the remaining clusters based on data-id in ascending order
filteredClusters.sort((a, b) => {
const idA = parseInt(a.d... | magicoder | javascript |
You are tasked with creating a Python function that utilizes the Shapely and Geopandas libraries to determine the country of a given latitude and longitude tuple offline. The function should take in the latitude and longitude as input parameters and return the corresponding country name.
Create a function called `get_... | ```python
import geopandas as gpd
from shapely.geometry import Point
def get_country_from_coordinates(latitude, longitude):
# Load the world map shapefile using Geopandas
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
# Create a Point object using the provided latitude and longitude
... | magicoder | python |
You are tasked with creating a PHP class that implements a simple file management system. The class should provide methods for adding, removing, and retrieving nodes from a file system tree structure.
Your task is to implement the `FileSystem` class with the following requirements:
- The class should have a constructo... | ```php
class FileSystem
{
private NodeNameResolver $nodeNameResolver;
private BetterNodeFinder $betterNodeFinder;
private NodeRepository $nodeRepository;
public function __construct(
NodeNameResolver $nodeNameResolver,
BetterNodeFinder $betterNodeFinder,
NodeRepository $nodeRepo... | magicoder | php |
You are tasked with implementing a function to encode a given input stream to a base64-encoded output stream. Base64 encoding is a method of encoding binary data into ASCII string format. The provided code snippet contains a test function `test_encode_stream_to_stream` that tests the encoding functionality. Your task i... | ```cpp
#include <iostream>
#include <sstream>
namespace base64 {
using size_type = std::size_t;
const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
size_type encode(std::istream &input, std::ostream &output) {
const int chunk_size = 3;
... | magicoder | cpp |
You are given a code snippet representing a set of assignments to an array `JB` using indices calculated from arithmetic operations and array elements. Your task is to write a function that takes in the arrays `JB`, `w`, `p`, `x`, and `dwdx` and returns the resulting array `JB` after applying the given assignments.
Th... | ```python
from typing import List
def applyAssignments(JB: List[float], w: List[float], p: List[float], x: List[float], dwdx: List[float]) -> List[float]:
for i in range(len(w)):
JB[2 + i*10] = -w[i]
for i in range(len(p)):
JB[2 + (i+1)*10] = -p[0]*p[1]
JB[3 + 1*10] = 1.0
JB[3 + 2*10] =... | magicoder | python |
You are given a scenario where a vector `v` is obtained by applying the hyperbolic tangent function (`tanh`) to a set of input values. Subsequently, for each timestamp, the vector of size A from `v` is reduced with a vector `u`. Your task is to implement a function that performs this reduction operation for a given set... | ```python
import numpy as np
def reduce_vector(vectors, reduction_vector):
return vectors - reduction_vector
# Test the function with the given example
vectors = np.array([[1, 2, 3], [4, 5, 6]])
reduction_vector = np.array([0.5, 0.5, 0.5])
result = reduce_vector(vectors, reduction_vector)
print(result) # Output:... | magicoder | python |
You are tasked with creating a program that can efficiently determine the dependencies between different software packages. Each package can have a list of dependencies, and these dependencies can have their own dependencies, forming a hierarchical structure. Your task is to implement a function that takes in a list of... | ```swift
func sortPackages(_ packages: [[String: Any]]) -> [String] {
var dependencyMap: [String: Set<String>] = [:]
var packageSet: Set<String> = Set()
for package in packages {
if let name = package["name"] as? String, let dependencies = package["dependencies"] as? [String] {
dependen... | magicoder | swift |
You are given a 2D array representing a maze. The maze consists of cells, some of which are blocked and others are open. The objective is to find the shortest path from the top-left corner to the bottom-right corner of the maze, moving only through open cells. You can move in four directions: up, down, left, and right.... | ```cpp
#include <vector>
#include <queue>
using namespace std;
int shortestPath(vector<vector<int>>& maze) {
int m = maze.size();
int n = maze[0].size();
vector<vector<int>> distance(m, vector<int>(n, -1));
queue<pair<int, int>> q;
q.push({0, 0});
distance[0][0] = 0;
vector<pair<int, int>>... | magicoder | cpp |
You are tasked with implementing a LikeFilter class in Java that can evaluate whether a given string matches a specified pattern. The LikeFilter class should take an IdentityExtractor and a pattern string as input and return true if the input string matches the pattern, and false otherwise.
The pattern string follows ... | ```java
import com.tangosol.util.extractor.IdentityExtractor;
public class LikeFilter {
private final IdentityExtractor extractor;
private final String pattern;
private LikeFilter(IdentityExtractor extractor, String pattern) {
this.extractor = extractor;
this.pattern = pattern;
}
... | magicoder | java |
You are tasked with implementing a custom error type and associated functionality in Rust. Your goal is to create a custom error type that can represent different error cases and implement the necessary traits to work with the Rust error handling system.
Your custom error type should be named `CustomError` and should ... | ```rust
use std::fmt::{Display, Formatter, Result};
enum CustomError {
ParseError,
IOError,
Custom(String),
}
impl From<String> for CustomError {
fn from(s: String) -> Self {
CustomError::Custom(s)
}
}
impl Display for CustomError {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
... | magicoder | rust |
You are tasked with implementing a function to determine whether a given integer is a prime number. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Your task is to create a Python function `es_primo` that takes an integer as input and returns `True` if the number... | ```python
def es_primo(n):
if n <= 1:
return False # Numbers less than or equal to 1 are not prime
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False # If n is divisible by any number in this range, it's not prime
return True # If no divisors are found, n is pri... | magicoder | python |
You are tasked with implementing a custom tokenizer for a natural language processing (NLP) model. The tokenizer should adhere to specific configuration parameters and tokenization rules. The provided code snippet outlines some of the key parameters and settings for the tokenizer.
Your task is to create a Python class... | ```python
class CustomTokenizer:
def __init__(self, max_seq_length, cls_token_at_end, cls_token, cls_token_segment_id, sep_token, sep_token_extra, pad_on_left, pad_token):
self.max_seq_length = max_seq_length
self.cls_token_at_end = cls_token_at_end
self.cls_token = cls_token
self.cl... | magicoder | python |
You are tasked with implementing a simplified version of a tray management system for a warehouse. The system should support adding and removing trays, as well as checking the availability of a specific tray.
You are given a partial implementation of the `TrayManager` class in Kotlin. The `TrayManager` class has the f... | ```kotlin
class TrayManager {
val trays = mutableSetOf<String>()
fun addTray(trayId: String) {
trays.add(trayId)
}
fun removeTray(trayId: String): Boolean {
val removed = trays.remove(trayId)
return removed
}
fun isTrayAvailable(trayId: String): Boolean {
retur... | magicoder | kotlin |
You are tasked with implementing a file compression and decompression utility using the Brotli compression algorithm. Brotli is a generic-purpose lossless compression algorithm that compresses data using a combination of a modern variant of the LZ77 algorithm, Huffman coding, and 2nd order context modeling.
Your task ... | ```rust
use std::io::{Read, Write, Result};
use brotli::{CompressorReader, Decompressor, Error};
const BUFFER_SIZE: usize = 4096;
const QUALITY: u32 = 11;
const WINDOWS_SIZE: u32 = 22;
pub(crate) fn compress_brotli<T: AsRef<[u8]>>(input: T) -> Result<Vec<u8>> {
let mut buf = Vec::new();
let mut compressor = C... | magicoder | rust |
You are working on a security module for a software application that involves encrypting and decrypting data using the Windows Cryptography API. The code snippet provided is a part of the encryption and decryption functions using the `CryptEncrypt` and `CryptDecrypt` functions from the `advapi32` library in Windows.
Y... | ```python
from ctypes import c_int, create_string_buffer, byref, windll
def assert_success(success):
if not success:
raise RuntimeError("CryptEncrypt failed")
def CryptEncrypt(hkey, plain_data):
# determine output buffer length
bdatalen_test = c_int(len(plain_data))
success = windll.advapi32.C... | magicoder | python |
You are tasked with creating a web application for a blogging platform using Flask and WTForms. Your goal is to implement a form for users to subscribe to the platform and a form for creating new blog posts. The provided code snippet includes the initial form definitions for the subscriber and blog post creation.
Your... | ```python
from flask import Flask, render_template, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, TextAreaField
from wtforms.validators import Required, DataRequired, Length
from flask_migrate import Migrate
app = Flask(__name__)... | magicoder | python |
You are tasked with creating a JUnit test suite for a simple Java class that represents a basic calculator. The calculator class has methods for addition, subtraction, multiplication, and division. Your goal is to write test cases to ensure that each method in the calculator class works as expected.
The calculator cla... | ```java
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
public class CalculatorTest {
private Calculator calculator;
@Before
public void setUp() {
calculator = new Calculator();
}
@Test
public void testAdd() {
... | magicoder | java |
You are tasked with creating a Python program that reads data from a file, manipulates it, and then performs an assertion test using the `unittest` module. Your program should read the contents of a file, modify the data, and then compare the modified data with an expected output using the `assertEqual` method. Finally... | ```python
import unittest
import os
class FileManipulationTest(unittest.TestCase):
def test_file_manipulation(self):
file_name_2 = "example_file.txt" # Replace with the actual file name
output_line = "Sample output line"
with open(file_name_2, 'r') as file:
output = file.read(... | magicoder | python |
You are tasked with implementing a card management system using Java interfaces and classes. The provided code snippet includes a `CardFactory` class with two methods: `openSession()` and `initMethod()`. Your task is to extend this code to create a complete card management system.
Your system should include the follow... | ```java
// Interface for card service
public interface ICardService {
void addCard(Card card);
void removeCard(String cardNumber);
Card getCardDetails(String cardNumber);
}
// Implementation of the ICardService interface
public class CardServiceImpl implements ICardService {
private Map<String, Card> c... | magicoder | java |
You are tasked with creating a script to launch a Java application using the command line. The script should set the classpath, specify system properties, and launch the application using the `sun.tools.jconsole.JConsole` class. Your task is to write a shell script that accomplishes this.
Your script should set the cl... | ```bash
#!/bin/bash
# Set the classpath
CLASSPATH="$(dirname $0)/../../../../jmx-adapter/target/jolokia-jmx-adapter-${VERSION}-standalone.jar:$(dirname $0)/../../../target/jolokia-kubernetes-1.6.3-SNAPSHOT-standalone.jar:$HOME/.m2/repository/io/kubernetes/client-java/5.0.0/client-java-5.0.0.jar:$JAVA_HOME/lib/jconsole... | magicoder | shell |
You are tasked with creating a script that processes a list of parameters and performs a specific action on each parameter. Your script should take the following form:
```bash
#!/bin/bash
# Iterate through the parameters and perform an action
for param in "$@"
do
echo "${param}"
done
```
Your task is to extend t... | ```bash
#!/bin/bash
# Iterate through the parameters and print each parameter along with its character count
for param in "$@"
do
echo "${param} ${#param}"
done
```
When executed with the parameters "apple" and "banana", the modified script will produce the desired output:
```
apple 5
banana 6
``` | magicoder | shell |
You are tasked with creating a Python class that processes data from a master file and extracts specific data based on keys provided in a separate file. Your task is to implement the `DataExtractor` class, which should have the following functionality:
- Initialize with the path to the master file and a list of tuples ... | ```python
# Sample usage of the DataExtractor class
if __name__ == "__main__":
# Sample data for initialization
master_path = "path_to_master_file.csv"
dml_line_tup = [("key1", "sheet1"), ("key2", "sheet2"), ("key3", "sheet3")]
# Initialize the DataExtractor object
data_extractor = DataExtractor(ma... | magicoder | python |
You are tasked with creating a Python class that can store data to an Excel file and load data from an Excel file. Your class should provide methods for adding data, saving the data to an Excel file, and loading data from an existing Excel file. The class should also support specifying the sheet name for storing and lo... | ```python
import pandas as pd
from typing import Any, Dict, List, Optional, Union
class ExcelHandler:
def __init__(self, file_path: str):
self.file_path = file_path
self.data_to_save = {}
def add_data(self, data: Dict[str, List[Any]], sheet_name: Optional[str] = None) -> None:
if sheet... | magicoder | python |
You are tasked with implementing a program to manage employee information using a custom data structure. The `EmployeeInfo` structure holds an employee's data, including their name, employee ID, and salary. Your task is to create a program that allows users to perform various operations on this employee information, su... | ```cpp
#include <iostream>
#include <string>
#include <unordered_map>
struct EmployeeInfo {
std::string name;
int employeeID;
double salary;
};
class EmployeeManager {
private:
std::unordered_map<int, EmployeeInfo> employeeMap;
public:
void addEmployee(const std::string& name, int employeeID, dou... | magicoder | cpp |
You are tasked with creating a Python function that parses a list of strings representing metadata for software packages. Each string contains information about the operating system, programming language, and topic associated with a particular package. Your goal is to extract this information and organize it into a str... | ```python
def parse_metadata(metadata_list):
parsed_metadata = {
'Operating System': [],
'Programming Language': [],
'Topic': []
}
for metadata in metadata_list:
if metadata.startswith('Operating System'):
os = metadata.split('::')[1].strip()
parsed_m... | magicoder | python |
You are tasked with implementing a function to handle the asynchronous login process for a gaming platform. The provided code snippet is part of a larger system that interacts with a game server to obtain login tokens for players. Your task is to complete the implementation of the `handle_login` function, which takes i... | ```rust
use std::result::Result;
// Assume these are defined elsewhere in the codebase
const LOCATOR_HOSTNAME: &str = "example.com";
const LOCATOR_PORT: u16 = 8080;
// Assume these are defined elsewhere in the codebase
struct LoginTokensRequest {
// Assume implementation details
}
// Assume these are defined els... | magicoder | rust |
You are tasked with implementing a settings module for a web application. The module should allow the application to read various configuration settings from environment variables or use default values if the environment variables are not set. Your task is to write a function `setting` that takes a setting name and a d... | ```python
import os
def setting(name, default):
return os.environ.get(name, default)
NOTICE_ENABLED = setting('NOTICE_ENABLED', False)
NOTICE_POSTING_NEW = int(setting('NOTICE_POSTING_NEW', 1))
NOTICE_POSTING_EXPIRES = int(setting('NOTICE_POSTING_EXPIRES', 1))
FROM_EMAIL = setting('FROM_EMAIL', '<EMAIL>')
ADS_PER... | magicoder | python |
You are working on a deep learning project and have encountered a bug in the code related to loading model states and handling input data. Your task is to identify the issue and fix it to ensure the smooth execution of the program.
Given the provided code snippet, you notice that there are potential issues with loadin... | ```python
import torch
import torch.nn as nn
import torch.autograd as autograd
# Assume model1 and model2 are defined and initialized before the try-except block
try:
model1.load_state_dict(torch.load('model1.pth')) # Assuming the model state is saved with the extension .pth
model2.load_state_dict(torch.load... | magicoder | python |
You are tasked with implementing a function that calculates the sum of all even Fibonacci numbers up to a given limit. The Fibonacci sequence is defined as follows: F(0) = 0, F(1) = 1, and F(n) = F(n-1) + F(n-2) for n > 1. For example, the first few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on.
Your ta... | ```rust
fn sum_even_fibonacci(limit: u64) -> u64 {
let (mut a, mut b) = (0, 1);
let mut sum = 0;
while b <= limit {
if b % 2 == 0 {
sum += b;
}
let next = a + b;
a = b;
b = next;
}
sum
}
fn main() {
let limit = 10;
println!("Sum of even ... | magicoder | rust |
You are tasked with creating a Python function that automates the process of uploading a file to a web application using Selenium. The function should take in the file path and the web application URL as input and should use Selenium to interact with the web page, locate the file upload input, and submit the file for u... | ```python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def upload_file_to_web_app(file_path: str, web_app_url: str) -> bool:
try:
# Open a web browser using... | magicoder | python |
You are tasked with implementing a simple program management system in C++. The system should allow the creation, deletion, and execution of programs. Each program has a name and a set of instructions to be executed. You are provided with a partial code snippet that declares a pointer to a `Program` object.
Your task ... | ```cpp
#include <iostream>
#include <string>
#include <vector>
class Program {
private:
std::string name;
std::vector<std::string> instructions;
public:
Program(const std::string& programName) : name(programName) {}
void addInstruction(const std::string& instruction) {
instructions.push_back(... | magicoder | cpp |
You are tasked with implementing a text processing algorithm that involves applying a specific style to a range of text in a document. The algorithm should take into account the existing style of the text and the range to be styled. The code snippet provided is a method call that applies a text substyle to a given rang... | ```java
public class TextSubstyle {
private Style style;
private Range range;
public TextSubstyle(Style style, Range range) {
this.style = style;
this.range = range;
}
public void applySubstyle(TextDocument document) {
Range existingRange = document.getRangeStyle(range.getS... | magicoder | java |
You are tasked with implementing a Python class that simulates a simplified version of a configuration object. The class should be able to convert a given protocol buffer (proto) configuration into an object, allowing for the overwriting of repeated fields.
Your task is to complete the implementation of the `ConfigObj... | The `ConfigObj` class is implemented with an `__init__` method to initialize the configuration object and a `convert_proto_to_obj` method to convert a given proto config into an object, allowing for the overwriting of repeated fields. The `convert_proto_to_obj` method iterates through all the fields of the proto config... | magicoder | python |
You are tasked with implementing a function to calculate the sediment flux at nodes in a river network simulation. The sediment flux is a crucial parameter in understanding the dynamics of sediment transport in river systems. In this problem, you are given a code snippet that includes a test for the sediment flux calcu... | ```python
import numpy as np
from numpy.testing import assert_almost_equal
def calculate_sediment_flux(elevation_data):
# Assuming elevation_data is a 1D array representing the elevation at each node
num_nodes = len(elevation_data)
sediment_flux = np.zeros(num_nodes)
for i in range(1, num_nodes):
... | magicoder | python |
You are tasked with implementing a Python class that can handle the decoding of WebP images. The given code snippet is a part of a class method that opens and decodes a WebP image file. Your task is to complete the implementation of the class by adding the missing methods and attributes to support the functionality of ... | ```python
from io import BytesIO
import _webp # Assuming the _webp module is available for decoding WebP images
class WebPImage:
def __init__(self, file_path):
with open(file_path, 'rb') as file:
self.fp = BytesIO(file.read())
self.mode = None
self.size = None
... | magicoder | python |
You are tasked with implementing a function to manage a currency exchange system. The function should handle the exchange of a specified amount of currency and provide the ability to stop the exchange action if it has not already been completed.
You are provided with a code snippet that includes a partial implementati... | ```rust
fn exchange(amount: u32) -> Result<(), String> {
// Simulate a successful exchange for demonstration purposes
if amount > 0 {
Ok(())
} else {
Err("Invalid amount for exchange".to_string())
}
}
fn stop() -> Result<(), String> {
// Simulate that the exchange had already been c... | magicoder | rust |
You are tasked with creating a function that processes a given Swift code file and extracts the titles of all the view controllers that inherit from a specific superclass. The superclass name and the file content will be provided as input to your function.
Write a function `extractViewControllerTitles` that takes in t... | ```swift
func extractViewControllerTitles(fileContent: String, superclassName: String) -> [String] {
var viewControllerTitles: [String] = []
let lines = fileContent.components(separatedBy: .newlines)
var currentViewController: String?
for line in lines {
if line.contains("class") {
... | magicoder | swift |
You are given a list of strings, each representing a word. Your task is to implement a function that returns the longest common prefix among all the strings. If there is no common prefix, the function should return an empty string.
Create a function `longestCommonPrefix(words: List[str]) -> str` where:
- `words`: a li... | ```python
def longestCommonPrefix(words):
if not words:
return ""
prefix = words[0]
for word in words[1:]:
while word.find(prefix) != 0:
prefix = prefix[:-1]
if not prefix:
return ""
return prefix
``` | magicoder | python |
You are tasked with creating a custom exception class and implementing error handling for a command-line utility. The utility runs external processes and needs to handle non-zero exit codes by raising a custom exception. Your task is to write a Python class that encapsulates this functionality.
Your class should be na... | ```python
import subprocess
class ANTSRuntimeError(Exception):
def __init__(self, command, arguments, output):
self.command = command
self.arguments = arguments
self.output = output
super().__init__(f"Command '{command} {arguments}' failed with output: {output}")
class ProcessRunne... | magicoder | python |
You are tasked with developing a Python program to process data from a database and perform specific operations on the retrieved information. The program should collect group information and process events for each group. The code snippet provided gives a glimpse of the program's functionality, but it requires completi... | ```python
import logging
# Sample data
groups = [{'id': 1, 'name': 'Group A'}, {'id': 2, 'name': 'Group B'}, {'id': 3, 'name': 'Group C'}]
done_groups = [2, 3] # Example list of processed group IDs
# Filter out groups that have already been processed
filtered_groups = [row for row in groups if row['id'] not in done_... | magicoder | python |
You are tasked with creating a Python function that handles database connections and disconnections based on different data sources. Your task is to implement a function that connects to a MySQL database via SSH tunneling or reads data from a file, and ensures that the database connection is properly closed in both cas... | ```python
import MySQLdb
import SQL
def handle_data_source(data_source: str, tunnel: str, db: str) -> None:
if data_source == "MYSQL":
try:
# Connect to MySQL database via SSH tunnel
tunnel = SQL.connectMySQLViaSSH(tunnel=tunnel, db=db)
# Perform operations on the databa... | magicoder | python |
You are tasked with implementing a Swift data structure to represent file permissions. The file permissions are represented by a set of options, each with a corresponding textual description. Your goal is to create a `FilePermission` structure that can store and manipulate these permissions.
Your task is to implement ... | ```swift
// Define the FilePermission structure
struct FilePermission: CustomStringConvertible, CustomDebugStringConvertible {
// Define the permission options and their corresponding textual descriptions
enum Permission {
case read, write, execute, otherWrite, otherExecute, setUserID, setGroupID, saveT... | magicoder | swift |
You are tasked with implementing a function to calculate the total number of occurrences of a specific word in a given C++ source code file. The function should take the file path and the target word as input and return the count of occurrences of the word in the file. The source code file may contain comments and the ... | ```cpp
#include <fstream>
#include <string>
#include <regex>
int countWordOccurrences(const std::string& filePath, const std::string& targetWord) {
std::ifstream file(filePath);
if (!file.is_open()) {
return -1; // File open error
}
int count = 0;
std::string line;
bool inMultiLineCom... | magicoder | cpp |
You are tasked with implementing a search and replace functionality for anchor names in a font editing software. The font editing software provides a macro window where users can execute predefined scripts to automate tasks. The given code snippet is a part of a Python script that is intended to perform a search and re... | ```python
def SearchAndReplaceInAnchorNames():
try:
# Get all glyphs in the font
all_glyphs = Glyphs.font.glyphs
# Iterate through each glyph
for glyph in all_glyphs:
# Iterate through each anchor in the glyph
for anchor in glyph.anchors:
# Pe... | magicoder | python |
You are tasked with implementing a text scrolling and clearing functionality for a text-based user interface. The provided code snippet is part of a larger program that manages a window displaying text. The `clear` function is responsible for clearing the main display area within the window, while the `scroll` function... | ```rust
fn clear(&mut self) {
for i in (self.border_y + 1)..(self.height - self.border_y - 1) {
for j in (self.border_x + 1)..(self.width - self.border_x - 1) {
self.window.get_cell(j as isize, i as isize).set_ch(' ');
}
}
}
fn scroll(&mut self) {
self.cursor_pos.1 -= 1;
sel... | magicoder | rust |
You are tasked with creating a program that simulates a simple command-line parser. The parser should be able to handle a set of predefined commands and their associated arguments. Your task is to implement the logic for parsing the command-line arguments and executing the corresponding commands.
You are given a code ... | ```csharp
using System;
using System.Collections.Generic;
class CommandLineParser
{
private Dictionary<string, Action<int, int>> commands;
public CommandLineParser()
{
commands = new Dictionary<string, Action<int, int>>();
}
public void AddCommand(string command, Action<int, int> action)
... | magicoder | csharp |
You are tasked with creating a Python script that processes a given Markdown file to extract specific information related to a software package. The script should read the content of the Markdown file, search for the relevant details, and then output the extracted information in a structured format.
Your script should... | ```python
import re
def extract_package_info(file_path):
package_info = {}
with open(file_path, encoding='utf-8') as f:
content = f.read()
# Extracting package details using regular expressions
pattern = r'''
name\s*=\s*["'](?P<name>[\w-]+)["'],
version\s*=\s*["'](?P<version>[\... | magicoder | python |
You are tasked with implementing a thread-safe singleton class in C#. The class should ensure that only one instance is created and provide a global point of access to that instance.
Your task is to complete the implementation of the `KeyValueCollection` class as a thread-safe singleton. The `KeyValueCollection` class... | ```csharp
using System;
public class KeyValueCollection
{
private static readonly object lockObject = new object();
private static KeyValueCollection singleton = null;
private KeyValueCollection()
{
// Private constructor to prevent instantiation outside the class
}
public static KeyV... | magicoder | csharp |
You are tasked with implementing a function that calculates the logarithm of an unsigned 8-bit integer. The function should take an unsigned 8-bit integer as input and return the logarithm of that number. You should handle the case where the input is zero and return a special value for that case.
Your task is to imple... | ```c
#include <stdint.h>
#include <math.h>
uint8_t log_uint8(uint8_t x) {
if (x == 0) {
return -1; // Special value for logarithm of 0
} else {
return (uint8_t)log2(x); // Calculate logarithm base 2
}
}
```
The `log_uint8` function first checks if the input `x` is zero. If it is, the functi... | magicoder | c |
You are tasked with implementing a class that represents a data buffer with a flushing mechanism. The class should have an `__init__` method that takes an interval (in seconds) and a flush function as parameters. The buffer should accumulate data and automatically flush it by calling the provided flush function at regu... | ```python
import threading
import time
class Buffer:
def __init__(self, interval, flush_fn):
self.buffer = []
self.interval = interval
self.flush_fn = flush_fn
self.auto_flush_thread = None
self.auto_flush_flag = threading.Event()
def append(self, data):
self.bu... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.