query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with simulating a system using the Rust programming language. The system consists of a number of "ptl" (presumably particles) and "rts" (real-time systems) components. Your goal is to implement a simulation using the provided libraries and components. Your task is to create a Rust program that simulates...
```rust use criterion::{criterion_group, criterion_main, Criterion}; use rts::prelude::*; use rts::system_mod::cont_circ::ContCircSystem; use rts::target_mod::cont_bulk::ContBulkTarget; use rts::searcher_mod::cont_passive_merge::ContPassiveMergeSearcher; fn main() { // Define the number of particles in the system ...
magicoder
rust
You are tasked with implementing a file download and upload retry mechanism for a cloud storage system. The provided code snippet contains a function `download_file` that attempts to download a file from a cloud storage location to a local path. If the download fails, the function retries the operation up to three time...
```python import logging import time class CloudFileManager: def __init__(self, max_retries: int): self.max_retries = max_retries def download_file(self, path_s3: str, path_local: str) -> bool: retry = 0 while retry < self.max_retries: # Simulate download operation (replace...
magicoder
python
You are tasked with creating a Python function that performs a specific type of rounding on a given decimal number. The function should take three parameters: the decimal number to be rounded, the precision to which it should be rounded, and the rounding mode. The rounding mode can be one of the following: "ROUND_UP", ...
```python from decimal import Decimal, ROUND_UP, ROUND_DOWN, ROUND_HALF_UP, ROUND_HALF_DOWN, ROUND_HALF_EVEN, ROUND_CEILING def custom_round(decimal_num, precision, rounding_mode): decimal_num = Decimal(decimal_num) precision = Decimal(precision) if rounding_mode == 'ROUND_UP': return decimal_...
magicoder
python
You are tasked with creating a custom React hook that manages the state of a to-do list. The hook should provide functions to add, delete, and update to-dos, as well as the ability to retrieve the list of to-dos and their associated metadata. Your task is to implement the `useTodoList` custom hook, which should have t...
```javascript import { useState } from 'react'; const useTodoList = () => { const [todos, setTodos] = useState([]); const addTodo = (text, updatedAt, orderIndex) => { const newTodo = { id: Math.random().toString(36).substr(2, 9), // Generate a unique ID text, completed: false, updatedA...
magicoder
javascript
You are tasked with implementing a class for managing areas in a system. The provided code snippet is a part of a program that interacts with the user to remove an area from the system. The `areas` list contains instances of the `Area` class, and the `controller_areas` is an instance of the `AreaController` class. The ...
```python class Area: def __init__(self, nome): self.nome = nome def get_nome(self): return self.nome class AreaController: def __init__(self): self.areas = [] def add_area(self, area): self.areas.append(area) def remove_area(self, nome): for area in self...
magicoder
python
You are tasked with creating a script to automate the installation and configuration of a specific hardware driver on a Linux system. The script should handle the installation of the necessary dependencies, removal of any existing driver modules, and cleanup of previous installations. Your task is to write a Bash scri...
```bash #!/bin/bash # Install libudev-dev package sudo apt-get install -y libudev-dev # Check if the configuration variable contains "qat" if echo $CONF | grep -q qat; then # Extract the base name of the driver location qat_tarball=$(basename $DRIVER_LOCATION_QAT) # Retrieve the major and minor version n...
magicoder
shell
You are tasked with implementing a falling edge detector for a digital input signal. A falling edge occurs when the signal transitions from a high (1) to a low (0) state. The provided code snippet is a part of the falling edge detection logic. Your task is to complete the implementation by writing the missing parts of ...
```python global old_input_value, flag_falling_edge, start, flag_output_mask, output, DELAY_CONST if flag_falling_edge: output = True end = time.perf_counter() if end - start > DELAY_CONST: if flag_output_mask: output = False else: ...
magicoder
python
You are tasked with implementing a function that constructs a `HeightField` object in a 3D graphics application. The `HeightField` represents a terrain surface and is composed of a `ColliderHandle`, a reference to a `HeightField` shape, a color, and a mutable reference to a window for rendering. The function takes the...
```rust fn construct_height_field( collider: ColliderHandle, heightfield: &shape::HeightField<f32>, color: Point3<f32>, window: &mut Window, ) -> HeightField { let mesh = heightfield.to_trimesh(()); // Convert the heightfield to a trimesh let mut res = HeightField { color, base_...
magicoder
rust
You are tasked with implementing a simple web server endpoint in Rust using the Actix web framework. The provided code snippet contains a partial implementation of an Actix web server with an asynchronous function to display the current visitor count. Your task is to complete the implementation by adding a new endpoint...
```rust use actix_web::{web, App, HttpServer, Responder}; use std::sync::atomic::{AtomicUsize, Ordering}; /// Displays state async fn get_count(count: web::Data<AtomicUsize>) -> impl Responder { let current_count = count.load(Ordering::SeqCst); format!("Visitors: {}", current_count) } /// Increments the visit...
magicoder
rust
You are tasked with implementing a Python class that manages a collection of bags. Each bag can contain a variety of items, and the class should provide methods for adding and removing items from the bags, as well as for retrieving information about the bags and their contents. Your task is to complete the implementat...
```python class BagProject: def __init__(self, impl_lib): if not impl_lib: raise ValueError('BagProject instance is not given.') self.specs = {'impl_lib': impl_lib, 'bags': {}} def add_bag(self, bag_name): if bag_name not in self.specs['bags']: self.specs['bags']...
magicoder
python
You are tasked with implementing a Python function that processes a given string containing nutritional information and calculates the total calories based on the provided macronutrient values. The nutritional information is represented in the format "name fat/protein/carbohydrates kcal", where "name" is the food item ...
```python def calculate_total_calories(nutritional_info: str) -> int: total_calories = 0 items = nutritional_info.split(';') # Split the input string into individual food items for item in items: parts = item.split() # Split each food item into its components macronutrients = parts[1].spli...
magicoder
python
You are tasked with creating a migration script for a database schema update in a Python Django project. The project involves a model called `MyFile` in an app named `classroom`. The goal is to add a new field called `file` to the `MyFile` model. The field should be a character field with a maximum length of 100 charac...
```python def generate_migration_script(app_name: str, model_name: str, field_name: str, field_type: str, max_length: int, allow_blank: bool) -> str: migration_script = f''' dependencies = [ ('{app_name}', '0024_auto_20190825_1723'), ] operations = [ migrations.AddField( mod...
magicoder
python
You are tasked with implementing a matrix factorization algorithm for collaborative filtering. Collaborative filtering is a technique commonly used in recommendation systems to predict a user's preference for a particular item by leveraging the preferences of other users. One popular approach for collaborative filterin...
```python import numpy as np import math # Complete the convergence check if abs((U - U_old).sum()) < 0.01 and abs((V - V_old).sum()) < 0.01: is_convergence = True # Implement the normalization step for matrix U u_pow_2 = (U ** 2).sum(axis=0) u_sqrt_pow_2 = [math.sqrt(w) for w in u_pow_2] U = U / u_sqrt_pow_2 ``...
magicoder
python
You are tasked with implementing a Locality Sensitive Hashing (LSH) data structure and its associated operations. LSH is a technique for efficiently finding approximate nearest neighbors in high-dimensional spaces. The code snippet provided contains assertions and function calls related to LSH and Weighted MinHash. Yo...
```python import numpy as np from collections import defaultdict class WeightedMinHashGenerator: def __init__(self, num_perm, num_weight): self.num_perm = num_perm self.num_weight = num_weight def minhash(self, weights): if len(weights) != self.num_weight: raise ValueError(...
magicoder
python
You are tasked with creating a Python program that monitors the CPU utilization of a system using the `psutil` library. Your program should continuously monitor the CPU utilization and display a message when the utilization exceeds a certain threshold. Additionally, the program should provide the average CPU utilizatio...
```python import psutil import time def monitor_cpu_utilization(threshold, monitoring_duration): utilization_values = [] start_time = time.time() while True: cpu_utilization = psutil.cpu_percent(interval=1) utilization_values.append(cpu_utilization) if cpu_utilization > threshold:...
magicoder
python
You are tasked with implementing a module system for a web server framework in Rust. The provided code snippet is a part of the module system for handling HTTP headers. Your goal is to create a new module for handling the "ContentEncoding" header and ensure that it can be used by the web server framework. Your task is...
```rust // content_encoding.rs pub struct ContentEncoding { encoding_type: String, } impl ContentEncoding { pub fn new(encoding_type: &str) -> ContentEncoding { ContentEncoding { encoding_type: encoding_type.to_string(), } } pub fn encode(&self, content: &str) -> String { ...
magicoder
rust
You are tasked with implementing a file manipulation class in C#. The class should provide methods for performing various file operations, such as deleting a file if it exists, getting the path of a file, and reading a specific portion of a file. You are given a partial code snippet of the file manipulation class with...
```csharp public byte[] GetData(BinaryReader br, long offset, int size) { br.BaseStream.Seek(offset, SeekOrigin.Begin); // Move the stream position to the specified offset return br.ReadBytes(size); // Read the specified number of bytes from the current position } ``` In the `GetData` method, the `Seek` meth...
magicoder
csharp
You are tasked with implementing a Python function that simulates a simplified version of a neural network training process using TensorFlow. The function should initialize a TensorFlow session, configure GPU options, build a model, set a random seed, and initialize global variables. Your task is to complete the functi...
```python import tensorflow as tf class NeuralNetworkTrainer: def train_neural_network(self, model, config): """ Trains a neural network model using TensorFlow. Args: - model: An instance of the neural network model to be trained. - config: A configuration object containing...
magicoder
python
You are tasked with implementing a function to concatenate two strings without using the built-in string concatenation operator (+). Your function should take two strings as input and return a new string that is the concatenation of the input strings. Your task is to implement the `ConcatenateStrings` function, which ...
```csharp public string ConcatenateStrings(string str1, string str2) { char[] result = new char[str1.Length + str2.Length]; int index = 0; foreach (char c in str1) { result[index] = c; index++; } foreach (char c in str2) { result[index] = c; index++; } ...
magicoder
csharp
You are tasked with implementing a clustering evaluation metric using Python. The evaluation metric is based on comparing two sets of documents: a set of gold standard documents (`gold_documents`) and a set of automatically generated documents (`auto_documents`). The evaluation metric is used to calculate the confusion...
```python def evaluate_clusters(gold_documents, auto_documents): # Implement the evaluate_clusters function based on the specific clustering evaluation method (e.g., Jaccard index, Rand index, etc.) # Compare the clustering results of gold_documents and auto_documents and return the evaluation result # Exa...
magicoder
python
You are tasked with implementing a function to calculate the first set of a non-terminal symbol in a context-free grammar. The first set of a non-terminal symbol consists of all terminal symbols that can appear as the first symbol in some string derived from the non-terminal symbol. You are given a partial code snippe...
```rust use std::collections::HashSet; struct ContextFreeGrammar<T> { productions: Vec<Production<T>>, } struct Production<T> { consumed_symbols: Vec<T>, } impl<T: PartialEq + Clone> ContextFreeGrammar<T> { fn calculate_first_set(&self, non_terminal: &T) -> HashSet<PossiblyEmptyTerminalSymbol<T>> { ...
magicoder
rust
You are tasked with implementing a Fast Binary Encoding (FBE) character field model in Swift. FBE is a high-performance binary serialization format that allows for efficient encoding and decoding of structured data. The character field model is used to represent strings in the FBE format. The character field model con...
```swift import Foundation class FBECharacterField { func encode(_ value: String) -> Data { var encodedData = Data() // Encode the length of the string as a variable-length integer var length = value.utf8.count while length >= 0x80 { encodedData.append(UInt8(len...
magicoder
swift
You are tasked with implementing a lexer for a custom grammar that recognizes specific tokens in a given input string. The grammar is defined using a custom specification format, and the lexer should be able to tokenize the input string based on this grammar. The grammar specification is provided in the form of a stri...
```java import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CustomGrammarLexer { public static List<String> tokenizeInput(String input, String grammarSpecification) { List<String> tokens = new ArrayList<>(); String[] rules ...
magicoder
java
You are given a code snippet representing a multi-dimensional array and a versioning system. Each array contains a mix of `UInt` values and integers. The versioning system consists of a version number and a series of nested `UInt` types. Your task is to write a program to extract and process the `UInt` values from the ...
```python def extract_uint_values(array, version): version_number, *nested_types = version result = [] def extract_recursive(arr, nested_types): if not nested_types: for item in arr: if isinstance(item, str) and item.startswith('U'): result.append(ite...
magicoder
python
You are tasked with implementing a class for a training pipeline in a machine learning framework. The training pipeline is responsible for training a neural network model using provided data. Your task is to complete the implementation of the `TrainingPipeline` class by adding the `run` method, which will execute the t...
```python class TrainingPipeline: def __init__(self, model, base_path, epochs): self.model = model self.base_path = base_path self.epochs = epochs def import_data(self): # Implement data import logic here pass # Placeholder for data import logic def run(self): ...
magicoder
python
You are tasked with creating a script that automates the process of starting a development environment for a messaging broker plugin. The messaging broker in question is Mosquitto, and the script should handle the setup and initialization of the plugin for development purposes. Your task is to write a shell script nam...
```bash #!/usr/bin/env sh # Set up the necessary environment for plugin development # (e.g., setting environment variables, configuring paths, etc.) # Start the Mosquitto broker with the plugin enabled mosquitto -c /path/to/mosquitto.conf -v -d # Check if Mosquitto is running with the plugin enabled if pgrep -x "mos...
magicoder
shell
You are tasked with implementing a custom generator in Python that yields a sequence of prime numbers. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Your generator function should yield the next prime number each time it is called. Your task is to implement th...
```python def prime_generator(): def is_prime(num): if num < 2: return False for i in range(2, int(num ** 0.5) + 1): if num % i == 0: return False return True num = 2 while True: if is_prime(num): yield num num += 1...
magicoder
python
You are tasked with automating the setup of a Docker environment on an Ubuntu server. Your goal is to write a script that performs the necessary package installations and configurations to set up Docker and its dependencies. Below is a simplified version of the script that you need to automate: ```bash apt full-upgrad...
```bash #!/bin/bash # Perform system upgrade and cleanup apt full-upgrade -y apt autoremove -y # Install unattended-upgrades apt install -y unattended-upgrades # Remove existing Docker packages apt remove -y docker docker-engine docker.io containerd runc # Install required dependencies apt install -y apt-transport-...
magicoder
shell
You are tasked with implementing a simplified version of a memory management system in C++. The system should handle the allocation and deallocation of memory for objects of a specific class. Your task is to create a class `MemoryManager` that manages the memory for objects of class `Widget`. The `Widget` class has a d...
```cpp #include <iostream> class Widget { public: Widget() { std::cout << "Widget constructed" << std::endl; } ~Widget() { std::cout << "Widget destructed" << std::endl; } }; class MemoryManager { public: Widget* allocate() { return new Widget(); } void deallocate...
magicoder
cpp
You are tasked with creating a Python function that counts the occurrences of each letter in a given list and stores the results in a dictionary. The function should take a list of letters as input and return a dictionary where the keys are the unique letters in the input list and the values are the counts of each lett...
```python def count_letters(letter_list): letter_count = {} for letter in letter_list: if letter in letter_count: letter_count[letter] += 1 else: letter_count[letter] = 1 return letter_count # Example usage input_list = ['a', 'b', 'a', 'c', 'b', 'a'] sorted_keys = so...
magicoder
python
You are tasked with creating a Python function that handles exceptions raised by a third-party library and provides a mock response in case of a specific error. The function should utilize the `mock` library to create a mock response and handle the `BotoServerError` exception from the `boto` library. Write a function ...
```python import mock from boto.exception import BotoServerError def handle_boto_error(boto_response, mock_response): try: return boto_response() except BotoServerError as e: if e.error_code == 'MockableError': return mock_response else: raise ``` The `handle_bo...
magicoder
python
You are tasked with implementing a function to solve the Traveling Salesman Problem (TSP) using the OR-Tools library. The TSP is a classic optimization problem where the goal is to find the shortest possible route that visits a set of given cities and returns to the original city. The provided code snippet contains a p...
```python from ortools.constraint_solver import pywrapcp, routing_enums_pb2 def solve_it(input_data): # Parse the input data to extract necessary information for solving the TSP # Example: parsing the input_data to obtain the distance matrix and other relevant information # Create a routing model ...
magicoder
python
You are tasked with implementing a registration system for various entities in a web application. The system uses a registration framework that allows for the dynamic registration of different entity types with specific options. The provided code snippet demonstrates the registration of two entity types, `Site` and `Co...
```python class EntityRegistry: def __init__(self): self.registered_entities = {} def register(self, entity_type, options, menu_enabled): self.registered_entities[entity_type] = {'options': options, 'menu_enabled': menu_enabled} def get_registered_entities(self): return self.regist...
magicoder
python
You are tasked with creating a Python program that simulates a simple task execution framework. The framework consists of rules that define tasks and their dependencies. Each task rule can have inputs and outputs, and when executed, it performs a specific action. Your goal is to implement a simplified version of this f...
```python class Remake: pass # Placeholder class for task rules class TaskRule: def __init__(self): self.inputs = {} self.outputs = {} def rule_run(self): raise NotImplementedError("Subclasses must implement rule_run method") # Example usage: ex8 = Remake() class CannotRun(Tas...
magicoder
python
You are tasked with creating a Python class that extends the functionality of the `TimestampedModel` class from the `mitol.common.models` module. The `TimestampedModel` class is a base model class that provides fields for `created_at` and `updated_at` timestamps. Your task is to create a new class called `CustomTimesta...
```python from oauth2_provider.settings import oauth2_settings from django.db import models from mitol.common.models import TimestampedModel APPLICATION_MODEL = oauth2_settings.APPLICATION_MODEL class CustomTimestampedModel(TimestampedModel): custom_field = models.CharField(max_length=100) ``` In the solution, we...
magicoder
python
You are tasked with creating a script to automate the setup of a Kubernetes cluster using Minikube. Minikube is a tool that enables you to run Kubernetes clusters locally. The provided code snippet demonstrates the command to start Minikube with specific memory, CPU, and Kubernetes version settings, as well as addition...
```python def generate_minikube_start_command(memory, cpus, kubernetes_version, cert_file, key_file): # Validate inputs if not isinstance(memory, int) or memory <= 0: return "Memory should be a positive integer." if not isinstance(cpus, int) or cpus <= 0: return "CPUs should be a positive in...
magicoder
python
You are tasked with creating a Python program to simulate a simple banking system. The program should allow users to create accounts, deposit funds, withdraw funds, and check their balance. Additionally, the program should be able to handle multiple accounts and perform basic validation checks. Your task is to impleme...
```python class BankAccount: def __init__(self, account_number, initial_balance): self.account_number = account_number self.balance = initial_balance def deposit(self, amount): if amount > 0: self.balance += amount else: print("Invalid deposit amount") ...
magicoder
python
You are tasked with creating a password validation system for a web application using Django. The system should enforce a set of password validation rules, including common password checks, numeric password checks, and a custom validation rule for the minimum number of symbols. Your task is to implement a custom Djang...
```python # Custom validator for minimum number of symbols from django.core.exceptions import ValidationError from django.utils.translation import gettext as _ import re class MinimumNumberOfSymbolsValidator: def __init__(self, min_symbols=2): self.min_symbols = min_symbols def validate(self, password...
magicoder
python
You are tasked with implementing a simple web application framework in Java. The framework consists of an `Engine` class and a method to handle HTTP requests. The `Engine` class has a static method `instance()` that returns an instance of the `Engine` class. The `Engine` instance is stored in the application's servlet...
```java import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Engine { private static final String KEY_ENGINE = "engine"; private static Engine engineInstance; private Engine() { // Private constructor to pre...
magicoder
java
You are tasked with creating a program that analyzes the distribution of words in a given text file. Your program should read a text file and output the frequency of each word in the file, sorted in descending order based on their frequency. For the purpose of this problem, a word is defined as a sequence of characters...
```python import re from collections import Counter def read_stop_words(stop_words_file): with open(stop_words_file, 'r') as file: stop_words = file.read().split() return stop_words def analyze_text(text_file, stop_words_file): stop_words = read_stop_words(stop_words_file) with open(text_file,...
magicoder
python
You are tasked with creating a Python function that manages logging for a given file. The function should remove the file if it already exists, create a logger, set its level to DEBUG, and add two handlers - one for logging to a file and another for logging to the standard output. The log messages should be formatted i...
```python import os import logging def setup_logger(name: str) -> logging.Logger: if os.path.exists(name): os.remove(name) logger = logging.getLogger(name) logger.setLevel(logging.DEBUG) # handler for logger file handler1 = logging.FileHandler(name) handler1.setFormatter(logging.Formatt...
magicoder
python
You are given a code snippet representing a data structure used to store information about particle tracks in a physics experiment. The snippet shows the structure of the `fTracks` object, which contains various arrays and nested arrays to store different types of data. Your task is to write a function that processes t...
```cpp #include <iostream> struct Tracks { float fTArray[3][3]; struct TriggerBits { uint8_t fAllBits[3][3]; uint32_t fBits[3]; uint32_t fNbits[3]; } fTriggerBits; }; int countTriggerBits(const Tracks& fTracks) { int totalTriggerBits = 0; for (int i = 0; i < 3; i++) { ...
magicoder
cpp
You are tasked with implementing a simple module system for a 3D graphics application. The application should support modules for handling cameras and generating histograms. The provided code snippet shows the initial module structure with two modules: `camera` and `histogram`. Your task is to extend the module system...
```rust // camera.rs pub struct Camera { position: (f64, f64, f64), orientation: (f64, f64, f64), field_of_view: f64, } impl Camera { pub fn new(position: (f64, f64, f64), orientation: (f64, f64, f64), field_of_view: f64) -> Self { Camera { position, orientation, ...
magicoder
rust
You are given a list of integers representing the difficulty levels of programming problems. Each difficulty level is a positive integer. Your task is to find the percentage of problems that are classified as "Hard," where a problem is considered hard if its difficulty level is greater than or equal to 40. Write a fun...
```python from typing import List def hardProblemPercentage(difficulty_levels: List[int]) -> float: hard_count = sum(1 for level in difficulty_levels if level >= 40) percentage = (hard_count / len(difficulty_levels)) * 100 return round(percentage, 2) ```
magicoder
python
You are tasked with implementing a program that processes and visualizes image masks using the OpenCV library in Python. The program should perform the following tasks: 1. Display the "mask1" image using the `cv2.imshow` function and wait for 3000 milliseconds before closing the window. 2. Visualize the "ppp" image by...
```python import cv2 import numpy as np # Load the "mask1" image mask1 = cv2.imread("mask1.jpg") # Display the "mask1" image for 3000 milliseconds cv2.imshow("mask1", mask1) cv2.waitKey(3000) cv2.destroyAllWindows() # Load the "ppp" image ppp_image = cv2.imread("ppp.jpg") # Scale the "ppp" image scaled_ppp_image = ...
magicoder
python
You are tasked with implementing a custom dependency injection framework in Java. The framework should support the `@Resource` annotation for injecting dependencies into classes. The `@Service` annotation should mark classes as services that can be injected into other classes. Your task is to complete the implementati...
```java import java.lang.reflect.Field; class DependencyInjector { private ServiceRegistry serviceRegistry; public DependencyInjector(ServiceRegistry serviceRegistry) { this.serviceRegistry = serviceRegistry; } public void injectDependencies(Object instance) { Class<?> instanceClass =...
magicoder
java
You are tasked with creating a custom web component for displaying advertisements using the Stencil.js framework. The code snippet provided is a part of the component definition in Stencil.js, which is a popular tool for building web components using modern web standards. Your task is to complete the implementation of...
```typescript import { Component, h } from '@stencil/core'; @Component({ tag: 'app-admob', styleUrl: 'app-admob.scss', shadow: true, }) export class AppAdmob { // Define properties to handle advertisement data @Prop() adId: string; @Prop() adType: string; // Method to load and display the advertisement ...
magicoder
typescript
You are tasked with creating a custom layer for a neural network model in Python using the Keras library. The custom layer should implement a simplified version of the Conditional Random Field (CRF) layer, which is commonly used in sequence labeling tasks such as named entity recognition and part-of-speech tagging. Yo...
```python import tensorflow as tf from tensorflow.keras import layers class CustomCRFLayer(layers.Layer): def __init__(self, num_labels, sparse_target=True): super(CustomCRFLayer, self).__init__() self.num_labels = num_labels self.sparse_target = sparse_target def build(self, input_sha...
magicoder
python
You are working on a computer vision project and need to implement a function to interpolate pixel values from an image based on a set of landmarks. The landmarks are represented as a numpy array and need to be flipped along the horizontal axis before interpolation. The interpolated values, along with vertex indices an...
To solve this problem, you can use the following code: ```python import torch import numpy as np def interpolate_from_landmarks(image, landmarks): landmarks = torch.from_numpy(landmarks).flip(dims=(-1,)) # Perform flipping of landmarks along the horizontal axis using PyTorch # Implement the interpolation...
magicoder
python
You are tasked with creating a Python function that parses a given setup.py file and extracts specific information from it. The setup.py file is used in Python projects to define the project's metadata and dependencies. Your function should extract the following information from the setup.py file: 1. List of supported ...
```python import re def parse_setup_file(file_path): with open(file_path, 'r') as file: setup_content = file.read() python_versions = re.findall(r"'Programming Language :: Python :: (\d\.\d)'", setup_content) keywords = re.findall(r"keywords='([^']*)'", setup_content)[0].split() packages = re....
magicoder
python
You are tasked with implementing a file hashing program in Python. The program should read a file in chunks, calculate the MD5 and SHA1 hashes of the file, and then print the hashes in hexadecimal format. Your task is to complete the `calculate_file_hashes` function, which takes a file path as input and returns a dict...
```python import hashlib def calculate_file_hashes(file_path: str) -> dict: BUF_SIZE = 65536 # Read file in 64KB chunks md5 = hashlib.md5() sha1 = hashlib.sha1() with open(file_path, 'rb') as f: while True: data = f.read(BUF_SIZE) if not data: break ...
magicoder
python
You are tasked with implementing a Java class that manages a list of items using the Canoo Platform Remoting framework. The class should provide methods to add, remove, and retrieve items from the list, and it should notify observers of any changes to the list. Your task is to complete the implementation of the `ItemM...
```java package com.canoo.dp.impl.server.gc; import com.canoo.platform.remoting.ObservableList; import com.canoo.platform.remoting.RemotingBean; import org.apiguardian.api.API; @RemotingBean public class ItemManager { private ObservableList<String> items; public ItemManager() { items = new Observabl...
magicoder
java
You are tasked with implementing a function that generates all possible paths in a given graph from a starting node to an ending node. The graph is represented using an adjacency list, where each node is associated with a list of its neighboring nodes. The function should take the graph, the starting node, and the endi...
```python def all_paths(graph, start, end): def find_paths(current, end, path, visited, all_paths): visited[current] = True path.append(current) if current == end: all_paths.append(path.copy()) else: for neighbor in graph[current]: if not visit...
magicoder
python
You are tasked with creating a web application feature that allows users to add a reminder for products that are out of stock. The code snippet provided is a part of the backend logic for adding a reminder when a product is out of stock. The `add_reminder` function is called when a user submits a request to add a remi...
```python from django.http import JsonResponse from django.utils.translation import ugettext as _ from django.core.exceptions import ValidationError from django.forms.models import model_to_dict def add_reminder(request): if request.is_ajax(): data = json.loads(request.body.decode('utf-8')) form = ...
magicoder
python
You are tasked with implementing a binary search tree (BST) and its associated operations. A binary search tree is a data structure that satisfies the binary search property: for any node `n`, all nodes in its left subtree have values less than `n`, and all nodes in its right subtree have values greater than `n`. You n...
```python class Node: def __init__(self, key): self.key = key self.left = None self.right = None class BinarySearchTree: def __init__(self): self.root = None def populate_tree(self, values): for value in values: self.root = self._insert(self.root, value)...
magicoder
python
You are tasked with implementing a function to rebuild a data source for a navigation app. The function should check if the current step and leg in the route progress have been processed, and if not, it should rebuild the data source by adding the remaining steps for the current leg. The given code snippet is the begi...
```swift func rebuildDataSourceIfNecessary(routeProgress: RouteProgress, previousLegIndex: Int, previousStepIndex: Int, dataSource: DataSource) -> Bool { let legIndex = routeProgress.legIndex let stepIndex = routeProgress.currentLegProgress.stepIndex let didProcessCurrentStep = previousLegIndex == legIndex ...
magicoder
swift
You are tasked with implementing a class hierarchy for handling different types of events in a software system. The provided code snippet is a partial class definition for a class named `BlobEventInit`, which inherits from another class named `EventInit`. Your goal is to complete the class definition for `BlobEventInit...
```csharp public partial class BlobEventInit : EventInit { public string BlobName { get; set; } public long BlobSize { get; set; } public string BlobType { get; set; } public BlobEventInit(string blobName, long blobSize, string blobType) { BlobName = blobName; BlobSize = blobSize; ...
magicoder
csharp
You are tasked with implementing a function that converts a callable object to a function pointer. A callable object is any object that can be called as a function, such as a function pointer, a function object, or a lambda function. The function pointer should have the same signature as the callable object. You are g...
```cpp #include <iostream> // Define a helper struct to extract the function pointer type from a callable object template <typename T> struct function_pointer_traits; // Specialization for function pointers template <typename ReturnType, typename... Args> struct function_pointer_traits<ReturnType (*)(Args...)> { ...
magicoder
cpp
You are given a code snippet that sets the values of a rectangle `r` based on the state of an animation. The rectangle `r` has four properties: `left`, `top`, `right`, and `bottom`. The animation state is represented by the variable `p.animationState`. When `p.animationState` is 4, the rectangle's properties are set as...
```python from typing import Tuple def calculate_rectangle_properties(animation_state: int, f: int) -> Tuple[int, int, int, int]: TS = 10 # Example value for TS, replace with actual value maxf = 8 # Example value for maxf, replace with actual value delay = 35 # Example value for delay, replace with actu...
magicoder
python
You are tasked with implementing a Python function that parses a JSON object and constructs an EPG (Electronic Program Guide) object from the provided data. The EPG object contains information about a TV program schedule. The EPG class has a method to convert the object to a dictionary, and a class method to construct ...
```python def epg_from_dict(s: Any) -> Epg: tv_data = s.get("tv") # Extract the TV data from the input JSON object tv_obj = Tv.from_dict(tv_data) # Construct a TV object from the extracted data epg_obj = Epg(tv_obj) # Construct an EPG object using the TV object return epg_obj # Return the constructe...
magicoder
python
You are working on a user authentication system that uses various hashing algorithms to store and verify passwords. One of the methods used is the PBKDF2 algorithm with SHA-256, and another is the salted SHA-1 algorithm. You need to implement a function to check the validity of a password against the stored hash and an...
```python import hashlib import hmac import os class ldap_pbkdf2_sha256: @staticmethod def identify(hash): return hash.startswith('pbkdf2_sha256$') @staticmethod def verify(password, hash): iterations, salt, stored_hash = hash.split('$')[1:] iterations = int(iterations) ...
magicoder
python
You are working with a serverless computing platform where you need to update actions and sequences using a command-line tool called `wsk`. The provided code snippet contains a series of commands that update actions and sequences with specific projections and sequences. Your task is to understand the sequence of comman...
The provided code snippet contains a series of commands that update actions and sequences using the `wsk` command-line tool. To determine the final sequence of actions created, we need to analyze the commands and their effects. 1. The first command updates an action named `Proj_hol4EgN5e4` with a projection specified ...
magicoder
python
You are tasked with creating a Python function that extracts and processes IPv4 addresses from a set of LXC (Linux Containers) configuration files. The code snippet provided serves as a starting point for this task. Your function should take the directory path where the LXC configuration files are located as input and ...
```python import glob import re def extract_ipv4_addresses(lxc_dir): cipv4s = [] pattern = 'lxc.network.ipv4 = ' for i in glob.glob('{0}/*/config'.format(lxc_dir)): with open(i) as fic: lines = fic.readlines() cipv4s.extend([a.split(pattern, 1)[1].strip() ...
magicoder
python
You are tasked with implementing a credit risk modeling system for a financial institution. The system involves defining various assumptions for different segments of the institution's loan portfolio. Each segment has specific assumptions for Probability of Default (PD), Exposure at Default (EAD), Loss Given Default (L...
```python class PDAssumptions: def __init__(self, pd_value: float): self.pd_value = pd_value class EADAssumptions: def __init__(self, ead_value: float): self.ead_value = ead_value class LGDAssumptions: def __init__(self, lgd_value: float): self.lgd_value = lgd_value class EIRAssum...
magicoder
python
You are tasked with implementing a Python class for factor covariance calculation. The class should incorporate spatial and cross covariance functions to compute the covariance matrix for a given number of output dimensions. The spatial covariance function is based on the Matern 3/2 model, while the cross covariance fu...
```python import numpy as np class Matern32: def __init__(self, lmbda, sigma): self.lmbda = lmbda self.sigma = sigma def covariance(self, x1, x2): r = np.linalg.norm(x1 - x2) return self.sigma**2 * (1 + np.sqrt(3) * r / self.lmbda) * np.exp(-np.sqrt(3) * r / self.lmbda) class ...
magicoder
python
You are tasked with creating a Python program that processes a list of video files and extracts specific information from them. The program should read a list of video file names from a text file and then locate and process the corresponding video files in a specified directory. The extracted information should be used...
```python import os import subprocess # Read the list of video file names from the file specified in DATA_SPLIT with open(DATA_SPLIT, 'r') as file: video_files = file.read().splitlines() # Locate the corresponding video files in the directory specified in VIDEO_DIR video_files_path = [os.path.join(VIDEO_DIR, file...
magicoder
python
You are tasked with implementing a simple interpreter for a custom programming language. The language supports variables, expressions, and error handling for undefined variables. Your task is to write a function that takes in a recipe, a set of variable assignments, and a text input, and returns the result of interpret...
```rust use std::collections::HashMap; struct Variable { lexeme: String, // Other variable properties } struct CompilationError { index: usize, // Other error properties } struct UndefinedVariable { variable: String, } struct Expression { // Expression properties fn variables(&self) -> V...
magicoder
rust
You are tasked with creating a Python program that simulates a simple text-based game. The game involves a character navigating through a grid-based world, collecting treasures, and avoiding obstacles. The character's movements are controlled using the arrow keys on the keyboard. Your task is to implement the key input...
```python import pygame class Game: def __init__(self): self.character_position = [0, 0] # Initial position of the character self.grid_size = (10, 10) # Size of the game grid self.mod_bits = [ (pygame.KMOD_ALT, 'A'), (pygame.KMOD_CTRL, 'C'), (pygame.KMO...
magicoder
python
You are tasked with implementing a simplified version of a buffered I/O system in Rust. The provided code snippet contains a test case for the `write_buf_flatten` function, which is part of the buffered I/O system. Your task is to complete the implementation of the `AsyncIo` struct and its associated methods to support...
```rust struct WriteQueue { bufs: Vec<Vec<u8>>, } struct WriteBuffer { queue: WriteQueue, } impl WriteBuffer { fn new() -> WriteBuffer { WriteBuffer { queue: WriteQueue { bufs: Vec::new() }, } } fn flatten(&mut self) { let mut flattened: Vec<u8> = Vec::new(); ...
magicoder
rust
You are tasked with creating a Python class that simulates a simple state machine for controlling a robotic system. The state machine will transition between different states based on the success or failure of specific actions. Your task is to implement the state machine class and define the states and transitions as d...
```python import smach import rospy import pole # Assuming the pole module is available class RobotStateMachine: def __init__(self): self.machine = smach.StateMachine(outcomes=['preempted', 'success', 'failure']) with self.machine: smach.StateMachine.add('DRIFT', smach.CBState(self.dri...
magicoder
python
You are tasked with implementing a custom error type and handling it within a Rust function. The provided code snippet is a method signature and an error return statement from the `otspec` crate, which is used for working with OpenType font files. The method signature indicates that the function takes a reference to `s...
```rust use std::error::Error; use std::fmt; // Define a custom error type #[derive(Debug)] struct CustomError(String); impl fmt::Display for CustomError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Custom Error: {}", self.0) } } impl Error for CustomError {} // Implement the ...
magicoder
rust
You are tasked with implementing a method to determine the super categories of a finite dimensional Hopf algebra with a basis. A finite dimensional Hopf algebra is a mathematical structure with both algebraic and coalgebraic properties, and a basis is a set of linearly independent vectors that span the space. The metho...
```python def super_categories(self): """ Return the super categories of the finite dimensional Hopf algebra with a basis. Returns: list: A list of categories to which the Hopf algebra belongs. EXAMPLES: :: sage: FiniteDimensionalHopfAlgebrasWithBasis(QQ).super_categories() ...
magicoder
python
You are tasked with implementing a generic data structure in Rust that supports a specific set of operations. The data structure is a singly linked list with a twist: it allows for constant-time access to the first and last elements, as well as constant-time insertion and removal at both ends. To achieve this, you need...
```rust struct Node<T> { value: T, next: Option<Box<Node<T>>>, } pub struct ConstantTimeList<T> { head: Option<Box<Node<T>>>, tail: *mut Node<T>, } impl<T> ConstantTimeList<T> { pub fn new() -> Self { ConstantTimeList { head: None, tail: std::ptr::null_mut(), ...
magicoder
rust
You are tasked with implementing a Swift program that involves working with protocols and type aliases. Your goal is to create a protocol hierarchy and define type aliases to conform to these protocols. Given the following code snippet as a starting point: ``` // Licensed under Apache License v2.0 with Runtime Library...
```swift protocol P {} protocol A { associatedtype e } typealias a = A protocol B: A {} // Definition of protocol B that inherits from protocol A typealias X = a // Creation of a type alias X that conforms to protocol B ``` In the solution, we first define the protocol `B` that inherits from protocol `A`. Then...
magicoder
swift
You are given a grid representing a maze, where 0 denotes an open cell and 1 denotes a blocked cell. The grid is represented as a 2D list of integers. Your task is to write a function `count_valid_paths(grid)` that calculates the number of valid paths from the top-left corner to the bottom-right corner of the grid. A v...
```python from typing import List def count_valid_paths(grid: List[List[int]]) -> int: rows, cols = len(grid), len(grid[0]) def traverse_grid(i=0, j=0): if i > rows - 1 or j > cols - 1 or grid[i][j] == 1: return 0 if i == rows - 1 and j == cols - 1: return 1 ret...
magicoder
python
You are tasked with implementing a custom settings manager for a software application. The settings manager should be able to handle user-specific settings and provide a default instance for global settings. Your task is to create a class that encapsulates this functionality and allows for easy access to both user-spec...
```csharp using System.Configuration; public class CustomSettingsManager : ApplicationSettingsBase { private static CustomSettingsManager defaultInstance = (CustomSettingsManager)Synchronized(new CustomSettingsManager()); public static CustomSettingsManager Default { get { return defaultInstance; ...
magicoder
csharp
You are tasked with implementing a PDF merging functionality using Python. Your task is to create a class that can merge multiple PDF files based on a common identifier. The class should provide a method to perform the merging operation. You are given a code snippet that initializes an object of the `Merger` class and...
```python from PyPDF2 import PdfReader, PdfWriter class Merger: def joinpdf(self, pdf_files, merger_obj, file_type): merged_pdf = PdfWriter() common_id = None for file_path in pdf_files: with open(file_path, 'rb') as file: pdf = PdfReader(file) i...
magicoder
python
You are tasked with creating a function that parses an HTML form and extracts information about the input elements present in the form. The function should take the HTML code of the form as input and return a list of dictionaries, where each dictionary represents an input element and contains its attributes. For the p...
```python import re def parse_input_elements(html_code): input_elements = re.findall(r'<input(.*?)>', html_code) parsed_elements = [] for element in input_elements: attributes = re.findall(r'(\S+)=["\'](.*?)["\']', element) element_dict = {} for attr in attributes: eleme...
magicoder
python
You are tasked with implementing a module-based client library manager service in Java. The `ClientLibManagerService` interface provides a method `getModuleBasedClientLibServices()` that returns a list of `ModuleBasedClientLibService` instances. Your goal is to create a concrete implementation of this interface and wri...
```java import java.util.ArrayList; import java.util.List; public interface ClientLibManagerService { List<ModuleBasedClientLibService> getModuleBasedClientLibServices(); } public interface ModuleBasedClientLibService { String getModuleName(); // Other methods and properties can be assumed to exist } pub...
magicoder
java
You are tasked with creating a program that simulates a simplified version of a process manager. The program should be able to start and manage multiple processes concurrently. Each process will be represented by a unique identifier and will have a specific set of properties associated with it. Your task is to implemen...
```python from typing import List, Tuple class ProcessManager: def __init__(self): self.processes = {} self.next_id = 1 def start_process(self, process_name: str) -> int: process_id = self.next_id self.processes[process_id] = process_name self.next_id += 1 retur...
magicoder
python
You are tasked with creating a simple routing system for a web application using PHP. Your goal is to implement a basic router class that can match incoming HTTP requests to specific routes and execute the corresponding controller action. You are provided with a skeleton code for the router class, along with the defin...
```php use Psr\Http\Message\ResponseInterface; use Laminas\Diactoros\ServerRequest; use Laminas\Diactoros\Uri; class Router { private $routes = []; public function addRoute($method, $uri, $controller) { $this->routes[$method][$uri] = $controller; } public function matchRequest(ServerReque...
magicoder
php
You are tasked with implementing a genetic algorithm to optimize a specific problem. The genetic algorithm involves the use of mutation, crossover, and selection to evolve a population of candidate solutions over multiple generations. Your task is to implement the mutation operation for the genetic algorithm. You are ...
```python import random def mutate_individual(individual, mutation_rate): mutated_individual = list(individual) # Create a copy of the individual to avoid modifying the original for i in range(len(mutated_individual)): if random.random() < mutation_rate: # Check if the mutation should occur based on ...
magicoder
python
You are tasked with creating a Python class that manages event listeners and handles WebSocket connections. Your class, `EventManager`, should have the following functionalities: 1. Registering event listeners: The class should allow registering callback functions to be executed when an event occurs. 2. Handling WebS...
```python import asyncio import json import logging import websockets _LOGGER = logging.getLogger(__name__) class EventManager: def __init__(self): self._evt_listeners_ = [] def register_listener(self, callback): self._evt_listeners_.append(callback) async def connect_websocket(self, url...
magicoder
python
You are given a Python code snippet that manipulates a hierarchical data structure represented by nested dictionaries and lists. Your task is to understand the code and implement a function that performs the same operations as the code snippet. The code snippet is designed to handle a path within the hierarchical data...
```python def handle_path(hmap, path, next_element_type) -> dict: if len(path) == 1: return hmap, path[0] if isinstance(path[1], int): next_element_type = list if isinstance(path[0], int) and isinstance(hmap, list): while len(hmap) < path[0]: hmap.append(None) if ...
magicoder
python
You are tasked with implementing a connection pool manager for a network application. The connection pool manager is responsible for acquiring, validating, and destroying connections to a remote server. The code snippet provided is a part of the connection pool manager's logic. The `ThrowConnectionAcquisitionTimedOutEx...
```csharp using System; using System.Threading.Tasks; public class ConnectionAcquisitionTimedOutException : Exception { public ConnectionAcquisitionTimedOutException(string message) : base(message) { } } public class ConnectionPoolManager { private readonly ConnectionValidator _connectionValidator; publi...
magicoder
csharp
You are tasked with creating a Python module that mimics the behavior of a command-line tool called "Opy." The module should provide a function called `run` that simulates the command-line activation without starting a new interpreter. The `run` function should accept strings as parameters, which would normally be the ...
```python import sys def run(*args): # Mimic the behavior of Opy command line tool # Perform the necessary operations based on the provided command-line arguments # For the purpose of this example, let's assume some sample behavior normal_report = "Sample normal report" error_report = "Sample ...
magicoder
python
You are tasked with creating a Python function that simulates a simple file system navigation system. Your function should take a list of commands as input and return the final directory structure after executing the commands. The commands will be in the form of strings, where each string represents a command to be ex...
```python def simulate_file_system(commands): current_path = "/" directory_structure = {"/": []} for command in commands: if command.startswith("mkdir"): directory_name = command.split()[1] directory_structure[current_path].append(directory_name) directory_struct...
magicoder
python
You are working on a debugging tool for a multi-threaded application. The code snippet provided is a part of a debugger script written in a custom scripting language. The script interacts with a debugger object to retrieve information about the currently selected target, process, thread, and frame. It then evaluates ex...
```python def evaluate_debugger_expression(target, process, thread, frame, expressions): result = {} for expr in expressions: value = None if expr.startswith("v8::internal::Isolate::Current()->thread_local_top()->js_entry_sp_"): value = frame.EvaluateExpression(expr).GetValue() ...
magicoder
python
You are tasked with implementing a Java class that represents a person's name. The class should provide methods for setting and getting the first name, last name, and full name of the person. Additionally, the class should include a method to generate a username based on the person's first name and last name. Your tas...
```java package org.appdapter.peru.core.name; public class PersonName { private String firstName; private String lastName; public void setFirstName(String firstName) { this.firstName = firstName; } public String getFirstName() { return firstName; } public void setLastName...
magicoder
java
You are tasked with creating a Python function that simulates the performance testing of a ledger component with a varying size of key-value pairs using a specific state database. The function should measure the time taken to complete a set number of ledger operations and determine if the performance meets the passing ...
```python import time def performance_test(state_database, key_value_sizes, num_operations): performance_results = {} passing_criteria_met = True for size in key_value_sizes: # Simulate ledger operations with varying key-value sizes using the specified state database start_time = time.time...
magicoder
python
You are tasked with implementing a function that calculates the area of a shadow cast by a given UIView. The shadow is created using the `dropShadow` method, which takes in parameters for color, opacity, offset, and radius. You are provided with the following information: - The `dropShadow` method is called on a UIView...
```swift func calculateShadowArea(initialHeight: CGFloat) -> CGFloat { // Constants for shadow parameters let shadowOpacity: CGFloat = 0.05 let shadowOffset = CGSize(width: 0, height: 3) let shadowRadius: CGFloat = 5 // Calculate the area of the shadow using the formula for the area of a shadow...
magicoder
swift
You are tasked with creating a program that simulates the setup and communication with a hidden service on the Tor network. In the Tor network, hidden services are accessed through randomly generated .onion addresses and provide a way for services to be hosted anonymously. The provided code snippet shows a relevant con...
```python import stem.process import socket import requests # Start Tor process tor_process = stem.process.launch_tor_with_config( config = { 'HiddenServiceDir': './hidden_service/', 'HiddenServicePort': '80 127.0.0.1:53415' } ) # Get the generated .onion address with open('./hidden_service/ho...
magicoder
python
You are tasked with creating a program that processes a given source file and generates a destination file based on certain rules. The source file contains a list of words and their corresponding phonetic representations. The program should read the source file, process the data, and write the results to a destination ...
```python import codecs def main(): src_lexicon = "source_lexicon.txt" # Replace with the actual source file path dst_lexicon = "destination_lexicon.txt" # Replace with the actual destination file path unit2id = {"pronunciation1": "id1", "pronunciation2": "id2"} # Replace with the actual predefined dict...
magicoder
python
You are tasked with implementing a file manager class in JavaScript that provides methods for listing files in a directory and creating a singleton instance of the file manager. Your task is to complete the implementation of the FileManager class by adding the following methods: 1. `listFiles(path)`: This method shoul...
```javascript import fs from 'fs'; class FileManager { static instance = null; async listFiles(path) { return new Promise((resolve, reject) => { fs.readdir(path, (err, files) => { if (err) { reject(err); } else { resolve(files); } }); }); } stat...
magicoder
javascript
You are tasked with simulating a simple volume control system for a multimedia device. The system has a class `VolumeDevice` that represents the device's volume control. The class has methods `increase()` and `decrease()` to adjust the volume level. Additionally, there is a function `volume_down()` that decreases the s...
```python class VolumeDevice: def __init__(self): self.volume_level = 50 def increase(self): self.volume_level = min(self.volume_level + 10, 100) def decrease(self): self.volume_level = max(self.volume_level - 10, 0) def volume_down(): """ Decrease system volume by trigger...
magicoder
python
You are tasked with implementing a custom event handling system in Java. Your goal is to create a class that allows other classes to register event handlers and trigger events. The event handling system should be able to handle multiple types of events and allow for the registration of multiple handlers for each event ...
```java import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Consumer; public class CustomEventSource { private Map<String, EventHandlers> eventHandlersMap = new HashMap<>(); public void addEventHandler(String eventType, Consumer<Object> ...
magicoder
java
You are tasked with implementing a function that generates a unique identifier for a financial transaction record. The function takes a `Transaction` object as input, which has the following attributes: - `date`: the date of the transaction - `amount`: the amount of the transaction - `trntype`: the type of transaction ...
```python import hashlib class Transaction: def __init__(self, date, amount, trntype, payee, memo): self.date = date self.amount = amount self.trntype = trntype self.payee = payee self.memo = memo self.id = None def generate_transaction_id(transaction): h = hash...
magicoder
python
You are tasked with implementing a Python class that interacts with a Gearman job server. Gearman is a system to farm out work to other machines or processes, and this class is responsible for submitting jobs to the server, retrieving job results, and shutting down the connection. Your task is to complete the implemen...
```python import json class GearmanClient: def __init__(self, gearman): self.gearman = gearman def submit_job(self, function_name, data): job_request = self.gearman.submit_job(function_name, json.dumps(data)) return job_request.job_handle def get_job_result(self, job_handle): ...
magicoder
python
You are tasked with implementing a Python class that simulates a simple database query builder. The class, `QueryBuilder`, is responsible for constructing and modifying database queries. Your task is to complete the implementation of the `QueryBuilder` class by adding the necessary methods to support query building ope...
```python from unittest.mock import Mock class QueryBuilder: def __init__(self, model): self._model = model self._or_invoked = False def filter(self, filter_fn): # Apply the provided filter function to the query # (Assuming filter_fn is a function that modifies the query) ...
magicoder
python
You are tasked with creating a custom error handling system for a new programming language. The system should allow developers to define foreign links to external error types and provide a mechanism for handling these errors within the language. Your task is to implement a data structure and associated methods to mana...
```rust struct ForeignErrorLinks { links: std::collections::HashMap<String, String>, } impl ForeignErrorLinks { fn new() -> Self { ForeignErrorLinks { links: std::collections::HashMap::new(), } } fn add_link(&mut self, link_name: &str, link_type: &str) { self.links....
magicoder
rust