query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a function that manages user activities for a sports training application. The function `addOrDeleteComparableUser` takes two parameters: `userId`, a string representing the user's ID, and `addUser`, a boolean indicating whether to add or delete the user from the list of comparable user... | ```typescript
import { filter, tap } from 'rxjs/operators';
import { Store } from '@ngrx/store';
import { TrainingActions } from 'path-to-training-actions';
class UserActivityManager {
constructor(private store: Store) {}
activitiesBySportTypesDayRangeUsersData$; // Assume this observable is properly initialized
... | magicoder | typescript |
You are tasked with implementing a protein site mapper that takes in a set of conditions and returns a mapped site based on those conditions. The code snippet provided is a part of a larger protein mapping system and includes the definition of a default site mapper class and a method for mapping protein sites based on ... | ```python
class SiteMapper:
def __init__(self, residue, position):
self.residue = residue
self.position = position
def map_protein_site(residue, position, do_methionine_offset, do_orthology_mapping, do_isoform_mapping):
if do_methionine_offset:
position += 1 # Apply methionine offset
... | magicoder | python |
You are tasked with creating a class that represents a student (aluno) in a university system. The student class should have attributes for the student's name, country, and the professor who is responsible for mentoring the student. Additionally, you need to implement a method to retrieve the professor's information ba... | ```javascript
class NotFoundException extends Error {
constructor(message) {
super(message);
this.name = 'NotFoundException';
}
}
class Student {
constructor(name, country, professor) {
this.name = name;
this.country = country;
this.professor = professor;
}
async getProfessorInfo(usernam... | magicoder | javascript |
You are tasked with creating a command-line utility that extracts and prints specific information about the machine's hardware. The utility should accept various command-line options to specify which hardware information to display. The code snippet provided is a part of the utility's implementation, using the Rust pro... | ```rust
use clap::{App, Arg};
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
let matches = App::new("Hardware Info")
.about("Prints machine hardware information")
.arg(Arg::with_name("kernelname")
.short("k")
.long("kernelname")
.help("Print the... | magicoder | rust |
You are tasked with creating a SwiftUI app that integrates with ArcGIS to display a map with custom layers. Your goal is to implement a feature that allows users to toggle the visibility of different map layers using SwiftUI controls. You will need to create a SwiftUI view that contains a map view with multiple layers ... | ```swift
import SwiftUI
import ArcGIS
struct MapLayerToggleView: View {
let mapView: AGSMapView
let layerNames: [String]
var body: some View {
VStack {
ForEach(layerNames, id: \.self) { layerName in
Toggle(layerName, isOn: self.binding(for: layerName))
}... | magicoder | swift |
You are tasked with implementing a custom widget for an image editing application. The widget, named `PixlrWidget`, will be used in the `HomePageView` of the application. The `HomePageView` is a part of the application's UI and is created using UiBinder. The `HomePageView` class has a nested interface `Binder` which ex... | ```java
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiConstructor;
import com.google.gwt.uibinder.client.UiTemplate;
public class PixlrWi... | magicoder | java |
You are tasked with creating a program that simulates a simplified version of a CPU scheduler. The scheduler will be responsible for managing a set of processes and allocating CPU time to each process based on their priority. The processes will be represented by a set of integers, where each integer represents the prio... | ```python
def simulateScheduler(processes, timeSlice):
executionOrder = []
queue = list(processes)
while queue:
currentProcess = queue.pop(0)
executionOrder.append(currentProcess)
if len(queue) > 0:
queue.extend(queue[:timeSlice])
del queue[:timeSlice]
ret... | magicoder | python |
You are tasked with implementing a binary search algorithm to find a specific element within a sorted array. The binary search algorithm works by repeatedly dividing in half the portion of the array that could contain the item, until the possible locations are narrowed down to just one. The algorithm compares the middl... | ```c
int binarySearch(int data[], int size, int key) {
int min = 0;
int max = size - 1;
while (min <= max) {
int mid = min + (max - min) / 2; // calculate the midpoint for roughly equal partition
if (data[mid] == key) {
return mid; // key found at index mid
... | magicoder | c |
You are tasked with creating a Python class that represents a configuration for a project. The configuration should include a boolean flag for verbosity and a set of paths for the project. Your task is to define the class `AppConfig` with the following specifications:
- The `AppConfig` class should be a dataclass with... | ```python
from dataclasses import dataclass
from typing import List
from pathlib import Path
@dataclass(frozen=True)
class PathConfig:
project_root: Path
source_code: Path
tests: Path
documentation: Path
@dataclass(frozen=True)
class AppConfig:
verbose: bool
paths: PathConfig
# Example usa... | magicoder | python |
You are tasked with creating a Rust function that processes HTTP requests using the Hyper and http crates. Your function will need to handle generic types and traits, and ensure that the input and output types are correctly managed.
Your function signature should resemble the following:
```rust
fn process_request<R,... | ```rust
use hyper::service::{Service, make_service_fn};
use hyper::{Body, Request, Response, Server};
use http::Error;
async fn process_request<R, B>(request: R) -> Result<http::Response<B>, Error>
where
R: Service<http::Request<HttpBody>, Response = http::Response<B>, Error = Never> + Clone,
R::Error: Into<Er... | magicoder | rust |
You are tasked with creating a program that can analyze the structure of HTML code and identify the number of nested elements within a given HTML snippet. For the purpose of this problem, an element is defined as any tag enclosed within angle brackets, such as `<div>`, `<section>`, or `<main>`. The nesting level of an ... | ```python
def countNestedElements(html):
stack = []
count = 0
i = 0
while i < len(html):
if html[i] == '<':
if html[i+1] != '/':
stack.append(html[i:i+html[i:].index('>')+1])
else:
stack.pop()
count = max(count, len(stack))
... | magicoder | python |
You are tasked with implementing a custom neural network layer in PyTorch for natural language processing (NLP) tasks. The layer will incorporate word embeddings, dropout, and LSTM (Long Short-Term Memory) units. Your goal is to create a class that initializes these components and applies them to input sequences of wor... | ```python
import torch
import torch.nn as nn
class CustomNLPModule(nn.Module):
def __init__(self, embedding_matrix, dropout, bidirectional=False):
super(CustomNLPModule, self).__init__()
# Word embeddings
self.word_embeddings = nn.Embedding.from_pretrained(torch.tensor(embedding_matrix, dt... | magicoder | python |
You are working on a project to analyze brain activity data collected from multiple participants. The data is organized into a 3D array where the dimensions represent the participant, time window, and features. Your task is to create a function that processes this data to generate a prediction matrix for each time wind... | ```python
import numpy as np
def generate_prediction_matrix(data, win_size):
n_subjs, n_features, n_TR = data.shape
n_seg = n_TR - win_size
train_data = np.zeros((n_features * win_size, n_seg))
for ppt_counter in range(n_subjs):
for window_counter in range(win_size):
train_data[
... | magicoder | python |
You are tasked with creating a custom email notification system using Laravel's Mailable and Queue features. Your goal is to implement a system that sends out personalized email notifications to users based on specific events. To achieve this, you need to create a Mailable class that extends the Illuminate\Mail\Mailabl... | ```php
// CustomNotification.php
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class CustomNotification extends Mailable implements Shoul... | magicoder | php |
You are working on a project that involves reading data from a file, processing it, and then resizing it. The code snippet provided is a part of this project. The snippet shows the following operations:
1. Reading data from a file using the `fromfile` method of an array `a`.
2. Closing the file after reading.
3. Conver... | ```python
import numpy as np
def process_data(file_path, length, remove):
try:
with open(file_path, 'rb') as f:
a = np.fromfile(f, dtype=np.int32)
a = a[:-remove] # Remove elements from the end
a.resize((length,)) # Resize the array
return a
except File... | magicoder | python |
You are tasked with implementing a utility function to validate the input data in a C# application. The `Utility` class contains a method `HasValue` that checks whether the input object has a non-null and non-empty string representation. Your task is to extend this utility class by adding a new method that validates wh... | ```csharp
using System;
using System.Text.RegularExpressions;
namespace JRequest.Net
{
internal class Utility
{
internal static bool HasValue(object item)
{
return (item != null && !string.IsNullOrWhiteSpace(item.ToString()));
}
internal static bool IsValidEmail(str... | magicoder | csharp |
You are tasked with implementing a feature benchmarking system for various computer vision algorithms. The system will evaluate the performance of different feature extraction algorithms on a specific dataset. The code snippet provided initializes the benchmarking system and imports different feature extraction modules... | ```python
import features.cv_fast
import features.cv_akaze
import features.cv_kaze
import features.superpoint
import dset.W1BS_dataset
import bench.W1BSBench
if __name__ == "__main__":
# Define baseline benchmark
w1bs_bench = bench.W1BSBench.W1BSBench()
# Define feature extraction algorithm
chosen_fea... | magicoder | python |
You are given a Python code snippet that reads data from a file and processes it. Your task is to create a function that simulates the `design_size` function used in the code snippet. The `design_size` function takes a file name as input and returns the number of nodes and edges in the design represented by the file. T... | ```python
def design_size(design_file):
with open(design_file, 'r') as f:
edges = 0
nodes = set()
for line in f:
node1, node2 = map(int, line.strip().split())
nodes.add(node1)
nodes.add(node2)
edges += 1
return len(nodes), edges
def pr... | magicoder | python |
You are given a list of integers representing the scores of a game. The game has a rule that a player's score is the sum of the scores of the last two turns. However, if the last two turns have the same score, the player's score is doubled. Your task is to write a function that calculates the player's total score based... | ```python
from typing import List
def calculate_total_score(scores: List[int]) -> int:
total_score = 0
prev_score = 0
prev_prev_score = 0
for score in scores:
if score == prev_score and score == prev_prev_score:
total_score += score * 2
else:
total_score += score... | magicoder | python |
You are given a list of coordinates representing the vertices of a polygon in 2D space. Each coordinate is represented as a pair of latitude and longitude values. Your task is to write a function to calculate the area of the polygon defined by these coordinates.
Write a function `calculatePolygonArea(coordinates)` tha... | ```python
import math
def haversine(theta):
return math.sin(theta / 2) ** 2
def calculateDistance(lat1, lon1, lat2, lon2):
r = 6371 # Radius of the Earth in kilometers
phi1 = math.radians(lat1)
phi2 = math.radians(lat2)
delta_phi = math.radians(lat2 - lat1)
delta_lambda = math.radians(lon2 - ... | magicoder | python |
You are tasked with implementing a game AI for a real-time strategy (RTS) game. The game features various types of weapons, and your AI needs to control the behavior of a specific weapon object. The given code snippet is a part of the AI logic for controlling a weapon object. The snippet includes a series of commands t... | ```python
class WeaponAI:
def __init__(self):
self.Firing = False
self.Charged = False
self.EnemyID = None
self.EffectID = None
def process_commands(self, Commands, WeaponObj):
Commands.Set_Player_Type(WeaponObj, 0) # Set the player type for the weapon object
Co... | magicoder | python |
You are tasked with writing a Python script to parse a given JSON configuration and extract specific information related to file copies for different operating systems and architectures. The JSON configuration contains a list of file copies for different build configurations, and your script needs to extract the destin... | ```python
from typing import List, Tuple
def extract_file_copies(json_config: dict, os_condition: str, arch_condition: str) -> List[Tuple[str, List[str]]]:
matching_copies = []
for copy in json_config.get("copies", []):
conditions = copy.get("conditions", "")
if eval(conditions, {"OS": os_condi... | magicoder | python |
You are tasked with creating a Python function that processes a list of data extracted from a web page and extracts specific information related to vessel coordinates and position received time. The function should take the list of data as input and return a dictionary containing the vessel name, coordinates, and the p... | ```python
from datetime import datetime
def process_vessel_data(data):
result = {}
for item in data:
if item["key"] == "Coordinates":
result["coordinates"] = item["value"]
elif item["key"] == "Vessel Name":
result["vessel_name"] = item["value"]
elif item["key"] =... | magicoder | python |
You are tasked with implementing a unique queue data structure in Python. The unique queue should only allow unique elements to be enqueued, and it should maintain the order of insertion. To achieve this, you need to complete the `UniqueQueue` class by implementing the `enqueue` and `__init__` methods.
The `UniqueQueu... | ```python
import queue
class FakeGenericMeta(type):
pass
class SimpleQueue(queue.SimpleQueue, metaclass=FakeGenericMeta):
pass
class UniqueQueue(SimpleQueue):
def __init__(self):
super().__init__()
def enqueue(self, element):
if element not in self.queue:
self.put(element... | magicoder | python |
You are given an array of non-negative integers representing the maximum number of steps you can take from each position in the array. Write a function `minJumps` to find the minimum number of jumps needed to reach the last index of the array, starting from the first index. If it is not possible to reach the last index... | ```swift
func minJumps(_ nums: [Int]) -> Int {
guard nums.count > 0 else {
return -1 // Invalid length
}
guard nums.filter({ $0 > 0 }).count > 0 else {
return -1 // All inputs must be positive
}
var jumps = 0
var currentEnd = 0
var farthest = 0
for i in 0..... | magicoder | swift |
You are tasked with creating a Python program that reads data from an input file, processes it, and writes the result to an output file. The input file contains a series of integers, each represented as 4 bytes in little-endian format. Your program should read these integers, calculate their sum, and write the result a... | ```python
import sys
import struct
if len(sys.argv) != 3:
print(f'Usage: {sys.argv[0]} <in_file> <out_file>')
sys.exit(1)
try:
with open(sys.argv[1], 'rb') as in_file:
data = in_file.read()
num_integers = len(data) // 4 # Each integer is 4 bytes
integers = struct.unpack('<' + 'i' ... | magicoder | python |
You are tasked with simulating a simple load testing scenario for a web application using a bash script. The script should continuously send a specified number of HTTP requests to a given URL and monitor the number of running pods in a Kubernetes cluster.
The provided code snippet is a simplified version of a bash scr... | ```bash
#!/bin/bash
# Input parameters
TOTAL_REQ=10 # Replace with the desired total number of requests
URL="http://example.com" # Replace with the actual URL
while true; do
for ((i=1; i<=$TOTAL_REQ; i++)); do
curl $URL > /dev/null 2>&1 &
done
# Retrieve the count of running pods for a specific applicati... | magicoder | shell |
You are tasked with creating a script to automate the training process for a deep learning model using FlowNet2 for optical flow estimation. The provided code snippet is a part of a larger script that sets up the necessary environment for running the FlowNet2 training process. Your task is to complete the script by inc... | ```bash
#!/bin/bash
# Set the necessary environment variables
export FLOWNET2_CHECKPOINTS_DIR=/path/to/flownet2/checkpoints
export dataset_dir=/path/to/dataset/frames
export COMMAND="python train.py"
# Create and run the Docker container for FlowNet2 training
docker run -v $FLOWNET2_CHECKPOINTS_DIR:/data/flownet2-che... | magicoder | shell |
You are tasked with creating a script to automate the setup of a Yocto Project environment for building embedded Linux systems. The Yocto Project is an open-source collaboration project that provides templates, tools, and methods to help create custom Linux-based systems for embedded products. Your script should clone ... | ```bash
#!/bin/bash
# Check if the poky directory exists, if not, clone the repository
if [ ! -d ./poky ]; then
echo "--------- Clone poky --------- "
git clone https://github.com/sirkt0131/poky.git -b gatesgarth
fi
# Change directory to poky
cd poky
# Check if the meta-intel directory exists within poky, if... | magicoder | shell |
You are tasked with implementing a function that simulates a memory allocation strategy using the Best Fit algorithm. The Best Fit algorithm allocates the smallest free partition that is large enough to accommodate the incoming process. You are given a list of free memory blocks and a list of processes with their respe... | ```python
class MemoryBlock:
def __init__(self, start_address, size):
self.start_address = start_address
self.size = size
class Process:
def __init__(self, name, size):
self.name = name
self.size = size
def best_fit_allocation(free_blocks, processes):
allocation_status = []... | magicoder | python |
You are working on a 3D geometry visualization library that supports various geometric shapes and transformations. Your task is to implement a function that takes a geometric object and its properties as input and generates the necessary visualization code. The code snippet provided is a part of the visualization funct... | ```python
import visual # Assuming the visualization library is imported as 'visual'
import geometry as geo # Assuming the geometry library is imported as 'geo'
def generate_visualization_code(shape, properties):
if isinstance(shape, geo.FinitePlane):
colour = properties.get('color', visual.color.blue)
... | magicoder | python |
You are tasked with creating a Python package for shortening URLs. Your package should include a module named `link` that provides functionality for shortening and expanding URLs using a third-party service. The package should be able to interact with the specified third-party service to perform URL shortening and expa... | ```python
# link/__init__.py
import requests
class LinkShortener:
def __init__(self, api_url):
self.api_url = api_url
def shorten_url(self, original_url):
try:
response = requests.post(self.api_url, json={"url": original_url})
if response.status_code == 200:
... | magicoder | python |
You are tasked with implementing a neural network architecture for image processing using PyTorch. The given code snippet is a part of the network architecture definition and includes a sequence of operations applied to the input data. Each operation is represented by a PyTorch module, such as convolutional layers, act... | ```python
import torch
import torch.nn as nn
class ImageProcessingNetwork(nn.Module):
def __init__(self, nfg):
super(ImageProcessingNetwork, self).__init__()
self.nfg = nfg
self.conv1 = nn.Conv2d(3, nfg, kernel_size=4, stride=2, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(nfg)
... | magicoder | python |
You are tasked with implementing a custom progress tracking system in Swift. The system should consist of a `ProgressSource` class and a `Progress` class. The `ProgressSource` class will be responsible for updating the progress value, while the `Progress` class will be responsible for tracking and reporting the progres... | ```swift
import XCTest
// ProgressSource class
class ProgressSource {
var value: Double = 0.0
func updateProgress(to value: Double) {
self.value = value
}
}
// Progress class
class Progress {
var source: ProgressSource
var currentValue: Double {
return source.value
}
... | magicoder | swift |
You are working as a system administrator for a company that uses a Linux server to host various services. Your task is to automate the setup and configuration of the server using a shell script. The script should perform the following tasks:
1. Compile and install any necessary software using the `make` command.
2. U... | ```bash
#!/bin/bash
# Compile and install necessary software
make
make install
# Update PHP configuration for timezone
echo 'date.timezone = "Europe/Berlin"' | sudo tee -a /etc/php/7.3/apache2/php.ini > /dev/null
# Restart Apache web server
sudo systemctl enable apache2.service
sudo systemctl restart apache2.service... | magicoder | shell |
You are tasked with creating a layout for a mobile application's bottom banner view. The code snippet provided contains constraints for positioning two labels, `timeRemainingLabel` and `distanceRemainingLabel`, within the `bottomBannerView`. The constraints are written in Swift using the Auto Layout system.
Your task ... | ```swift
func calculateLabelPositions(constraints: [NSLayoutConstraint]) -> [String: (xOffset: CGFloat, yOffset: CGFloat)] {
var labelPositions: [String: (xOffset: CGFloat, yOffset: CGFloat)] = [:]
for constraint in constraints {
if let firstItem = constraint.firstItem as? UILabel, let secondItem =... | magicoder | swift |
You are tasked with creating a Python function that can determine whether a specified build directory can be set using an environment variable. The function should take two parameters: `changedir` and `tmpdir`. The `changedir` parameter represents the current working directory, and the `tmpdir` parameter represents a t... | ```python
import os
import shutil
def test_build_dir_can_be_specified_by_environment_variable(changedir, tmpdir):
conf_dir = str(tmpdir.mkdir('test_env_variables')) # Create 'test_env_variables' directory within the temporary directory
build_dir = str(tmpdir.mkdir('test_build_dir')) # Create 'test_build_dir'... | magicoder | python |
You are tasked with implementing a robustness testing algorithm for a machine learning model. The model is to be tested using a given test dataset. The model and test dataset are represented by the functions `model()` and `testdata()` respectively. The `test()` function is provided to perform the robustness testing.
T... | ```python
def test(model, testdata):
"""
Perform robustness testing on the given model using the provided test dataset.
Args:
model (function): A function representing the machine learning model to be tested.
testdata (function): A function representing the test dataset.
Returns:
None
... | magicoder | python |
You are tasked with implementing a custom extension for the UIImageView class in Swift. The extension should add a method that asynchronously loads an image from a given URL and sets it on the image view. Additionally, the method should handle caching the downloaded images to improve performance.
Your task is to compl... | ```swift
import UIKit
let imageCache = NSCache<NSString, UIImage>()
extension UIImageView {
func loadImageFromURL(_ url: URL, placeholder: UIImage? = nil) {
self.image = placeholder
if let cachedImage = imageCache.object(forKey: url.absoluteString as NSString) {
self.image = c... | magicoder | swift |
You are tasked with creating a Python program that utilizes the `pyuv` library to handle asynchronous I/O operations. The program should implement a simple file watcher that monitors a specified directory for any changes and logs the details of the changes to the console.
Your task is to complete the `FileWatcher` cla... | ```python
import os
import pyuv
class FileWatcher:
def __init__(self, directory):
self.directory = directory
self.loop = pyuv.Loop.default_loop()
self.fs_event = pyuv.fs.FSEvent(self.loop)
self.fs_event.start(directory, 0, self._on_file_change)
def start_watching(self):
... | magicoder | python |
You are tasked with implementing a Python class that simulates a social media state. The class, `_SocialState`, should support the addition and retrieval of social media providers. Additionally, it should raise an `AttributeError` when attempting to access an attribute that does not exist within the state.
Your task i... | ```python
class _SocialState:
def __init__(self, providers):
self.providers = providers
def add_provider(self, provider_name, provider_data):
self.providers[provider_name] = provider_data
def get_provider(self, provider_name):
return self.providers.get(provider_name)
def __get... | magicoder | python |
You are tasked with simulating a simple unreliable data packet transmission system using Python. The code snippet provided is a simplified version of a packet transmission system using the `ioloop` module for asynchronous event handling. The `packet_send` function is responsible for sending packets, and the `packet_los... | ```python
import time
import random
def packet_send(counter):
print(f"Sending packet {counter}")
# Simulate packet loss with a 30% probability
if random.random() < 0.3:
print(f"Packet {counter} lost")
ioloop.IOLoop.instance().call_later(5, packet_lost)
else:
# Simulate successfu... | magicoder | python |
You are tasked with analyzing and visualizing the instantaneous frequency (IF) and phase of a signal using Python's matplotlib and numpy libraries. The given code snippet is part of a larger program that processes and plots the IF and phase information for different cycles of a signal. Your task is to complete the impl... | ```python
import numpy as np
import matplotlib.pyplot as plt
def calculate_and_visualize_phase_if(ax2, ax3, F, cycle_inds, ii, lw, cols):
ax2.set_ylabel('Instantaneous Frequency (Hz)')
decorate(ax2, bottom_row=(ii in [6, 7]), mode='phasex')
if ii == 0 or ii == 1:
ax2.set_title('Phase-aligned IF')
... | magicoder | python |
You are tasked with implementing a resolution manager for a client-server application. The resolution manager is responsible for building a resolver map, which contains a list of resolvers used to handle different types of data. Each resolver is a class that implements a specific resolution strategy. The resolvers are ... | ```python
class ResolutionManager:
def __init__(self, easy_client=None):
self.easy_client = easy_client
self.resolver_map = []
def build_resolver_map(self):
"""Builds the resolver map using the build_resolver_map function"""
self.resolver_map = build_resolver_map(self.easy_clien... | magicoder | python |
You are tasked with implementing a parallel job scheduling algorithm for a distributed computing system. The system consists of multiple worker nodes and a master node. The master node is responsible for distributing jobs to the worker nodes and collecting the results.
The provided code snippet is a part of the master... | To complete the job distribution algorithm, you can use a round-robin scheduling approach to distribute the jobs from the `evalPool` to the worker nodes. The following solution provides a comprehensive implementation of the job distribution logic based on the given code snippet and the context.
```cpp
#include <iostre... | magicoder | cpp |
You are tasked with implementing a function to calculate the minimum auto-completion velocity for a rotation animation based on the given parameters. The function should consider various conditions and adjust the distance to complete accordingly.
You are given the following variables and their meanings:
- `previousTim... | ```swift
func calculateMinimumAutoCompletionVelocity(previousTimerIncrement: Double, initialVelocity: Double, angleStride: Double, currentAngle: Double, timerHasBeenCancelled: Bool, isRotationAngleCompensated: Bool, configuration: Configuration, containerWidth: Double) -> Double {
let previousTimerDirectionMatchesW... | magicoder | swift |
You are tasked with creating a C# class that represents a simple banking account. The account should support depositing and withdrawing funds, and should also provide a method to calculate the interest accrued over a certain period of time. Additionally, the account should raise an event whenever a deposit or withdrawa... | ```csharp
using System;
public class FundsDepositedEventArgs : EventArgs
{
public decimal Amount { get; }
public FundsDepositedEventArgs(decimal amount)
{
Amount = amount;
}
}
public class FundsWithdrawnEventArgs : EventArgs
{
public decimal Amount { get; }
public FundsWithdrawnEvent... | magicoder | csharp |
You are tasked with creating a custom data structure to store and manage a collection of `DtoEntry` objects. The `DtoEntry` class represents an entry with a string property called `Entry`. Your task is to implement a custom data structure called `DtoEntryCollection` that allows adding, removing, and retrieving `DtoEntr... | ```csharp
using System;
using System.Collections.Generic;
using System.Linq;
namespace ui.Models.Dtos
{
public class DtoEntry
{
public string Entry { get; set; }
}
public class DtoEntryCollection
{
private List<DtoEntry> entries;
public DtoEntryCollection()
{
... | magicoder | csharp |
You are tasked with implementing a reinforcement learning algorithm for a simple game. The game has a reward system, and the player's actions may trigger a reset of the game state. The reinforcement learning algorithm will receive the current state of the game and must return two values: the reward gained from the curr... | ```python
from typing import Tuple
class GameState:
def __init__(self, player_position: Tuple[int, int], enemy_position: Tuple[int, int], health: int):
self.player_position = player_position
self.enemy_position = enemy_position
self.health = health
def reinforcement_learning(current_state:... | magicoder | python |
You are tasked with implementing a program that simulates a simple encryption algorithm. The algorithm involves transforming a given string using a set of rules and operations. The input string will consist of lowercase letters, uppercase letters, and digits. The encryption algorithm follows these steps:
1. Reverse th... | ```python
def encrypt_string(input_string: str) -> str:
# Step 1: Reverse the input string
reversed_string = input_string[::-1]
# Step 2: Replace specific characters with their corresponding replacements
replacements = {'a': '4', 'e': '3', 'i': '1', 'o': '0', 'u': '9'}
modified_string = ''.join... | magicoder | python |
You are tasked with implementing a class for managing spice inventory. The class should support adding, removing, and checking the availability of various spices. Additionally, the class should provide a method to compare two instances of the inventory and ensure that they contain the same spices in the same quantities... | ```python
class SpiceInventory:
def __init__(self):
self.inventory = {}
def add_spice(self, spice, quantity):
if spice in self.inventory:
self.inventory[spice] += quantity
else:
self.inventory[spice] = quantity
def remove_spice(self, spice, quantity):
... | magicoder | python |
You are tasked with implementing a neural network training algorithm using Python and NumPy. The given code snippet is part of the backpropagation process in a neural network with three layers: input layer, hidden layer, and output layer. The code snippet calculates the gradients of the cost function with respect to th... | ```python
import numpy
class NeuralNetwork:
def __init__(self, input_layer_size, hidden_layer_size, output_layer_size, delays):
self.input_layer_size = input_layer_size
self.hidden_layer_size = hidden_layer_size
self.output_layer_size = output_layer_size
self.delays = delays
... | magicoder | python |
You are working as a DevOps engineer for a company that uses Kubernetes for managing its containerized applications. As part of your responsibilities, you need to automate the process of accessing the Kubernetes dashboard using a script. The Kubernetes dashboard is accessible via a specific URL, and it requires a token... | ```python
import requests
from bs4 import BeautifulSoup
url = "http://localhost:8001/api/v1/namespaces/kubernetes-dashboard/services/https:kubernetes-dashboard:/proxy/#/overview?namespace=default"
# Make a GET request to the URL
response = requests.get(url)
# Check if the request was successful
if response.status_co... | magicoder | python |
You are tasked with implementing a simple graphical user interface (GUI) for a timer application using Python's Pygame library. The given code snippet is part of a larger program that sets up the initial display of the GUI. The `self.Screen` object represents the main display surface, and various buttons and controls a... | ```python
import pygame
import time
class TimerControl:
def __init__(self, position):
self.position = position
self.start_time = 0
self.is_running = False
def start_timer(self):
self.start_time = time.time()
self.is_running = True
def stop_timer(self):
self... | magicoder | python |
You are tasked with implementing a class for managing the running of several page watchers. The class, `WatcherManager`, should be designed to handle a collection of `PageWatcher` instances and provide functionality for managing their execution.
The `WatcherManager` class should have the following features:
- A constr... | ```python
import logging
class WatcherManager:
""" Manages the running of several PageWatchers """
def __init__(self, page_watchers=None, alert_function=logging.info):
self.watchers = page_watchers if page_watchers is not None else []
self.alert_function = alert_function
def add_watcher(se... | magicoder | python |
You are tasked with creating a Python function that generates unique usernames for new users in a web application. The function should take a string representing the user's first name and a string representing the user's last name as input and return a unique username based on the following rules:
1. The username shoul... | ```python
def generate_username(first_name: str, last_name: str) -> str:
base_username = first_name[0].lower() + last_name.lower()
username = base_username
suffix = 2
while User.objects.filter(username=username).exists():
username = base_username + str(suffix)
suffix += 1
return user... | magicoder | python |
You are working on a project that involves generating reports using JasperReports, a popular Java reporting library. As part of this project, you need to understand and manipulate font extensions using the SimpleFontExtensionHelper class.
Your task is to create a Java method that takes a font file path and a font fami... | ```java
import net.sf.jasperreports.engine.fonts.SimpleFontExtensionHelper;
import net.sf.jasperreports.engine.fonts.SimpleFontFace;
public class FontExtensionHelper {
public SimpleFontFace createFontExtension(String fontFilePath, String fontFamily) {
SimpleFontExtensionHelper fontExtensionHelper = new Sim... | magicoder | java |
You are tasked with implementing a function to process a list of strings and remove any trailing whitespace from each string. Additionally, you need to compare the processed strings with their original versions and identify any differences.
You are given the following code snippet as a starting point:
```python
trim_... | ```python
def trim_trailing_whitespace(strings):
"""
Removes trailing whitespace from each string in the input list.
Args:
strings: A list of strings to be processed.
Returns:
A list of strings with trailing whitespace removed.
"""
trimmed_strings = [s.rstrip() for s in strings... | magicoder | python |
You are tasked with implementing a Python decorator that handles errors for a given function. The decorator should catch a specific type of exception and perform a specific action when that exception is raised within the decorated function. Your task is to complete the implementation of the `handle_request_error_gen` d... | ```python
from typing import Any, Callable, TypeVar
from functools import wraps
TFunc = TypeVar('TFunc', bound=Callable)
class RpcError(Exception):
pass
class Call(RpcError):
pass
def get_metadata_from_call(e: RpcError) -> Any:
# Implementation of get_metadata_from_call function
pass
def handle_req... | magicoder | python |
You are tasked with implementing a program to simulate the movement of disks between towers in the classic "Tower of Hanoi" puzzle. The Tower of Hanoi consists of three rods and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size... | ```python
def valid_transition(currentState, tower_i, tower_j):
if tower_i == tower_j: # Same tower not allowed
return False
if len(currentState[tower_i]) == 0: # No disk to move from tower_i
return False
if len(currentState[tower_j]) == 0: # Valid move if tower_j is empty
retur... | magicoder | python |
You are tasked with creating a Python function that processes Facebook video URLs and downloads the videos based on their source. The function should take a URL as input and determine the source of the video (either from the "watch" section or a group) and then download the video accordingly.
The function should be na... | ```python
def download_facebook_video(url: str) -> str:
url = url.replace("https://www", "https://m")
if url.startswith("https://m.facebook.com/watch/"):
return download_from_watch(url)
elif url.startswith("https://m.facebook.com/groups"):
return download_from_group(url)
else:
r... | magicoder | python |
You are tasked with implementing a shift cipher algorithm for encoding a given input string. A shift cipher, also known as a Caesar cipher, is a type of substitution cipher where each letter in the plaintext is shifted a certain number of places down or up the alphabet. For example, with a shift of 3, 'A' would be repl... | ```python
class ShiftCipher:
def encode(self, input_str, shift_amount):
result = ""
for char in input_str:
if char.isalpha():
shift = 65 if char.isupper() else 97
result += chr((ord(char) - shift + shift_amount) % 26 + shift) if char.isalpha() else char
... | magicoder | python |
You are tasked with implementing a Python class that simulates a stack data structure. The stack should support the following operations:
1. `push(item)`: Add an item to the top of the stack.
2. `pop()`: Remove and return the item at the top of the stack.
3. `peek()`: Return the item at the top of the stack without rem... | ```python
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
def isEmpty(self):
return len(self.items) == 0
def size(self):
... | magicoder | python |
You are tasked with implementing a file reading and processing system for a dictionary file in a C++ program. The provided code snippet is a part of the `open_d1` function in the `DCTRD` class. The function is responsible for opening and reading a dictionary file, and it calls the `ReadFileInfo` function to read the di... | ```cpp
#include <iostream>
#include <fstream>
#include <string>
class CFSFileName {
// Define the CFSFileName class as per the requirements
};
class DCTRD {
public:
void open_d1(const CFSFileName *dct_file) {
// Read the dictionary file's information block
ReadFileInfo(dct_file);
// Pe... | magicoder | cpp |
You are tasked with implementing a simplified version of a neural network layer using Python and NumPy. The layer to be implemented is a max-pooling layer, which takes an input tensor and applies max-pooling to it.
The max-pooling operation involves dividing the input tensor into non-overlapping subregions and computi... | ```python
import numpy as np
def max_pooling(x, k):
N, C, H, W = x.shape
H_out = H // k
W_out = W // k
pooled_output = np.zeros((N, C, H_out, W_out))
for i in range(H_out):
for j in range(W_out):
h_start = i * k
h_end = h_start + k
w_start = j * k
... | magicoder | python |
You are tasked with creating a Python program that simulates a simple game of rock-paper-scissors. The program should allow a user to play against the computer and keep track of the score. The game should consist of a series of rounds, and the winner of each round should be determined based on the classic rules of rock... | ```python
import random
def rock_paper_scissors_game(n: int) -> None:
choices = ["rock", "paper", "scissors"]
user_score = 0
computer_score = 0
for i in range(1, n + 1):
print(f"Round {i}:")
user_choice = input("Enter your choice (rock, paper, scissors): ").lower()
computer_cho... | magicoder | python |
You are tasked with creating a program to calculate the total number of days in a given range of years, accounting for leap years. A leap year occurs every 4 years, except for years that are divisible by 100 but not by 400. The program should consider the number of days in each month and account for leap years accordin... | ```javascript
function isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
function calculateTotalDaysInRange(startYear, endYear) {
var totalDays = 0;
var daysInMonth = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
for (var year = startYear; year <= endYear; ye... | magicoder | javascript |
You are tasked with implementing a database utility function for updating records in a table. The function `update` takes four parameters: `$tablename` (the name of the table to update), `$field_name` (the name of the field to use for the update condition), `$field_value` (the value to match in the specified field), an... | ```php
function update($tablename, $field_name, $field_value, $data) {
$updateFields = [];
foreach ($data as $key => $value) {
$updateFields[] = "$key = '" . addslashes($value) . "'";
}
$updateQuery = "UPDATE $tablename SET " . implode(', ', $updateFields) . " WHERE $field_name = " . intval($fie... | magicoder | php |
You are tasked with implementing a message sender component using Java and Spring Framework. The `AuthorSender` class is responsible for sending messages to a JMS (Java Message Service) queue using the `JmsTemplate` provided by Spring.
Your task is to complete the implementation of the `AuthorSender` class by adding a... | ```java
import lombok.extern.slf4j.Slf4j;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class AuthorSender {
private final JmsTemplate jmsTemplate;
public AuthorSender(JmsTemplate jmsTemplate) {
this.jmsTemplate = jmsTemplat... | magicoder | java |
You are tasked with writing a script to handle backup configurations using the given code snippet as a reference. The script should source a configuration file, set the RSYNC_PASSWORD environment variable if a password file exists, and configure the RSYNC_CONNECT_PROG and BACKUPURL variables based on the presence of th... | ```bash
#!/bin/bash
die() {
echo "$1" >&2
exit 1
}
[[ -e $BKIT_CONFIG ]] || die "Can't source file '$BKIT_CONFIG'"
source "$BKIT_CONFIG"
[[ -e $PASSFILE ]] && export RSYNC_PASSWORD="$(<${PASSFILE})" || die "Pass file not found on location '$PASSFILE'"
if [[ ${NOSSH+isset} == isset ]]; then
unset RSYNC_CONNEC... | magicoder | shell |
You are given the following Python code snippet that manipulates a binary tree using a stack:
```python
stack = [root]
while stack:
node = stack.pop()
if node.left:
stack.append(node)
stack.append(node.left)
node.left = None
elif node.right:
# Missing code snippet
```
Your... | ```python
class TreeNode:
def __init__(self, value=0, left=None, right=None):
self.value = value
self.left = left
self.right = right
def modify_tree(root):
stack = [root]
while stack:
node = stack.pop()
if node.left:
stack.append(node)
stack.... | magicoder | python |
You are tasked with implementing a function to create a new XKB (X Keyboard Extension) state for a given X11 core keyboard device using the xkb-rs library in Rust. The xkb-rs library provides Rust bindings for the X Keyboard Extension, which allows for advanced keyboard input handling.
You are provided with a partial ... | ```rust
fn create_new_xkb_state(conn: &Connection, xkb_context: &Context, xkb_device_id: i32) -> (Keymap, State) {
// Retrieve the XKB keymap for the specified device using the XKB context and connection
let keymap_str = xkb::x11::get_keymap(conn, xkb_device_id, xkb::x11::KEYMAP_COMPILE_NO_FLAGS);
let xkb_k... | magicoder | rust |
You are given a code snippet that is part of a primality testing algorithm. The code checks whether a given number `n` is a probable prime using the Jacobi symbol and modular exponentiation. Your task is to implement a function that completes the primality testing algorithm using the given code snippet as a reference.
... | ```python
from random import randint
def jacobi_symbol(a, n):
if a == 0:
if n == 1:
return 1
else:
return 0
if a % 2 == 0:
return jacobi_symbol(a // 2, n) * pow(-1, ((n ** 2 - 1) // 8))
else:
if a % 4 == 3 and n % 4 == 3:
return -jacobi_sy... | magicoder | python |
You are tasked with implementing a Python class that manages a daemon process. The class, named `Daemon`, should provide methods for starting, stopping, and restarting the daemon process. The daemon process is responsible for performing a specific task in the background, such as monitoring a directory for file changes.... | ```python
import os
import sys
import time
import atexit
import signal
class Daemon:
def __init__(self, pidfile):
self.pidfile = pidfile
def _write_pid_file(self, pid):
with open(self.pidfile, 'w') as f:
f.write(str(pid))
def _read_pid_file(self):
with open(self.pidfil... | magicoder | python |
You are tasked with creating a program that simulates a simple banking system. The program should be able to handle multiple user accounts, allowing users to check their balance, deposit funds, withdraw funds, and transfer money between accounts. The program should also be able to display a transaction history for each... | ```python
class Account:
def __init__(self, account_number, initial_balance):
self.account_number = account_number
self.balance = initial_balance
self.transaction_history = []
def deposit(self, amount):
self.balance += amount
self.transaction_history.append(f"Deposited {... | magicoder | python |
You are tasked with creating a Python class that simulates a simple job scheduler for a high-performance computing (HPC) system. The job scheduler will be responsible for submitting, monitoring, and managing jobs on the HPC system. Your task is to implement the `JobScheduler` class with the following functionalities:
... | ```python
import uuid
class JobError(Exception):
pass
class JobScheduler:
def __init__(self):
self.jobs = {}
def submit_job(self, job_script):
job_id = str(uuid.uuid4())
self.jobs[job_id] = 'pending'
# Submit the job_script to the HPC system and update job status
#... | magicoder | python |
You are tasked with implementing a priority queue data structure using a max-heap. A priority queue is a data structure that maintains a set of elements, each associated with a priority. The max-heap property states that the priority of a parent node is always greater than or equal to the priorities of its children. Yo... | ```cpp
#include <iostream>
#include <vector>
#include <utility>
using namespace std;
template<typename T>
ostream& operator<<(ostream& out, const vector<T>& v)
{
out << '[';
if (!v.empty()) {
auto it = v.begin();
out << *it;
++it;
while (it != v.end()) {
out << ", "... | magicoder | cpp |
You are working on a project to optimize a neural network model for deployment on edge devices. As part of this optimization, you need to implement a graph-based transformation on the model's operations. The given code snippet is a part of the transformation process, where operations and tensors are connected in a grap... | ```cpp
void performGraphTransformation(Operation* op, Tensor* inputTensor, Tensor* outputTensor) {
// Create new operations and tensors as per the transformation logic
Operation* output_quant = new Operation("output_quant");
Operation* mul = new Operation("mul");
Operation* max = new Operation("max");
... | magicoder | cpp |
You are tasked with implementing a function to optimize a parameter for a quantum algorithm using the given code snippet as a reference. The function `loss_func` takes two parameters: `new_param` (an array of parameters) and `shots` (an integer representing the number of shots for the quantum algorithm). The goal is to... | ```python
import numpy as np
class QuantumOptimizer:
def __init__(self):
self._loss_history = []
def optimize_parameter(self, new_param, shots):
curr_loss = float('inf') # Initialize curr_loss to a large value
self._loss_history = [] # Initialize loss history
for j in range(... | magicoder | python |
You are tasked with creating a Python class that interacts with an OAuth-protected API. Your class should be able to handle the authentication process and make requests to the API endpoints. You are provided with a code snippet that initializes an OAuthAPIClient using the LMS_ROOT_URL, api_client_id, and api_client_sec... | ```python
import requests
class OAuthAPIClient:
def __init__(self, lms_root_url, client_id, client_secret):
self.lms_root_url = lms_root_url
self.client_id = client_id
self.client_secret = client_secret
self.access_token = None
def authenticate(self):
auth_url = f"{self... | magicoder | python |
You are tasked with creating a Python class to manage actions within a reliability, availability, and maintainability (RAM) software tool. The class should be able to perform various operations on action records, such as adding, deleting, and updating them in a database.
Your task is to implement the `RAMSTKAction` cl... | ```python
# Standard Library Imports
from datetime import date, timedelta
# Third Party Imports
from pubsub import pub
# RAMSTK Package Imports
from ramstk.models.dbrecords import RAMSTKActionRecord
from ramstk.models.dbtables import RAMSTKActionTable
from tests import MockDAO
class RAMSTKAction:
def __init__(s... | magicoder | python |
You are tasked with implementing a scheduling service for a company. The service should provide methods to create, update, and delete schedules. You are given a code snippet that outlines the interface for the scheduling service:
```typescript
interface SchedulingService {
create(category: CreateScheduleDto);
upda... | ```typescript
// Define the CreateScheduleDto type
type CreateScheduleDto = {
// Define the properties required to create a schedule
// For example:
title: string;
startTime: Date;
endTime: Date;
// Add other properties as needed
};
// Define the UpdateScheduleDto type
type UpdateScheduleDto = {
// Defin... | magicoder | typescript |
You are tasked with implementing a Python class method that calculates the total message processing time for a subscription. The class `Subscription` has the following attributes:
- `consumerGroupId`: The ID of the consumer group.
- `endPoint`: The endpoint for the subscription.
- `messageInvisibleTimeInSeconds`: The t... | ```python
class Subscription(object):
def __init__(self, consumerGroupId=None, endPoint=None, messageInvisibleTimeInSeconds=None, subscriptionType=None, tags=None, dlqEnable=None, maxRetryTimes=None, createTime=None, lastUpdateTime=None, consumerNumbers=None):
self.consumerGroupId = consumerGroupId
... | magicoder | python |
You are tasked with implementing a class that utilizes the `IUnderlyingExecutor` interface to execute a query asynchronously and process the results. The `IUnderlyingExecutor` interface has a single method `ExecuteAsync` that takes a `Query` object and a `Uri` representing the data location, and returns an asynchronous... | ```csharp
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
public interface IUnderlyingExecutor
{
IAsyncEnumerable<ResultRow> ExecuteAsync(Query query, Uri dataLocation);
}
public class QueryProcessor
{
public async Task<List<ResultRow>> ProcessQueryAsync(IUnderlyingExecutor execu... | magicoder | csharp |
You are tasked with implementing a custom TensorFlow operation for calculating the mean and standard deviation of a given input tensor. The operation should be implemented using TensorFlow's custom op API and should be able to handle tensors of any shape. The mean and standard deviation should be calculated along a spe... | ```python
import tensorflow as tf
from common.ops import shape_ops
def mean_stddev_op(input_tensor, axis):
# Calculate the mean and standard deviation of the input tensor along the specified axis
mean = tf.reduce_mean(input_tensor, axis=axis)
variance = tf.reduce_mean(tf.square(input_tensor - mean), axis=a... | magicoder | python |
You are tasked with implementing a message queuing system using Python and Redis. The provided code snippet demonstrates the process of creating a task in the message queue and pushing items into a list within Redis. Your goal is to extend this functionality by implementing a function that retrieves and processes items... | ```python
import redis
import time
def process_queue_items(redis_host: str, redis_port: int, list_name: str, timeout_seconds: int) -> None:
r = redis.StrictRedis(host=redis_host, port=redis_port, decode_responses=True)
start_time = time.time()
while time.time() - start_time < timeout_seconds:
item... | magicoder | python |
You are tasked with implementing a file delta computation function for a version control system. The function `compute_delta` takes in a rule path, a mode, and a list of source paths. The rule path specifies the rule file to be used for computing the delta, the mode specifies the mode of computation, and the source pat... | ```python
from typing import List, Dict, Any
class VersionControlSystem:
def compute_delta(self, rule_path: str, mode: str, src_paths: List[str]) -> Dict[str, Any]:
# Placeholder for the actual implementation
delta_info = {}
# Perform computation based on rule_path and mode for each src_pat... | magicoder | python |
You are tasked with implementing a TypeScript function that validates the properties of a `DialogBoxParameters` object. The `DialogBoxParameters` interface represents the parameters for a dialog box, and your function should ensure that the required properties are present and have the correct data types.
The `DialogBo... | ```typescript
function validateDialogBoxParameters(params: DialogBoxParameters): boolean {
if (typeof params.text !== 'string' || typeof params.old !== 'boolean' || typeof params.interactive !== 'boolean') {
return false;
}
if (params.title && typeof params.title !== 'string') {
return false;
}
if (... | magicoder | typescript |
You are tasked with implementing a decorator function in JavaScript that modifies the behavior of a given function. The decorator function should intercept the return value of the decorated function and replace it with a specified value if the original return value matches a certain condition.
You are provided with th... | ```javascript
export const PSEUDO_RETURN = Symbol('TO_BE_DECORATED')
function decorate(condition, newValue) {
return function (func) {
return function (...args) {
const result = func.apply(this, args)
if (condition(result)) {
return newValue
}
return result
}
}
}
function a... | magicoder | javascript |
You are tasked with implementing a market tagging system for a trading platform. The system should allow users to tag various market events with specific tags for easy categorization and filtering. Your task is to create a class that manages these market tags and provides methods for adding, removing, and querying tags... | ```typescript
interface MarketTags {
addTag(tag: string, event: number): void;
removeTag(tag: string, event: number): void;
getEventsWithTag(tag: string): number[];
}
class MarketTagManager implements MarketTags {
private tagsMap: Map<string, Set<number>>;
constructor() {
this.tagsMap = ne... | magicoder | typescript |
You are tasked with implementing a function that recalculates the polygonization of text lines in an image. The function takes an input image and a list of dictionaries, where each dictionary contains information about a text line, including its boundary, baseline, and the actual text. The goal is to modify the polygon... | ```python
from shapely.geometry import Polygon, LineString
def recalculate_polygonization(im, lines):
for line in lines:
boundary_points = line['boundary']
baseline_points = line['baseline']
# Create a Shapely LineString from the baseline points
baseline = LineString(baseline_point... | magicoder | python |
You are tasked with implementing a retry mechanism for handling HTTP response status codes in a Python program. The program interacts with an external API and needs to handle specific status codes by retrying the request after a certain delay. The provided code snippet demonstrates a part of the retry logic for handlin... | ```python
import time
import json
import requests
def handle_http_response(response):
if response.status_code == 429:
logger.warning("Too Many Requests (429), retrying.")
time.sleep(10)
return retry()
elif response.status_code == 500:
logger.warning("Internal Server Error (500),... | magicoder | python |
You are tasked with implementing a function that takes an integer as input and returns a Promise that resolves to a string. The function should handle the case where the input is not a number and should reject the Promise with an appropriate error message in such cases. Additionally, the function should handle the case... | ```typescript
function fn(input: number): Promise<string> {
return new Promise((resolve, reject) => {
if (typeof input !== 'number' || isNaN(input)) {
reject(new Error('Input is not a valid number'));
} else if (input < 0) {
reject(new Error('Input should be a non-negative number'));
} else {
... | magicoder | typescript |
You are tasked with creating a part-of-speech (POS) tagging system for Chinese text using a pre-trained model and evaluating its performance. The code snippet provided demonstrates the loading of a pre-trained tagger model, tagging a sample sentence, evaluating the model's performance on a test dataset, and then saving... | ```python
def pos_tagging_workflow(tagger, save_dir, sample_sentence, test_dataset_path):
try:
# Step 1: Load the pre-trained model
tagger.load(save_dir)
# Step 2: Tag the sample sentence using the loaded model
tagged_sentence = tagger(sample_sentence)
# Step 3: Evaluate th... | magicoder | python |
You are tasked with implementing a custom file handling class in Python. The class should support setting and getting attributes for the file, while also providing the ability to restrict certain attribute names from being set. Your task is to complete the implementation of the `FileHandler` class by adding the necessa... | ```python
class FileHandler:
def __init__(self, file_name):
self.file = open(file_name, 'w+')
def set_attribute(self, name, value):
restricted_attributes = ['size', 'name'] # Example restricted attribute names
if name in restricted_attributes:
raise PermissionError(f"Settin... | magicoder | python |
You are tasked with creating a function that processes plugin manifests to generate target settings for a project. The plugin manifests contain information about the plugins, such as their paths, helper directories, and template directories. Your goal is to implement a function that takes the plugin manifests as input ... | ```swift
struct PluginManifest {
let path: String
// Other properties specific to the plugin manifest
}
struct Target {
let name: String
let settings: Settings
// Other properties specific to the target
}
func generateTargetSettings(pluginManifests: [PluginManifest]) -> [Target] {
return plugi... | magicoder | swift |
You are tasked with implementing a frequency modulation (FM) modulator using C++. The modulator should take an input signal and modulate it using frequency modulation before outputting the modulated signal. You are provided with the `modulator.hpp` header file, which contains the necessary class and function declaratio... | ```cpp
// modulator.cpp
#include "modulator.hpp"
#include <cmath>
FMModulator::FMModulator(double modulationIndex) : modulationIndex(modulationIndex) {}
std::vector<double> FMModulator::modulate(const std::vector<double>& inputSignal) {
std::vector<double> modulatedSignal;
double phase = 0.0;
for (doubl... | magicoder | cpp |
You are tasked with creating a custom error handling system for a media player application. The application uses the FMOD library for audio processing and encounters various file-related errors during runtime. Your goal is to implement a custom error handling mechanism that can interpret and handle these file-related e... | ```python
class CustomErrorHandling:
error_messages = {
"FMOD_ERR_FILE_COULDNOTSEEK": "Media file could not be seeked.",
"FMOD_ERR_FILE_DISKEJECTED": "Media was ejected while reading.",
"FMOD_ERR_FILE_EOF": "End of file unexpectedly reached while trying to read essential data (truncated?).",... | magicoder | python |
You are tasked with creating a program to validate passport data based on strict rules. The passport data is represented as a series of key-value pairs separated by spaces and newlines. Each key-value pair is in the format "key:value". A passport is valid if it contains the following fields:
- byr (Birth Year) - four ... | ```rust
use std::collections::HashMap;
fn is_valid_passport(passport_data: &str) -> bool {
let mut fields: HashMap<&str, &str> = HashMap::new();
for pair in passport_data.split_whitespace() {
let parts: Vec<&str> = pair.split(":").collect();
if parts.len() == 2 {
fields.insert(parts... | magicoder | rust |
You are tasked with implementing a custom progress dispatcher in Swift. The progress dispatcher should be able to handle the dispatching of progress updates and errors. You need to create a subclass of the `ProgressDispatcher` class and implement the required functionality.
Your task is to complete the implementation ... | ```swift
import Foundation
class ProgressDispatcher: ProgressDispatcher {
override func updateProgress(_ progress: Progress) {
let dispatchedProgress = dispatcher.dispatch(progress)
// Perform any additional operations with dispatchedProgress
}
override func updateError(_ error: NSError) {... | magicoder | swift |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.