query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with creating a Python function that processes a file containing hexadecimal data and performs a specific transformation on the data. Your task is to implement the `clean_hex_output` function, which takes a string of hexadecimal bytes as input and returns a modified version of the input string. The `cle...
```python def clean_hex_output(hex_bytes): raw_crypt_bytes = b"" for byte in hex_bytes.split(): byte = byte.replace("0x", '') # Remove leading "0x" byte = byte.replace(",", '') # Remove commas if len(byte) == 1: raw_crypt_bytes += bytes.fromhex(byte) # Single digit byte,...
magicoder
python
You are tasked with creating a program to analyze and display information about the available video displays and their display modes using the SDL (Simple DirectMedia Layer) library. The SDL library provides functions to retrieve information about video displays and their display modes. Your program should retrieve an...
```cpp #include <SDL.h> #include <sstream> #include <iostream> std::string getDisplayInformation() { std::stringstream stream; int numDisplays = SDL_GetNumVideoDisplays(); for (int d = 0; d < numDisplays; ++d) { const char* displayName = SDL_GetDisplayName(d); if (displayName) {...
magicoder
cpp
You are tasked with implementing a function to find the maximum depth of a binary tree. The binary tree is represented as a series of nested nodes, and the depth of a node is defined as the number of edges from the node to the tree's root node. The depth of the tree is the maximum depth of all the nodes in the tree. Y...
```cpp int maxDepth(TreeNode* root) { if (root == nullptr) { return 0; } int left_depth = maxDepth(root->left); int right_depth = maxDepth(root->right); return 1 + std::max(left_depth, right_depth); } ``` The provided solution implements the `maxDepth` function using a recursive approach. It checks if th...
magicoder
cpp
You are tasked with implementing a discount policy workflow system for a retail application. The system should apply various discount rules based on specific conditions and calculate the final discounted price for a given item. You are provided with a partial code snippet for the `DiscountPolicyWorkflow` class, which ...
```csharp using System; using System.Collections.Generic; public sealed partial class DiscountPolicyWorkflow { private bool CanModifyActivities { get; set; } private List<DiscountRule> discountRules; public DiscountPolicyWorkflow() { CanModifyActivities = true; discountRules = new List...
magicoder
csharp
You are tasked with implementing a method to remove a specific node from a scene graph. A scene graph is a data structure used to organize and represent the objects in a graphical scene. Each node in the scene graph may have children nodes, forming a hierarchical structure. Your task is to write a function that removes...
```python class SceneGraph: def __init__(self, root): self.root = root def get_root(self): return self.root def remove_node(self, node): if node == self.root: self.root = None else: parent = self._find_parent(self.root, node) if parent: ...
magicoder
python
You are tasked with creating a Python function that manages Tmux sessions. Tmux is a terminal multiplexer that allows multiple terminal sessions to be accessed and controlled from a single window. Your function should handle the scenario where no Tmux sessions exist and then invoke another function to add a new session...
```python def manage_tmux_sessions(ctx): if ctx.invoked_subcommand is None: sessions = tm.tmux_sessions() if len(sessions) <= 0: return ctx.invoke(add) ``` In the solution, the `manage_tmux_sessions` function checks if a subcommand has been invoked. If not, it retrieves the list of exist...
magicoder
python
You are tasked with creating a Python function that processes a list of integers and returns the maximum difference between any two elements in the list. The difference is calculated by subtracting the smaller integer from the larger one. If the list contains fewer than two elements, the function should return 0. Your...
```python def max_difference(nums): if len(nums) < 2: return 0 else: return max(nums) - min(nums) ```
magicoder
python
You are tasked with creating a messaging system for a social media platform. The system should generate random messages from a specified number of allowed senders and store them in a collection. Additionally, the system should disable custom messages by setting a flag in the user defaults. Your task is to implement the...
```swift func getMessages(count: Int, allowedSenders: [MockUser], completion: ([MockMessage]) -> Void) { var messages: [MockMessage] = [] // Disable Custom Messages UserDefaults.standard.set(false, forKey: "Custom Messages") for _ in 0..<count { let uniqueID = UUID().uuidString let user ...
magicoder
swift
You are tasked with implementing a function to determine whether a user's heading and an item's heading meet certain criteria for a grid visor orientation system. The grid visor orientation system has a maximum threshold for the item's heading and a minimum threshold for the user's heading. You need to write a function...
```swift func checkVisorOrientation(itemHeading: Float, userHeading: Float) -> Bool { let itemMaxThreshold: Float = MGridVisorOrientation.kItemMaxThreshold let userMinThreshold: Float = MGridVisorOrientation.kMinThreshold if (itemHeading < itemMaxThreshold) && (userHeading < 0 && userHeading > userMinT...
magicoder
swift
You are tasked with implementing a class that calculates probabilities using Bayes' theorem and odds ratios. The class should have the following methods: 1. `constructor(favor: number, against: number)`: A constructor that takes in two numbers representing the count of favorable outcomes and the count of unfavorable o...
```typescript class ProbabilityCalculator { favor: number; against: number; constructor(favor: number, against: number) { this.favor = favor; this.against = against; } static BayesRule(prior: Odds, likelihood: Odds): number { const posteriorProbability = (prior.value * like...
magicoder
typescript
You are tasked with implementing a custom data structure that represents a functional programming concept. The structure should support various operations and functionalities related to functional programming. Your task is to design and implement a class or module that encapsulates this functionality. Your custom data...
```python class FunctionalDataStructure: def __init__(self, brackets, sep, cnull, cunit, functions): self.brackets = brackets self.sep = sep self.cnull = cnull self.cunit = cunit self.functions = functions def group_expressions(self, expression): return f"{self.b...
magicoder
python
You are tasked with creating a program that processes license information for a software package. The license information is stored in a file named "LICENSE.txt" and contains the terms of the MIT License. Your program needs to read the "LICENSE.txt" file and extract specific details from the license text. The MIT Lice...
```python def extract_license_details(file_path): with open(file_path, 'r') as file: license_text = file.read() # Extracting the type of license license_type = license_text.split(' ')[0] # Assuming the license type is the first word in the text # Extracting permissions, conditions, and limita...
magicoder
python
You are tasked with implementing a nested dictionary data structure and its associated methods. The data structure should support setting and getting values at multiple levels of nesting. The `set` method should allow setting a value at a specified nested key, and the `get` method should retrieve the value at a specifi...
```python class NestedDict: def __init__(self): self.data = {} def set(self, *keys, value): current_level = self.data for key in keys[:-1]: current_level = current_level.setdefault(key, {}) current_level[keys[-1]] = value def get(self, *keys, default=None): ...
magicoder
python
You are tasked with creating a script to automate the verification of chaincode on a blockchain network. The script should handle the verification process and provide appropriate feedback based on the outcome. Your task is to write a Bash script that verifies the specified chaincode on a given channel, using a designa...
```bash #!/bin/bash # Function to list all available chaincodes listChaincodes() { # Add code to list all available chaincodes echo "Available chaincodes: chaincode1, chaincode2, chaincode3" } # Verify the specified chaincode verifyChaincode() { chaincode=$1 version=$2 channel=$3 cli=$4 peer=$5 # Add...
magicoder
shell
You are tasked with simulating the motion of a damped harmonic oscillator using numerical methods. The motion of the oscillator is governed by the following differential equation: \[ m\frac{d^2x}{dt^2} + c\frac{dx}{dt} + kx = F(t) \] Where: - \( m \) is the mass of the oscillator - \( c \) is the damping coefficient ...
To solve the differential equation and simulate the motion of the damped harmonic oscillator, we can use the Euler method for numerical integration. The Euler method is a simple and intuitive method for solving ordinary differential equations. We can start by initializing the variables and then iteratively updating th...
magicoder
python
You are working on a project that involves processing audio signals using the librosa library in Python. Your task is to create a function that takes an audio signal as input and generates a set of feature vectors for machine learning analysis. The provided code snippet is a part of the function that processes the audi...
```python import numpy as np import librosa class FeatureExtractor: def __init__(self, FRAME_LENGTH): self.FRAME_LENGTH = FRAME_LENGTH def refFun(self, spectrogram): # Placeholder for the actual implementation of refFun # Assume the implementation is provided and can be used as is ...
magicoder
python
You are tasked with creating a custom Angular module that will handle user authentication and authorization for a web application. The module should include a service for user authentication, a guard for route authorization, and a component for user login. Your task is to complete the implementation of the `AuthModule...
```typescript // DashboardComponent implementation import { Component } from "@angular/core"; @Component({ selector: "app-dashboard", template: "<p>Welcome to the Dashboard</p>" }) export class DashboardComponent { } // AuthGuardService implementation import { Injectable } from "@angular/core"; import { CanActiva...
magicoder
typescript
You are tasked with implementing a parser for SVG image markers in Python. SVG (Scalable Vector Graphics) is an XML-based vector image format for two-dimensional graphics. The parser should extend the functionality of a base class `MarkerLayerParser` and handle the specific requirements for parsing SVG image markers. ...
```python # Complete implementation of SvgMarkerParser for parsing SVG image markers class SvgMarkerParser(MarkerLayerParser): def __init__(self, svgMarkerParser): super().__init__(svgMarkerParser) # Initialize marker configuration for SVG images shapeConfig = self.DEFAULT_MARKER_CONFIG ...
magicoder
python
You are tasked with creating a program to efficiently count the number of prime numbers within a given range using parallel processing. The provided code snippet demonstrates a parallel processing approach to count prime numbers within a specified range. Your task is to implement the `Magma.IsPrime` method and the nece...
```csharp using System; using System.Threading; using System.Threading.Tasks; public class Magma { public static bool IsPrime(int number) { if (number <= 1) return false; if (number == 2) return true; if (number % 2 == 0) return false; int boundary = (int)Math.Floor(Math.Sqrt(n...
magicoder
csharp
You are tasked with creating a Python class to simulate a simple dice game. The class should include methods for rolling the dice, calculating the total score, and checking for specific combinations. Create a class `DiceGame` with the following specifications: - The class should have a constructor that initializes a l...
```python import random class Die: def roll(self): return random.randint(1, 6) class DiceGame: def __init__(self): self.dice = [Die() for _ in range(5)] self.has_rolled = False def roll_dice(self): if not self.has_rolled: for die in self.dice: d...
magicoder
python
You are tasked with implementing a Python class that can serialize objects into a dictionary format. The class should be able to handle various data types, including simple types, sequences, and mappings. Your task is to complete the implementation of the `Serializer` class by adding the missing `serialize` method for ...
```python from collections.abc import Mapping, Sequence from collections import ChainMap from typing import Any class Serializer: def serialize(self, obj: Any) -> dict: if isinstance(obj, Sequence) and not isinstance(obj, str): return self.serialize_sequence(obj) elif isinstance(obj, Ma...
magicoder
python
You are tasked with implementing a function that reverses the order of words in a given string. The function should take a string as input and return a new string with the words in reverse order. A word is defined as a sequence of non-space characters. You are provided with a code snippet that partially implements the...
```java public class WordReverser { public static String reverseWords(String input) { String[] splitData = input.split(" "); StringBuilder reversedString = new StringBuilder(); for (int i = splitData.length - 1; i >= 0; i--) { reversedString.append(splitData[i]); if (...
magicoder
java
You are tasked with implementing a Python module that manages forms for a blood donation application. The module should include classes for login, registration, profile, and a search feature for blood donors. The given code snippet is a partial import statement from the module, indicating the classes and features that ...
```python # Implementing the missing classes class LoginForm: def __init__(self, username, password): self.username = username self.password = password def authenticate_user(self): # Implement authentication logic pass def validate_input(self): # Implement input val...
magicoder
python
You are tasked with creating a Python program that serves static web content using Trio, a friendly Python library for async concurrency and I/O. Your program should read and serve static HTML content from a package using importlib.resources (or importlib_resources for Python versions earlier than 3.7). Your program s...
```python import trio import http import h11 # HTTP/1.1 import socket import ssl import mimetypes import os import functools try: import importlib.resources as pkg_resources except ImportError: import importlib_resources as pkg_resources # Try backported to PY<37 `importlib_resources`. from . import static ...
magicoder
python
You are tasked with creating a script to automate the process of updating a software repository. The script should perform the following steps in sequence: 1. Pull the latest changes from the remote repository and rebase the current branch. 2. Merge the changes from a specified branch into the current branch. 3. Clean...
```bash #!/bin/bash # Input: branch_name branch_name=$1 # Step 1: Pull the latest changes from the remote repository and rebase the current branch git pull -r # Step 2: Merge the changes from the specified branch into the current branch git merge $branch_name # Step 3: Clean the project and rebuild it make clean &&...
magicoder
shell
You are working on a medical imaging project and need to simulate the acquisition of projection images for a 3D object using computed tomography (CT). The code snippet provided is part of a Python class that sets up the parameters for the simulation. The class has several attributes related to the imaging setup, such ...
```python import numpy as np def simulate_projection_images(center_of_rot_y, projection_angs, voxel_size_x, voxel_size_y, voxel_size_z, pixel_size_u, pixel_size_v, object_xs, object_ys): projection_images = [] for angle in projection_angs: # Simulate acquisition of projection image at the given angle ...
magicoder
python
You are tasked with implementing the `imageSmoother` function, which takes a 2D integer array representing an image as input and returns a new 2D integer array representing the smoothed image. The smoothing process involves replacing each pixel's value with the average value of the pixel and its surrounding pixels (inc...
```swift func imageSmoother(_ img: [[Int]]) -> [[Int]] { let m = img.count let n = img[0].count var result = Array(repeating: Array(repeating: 0, count: n), count: m) for i in 0..<m { for j in 0..<n { var sum = 0 var count = 0 for r in -1...1 { ...
magicoder
swift
You are tasked with implementing an AI search algorithm to solve the vacuum world problem. The vacuum world is a grid environment where an autonomous agent (the vacuum) needs to clean all the dirty cells. The agent can move in four directions (up, down, left, right) and can perform the "suck" action to clean the curren...
```python def or_search(initial_state): if vacuum_goal_test_function(initial_state): return [] # No actions needed, already at the goal state else: actions = vacuum_actions_function(initial_state) for action in actions: results = vacuum_results_function(initial_state, action...
magicoder
python
You are tasked with implementing a function that efficiently generates unique test cases for a given set of constraints. The function should take in the minimum length of the test case and the minimum number of sequences required, and then produce unique test cases that satisfy these constraints. The function should e...
```python import itertools # Define a global set to store generated test cases generated_test_cases = set() def generate_unique_test_case(minLength, minSequences): global generated_test_cases # Generate all possible combinations of sequences with the given minimum length all_combinations = list(itertools...
magicoder
python
You are tasked with implementing a custom data structure in C# that simulates a stack with an additional feature. The stack should support the usual push and pop operations, but it should also have a method that returns the minimum element in the stack at any given time. You need to implement the `MinStack` class with ...
```csharp public class MinStack { private Stack<int> stack; private Stack<int> minStack; public MinStack() { stack = new Stack<int>(); minStack = new Stack<int>(); } public void Push(int x) { stack.Push(x); if (minStack.Count == 0 || x <= minStack.Peek()) ...
magicoder
csharp
You are tasked with creating a program that parses HTML code to extract the URLs from anchor tags. Your program should be able to handle multiple anchor tags and extract the URLs from the "href" attribute within each anchor tag. Write a function `extract_urls(html)` that takes a string `html` representing the HTML cod...
```python import re def extract_urls(html): pattern = r'<a\s+[^>]*href=["\']([^"\']*)["\'][^>]*>' urls = re.findall(pattern, html) return urls ``` The `extract_urls` function uses the `re.findall` method to search for all occurrences of the specified pattern within the HTML code. The regular expression pa...
magicoder
python
You are tasked with creating a Python class that handles HTTP requests and responses. Your task is to implement a method `post_url` within the `Requester` class that sends a POST request to a specified URL and processes the response. The method should handle potential HTTP errors and optionally convert the response to ...
```python import requests import logging from typing import Union class Requester: def __init__(self): # Initialize any configurations or settings here pass def jsonify_response(self, response: requests.Response) -> dict: # Implement the logic to convert response to JSON format ...
magicoder
python
You are tasked with creating a Python function that processes 3D mesh data to collect information about bounding boxes. The function should take in the path to a directory containing mesh files, a path to an output JSON file, and an optional boolean flag indicating whether the bounding boxes should be oriented. The fun...
```python import json from typing import List, Dict, Any def load_bop_meshes(model_path: str) -> Tuple[List[str], Dict[int, int]]: # Implementation of load_bop_meshes function is assumed to be provided elsewhere def load_bbox_3d(jsonFile: str) -> Dict[str, Any]: with open(jsonFile, 'r') as f: bbox_3d ...
magicoder
python
You are tasked with creating a secure token management system for a web application. The system should utilize environment variables to store sensitive access tokens. Your task is to implement a function that retrieves the access token from the environment variables and validates it. You are given a code snippet from ...
```php function validateAccessToken($token) { if (empty($token) || strlen($token) < 10) { return false; } if (!preg_match('/[A-Z]/', $token) || !preg_match('/[a-z]/', $token) || !preg_match('/[0-9]/', $token)) { return false; } return true; } ``` The `validateAccessToken` function f...
magicoder
php
You are tasked with creating a function that calculates the sum of all even Fibonacci numbers up to a given limit. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. For example, the first few numbers in the Fibonacci sequence are 0, 1...
```rust fn sum_even_fibonacci(limit: u64) -> u64 { let (mut a, mut b) = (1, 1); let mut sum = 0; while b <= limit { if b % 2 == 0 { sum += b; } let next = a + b; a = b; b = next; } sum } fn main() { println!("{}", sum_even_fibonacci(10)); //...
magicoder
rust
You are tasked with implementing a function to enrich a message object with contextual data from the calling environment. The message object has properties that need to be augmented with additional information such as user details, domain, etc. Your task is to create a function that takes the message object as input an...
```csharp using System; class Message { public string Content { get; set; } public string User { get; set; } public string Domain { get; set; } } class Program { static void Main() { // Sample Message object Message message = new Message { Content = "Hello, worl...
magicoder
csharp
You are tasked with implementing a custom map data structure in Rust. The map should support key-value pairs, where the keys are integers and the values are floating-point numbers. Additionally, the map should allow for duplicate keys, with the values associated with the same key being stored in a vector. Your task is...
```rust struct CustomMap { map: std::collections::HashMap<i32, Vec<f64>>, } impl CustomMap { fn new() -> CustomMap { CustomMap { map: std::collections::HashMap::new(), } } fn insert(&mut self, key: i32, value: f64) { self.map.entry(key).or_insert(Vec::new()).push(va...
magicoder
rust
You are tasked with implementing a Python decorator that can be used to selectively apply a function to certain inputs based on a given condition. The decorator should allow the user to specify whether the decorated function should be executed based on a selection condition. The decorator should also provide the abilit...
```python def inner(): return "Inner function executed" def selection(condition): def decorator(func): def wrapper(*args, **kwargs): if condition(*args, **kwargs): return func(*args, **kwargs) else: return deselection() return wrapper ...
magicoder
python
You are tasked with implementing a custom logging system in Python. Your goal is to create a class that can handle logging messages at different severity levels and direct them to different output streams based on their severity. The severity levels are defined as follows: - DEBUG - INFO - WARNING - ERROR - CRITICAL Y...
```python import sys import logging class CustomLogger: def __init__(self, level=logging.DEBUG): self.level = level self.console_handler = logging.StreamHandler(sys.stdout) self.console_formatter = logging.Formatter('%(levelname)s: %(message)s') self.console_handler.setFormatter(sel...
magicoder
python
You are tasked with creating a script to manage GTFS (General Transit Feed Specification) data for a public transportation system. The script is responsible for updating the GTFS data in a database if the calendar.txt file has changed. The script also handles the removal of temporary files and the unzipping of a new GT...
```bash # 2. Complete the script by adding the necessary command(s) to update the database with the new GTFS data file. unzip "${GTFS_STATIC_DIR}"/google_transit_dublinbus.zip -d "${GTFS_STATIC_DIR}"/data/ # 3. Provide the command(s) to be added after the existing code snippet to achieve the database update. # Assumin...
magicoder
shell
You are tasked with creating a Bash script that processes a log file and adds a timestamp to each line. The script should read the log file line by line, prepend each line with the current date and time in a specific format, and then output the modified lines. Your task is to complete the Bash script by implementing t...
```bash #!/bin/bash adddate() { while IFS= read -r line; do echo "$(date +'%a %d %b %T') - $line" done } # Example usage: process_log.sh logfile.txt process_log.sh() { if [ -f "$1" ]; then adddate < "$1" else echo "Error: File not found" fi } # Usage: ./process_log.sh logf...
magicoder
shell
You are tasked with simulating customer movement within a store using the provided configuration parameters. The store is represented as a grid, with a specified height and width. Additionally, there is an average number of customers present in the store at any given time, and a file containing a list of customers. Yo...
```python import os import csv import random STORE_HEIGHT = int(os.getenv('STORE_HEIGHT', 10)) STORE_WIDTH = int(os.getenv('STORE_WIDTH', 6)) CUSTOMERS_AVERAGE_IN_STORE = int(os.getenv('CUSTOMERS_AVERAGE_IN_STORE', 6)) CUSTOMERS_LIST_FILE = os.getenv('CUSTOMERS_LIST_FILE', 'customers.csv') def read_customer_list(file...
magicoder
python
You are tasked with extending the `TenantFilter` class in the `App\CustomHelpers\User` namespace to include additional filtering capabilities for retrieving tenants based on specific criteria. The existing method `getTenants` accepts two parameters, `$sortField` and `$orderBy`, to sort the tenants based on the specifie...
```php use App\Tenant; use Carbon\Carbon; class TenantFilter { // Existing method to get tenants ordered based on supplied filters public function getTenants($sortField, $orderBy) { // Implementation to retrieve tenants based on sortField and orderBy // ... } // New method to filte...
magicoder
php
You are given a Python class `Maybe` that represents a container type that may or may not hold a value. The class has two subclasses: `Just` for holding a value, and `Nothing` for representing an empty container. The class `Maybe` has the following methods: - `map(func)`: Applies the function `func` to the value insid...
```python class Maybe: def map(self, func): if isinstance(self, Just): return Just(func(self.value)) else: return Nothing() def __str__(self): if isinstance(self, Just): return str(self.value) else: return 'Nothing' class Just(Ma...
magicoder
python
You are tasked with implementing a string searching algorithm using the Boyer-Moore algorithm with the Bad Character Heuristic. The Boyer-Moore algorithm is an efficient string searching algorithm that works by comparing and shifting the pattern to be searched for within the text based on certain heuristic rules. The B...
```rust // Define a custom type that implements the BMByteSearchable trait struct MyType<'a> { data: &'a [u8], } // Implement the BMByteSearchable trait for the custom type impl<'a> BMByteSearchable for MyType<'a> { fn len(&self) -> usize { self.data.len() } fn byte_at(&self, index: usize) -> ...
magicoder
rust
You are tasked with implementing a drawing application that can render shapes using different drawing APIs. The application should support rendering shapes such as circles, squares, and triangles. To achieve this, you need to create a set of shape classes that utilize a provided drawing API to render the shapes. The dr...
```python class Circle: def __init__(self, x, y, radius, drawing_api): self.x = x self.y = y self.radius = radius self.drawing_api = drawing_api def draw(self): self.drawing_api.draw_circle(self.x, self.y, self.radius) def resize_by_percentage(self, pct): se...
magicoder
python
You are tasked with implementing a class hierarchy for a form builder application. The application should support different types of form questions, including multiple-choice, true/false, and open-ended questions. Your task is to design and implement the necessary classes to support this functionality. You are provide...
```python class FormAtomicQuestion: def __init__(self, prompt): self.prompt = prompt def get_prompt(self): return self.prompt def set_prompt(self, prompt): self.prompt = prompt class FormCheckBoxQuestion(FormAtomicQuestion): def __init__(self, prompt, value, desc): su...
magicoder
python
You are tasked with implementing a Rust function that processes a stream of `Either` values and returns the unified result. The `Either` enum has two variants, `A` and `B`, each containing a single value. Your task is to complete the implementation of the `process_stream` function, which takes a stream of `Either` valu...
```rust fn process_stream<S, A, B, F>(stream: S) -> F where S: Stream<Item = Either<A, B>, Error = ()>, F: Future<Item = A, Error = ()>, { let unified = stream.into_future() .map(|(item, _)| match item { Some((Either::A(a), _)) => a, Some((Either::B(b), _)) => b, ...
magicoder
rust
You are tasked with creating a Python class to control a digital potentiometer using a microcontroller. The digital potentiometer is controlled by a voltage signal, and the class should provide methods to set the voltage level and enable/disable the potentiometer. You are given the following code snippet as a starting...
```python import math import board from digitalio import DigitalInOut from analogio import AnalogOut class DigitalPotentiometer: def __init__(self, pin, max_voltage=3.3): self.pin = pin self.max_voltage = max_voltage self.analog_out = AnalogOut(pin) self.enable_pin = DigitalInOut(bo...
magicoder
python
You are tasked with implementing a function that takes a string as input and returns the number of distinct substrings that can be formed from the input string. A substring is a contiguous sequence of characters within a string. For example, the substrings of "abc" are "a", "b", "c", "ab", "bc", and "abc". Your task i...
```python def countDistinctSubstrings(s: str) -> int: substrings = set() n = len(s) for i in range(n): for j in range(i, n): substrings.add(s[i:j+1]) return len(substrings) ``` The solution defines the function `countDistinctSubstrings` that initializes an empty set `substrings` to ...
magicoder
python
You are given two matrices, A and B, both of dimensions m x n. Your task is to write a function to perform matrix multiplication of A and B and return the resulting matrix. The matrix multiplication of A and B, denoted as C = A * B, is defined as follows: For each element C[i][j] in the resulting matrix C, it is calcu...
```python from typing import List def matrix_multiplication(A: List[List[int]], B: List[List[int]]) -> List[List[int]]: m = len(A) n = len(B[0]) p = len(B) C = [[0 for _ in range(n)] for _ in range(m)] for i in range(m): for j in range(n): for k in range(p): ...
magicoder
python
You are tasked with implementing a function to retrieve the configuration file path within a Python project directory structure. The project follows a specific directory hierarchy, and the function needs to navigate through the directories to locate the configuration file. You are provided with a code snippet that con...
```python import os def get_root_path(): current_path = os.path.abspath(os.path.dirname(__file__)) root_path = os.path.dirname( os.path.dirname(os.path.dirname(os.path.dirname(current_path))) ) return os.path.join(root_path, "xbot") def get_config_path(): root_path = get_root_path() c...
magicoder
python
You are tasked with implementing a variable declaration system for a data modeling application. The system should allow for the declaration of variables with specific flags and scopes. You are given a code snippet from the existing system, which includes a call to a function `context.VariableDeclare` with three argum...
```python class Variable: def __init__(self, name, flags): self.name = name self.flags = flags class VarDeclareScope: BlockScope = "BlockScope" # Add other scope types as needed class Context: @staticmethod def VariableDeclare(name, scope, variable): # Implement variable de...
magicoder
python
You are tasked with implementing a macro for a web framework that generates HTML for displaying a user's Twitter followers. The macro takes several optional parameters to customize the appearance of the generated HTML. Your task is to write a function that generates the HTML based on the given parameters. The function...
```php function twitter_followers($user, $linkEnabled = true, $withIcon = true, $withText = true, $withBg = true, $pullRight = true, $text = '', $bgClass = '', $itemCount = '') { $html = ''; if ($linkEnabled) { $html .= '<a href="https://twitter.com/' . $user->profile->twitter_username . '">'; } ...
magicoder
php
You are tasked with implementing a simple server-side chat application that communicates with clients over a network connection. The server should handle incoming messages from clients and respond accordingly. The provided code snippet is a part of the server-side logic for processing client messages. Your task is to ...
```java import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; public class ChatServer { public static void main(String[] args) { try (ServerSocket s...
magicoder
java
You are tasked with implementing a custom view in Swift for a food delivery app called "HungryNow." The view should display a tutorial for new users on how to use the app's main features. The tutorial view should consist of a series of pages, each displaying an image and a brief description of a specific feature. Your ...
```swift import UIKit class TutorialView: UIView { private var tutorialPages: [(image: UIImage, description: String)] = [] private var currentPageIndex: Int = 0 private let imageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit imageVie...
magicoder
swift
You are tasked with implementing a distributed training system for a machine learning model. The system consists of multiple engines, each running on a separate machine, and a central server for coordination. The provided code snippet is a part of the engine's logic for saving and resetting checkpoints during the train...
The `broadcast` function should send the value of `flag` to all engines in the distributed system. This can be achieved using a communication protocol such as MPI or a distributed computing framework like PyTorch Distributed. The `engine._setup_optimizer` method should initialize the optimizer for the engine's model. ...
magicoder
python
You are tasked with implementing a quantum computing simulator that can handle single-qubit Hamiltonians. A single-qubit Hamiltonian is a mathematical representation of the energy of a single quantum bit (qubit) in a quantum system. Your task is to complete the implementation of the `SingleQubitHamiltonian` class by ad...
```python import numpy as np from scipy.linalg import eigh class SingleQubitHamiltonian(Hamiltonian): def __init__(self, sq=True, **kw): self._order = 1 self._model = 'sq' self._qubOp = '' def energy_eigenvalues(self): # Define the single-qubit Hamiltonian matrix hamilt...
magicoder
python
You are tasked with implementing a function to perform a 1D convolution operation on a set of input features using given weights. The input features and weights are represented as arrays of floating-point numbers. Your goal is to write a function that takes these arrays as input and produces the result of the convoluti...
```c void performConvolution(const float_type input_feature[], const float_type weights[], float_type output[], int input_size, int weight_size) { int output_size = input_size - weight_size + 1; for (int i = 0; i < output_size; i++) { output[i] = 0; for (int j = 0; j < weight_size; j++) { ...
magicoder
c
You are given a sequence of integers and a target sum. Your task is to find a pair of distinct elements in the sequence that sum up to the target. If such a pair exists, you need to output the indices of the two elements. If there are multiple valid pairs, output the pair with the smallest index for the first element. ...
```cpp #include <vector> #include <unordered_map> vector<int> findPair(vector<int>& nums, int target) { unordered_map<int, int> numIndexMap; vector<int> result; for (int i = 0; i < nums.size(); ++i) { int complement = target - nums[i]; if (numIndexMap.find(complement) != numIndexMap.end())...
magicoder
cpp
You are tasked with implementing a function that processes an array of filters for a command. Each filter is represented as an associative array containing the keys 'name', 'required', and 'filters'. The 'name' key holds the name of the filter, 'required' indicates whether the filter is mandatory, and 'filters' contain...
```python def validate_filters(filters: list) -> bool: for filter in filters: if filter['required'] and filter['name'] not in [f['name'] for f in filter['filters']]: return False if filter['filters']: if not validate_filters(filter['filters']): return False ...
magicoder
python
You are tasked with implementing a simplified version of a class registration system in Python. The system should allow for the registration of different classes or chapters within a larger educational application. You are provided with a code snippet that registers three classes or chapters - 'RegistryApp', 'DiseaseC...
```python class ClassRegistry: def __init__(self): self.registered_classes = [] def register(self, class_name): self.registered_classes.append(class_name) def get_registered_classes(self): return self.registered_classes # Usage registry = ClassRegistry() registry.register('Registr...
magicoder
python
You are tasked with implementing a neural network architecture for image processing. The architecture consists of multiple layers, each with specific configurations for input and output channels, dilation, convolution type, block type, and upsampling type. Your goal is to create a class that can instantiate these layer...
```python class HED: def __init__(self, in_channels, out_channels, dilation, conv_type_key, block_type_key, output_type_key, upsampling_type_key): # Constructor implementation pass class NeuralNetwork: def create_layers(self, layer_configs): layers = [] for config in layer_confi...
magicoder
python
You are tasked with implementing a class for calculating the total mass of an object in motion, considering both the mass of the surrounding air and the mass of the propulsion system. The class contains methods for calculating the total mass (`_get_mB_tot`), the mass of the surrounding air (`_get_mB_air`), and the mass...
```python import numpy as np class MassCalculator: def __init__(self, R, v): self.R = R self.v = v def _get_mB_tot(self, u): mB_tot = self._get_mB_air(u) + self._get_mB_prop(u) return mB_tot def _get_mB_air(self, u): vB = np.dot(self.R, self.v) alpha = ...
magicoder
python
You are given a list of integers representing the scores of a game. Your task is to implement a function that calculates the final ranking of the players based on their scores. The ranking should be in descending order, with the highest score at the top. You need to write a function `calculateRanking(scores)` that tak...
```python def calculateRanking(scores): sorted_scores = sorted(enumerate(scores, 1), key=lambda x: x[1], reverse=True) ranking = [rank for rank, _ in sorted_scores] return ranking ``` The `calculateRanking` function first creates a list of tuples containing the original index and the score using `enumerate...
magicoder
python
You are tasked with implementing a generic decoder for a protocol buffer message in C++. The provided code snippet is a part of a larger program that defines a `codec_map` struct and a `decode` function. The `decode` function is responsible for decoding a protocol buffer message and populating a map with the decoded da...
```cpp template <typename T> struct codec_map { static bool decode(pb_istream_t *stream, const pb_field_t *field, void **arg) { auto *mapping = static_cast<std::map<typename T::KeyType, typename T::ValueType> *>(*arg); T map_entry; // Read the protocol buffer message from the input stream ...
magicoder
cpp
You are given a Python class `SampleCollection` that represents a collection of samples. The class has the following attributes and methods: Attributes: - `samples`: a list of strings representing the samples - `max_len`: an integer representing the maximum length allowed for each sample Methods: - `__len__(self)`: a...
```python class SampleCollection: def __init__(self, samples, max_len): self.samples = samples self.max_len = max_len self.lens = [max(1, len(samp) - max_len) for samp in self.samples] self.cum_lens = [0] + [sum(self.lens[:i+1]) for i in range(len(self.samples))] def __len__(sel...
magicoder
python
You are tasked with creating a program that simulates a simple version control system for a local repository within a server. The program should be able to perform basic version control operations such as adding files to the repository, committing changes, and viewing the commit history. Your task is to implement a cl...
```python class VersionControl: def __init__(self): self.repository = [] self.commit_history = [] def add_file(self, file_name): self.repository.append(file_name) def commit(self, message): self.commit_history.append(message) def view_commit_history(self): retu...
magicoder
python
You are tasked with creating a script to automate the deployment of subgraphs for different networks using the Yarn workspace tool. The script should take network and label parameters and execute the deployment command for the specified subgraph. You are given the following information: - The Yarn workspace tool is be...
```python import subprocess import sys def deploy_subgraph(network, label): subgraph_package = "@unlock-protocol/subgraph" command = f"yarn workspace {subgraph_package} run deploy --network {network} --label {label}" try: subprocess.run(command, shell=True, check=True) print(f"Subgraph...
magicoder
python
You are tasked with implementing a function that processes requests in an enclave. The function takes in a message and credentials, and it should perform certain operations based on the provided inputs. Your task is to complete the implementation of the `enclave_request` function by filling in the missing logic. You a...
```rust fn enclave_request( &mut self, msg: &attest::Message, creds: &BasicCredentials, ) -> Result<attest::Message, grpcio::Error> { // Perform additional operations based on the message and credentials let call_option = creds.call_option()?; let checked_images = self.check_key_images_opt(msg, ...
magicoder
rust
You are tasked with implementing a simple peer-to-peer chat application using Python's socket programming. Your goal is to create a program that allows two users to communicate with each other over a local network. The provided code snippet is a part of the server-side implementation, which listens for incoming connect...
```python import socket # Define the server's IP address and port server_ip = '127.0.0.1' # Replace with the actual server IP address server_port = 12345 # Replace with the actual server port number # Create a socket object for the client client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect ...
magicoder
python
You are tasked with implementing a class `QueryHistoryStats` that keeps track of the history of queries and provides statistics based on the query history. The class should have the following methods: 1. `record_query(query_time: int)`: This method records the time at which a query was executed. The `query_time` is a ...
```python from collections import defaultdict from typing import Tuple class QueryHistoryStats: def __init__(self): self.query_times = [] self.query_frequency = defaultdict(int) def record_query(self, query_time: int): self.query_times.append(query_time) self.query_frequency[qu...
magicoder
python
You are tasked with implementing a trait and its associated methods in Rust. The trait, `ForSelectGeneratorType`, is defined with three associated functions: `get_generator_type`, `parse`, and `to_data_value`. Your goal is to create a struct `SbrdString` and implement the `ForSelectGeneratorType` trait for it. The `ge...
```rust // Define the GeneratorType enum enum GeneratorType { SelectString, // Add other variants if needed } // Define the DataValue enum enum DataValue { String(String), // Add other variants if needed } // Define the ForSelectGeneratorType trait trait ForSelectGeneratorType { fn get_generator_t...
magicoder
rust
You are working on a Django project that involves filtering and querying a database using Django's QuerySet API. Your task is to create a custom filter backend that can handle filtering based on certain criteria. The provided code snippet shows two methods within a custom filter backend class. The `filter_owner` method...
```python class CustomFilterBackend: def filter_owner(self, queryset, name, value): return queryset.filter( Q(image_version__created_by__username=value) | Q(image_version__application__created_by__username=value) ) def filter_by_uuid(self, queryset, name, value): ...
magicoder
python
You are given a string containing a software license agreement. Your task is to write a function that extracts the license text from the given string. The license text is enclosed within two consecutive occurrences of the word "License" (case-insensitive) and may contain any characters, including newlines and special s...
```python def extract_license_text(input_str): start_index = input_str.lower().find('license') if start_index != -1: end_index = input_str.lower().find('license', start_index + 1) if end_index != -1: return input_str[start_index:end_index + len('License')] return '' ``` The `extr...
magicoder
python
You are working on a cross-platform game development project and need to implement a logging system that supports different platforms and environments. The provided code snippet is a part of the logging functionality and contains conditional compilation directives for different platforms and environments. Your task is...
```cpp #include <iostream> #include <cstring> // Platform and environment macros #define _RETAIL_ #define SHOOT_PLATFORM_ANDROID 1 #define SHOOT_PLATFORM_WIN32 2 #define SHOOT_PLATFORM_WP8 3 #define SHOOT_EDITOR // Function to be implemented void LogMessage(const char* message) { #if !defined(_RETAIL_) || (SHOOT_...
magicoder
cpp
You are tasked with implementing a function to calculate the total memory used by a given process on a Windows system. The function should take the process ID as input and return the total memory consumption in bytes. You are provided with the necessary Windows API functions to achieve this. You are given the followin...
```cpp #include <Windows.h> // Function to calculate the total memory consumption of a process SIZE_T CalculateProcessMemoryUsage(DWORD processId) { HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processId); if (hProcess == NULL) { // Handle error in opening the proce...
magicoder
cpp
You are tasked with implementing a Java method that processes a list of student names and identifies incompatible pairs of names. Incompatible pairs are defined as those where the Levenshtein distance between the names is less than or equal to a given threshold. The Levenshtein distance between two strings is the minim...
```java import java.util.ArrayList; import java.util.List; public class NameProcessor { public List<String> findIncompatibleNames(List<String> names, int threshold) { List<String> result = new ArrayList<>(); for (int i = 0; i < names.size(); i++) { for (int j = i + 1; j < names.size(); ...
magicoder
java
You are tasked with creating a Python class that can handle and test various API functions using the Earth Engine Python API. The Earth Engine Python API provides a way to interact with Google Earth Engine, a cloud-based platform for planetary-scale environmental data analysis. Your task is to create a class that inher...
```python # api_function_test.py import ee from ee import apitestcase class ApiFunctionTest(apitestcase.ApiTestCase): def test_api_function_1(self): # Test API function 1 # Make a request and check the response for correctness pass def test_api_function_2(self): # Test API fun...
magicoder
python
You are tasked with creating a Python script to monitor the CPU and memory usage of a specific process and send an email notification if the usage exceeds a certain threshold. You will need to utilize the `psutil` library to gather the CPU and memory usage information, and the `win32com.client` library to send an email...
```python import psutil import win32com.client as win32 import time # Prompt user for the process name to monitor process_name = input("Enter the name of the process to monitor: ") # Define the CPU and memory thresholds cpu_threshold = 80 memory_threshold = 90 # Connect to Outlook outlook = win32.Dispatch('outlook.a...
magicoder
python
You are tasked with creating a script to generate a system of processes based on a given number. The script should take an integer input `N` and generate a system of processes labeled `P1` to `PN`. Each process should be represented as `P<i> := Processes(<i>);`, where `<i>` is the process number. Your task is to write...
```bash #!/bin/bash if [ $# -ne 1 ]; then echo "Usage: $0 <N>" exit 1 fi N=$1 for ((i=1; i<=N; i++)); do echo "P${i} := Processes($i);" done if [ $N -gt 1 ]; then echo -n "system P1" for ((i=2; i<=N; i++)); do echo -n " P${i}" done echo "" fi ``` When the above script is execute...
magicoder
shell
You are tasked with creating a function that formats a given time in seconds into a human-readable logoff time. The logoff time should be in the format "HH:MM:SS AM/PM". The function should handle both 12-hour and 24-hour time formats. You are given a code snippet that starts the implementation of the `format_logoff_t...
```php function format_logoff_time($seconds) : string { $hours = floor($seconds / 3600); $minutes = floor(($seconds % 3600) / 60); $seconds = $seconds % 60; $formatted_time = sprintf("%02d:%02d:%02d", $hours, $minutes, $seconds); if ($hours >= 12) { $formatted_time .= " PM"; if ($h...
magicoder
php
You are tasked with creating a Python class for drawing circles using the Pyxel game engine. The class should have the ability to randomly generate the circle's radius and position within the game window. Your task is to implement the `Circle` class with the following requirements: - The class should have a constructo...
```python import pyxel from random import randint class Circle: def __init__(self, screen_width, screen_height, min_radius): self._x = randint(0, screen_width) self._y = randint(min_radius, screen_height - min_radius) self._r = randint(min_radius, min(screen_width, screen_height) // 2) - 4 ...
magicoder
python
You are tasked with implementing a simplified version of a queue cluster system. The `start_qcluster` function is provided to you, and your task is to create a class that can manage the queue cluster system. The `start_qcluster` function initializes the queue cluster and returns a unique identifier for the cluster. You...
```python from typing import Any def start_qcluster() -> str: # Assume this function is provided by the system and returns a unique cluster identifier pass class QueueClusterManager: def __init__(self): self.clusters = {} def add_queue(self) -> str: cluster_id = start_qcluster() ...
magicoder
python
You are working on a project that involves building a custom layer in a neural network using the Keras library. Your task is to create a custom layer that performs a specific mathematical operation on the input data. The operation involves taking the square of the input tensor and then concatenating it with the origina...
```python import keras.backend as K from keras.layers import Layer, concatenate class SquareConcatLayer(Layer): def __init__(self, axis, **kwargs): self.axis = axis super(SquareConcatLayer, self).__init__(**kwargs) def build(self, input_shape): super(SquareConcatLayer, self).build(inpu...
magicoder
python
You are tasked with implementing a function that checks if a given range of elements forms a heap, using a non-const version of the `std::is_heap` algorithm. A heap is a specific type of binary tree where the parent node is greater than or equal to its child nodes (max-heap) or less than or equal to its child nodes (mi...
```cpp #include <algorithm> #include <execution> template <typename Policy, typename Iterator, typename T> struct test_non_const_is_heap_until { void operator()(Policy&& exec, Iterator iter) { std::invoke_if(std::forward<Policy>(exec), [&](auto&& policy) { std::is_heap(policy, iter, non_con...
magicoder
cpp
You are tasked with implementing a Python class that processes incoming data packets according to a specific protocol. The class should be able to extract and store information from the incoming data, and also be capable of packing the data into the appropriate format for transmission. You are provided with a partial ...
```python import struct class DataProcessor: def __init__(self): self.cmdtype = struct.pack('I', 0x02) self.session_id = b'' self.guid = b'' self.hostname = b'' def process_data(self, data): if data is not None: self.session_id = data[0:4] self.g...
magicoder
python
You are tasked with implementing a data transfer object (DTO) for correlating messages in a workflow management system. The provided code snippet is a partial implementation of the `CorrelationMessageDto` struct in Rust. Your goal is to complete the implementation of this struct by adding methods to set and retrieve va...
```rust use std::collections::HashMap; struct CorrelationMessageDto { message_name: Option<String>, business_key: Option<String>, tenant_id: Option<String>, without_tenant_id: Option<String>, process_instance_id: Option<String>, correlation_keys: Option<Vec<String>>, local_correlation_keys:...
magicoder
rust
You are tasked with creating a class to represent a GitHub repository. The class should have properties to store various statistics and information about the repository. Your task is to implement the class with the given properties and then create a method to calculate the total number of activities in the repository. ...
```csharp public class GitHubRepository { public long Stars { get; set; } public long Forks { get; set; } public long Issues { get; set; } public long PullRequests { get; set; } public long Commits { get; set; } public long Branches { get; set; } public long Releases { get; set; } public...
magicoder
csharp
You are tasked with implementing a Python function that utilizes the Earley chart parsing algorithm to find the best parse for a given set of phrases. The Earley chart parsing algorithm is a dynamic programming algorithm used for parsing strings according to a given grammar. The function should take a grammar `g` and a...
```python # Sample usage of the function # Define a simple grammar grammar = nltk.CFG.fromstring(""" S -> NP VP VP -> V NP | V NP PP PP -> P NP V -> "saw" | "ate" | "walked" NP -> "John" | "Mary" | "Bob" | Det N | Det N PP Det -> "a" | "an" | "the" | "my" N -> "man" | "dog" | "cat" | "telesc...
magicoder
python
You are tasked with creating a custom message bus system in C# using the Orchard framework. The message bus system should utilize the SQL Server Service Broker feature provided by the Orchard.MessageBus.SqlServerServiceBroker module. Your task is to implement a message handler that subscribes to specific message types ...
```csharp using Orchard.Environment.Extensions; using Orchard.MessageBus.Handlers; using Orchard.MessageBus.Models; namespace Orchard.MessageBus { [OrchardFeature("Orchard.MessageBus.SqlServerServiceBroker")] public class MyCustomMessageHandler : IMessageHandler { public void Subscribe(Message<CustomMe...
magicoder
csharp
You are tasked with creating a unit test for a generic method that asserts the equality of properties between two instances of a class. The method `AssertEntityBasePropertiesAreEqual` is an abstract method that needs to be implemented in a derived class. The unit test `Can_Persist_Default_Entity` creates an instance of...
```csharp public abstract class BaseClass<T> { protected abstract void AssertEntityBasePropertiesAreEqual(T actual, T expected); } public class DerivedClass : BaseClass<EntityType> { public override void AssertEntityBasePropertiesAreEqual(EntityType actual, EntityType expected) { // Implement the c...
magicoder
csharp
You are tasked with implementing a dependency resolution algorithm for a software package management system. The system uses a list of dependencies in the form of tuples, where each tuple contains the name of a package and the version it depends on. The version is represented as a string in the format '0000_auto_YYYYMM...
```python from typing import List, Tuple def resolve_dependencies(dependencies: List[Tuple[str, str]]) -> List[str]: dependency_map = {} for package, version in dependencies: if package not in dependency_map: dependency_map[package] = [] dependency_map[package].append(version) ...
magicoder
python
You are tasked with creating a Rust module that implements a finite module structure for a real projective space. The real projective space is a fundamental concept in algebraic topology and is represented by the module `RealProjectiveSpace` in the code snippet provided. Your task is to define a Rust module that utili...
```rust use finite_module::FiniteModule; use finitely_presented_module::FinitelyPresentedModule as FPModule; use free_module::{FreeModule, OperationGeneratorPair}; use module_trait::{Module, ModuleFailedRelationError}; use rpn::RealProjectiveSpace; // Define a struct representing the finite module for the real project...
magicoder
rust
You are tasked with implementing a custom data structure in Python that simulates a queue with the ability to efficiently retrieve the maximum element in the current queue. You need to implement the `MaxQueue` class with the following methods: - `__init__(self)`: Initializes an empty queue. - `enqueue(self, val)`: Adds...
```python class MaxQueue: def __init__(self): self.queue = [] self.max_queue = [] def enqueue(self, val): self.queue.append(val) while self.max_queue and self.max_queue[-1] < val: self.max_queue.pop() self.max_queue.append(val) def dequeue(self): ...
magicoder
python
You are tasked with creating a program that simulates a simple text editor with find and replace functionality. The program should allow users to input a string of text, specify a word to find within the text, and then replace all occurrences of that word with a new word. The program should also provide feedback to the...
```python class TextEditor: def findAndReplace(self, text, word_to_find, replacement_word): count = text.count(word_to_find) modified_text = text.replace(word_to_find, replacement_word) return modified_text, count ``` The `findAndReplace` method first counts the occurrences of `word_to_find`...
magicoder
python
You are tasked with implementing a function that calculates the size of an icon for a React component based on the provided input. The function should handle both numeric and string inputs and should fall back to a default size if the provided size is not valid. You are given the following code snippet as a starting p...
```typescript // Define the iconSizes object with predefined sizes const iconSizes = { small: 16, medium: 24, large: 32, // Add more size definitions as needed }; // Implement the get function to retrieve size value from iconSizes const get = (key: string) => (props: any) => iconSizes[key]; // Create ...
magicoder
typescript
You are tasked with creating a Python script that integrates multiple translation modules for a sign language recognition system. The system should be able to translate both American Sign Language (ASL) gestures and speech into text. The provided code snippet includes import statements for the translation modules, but ...
```python from run_translation.RunPiModelStream import rasp_translation from run_translation.TestModelComputerLetters import asl_translation_letters from run_translation.SpeechToText import stt def translate_asl_raspberry_pi(): try: # Capture ASL gestures from Raspberry Pi camera and translate to text ...
magicoder
python
You are tasked with implementing a Python function that generates random walks on a graph based on different walk types. The graph is represented using the `graph` object, and the function takes in various parameters to customize the random walk generation process. Your task is to create a function that can handle diff...
```python import random import gensim def generate_random_walks(graph, walk_type, number_paths, path_length): if walk_type == "likely": walks = graph.build_likely_walk_corpus(number_paths, path_length, rand=random.Random(0), shuffle=True, deduplicate=False) ...
magicoder
python
You are given a Java package declaration as a string. Your task is to write a function to extract the package name from the given string. Write a Java method with the following signature: ```java public static String extractPackageName(String packageDeclaration) ``` The method should take a string `packageDeclaration...
```java public static String extractPackageName(String packageDeclaration) { int startIndex = packageDeclaration.indexOf("package") + "package".length(); int endIndex = packageDeclaration.indexOf(";"); return packageDeclaration.substring(startIndex, endIndex).trim(); } ```
magicoder
java