query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a shared coroutine queue system in Swift. The shared coroutine queue system should support a fixed capacity and allow multiple coroutines to enqueue and dequeue items concurrently. The system should be implemented using the `FifoQueue` data structure, which is a first-in-first-out queue... | ```swift
class SharedCoroutineQueue<T> {
private let stackSize, capacity: Int
private var queues = [FifoQueue<T>]()
init(stackSize: Int, capacity: Int) {
self.stackSize = stackSize
self.capacity = capacity
for _ in 0..<stackSize {
queues.append(FifoQueue<T>())
}
... | magicoder | swift |
You are tasked with creating a program that processes a batch of job submission records and extracts relevant information from each record. Each record is a string containing various directives and metadata related to a job submission on a high-performance computing (HPC) cluster. The directives include the number of G... | ```python
import re
def parse_job_submission(record):
result = {}
# Extract GitHub stars
stars_match = re.search(r'<gh_stars>(\d+)', record)
if stars_match:
result["gh_stars"] = int(stars_match.group(1))
# Extract job name
name_match = re.search(r'#PBS -N (.+)', record)
if... | magicoder | python |
You are tasked with implementing a Python function that processes a list of import statements and returns a dictionary containing the imported modules and their corresponding classes or functions. Each import statement follows the format `from <module> import (<class1>, <class2>, ...)`. If a module is imported multiple... | ```python
from typing import List, Dict, Set
def process_imports(import_statements: List[str]) -> Dict[str, Set[str]]:
imports_dict = {}
for statement in import_statements:
module, classes = statement.split(" import ")
module = module.split("from ")[1].strip()
classes = classes.str... | magicoder | python |
You are tasked with implementing a custom collection view layout for a weather app that displays the weather information for different cities. The given code snippet sets up the collection view and registers custom cell and header classes. Your task is to create a custom collection view layout that displays the weather... | To implement the custom collection view layout, you can create a subclass of `UICollectionViewFlowLayout` and override the necessary methods to achieve the desired layout behavior. Below is a sample implementation in Swift:
```swift
class CustomWeatherLayout: UICollectionViewFlowLayout {
override func prepare... | magicoder | swift |
You are given a Python code snippet that defines a class `map` which inherits from `BlockTransformation`. The class has a docstring that describes its functionality and an attribute `_map` of type `Optional[Dict[int, int]]`. Your task is to implement a method within the `map` class that performs the block transformatio... | ```python
from typing import Optional, Dict, Union, List
class map(BlockTransformation):
"""
Each block of the input data which occurs as a block of the index argument is replaced by the
corresponding block of the image argument. If a block size is specified, and if the index or
image argument are byte... | magicoder | python |
You are tasked with implementing a simplified version of a forum post management system. The system should allow users to post new threads and optionally save them for later viewing. Each thread has a unique identifier and can be marked for saving.
You are provided with the following code snippet as a starting point:
... | ```python
class Forum:
def __init__(self):
self.saved_threads = []
def post(self, thread, save):
if save:
self.saved_threads.append(thread)
def view_saved_threads(self):
return self.saved_threads
```
With the `Forum` class implemented as above, the given code snippet c... | magicoder | python |
You are tasked with creating a program to generate a Look Up Table (LUT) for Absolute Humidity (AH) at 100% Relative Humidity (RH) based on temperature values. The AH at 100% RH is calculated using a function `calc_ah(t, rh)` where `t` represents the temperature and `rh` represents the relative humidity. The LUT should... | ```python
import math
# Assuming the constants k and m for the calc_ah function
k = 0.622
m = 17.62
def calc_ah(t, rh):
""" Calculate Absolute Humidity (AH) based on temperature and relative humidity """
return k * rh * math.exp(m * t)
def gen_ah_lut(t_range):
""" Generate the AH Look Up Table at 100%RH ... | magicoder | python |
You are tasked with implementing a task scheduling system in Java using the Spring framework. The system should allow for the scheduling and execution of various tasks. The `taskManager` bean has been provided, which exposes methods for starting the scheduling process and queuing tasks. You need to create a new task cl... | ```java
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TaskConfiguration {
@Bean
public CustomTask customTask(... | magicoder | java |
You are tasked with creating a Python program that simulates a simple game where the player controls a character that can move around the screen. The player can move the character using the arrow keys and can exit the game by pressing the 'Esc' key or clicking the close button on the window.
Your task is to implement ... | ```python
import pygame
from pygame.locals import *
# Initialize Pygame
pygame.init()
# Set up the game window
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Simple Game')
# Define the colors
WHITE = (255, 255, 255)
RED = (255, 0, 0)... | magicoder | python |
You are tasked with creating a Python program that simulates a simple game of rock-paper-scissors. The program should allow a user to play against the computer. The game should consist of the following rules:
- Rock beats scissors
- Scissors beats paper
- Paper beats rock
Your program should prompt the user to input t... | main.py
```python
#!/usr/bin/env python3
import game
def main():
user_choice = input("Enter your choice (rock, paper, or scissors): ").lower()
computer_choice = game.get_computer_choice()
result = game.determine_winner(user_choice, computer_choice)
print(result)
if __name__ == "__main__":
main()
`... | magicoder | python |
You are tasked with creating a TypeScript class that represents an account in a financial system. The class should have specific properties and methods to handle account-related data and operations. Your task is to implement the missing parts of the class based on the given code snippet.
The class should have the foll... | ```typescript
class FinancialAccount {
public readonly paging_token!: string;
public readonly account_id!: string;
public sequence!: string;
public readonly subentry_count!: number;
public readonly inflation_destination!: string;
public readonly last_modified_ledger!: number;
public readonly thresholds!: ... | magicoder | typescript |
You are tasked with implementing a validation error handling system for a web application. The system should provide a way to retrieve error messages based on error names and format multiple error messages into a single block of text.
You are provided with a code snippet that contains a method `GetByName` which retrie... | ```csharp
public static string FormatErrors(List<string> errorNames)
{
StringBuilder formattedErrors = new StringBuilder();
foreach (var errorName in errorNames)
{
string errorMessage = GetByName(errorName);
formattedErrors.AppendLine($"- {errorName}: {errorMessage}");
}
return forma... | magicoder | csharp |
You are tasked with creating a Python function that interacts with GitHub and Telegram APIs to retrieve and send information about a developer's repositories. The function should take in GitHub and Telegram tokens, as well as the Telegram chat ID, and perform the following tasks:
1. Retrieve the list of repositories f... | ```python
import requests
BASE_URL = "https://github.com"
def format_repo_message(developer, repos):
lines = []
lines.append(f"Repositories for {developer.name}:")
for repo in repos:
lines.append(
f"\\| [{repo}]({BASE_URL}/{repo})"
)
lines.append("")
return "\n".join(li... | magicoder | python |
You are tasked with implementing a class for identifying pileup jets in a particle physics simulation. Pileup jets are jets of particles that originate from additional proton-proton interactions in the same bunch crossing as the hard-scatter interaction. The class `PileupJetIdentifier` is responsible for identifying an... | ```cpp
#include <vector>
#include "Jet.h" // Assuming Jet class is defined in Jet.h
class PileupJetIdentifier {
public:
PileupJetIdentifier() {
// Constructor implementation
}
void identifyPileupJets(const std::vector<Jet>& allJets) {
// Implement the identification and categorization of p... | magicoder | cpp |
You are given a list of hexadecimal numbers representing time durations in a specific format. Each hexadecimal number corresponds to a time duration in minutes. Your task is to convert these hexadecimal numbers to their decimal equivalent and then calculate the total time duration in hours and minutes.
Write a functio... | ```python
from typing import List, Tuple
def calculate_total_time(hex_times: List[str]) -> Tuple[int, int]:
total_minutes = sum(int(hex_time, 16) for hex_time in hex_times)
hours = total_minutes // 60
minutes = total_minutes % 60
return hours, minutes
# Test the function with the given input
hex_times... | magicoder | python |
You are tasked with implementing a function to scale a given floating-point number to a specific range. The function should take a floating-point number and a range, and return the scaled value within the specified range. The scaling should be performed using the following formula: scaled_value = (input_value - min_inp... | ```rust
fn scale_value(input_value: f64, min_input: f64, max_input: f64, min_output: f64, max_output: f64) -> f64 {
(input_value - min_input) / (max_input - min_input) * (max_output - min_output) + min_output
}
```
The `scale_value` function takes the input value and scales it to the specified output range using th... | magicoder | rust |
You are tasked with implementing an overuse detector for monitoring bandwidth usage in a real-time communication system. The provided code snippet is a part of the existing overuse detector implementation and includes relevant member variables and a method.
Your task is to complete the implementation of the `OveruseDe... | ```cpp
void OveruseDetector::UpdateState(double offset) {
int64_t nowMs = GetCurrentTimeMs(); // Assume a function to get the current time in milliseconds
if (lastUpdateMs == -1) {
lastUpdateMs = nowMs;
prevOffset = offset;
return; // Initial state, no update needed
}
double ... | magicoder | cpp |
You are tasked with implementing a simplified version of an asynchronous function for setting the owner of a contract in a blockchain environment. The provided code snippet is a part of a larger system that interacts with smart contracts on a blockchain. The `SetOwnerRequestAsync` method takes a `SetOwnerFunction` obje... | ```csharp
using System;
using System.Threading.Tasks;
public class SetOwnerFunction
{
public string ContractAddress { get; set; }
public string NewOwnerAddress { get; set; }
// Other properties as needed
}
public class ContractHandler
{
public static async Task<string> SetOwnerRequestAsync(SetOwnerFun... | magicoder | csharp |
You are given a string representing a pattern of braces, brackets, and parentheses. Your task is to determine if the pattern is valid, meaning that every opening brace, bracket, or parenthesis has a corresponding closing one in the correct order.
For example, the string "({})[]" is valid, while "({[})" is not.
Write ... | ```cpp
#include <stack>
#include <unordered_map>
#include <string>
bool isValidPattern(std::string pattern) {
std::stack<char> stack;
std::unordered_map<char, char> matching = {{')', '('}, {']', '['}, {'}', '{'}};
for (char c : pattern) {
if (c == '(' || c == '[' || c == '{') {
stack.p... | magicoder | cpp |
You are tasked with implementing a simple prompt system for a command-line interface. The prompt system should support requesting and responding to prompts of different kinds.
You are provided with a code snippet from a Rust module that imports and uses components related to the prompt system. The `PromptRequester` an... | ```rust
use crate::error::Result;
enum RequestKind {
Input,
Confirmation,
Selection,
}
enum ReportKind {
Success,
Error,
}
struct PromptRequester;
impl PromptRequester {
fn request_prompt(&self, kind: RequestKind) -> String {
match kind {
RequestKind::Input => {
... | magicoder | rust |
You are tasked with implementing a Python module for a language model challenge. The module should support the core functionality for the challenge and define a class `Model` along with various utilities. The provided code snippet is a part of the module and imports specific classes from the `model` submodule.
Your ta... | ```python
# Define the base class Model for the language model
class Model:
def __init__(self):
pass
# Add methods and attributes as needed for the base class
# Define a subclass FilteringWordModel inheriting from Model
class FilteringWordModel(Model):
def __init__(self):
super().__init__()... | magicoder | python |
You are tasked with implementing a class `AddressComparator` that contains a method `areOverlapping` to compare two network addresses. The method should return `true` if the two addresses overlap, i.e., if they represent overlapping IP ranges or if one address is contained within the other. The method should return `fa... | ```java
public class AddressComparator {
private boolean areOverlapping(String address1, String address2){
if(address1.contains("/") && address2.contains("/")){
return ipUtils.overlap(address1, address2);
} else if (address1.contains("/") && !address2.contains("/")){
return i... | magicoder | java |
You are tasked with implementing a custom view modifier in Swift that applies a style modification to a radial segments view. The provided code snippet is a part of the implementation of the `RadialSegmentsStyleWrapper` view modifier. Your task is to complete the implementation of the `RadialSegmentsStyleWrapper` and c... | ```swift
private struct RadialSegmentsStyleWrapper<StyleValue>: ViewModifier {
@Environment(\.radialSegmentsStyle)
private var currentStyle: RadialSegmentsStyle
var modifier: (RadialSegmentsStyle) -> RadialSegmentsStyle
init(segmentId: AnyHashable, value: StyleValue, keyPath: WritableKeyPath<RadialSe... | magicoder | swift |
You are given a Python function that takes in a list of integers and returns the maximum sum of a contiguous subarray within the input list. Your task is to complete the function by implementing the algorithm to find the maximum sum of a contiguous subarray.
The function signature is:
```python
def max_subarray_sum(ar... | ```python
from typing import List
def max_subarray_sum(arr: List[int]) -> int:
max_sum = arr[0]
current_sum = arr[0]
for num in arr[1:]:
current_sum = max(num, current_sum + num)
max_sum = max(max_sum, current_sum)
return max_sum
```
The solution uses Kadane's algorithm to find the m... | magicoder | python |
You are tasked with implementing a custom property wrapper in Swift that enforces a maximum length constraint on the wrapped value. The property wrapper should truncate the value to the specified maximum length if it exceeds it. Your task is to complete the implementation of the `MaxLength` property wrapper and apply i... | ```swift
// Define the MaxLength property wrapper
@propertyWrapper
struct MaxLength {
private var value: String = ""
private let maxLength: Int
init(maxLength: Int) {
self.maxLength = maxLength
}
var wrappedValue: String {
get { value }
set {
if newValue.count >... | magicoder | swift |
You are tasked with creating a parallel computing program to calculate the sum of a large array of numbers using MPI (Message Passing Interface). The program should be able to scale efficiently with an increasing number of processes.
Your task is to implement a parallel sum calculation program using MPI in C. The prog... | ```c
// parallel_sum.c
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#define ARRAY_SIZE 1000000000
int main(int argc, char *argv[]) {
int rank, size;
int *array;
long long local_sum = 0, global_sum = 0;
double start_time, end_time, total_time;
MPI_Init(&argc, &argv);
MPI_Comm_rank(M... | magicoder | c |
You are tasked with creating a Python function that processes and analyzes COVID-19 data from different regions and states. The function should take a list of dictionaries as input, where each dictionary represents COVID-19 data for a specific region and state on a given date. The function needs to perform the followin... | ```python
import datetime
def analyze_covid_data(covid_data):
region_state_cases_deaths = {}
max_cases = 0
max_deaths = 0
region_with_highest_cases = ''
state_with_highest_cases = ''
region_with_highest_deaths = ''
state_with_highest_deaths = ''
for entry in covid_data:
region ... | magicoder | python |
You are tasked with implementing a simple parameter loader for a machine learning framework. The parameter loader is responsible for initializing and managing a buffer of floating-point values used as parameters in a neural network.
Your task is to create a Swift class that conforms to the `ParameterLoader` protocol p... | ```swift
import Foundation
import MetalBender
class RandomParameterLoader: ParameterLoader {
private(set) var pointer: UnsafeMutablePointer<Float>
var checkpoint: String = ""
init(maxSize: Int) {
let p = malloc(maxSize * MemoryLayout<Float>.stride)
pointer = p!.bindMemory(to: Float.self, ... | magicoder | swift |
You are tasked with implementing a neural network training loop with different inference methods for a Bayesian neural network (BNN). The code snippet provided sets some initial configuration parameters for the training loop. Your task is to complete the training loop for each inference method and evaluate the performa... | ```python
# Import necessary libraries
import numpy as np
import tensorflow as tf
from tensorflow_probability import distributions as tfd
# Define the neural network architecture
def build_bnn_model():
model = tf.keras.Sequential([
tfp.layers.DenseFlipout(128, activation='relu'),
tfp.layers.DenseFl... | magicoder | python |
You are tasked with creating a command-line tool for running unit tests on a software project. The tool should support multiple subcommands and their respective functionalities. Your task is to implement the functionality for the "test" command, which has subcommands for "help", "nose", "pytest", and "tox".
The "test"... | ```python
class TestCommandHandler:
def handle_command(self, command):
if command.cmd == "test":
if command.argc > 1:
if command.cmd2 == "help":
self.display_help()
elif command.cmd2 == "nose":
self.run_nose_tests()
... | magicoder | python |
You are tasked with implementing a password hashing and verification system using the provided code snippet as a reference. Your goal is to create a class that provides methods for hashing passwords and verifying them against their hashes.
You need to implement a PHP class with the following methods:
```php
class Pass... | ```php
class PasswordManager {
/**
* Returns the hash of the given password using PHP's password_hash function.
*
* @param string $password
* @return string
*/
public function hash(string $password): string {
return password_hash($password, PASSWORD_DEFAULT);
}
/**
... | magicoder | php |
You are tasked with implementing a hill climbing algorithm to optimize a given function. The hill climbing algorithm is a heuristic search algorithm used for mathematical optimization problems. In this problem, you are required to implement the hill climbing iteration, acceptance criteria, and consideration steps.
The... | ```python
class HillClimbingAlgorithm:
def _hill_climb_iteration(self, _cand_, _p_, X, y):
# Implement the hill climbing iteration to update the candidate solution and the best solution found so far
# Example implementation:
# Update the candidate solution based on the input data X and y
... | magicoder | python |
You are tasked with creating a program that simulates a simple scene configuration system for a user interface. The program should allow users to define and select different configurations for creating new scenes. Each configuration consists of a name and a session role.
Your task is to implement a class `UISceneConfi... | ```swift
// UISceneConfiguration class representing a scene configuration
class UISceneConfiguration {
let name: String
let sessionRole: String
init(name: String, sessionRole: String) {
self.name = name
self.sessionRole = sessionRole
}
func description() -> String {
... | magicoder | swift |
You are tasked with implementing a custom iterator in C# that processes a sequence of values and performs a specific operation on each value. The iterator will be responsible for iterating through the values and applying the operation defined by the `DefinedValues` array.
Your task is to complete the implementation of... | ```csharp
using System;
namespace NQuery.Runtime.ExecutionPlan
{
internal sealed class ConstantIterator : Iterator
{
public RuntimeComputedValueOutput[] DefinedValues;
private bool _isEof;
private int _currentIndex;
public override void Open()
{
_isEof = fal... | magicoder | csharp |
You are tasked with implementing a simplified version of a routing system for an HTTP server. The provided code snippet is a part of a Java-based HTTP server framework. The `route` method is used to define routes for the server through the provided `HttpServerRoutes` builder. The `HttpServerRoutes` builder allows the d... | ```java
import java.util.Objects;
import java.util.function.Consumer;
// Represents an HTTP method (e.g., GET, POST)
enum HttpMethod {
GET, POST, PUT, DELETE
}
// Represents the context of an HTTP request
class HttpContext {
HttpMethod method;
String path;
public HttpContext(HttpMethod method, String... | magicoder | java |
You are tasked with implementing a validation system for a JSON schema. The system should be able to handle various types of errors and provide detailed information about the validation failures.
Your task is to create a Rust function that processes validation errors and constructs a detailed error message based on th... | ```rust
fn process_validation_errors(errors: Vec<SchemaValidationError>) -> Vec<String> {
let mut error_messages = Vec::new();
for error in errors {
match error.kind {
SchemaErrorKind::ValidationError { error: err_msg } => {
let mut message = format!("Validation error: {}", ... | magicoder | rust |
You are tasked with implementing a Python function that calculates the total number of unique words in a given text file. The function should ignore case sensitivity and consider any non-alphanumeric characters as word delimiters. Additionally, the function should exclude any common English stop words (e.g., "the", "an... | ```python
import re
def count_unique_words(file_path: str) -> int:
stop_words = {"the", "and", "is", "it", "for", "in", "of", "some", "a", "an"}
with open(file_path, 'r') as file:
text = file.read().lower()
words = re.findall(r'\b\w+\b', text)
unique_words = set(words) - stop_words
... | magicoder | python |
You are given a code snippet that contains a series of constraints being applied to various UI elements in a mobile application. Your task is to write a function that parses this code snippet and extracts the constraints being applied to each UI element.
Write a function `parseConstraints(code: String) -> [String: [St... | ```swift
func parseConstraints(code: String) -> [String: [String]] {
var constraints: [String: [String]] = [:]
let lines = code.components(separatedBy: .newlines)
var currentElement: String?
var currentConstraints: [String] = []
for line in lines {
if let element = line.components(... | magicoder | swift |
You are tasked with implementing a simple transaction processing system. The system should be able to handle deposits, withdrawals, and provide the account balance after each transaction. The transactions are represented as a list of dictionaries, where each dictionary contains the transaction type ('deposit' or 'withd... | ```python
def process_transactions(transactions):
balance = 0
for transaction in transactions:
if transaction['type'] == 'deposit':
balance += transaction['amount']
elif transaction['type'] == 'withdrawal':
balance -= transaction['amount']
return balance
```
The `proc... | magicoder | python |
You are tasked with implementing a function that processes a message header and returns an adjusted size value based on certain conditions. The function takes an integer `errno` and a buffer `header` as input. The code snippet provided is a part of the function and shows some operations performed on the return value `r... | ```c
#include <errno.h>
ssize_t processMessage(int errno, char* header) {
ssize_t ret = errno ? -errno : errno;
// Assuming pmsgHeader is a predefined structure or buffer
size_t pmsgHeaderSize = sizeof(pmsgHeader);
if (ret > (ssize_t)(sizeof(header) + pmsgHeaderSize)) {
ret -= (sizeof(header) - pmsgHeade... | magicoder | c |
You are tasked with implementing a Tic-Tac-Toe game in Python. The game will be played between two players, X and O, on a 3x3 grid. The game should have a method to play a turn, which takes the position (1-9) where the player wants to place their mark. The method should return 0 if the move is valid and the game contin... | ```python
class TicTacToe:
def __init__(self):
self.board = [' ']*9
self.winning_combinations = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)]
def play_turn(self, position):
if position < 1 or position > 9 or self.board[position-1] != ' ':
... | magicoder | python |
You are tasked with implementing a custom class that inherits from the `ndarray` class in Python's NumPy library. The provided code snippet serves as a starting point for the implementation. Your task is to complete the custom class by adding specific functionality and ensuring that it behaves as expected when used in ... | ```python
import numpy as np
class CustomArray(np.ndarray):
def __new__(cls, input_array):
# Input array is an already formed ndarray instance
# We first cast to be our class type
obj = np.asarray(input_array).view(cls)
return obj
@property
def shape(self):
return s... | magicoder | python |
You are tasked with implementing a password validation system for a user class in Python. The user class has a method `set_password` that takes a password as input and sets it for the user. The password must adhere to the following rules:
1. It must be at least 8 characters long.
2. It must contain at least one upperca... | ```python
import re
import unittest
class User:
def __init__(self, password=None):
self.password = password
def set_password(self, new_password):
if len(new_password) < 8:
raise ValueError("Password must be at least 8 characters long")
if not re.search(r"[A-Z]", new_passwor... | magicoder | python |
You are tasked with creating a Python class for training and evaluating a neural network model to calculate propensity scores for a medical treatment dataset. Propensity scores are used to estimate the causal effect of a treatment by balancing the distribution of observed covariates between treated and control groups. ... | ```python
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
class Propensity_score_network:
def __init__(self):
# Define the neural network architecture
self.model = nn.Sequential(
nn.Linear(input_size, hidden_size),
nn.ReLU(),
nn.... | magicoder | python |
You are tasked with implementing a function to compare two streams of data and determine if they are equal. The streams are represented as `std::stringstream` objects in C++. The function should return `true` if the streams are equal and `false` if they are not.
Your task is to implement the `compare_streams` function... | ```cpp
#include <sstream>
#include <string>
bool compare_streams(const std::stringstream& first, const std::stringstream& second) {
// Get the content of the streams as strings
std::string firstContent = first.str();
std::string secondContent = second.str();
// Compare the content of the streams
r... | magicoder | cpp |
You are tasked with creating a function that processes user updates and photo uploads in a user management system. The function `update` takes in various user details and a photo, and then makes an HTTP request to update the user information. If a photo is provided, it is also processed. Your task is to implement the l... | ```typescript
update(photo: File, id: string, name: string, surname: string, email: string, phoneNumber: string, city: string, degree: string, freelance: string, category: string, description: string): void {
this.userService.putUser(id, name, surname, email, phoneNumber, city, degree, freelance, category, descriptio... | magicoder | typescript |
You are tasked with creating a program that processes Excel spreadsheets and applies formatting to specific cell ranges. Your program should utilize the Laravel Excel package, which provides an event-driven architecture for manipulating Excel files. The given code snippet is a part of a Laravel Excel event listener tha... | ```php
use Maatwebsite\Excel\Sheet;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterSheet;
use PhpOffice\PhpSpreadsheet\Style\Font;
class ExcelFormatter implements WithEvents
{
private $cellRange;
private $fontSize;
private $bold;
public function __construct($cellRange, $f... | magicoder | php |
You are tasked with implementing a neural network using the Haiku library in JAX. The given code snippet is a part of a larger neural network definition and shows the usage of the `hk.Conv2D` layer, the `jax.nn.relu` activation function, and the `hk.Flatten` layer. Your task is to complete the neural network definition... | ```python
import haiku as hk
import jax
import jax.numpy as jnp
def create_neural_network(x, mode):
if mode == "complex":
net_fn = lambda x: hk.Sequential([
hk.Conv2D(64, kernel_shape=[3, 3], stride=[1, 1], padding='VALID'),
jax.nn.relu,
hk.Flatten(),
hk.Lin... | magicoder | python |
You are tasked with creating a script to unpack keys from a JSON file and perform specific actions based on the extracted data. The JSON file contains information about keys, including the associated user and group. Your task is to write a Bash script that accomplishes the following:
1. Check if the JSON file is empty... | ```bash
#!/bin/bash
keys_file="keys.json"
if [[ $(< "$keys_file") = "{}" ]]; then
echo "no keys to unpack"
exit
fi
echo "unpacking $keys_file"
# extract the keys from .user.json
for keyname in $(jq -S -r 'keys[]' "$keys_file"); do
echo "unpacking: $keyname"
user=$(jq -r ".\"$keyname\".\"user\"" < "$keys_fil... | magicoder | shell |
You are tasked with implementing a steganography algorithm to hide a message within an image. Steganography is the practice of concealing a message within another non-secret file or message in a way that the existence of the hidden message is undetectable. In this case, you will be hiding a message within the RGB value... | ```python
from typing import List, Tuple
def hide_message(image: List[List[Tuple[int, int, int]]], byte_arr: List[int]) -> List[List[Tuple[int, int, int]]]:
bit_idx = 0
for i in range(len(image)):
for j in range(len(image[0])):
ori_pixel = image[i][j]
val = [ori_pixel[0], ori_pi... | magicoder | python |
You are tasked with implementing a bingo game simulator in Rust. The game involves drawing numbers from a pool and marking them on a bingo card. The bingo card is represented as a 5x5 grid, with the center cell marked as "FREE". The numbers drawn are in the range of 1 to 75, and each column of the bingo card correspond... | ```rust
fn simulate_bingo_game() -> i32 {
let mut card: [[bool; 5]; 5] = [[false; 5]; 5];
card[2][2] = true; // Mark the center cell as "FREE"
let mut drawn_numbers: Vec<u32> = Vec::new();
let mut rng = rand::thread_rng();
// Function to check win conditions
fn check_win(card: &[[bool; 5]; 5])... | magicoder | rust |
You are tasked with creating a web application that allows users to manage announcements. The code snippet provided is a part of the user interface for deleting an announcement. The snippet includes an HTML-like syntax with a custom tag `<x:heroicon-o-trash>` representing an icon for the "Delete announcement" action. A... | The `deleteAnnouncement` function first retrieves the user object based on the provided `user_id`. It then checks if the user has the permission to delete announcements using the `hasPermission` method. If the user is authorized, the function retrieves the announcement object based on the provided `announcement_id` and... | magicoder | python |
You are tasked with creating a Python function that validates and processes a list of positive integers. The function should raise a custom exception if any non-positive integer is encountered in the list. Additionally, the function should return a new list containing the square of each valid positive integer.
Your ta... | ```python
from typing import List
class NonPositiveIntegerError(Exception):
pass
def process_positive_integers(input_list: List[int]) -> List[int]:
result = []
for num in input_list:
if num <= 0:
raise NonPositiveIntegerError("Non-positive integer found!")
result.append(num ** ... | magicoder | python |
You are tasked with implementing a custom exception handling mechanism for a simple file processing program. The program is expected to read data from a file, perform some operations, and then write the results to another file. Your task is to handle potential exceptions that may occur during the file processing and pr... | ```cpp
#include <iostream>
#include <fstream>
#include <string>
// Custom exception classes
class FileOpenException : public std::exception {
public:
const char* what() const noexcept override {
return "Error: Failed to open the file.";
}
};
class FileReadException : public std::exception {
public:
... | magicoder | cpp |
You are tasked with creating a Python program to visualize data using Matplotlib. The program should take input from the user to customize the plot appearance and display the data in a visually appealing manner.
Your program should include the following functionalities:
1. Accept user input for the type of plot to be ... | ```python
import matplotlib.pyplot as plt
# Function to create and display the plot based on user input
def create_custom_plot():
plot_type = input("Enter the type of plot (line/scatter/bar): ").lower()
# Prompt user for data points
data_points = input("Enter the data points (comma-separated values): ... | magicoder | python |
You are tasked with implementing a function to simplify a 3D mesh representation using the Douglas-Peucker algorithm. The input to the function is a list of vertices and a list of faces, where each face is represented by the indices of its vertices. The function should simplify the mesh by reducing the number of vertic... | ```python
import numpy as np
def simplify_mesh(vertices, faces, tolerance):
def distance_point_to_line(p, p1, p2):
# Calculate the distance between point p and the line formed by points p1 and p2
return np.linalg.norm(np.cross(p2 - p1, p1 - p)) / np.linalg.norm(p2 - p1)
def simplify_recursive(... | magicoder | python |
You are tasked with creating a step counter application for iOS using Swift. The application should utilize the Pedometer sensor to track the user's steps and display the step count on the screen. The Pedometer sensor provides data about the number of steps taken by the user.
Your task is to implement a function that ... | ```swift
import UIKit
import com_awareframework_ios_sensor_pedometer
class ViewController: UIViewController {
var sensor: PedometerSensor?
@IBOutlet weak var stepCountLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typi... | magicoder | swift |
You are given a list of 2D points representing the coordinates of various locations on a map. Your task is to write a function that calculates the distance between each pair of points and returns a matrix of distances.
Create a function `calculate_distances(points)` that takes in a list of tuples `points`, where each ... | ```python
import math
def calculate_distances(points):
n = len(points)
distances = [[0.0 for _ in range(n)] for _ in range(n)]
for i in range(n):
for j in range(i+1, n):
x1, y1 = points[i]
x2, y2 = points[j]
distance = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
... | magicoder | python |
You are tasked with implementing a tracking system for attributes in a Python program. The system should identify and track the usage of specific attributes within the program. The attributes to be tracked are denoted by comments in the code, using the format `$tracked=attr` or `$tracked tracked=attr`. The first format... | ```python
from typing import Optional, List
class AttributeTracker:
tracked_attributes: dict
def __init__(self):
self.tracked_attributes = {}
def track_attribute(self, attr: str, tracked: Optional[str] = None):
if tracked:
if attr in self.tracked_attributes:
se... | magicoder | python |
You are tasked with implementing a generic tree traversal function in C++. The function `treeNode` takes in a branch node, a command for the traversal, and the start and end indices for the traversal. The `BranchNodeSO` is a template class representing a branch node in a tree, and `WalkCmd` is an enum representing diff... | ```cpp
template <typename CtrT, typename NodeTypes>
VoidResult treeNode(const BranchNodeSO<CtrT, NodeTypes>& node, WalkCmd cmd, int32_t start, int32_t end) noexcept {
if (start < 0 || end < start) {
return VoidResult::Error("Invalid range");
}
if (cmd == WalkCmd::PreOrder) {
// Perform pre-... | magicoder | cpp |
You are tasked with creating a command-line tool to automate the process of pushing a podspec file to a private CocoaPods repository. The tool should handle various options and provide verbose output while allowing warnings during the push process.
Your task is to implement a Python script that takes in the necessary ... | ```python
import subprocess
import argparse
def push_podspec_to_repo(podspec_file, repo_name, verbose=False, allow_warnings=False):
command = ['pod', 'repo', 'push', repo_name, f'{podspec_file}.podspec']
if verbose:
command.append('--verbose')
if allow_warnings:
command.append('--... | magicoder | python |
You are tasked with implementing a class method for a grade calculator. The method `weight_average` takes a list of grades `v` and calculates the weighted average of the grades based on the credits associated with each grade. The class has attributes `owned_grades`, `owned_credits`, and `tot_credits` representing the g... | ```python
class GradeCalculator:
def __init__(self, owned_grades, owned_credits, tot_credits):
self.owned_grades = owned_grades
self.owned_credits = owned_credits
self.tot_credits = tot_credits
def weight_average(self, v):
term1 = 0
term2 = 0
for i in range(0, le... | magicoder | python |
You are tasked with implementing a function to calculate the value of a mathematical expression based on the given code snippet. The code snippet initializes some variables and calls a function to set the number of perturbations. Your task is to write a function that uses the initialized variables to compute the value ... | ```cpp
#include <cmath>
class ExpressionCalculator {
private:
double a;
double c;
double A;
double alpha;
double gamma;
public:
void initializeVariables(double a, double c, double A, double alpha, double gamma) {
this->a = a;
this->c = c;
this->A = A;
this->alph... | magicoder | cpp |
You are tasked with implementing a Python function that converts the result of an SQL query into a JSON array. The function should take a list of parameters as input and return an array containing JSON strings.
The function signature and documentation are provided in the following code snippet:
```python
"""
| ##@函数目的... | ```python
import json
def sql_to_json(paramList):
"""
Convert the result of an SQL query into a JSON array.
Args:
paramList (list): List of parameters.
Returns:
list: Array containing JSON strings.
Function Logic:
- Iterate through the paramList and convert each SQL result to a JSON ... | magicoder | python |
You are tasked with creating a Python function that reads a configuration file and extracts specific information from it. The configuration file follows the INI file format, which consists of sections, keys, and values. Each section is denoted by square brackets, and each key-value pair is separated by an equal sign.
... | ```python
def extract_config_info(file_path: str, section: str, key: str) -> str:
try:
with open(file_path, 'r') as file:
content = file.read()
section_start = content.find(f'[{section}]')
if section_start == -1:
return "Not found"
section_end ... | magicoder | python |
You are working on a 3D graphics engine and need to implement a class for managing mobile objects in a 3D space. The provided code snippet includes part of the implementation for the mobile object class. Your task is to complete the implementation of the `MobileObject` class by adding methods for rotation and scaling, ... | ```python
import numpy as np
class MobileObject:
def __init__(self):
self.position = np.array([0, 0, 0])
self.rotation_matrix = np.identity(3)
self.scale_factor = 1
def setPosition(self, x, y, z):
self.position = np.array([x, y, z])
def setRotation(self, angle, axis):
... | magicoder | python |
You are given a sequence of integers `seq` and a substitute value `sub_value`. Your task is to write a function `substitute_sequence(seq, sub_value)` that generates a new sequence `out1` by substituting elements of `seq` with `sub_value` under the following conditions:
1. The length of the substituted sequence should b... | ```python
from typing import List
def substitute_sequence(seq: List[int], sub_value: int) -> List[int]:
out1 = []
max_val = max(seq)
if sub_value <= max_val or len(seq) <= 1:
return out1
for num in seq:
if num < sub_value:
out1.append(sub_value)
else:
... | magicoder | python |
You are tasked with creating a Python function to train a reinforcement learning agent using the Advantage Actor-Critic (A2C) algorithm for a Snake game environment. The A2C algorithm is a popular reinforcement learning technique that combines value-based and policy-based methods for training agents in environments wit... | ```python
def train_a2c_model(agent, envs, params, num_batches):
for batch in range(num_batches):
# Reset environment and get initial state
states = envs.reset()
dones = [False] * params.num_envs
total_rewards = [0] * params.num_envs
while not all(dones):
# Colle... | magicoder | python |
You are working on a system that involves manipulating and signing image files using a tool called BPAK and then booting the signed image using a tool called PB. Your task is to write a script that automates this process.
Given the provided code snippet as a reference, write a script in Bash that performs the followin... | ```bash
#!/bin/bash
# Add metadata to the image file
$BPAK add $IMG --meta pb-load-addr --from-string 0x49000000 --part-ref kernel --encoder integer $V
# Add the kernel partition to the image file
$BPAK add $IMG --part kernel --from-file /tmp/random_data $V
# Sign the image file with a specific key and key ID
$BPAK ... | magicoder | shell |
You are tasked with implementing a custom scope management system for a programming language. The system should handle entering and exiting different scopes and keeping track of the current scope.
You are given a code snippet from a visitor class that traverses a CSS abstract syntax tree (AST). The `enterMixinDefiniti... | ```java
public class ScopeManager {
private Stack<Object> scopeStack = new Stack<>();
public void enterMixinDefinition(CssMixinDefinitionNode node) {
scopeStack.push(node);
}
public void enterRuleset(CssRulesetNode node) {
scopeStack.push(node);
}
public void exitScope() {
... | magicoder | java |
You are tasked with implementing an `EmailPredicate` class that validates email addresses based on the following criteria:
1. The email address must contain a local part and a domain part separated by an "@" symbol.
2. The local part can contain letters, digits, and the following special characters: ! # $ % & ' * + - /... | ```swift
class EmailPredicate {
func evaluate(with email: String) -> Bool {
let emailRegex = "^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)+$"
let emailPredicate = NSPredicate(format: "SELF MATCHES %@", emailRegex)
return emailPredicate.evaluate(with: email)
}
}
let ... | magicoder | swift |
You are tasked with creating a program to solve the graph coloring problem using a backtracking algorithm. The graph coloring problem involves assigning colors to vertices of a graph in such a way that no two adjacent vertices have the same color. The given code snippet is a sequence of commands that compiles and runs ... | ```java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class BacktrackingGraphColoring {
private int[][] graph;
private int[] colors;
private int numVertices;
private int numColors;
private int maxIterations;
public BacktrackingGraphColoring(String ... | magicoder | java |
You are working on a data processing library in Rust and need to implement a method for converting a data series to a new series containing the minimum and maximum values from the original series. The input series can contain numeric or UTF-8 data types. You need to handle the conversion and potential errors that may a... | ```rust
use arrow::array::{ArrayRef, concatenate};
use std::sync::Arc;
pub enum DataType {
// Implementation not relevant to this problem
}
impl DataType {
fn from(data_type: &str) -> DataType {
// Implementation not relevant to this problem
}
fn is_numeric(&self) -> bool {
// Implemen... | magicoder | rust |
You are tasked with implementing a markdown parser function in TypeScript. The function should take a markdown string and an optional set of parsing options, and return a Promise resolving to the parsed HTML string.
You are provided with the following interface for the markdown parser function:
```typescript
interface... | ```typescript
interface IMarkdownParserOptions {
// Define any specific parsing options here
}
class MyMarkdownParser implements IMarkdownParser {
parse(markdownText: string, options?: IMarkdownParserOptions): Promise<string> {
return new Promise<string>((resolve, reject) => {
// Implement the parsing lo... | magicoder | typescript |
You are given a code snippet that initializes an array `count` with zeros, and then iterates through a dictionary to extract key and value numbers from strings. Your task is to write a function that takes a dictionary and returns the total count of entries in the dictionary, along with the sum of all key and value numb... | ```python
def processDictionary(dictionary):
totalCount = 0
sumKeyNumbers = 0
sumValueNumbers = 0
for key, value in dictionary.items():
totalCount += 1
# Extract keyNumber from a string of the form key<keyNumber>
keyNumber = int(key[3:])
# Extract valueNumber from a st... | magicoder | python |
You are tasked with creating a Java program that simulates a simple banking system. The program should allow users to create accounts, deposit and withdraw funds, and check their balance. The accounts and their transactions should be stored in memory.
Your task is to implement the `BankingSystem` class, which should h... | ```java
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
class Account {
private int accountNumber;
private double balance;
public Account(int accountNumber, double initialBalance) {
this.accountNumber = accountNumber;
this.balance = initialBalance;
}
publ... | magicoder | java |
You are tasked with creating a program that extracts and processes URLs from a given input string. Your program should take a string as input and identify all the valid URLs within the input. A valid URL should start with "http://" or "https://" and may be followed by any combination of alphanumeric characters, dots, s... | ```python
import re
def extract_urls(input_string):
pattern = r'https?://\S+?\.\w+'
return re.findall(pattern, input_string)
```
The `extract_urls` function uses the `re.findall` method from the `re` module to search for all occurrences of the specified URL pattern within the input string. The pattern `r'http... | magicoder | python |
You are given a set of 3D points represented as (x, y, z) coordinates. Each point is represented as a triplet of integers. Your task is to write a program to calculate the distance between all pairs of points and find the pair of points with the maximum distance between them.
Write a function `max_distance_between_poi... | ```python
import itertools
import math
def distance(point1, point2):
return math.sqrt((point2[0] - point1[0])**2 + (point2[1] - point1[1])**2 + (point2[2] - point1[2])**2)
def max_distance_between_points(points):
max_dist = 0
max_pair = ()
for pair in itertools.combinations(points, 2):
dist = ... | magicoder | python |
You are tasked with implementing a Python function that generates a list of all possible combinations of a given list of items. The function should take a list of items as input and return a list of lists, where each inner list represents a unique combination of the input items.
The function signature should be:
```py... | ```python
from typing import List
def generate_combinations(items: List[int]) -> List[List[int]]:
result = []
n = len(items)
# Generate all possible combinations using bit manipulation
for i in range(1 << n):
combination = [items[j] for j in range(n) if (i & (1 << j))]
result.append(co... | magicoder | python |
You are given a string containing HTML tags. Your task is to write a function that removes all HTML tags from the string and returns the resulting plain text.
Write a function:
```python
def remove_html_tags(html: str) -> str:
pass
```
The function should take a single parameter:
- `html` (1 <= len(html) <= 10^5)... | ```python
import re
def remove_html_tags(html: str) -> str:
clean_text = re.sub(r'<[^>]*>', '', html) # Use regular expression to remove all HTML tags
return clean_text
```
The `remove_html_tags` function uses the `re.sub` method from the `re` module to replace all occurrences of HTML tags with an empty stri... | magicoder | python |
You are tasked with implementing a simplified version of a stack-based job execution system. The system consists of a `StackJob` struct, a `LockLatch` struct, and a `JobRegistry` struct. The `StackJob` struct represents a job to be executed, the `LockLatch` struct is used for synchronization, and the `JobRegistry` stru... | ```rust
// Define the StackJob struct
struct StackJob<T> {
op: T,
latch: LockLatch,
}
impl<T> StackJob<T> {
// Create a new StackJob with the given operation and a new LockLatch
fn new(op: T, latch: LockLatch) -> Self {
StackJob { op, latch }
}
// Get a reference to the job
fn as_j... | magicoder | rust |
You are tasked with implementing a data structure that efficiently stores a batch of states and their corresponding hash values. The data structure should have a method to submit new states and update their hash values. Additionally, it should have a method to retrieve the current batch of states and their hash values.... | ```python
class StateDataStructure:
def __init__(self, batch_size):
self.max_size = batch_size
self.indices = set()
self._total = 0
self.dict = {}
self.states = []
self.prev = 0
self.roll = self.roller()
def submit(self, state, new=False):
hs = se... | magicoder | python |
You are tasked with implementing a function to retrieve the supported input method styles for an X11 input method in a C++ environment. The provided code snippet outlines the declaration of the function `get_supported_styles`, which takes an `sge::x11input::xim::method` object as a parameter and returns a `supported_st... | ```cpp
#include <sge/x11input/xim/get_supported_styles.hpp>
#include <sge/x11input/xim/supported_styles.hpp>
namespace sge::x11input::xim
{
sge::x11input::xim::supported_styles_unique_ptr get_supported_styles(sge::x11input::xim::method const &input_method)
{
// Implementation to retrieve supported inpu... | magicoder | cpp |
You are tasked with creating a Python function to parse network speed test output and extract the ping time, download speed, and upload speed. The network speed test output is a string containing the ping time, download speed, and upload speed in various formats. The ping time is in milliseconds (ms), and the download ... | ```python
def parse_output(output):
lines = output.split('\n')
ping_time = float(lines[0].split(': ')[1].split(' ms')[0])
download_speed = float(lines[1].split(': ')[1].split(' ')[0])
upload_speed = float(lines[2].split(': ')[1].split(' ')[0])
if 'Kbit/s' in lines[1]:
download_speed *= 1000... | magicoder | python |
You are tasked with implementing a Python function that calculates the factorial of a given non-negative integer using recursion. The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. For example, the factorial of 5 (denoted as 5!) is 5 * 4 * 3 * 2 * 1 = 120.
Your t... | ```python
def factorial_recursive(n: int) -> int:
if n == 0 or n == 1:
return 1
else:
return n * factorial_recursive(n - 1)
```
The `factorial_recursive` function first checks if the input `n` is 0 or 1, in which case it returns 1. Otherwise, it recursively calls itself with `n-1` and multiplie... | magicoder | python |
You are tasked with implementing a Python class that manages supervisor nodes in a distributed system. The provided code snippet is the beginning of a class definition for `SupervisorManager`, which is a subclass of `NodeManager`. The `SupervisorManager` class is responsible for managing supervisor nodes, which are use... | ```python
from .node import SupervisorNode
from ..core.node.manager import NodeManager
from ..core.node.base_node import Node
from ..core.action.executor import action_executor, executor_forwarder
from ..core.common.coro import NoneCoroManager
class SupervisorManager(NodeManager):
def __init__(self):
super... | magicoder | python |
You are tasked with implementing a function to retrieve data from a PostgreSQL database using Rust's async/await syntax. The provided code snippet is a part of an asynchronous Rust program that uses the `tokio-postgres` library to interact with a PostgreSQL database.
The `pool` variable represents a connection pool to... | ```rust
use tokio_postgres::types::ToSql;
use tokio_postgres::Row;
use tokio_postgres::types::Type;
use tokio_postgres::NoTls;
use tokio_postgres::Client;
use tokio_postgres::Error;
use tokio_postgres::types::FromSql;
use tokio_postgres::types::accepts;
use tokio_postgres::types::to_sql_checked;
use tokio_postgres::typ... | magicoder | rust |
You are tasked with implementing a convex hull algorithm for a 2D point set. The convex hull of a set of points is the smallest convex polygon that contains all the points. One common algorithm for finding the convex hull of a set of points is the Graham scan algorithm.
Your task is to implement the `GrahamScan` class... | ```python
from typing import List, Tuple
class GrahamScan:
def __init__(self, points: List[Tuple[float, float]]):
self.points = points
self._hull = []
def compute_convex_hull(self) -> List[Tuple[float, float]]:
def calculate_slope(p1: Tuple[float, float], p2: Tuple[float, float]) -> fl... | magicoder | python |
You are tasked with implementing a thread-safe database connection holder class in Java. The class should manage a single database connection and provide methods for acquiring and releasing the connection safely. The class should also ensure that the connection is only created once and reused across multiple threads.
... | ```java
import java.sql.Connection;
public class DbConnectionHolder {
private final DbConnectionProvider dbConnectionProvider;
private Connection connection;
public DbConnectionHolder(DbConnectionProvider dbConnectionProvider) {
this.dbConnectionProvider = dbConnectionProvider;
}
public s... | magicoder | java |
You are tasked with creating a program that simulates a simple command-line utility for managing a list of tasks. The program should support adding tasks, marking tasks as completed, and listing all tasks. The tasks should be stored in memory and should not persist beyond the program's execution.
Your program should s... | ```python
class TaskManager:
def __init__(self):
self.tasks = []
def add_task(self, description):
self.tasks.append((description, False))
def mark_task_as_done(self, index):
if 0 <= index < len(self.tasks):
task, status = self.tasks[index]
self.tasks[index] ... | magicoder | python |
You are tasked with implementing a function that simulates a simple file transfer protocol. The protocol involves sending and receiving files between a client and a server. The server is already set up and running, and it exposes two methods: `QueryInterface` and `GiveFeedback`. The `QueryInterface` method is used to e... | ```python
import socket
def transferFile(serverAddress, filePath):
# Establish connection with the server
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.connect((serverAddress, 12345)) # Assuming server port is 12345
# Send file transfer request
server_socket.send... | magicoder | python |
You are tasked with designing a user management system for a software application. The system should support three types of users: Gold users, Guest users, and Normal users. Each user type has specific attributes and behaviors associated with it.
The code snippet provided imports classes related to user pools and user... | ```python
# Define the GoldUserPool class to manage gold users
class GoldUserPool:
def __init__(self):
self.users = []
def add_user(self, user):
self.users.append(user)
def remove_user(self, user):
self.users.remove(user)
# Other methods for managing gold users can be added as... | magicoder | python |
You are tasked with creating a Python function that performs a specific binary file manipulation. The function, `binary_hook`, takes two arguments: `binf` (the input binary file) and `outf` (the output binary file). The function reads the contents of the input binary file, appends it to a specific section of another bi... | ```python
import sys
def binary_hook(binf, outf):
with open(binf, 'rb') as f:
appbin = f.read()
with open('boot.bin', 'rb') as f:
bootbin = f.read()
with open(outf, 'wb') as f:
padding = b'\xFF' * (0xc000 - len(bootbin))
f.write(bootbin + padding + appbin)
if __name__ == '_... | magicoder | python |
You are working on a quantum computing project and need to implement a function to manipulate quantum states. The function takes in three parameters: `p`, `n`, and `c`. The parameters `p` and `n` are positive integers representing the prime number and the dimension of the finite field, respectively. The parameter `c` i... | ```python
import numpy as np
def manipulate_quantum_state(p, n, c):
def zero_state(p, n):
# Implementation of zero_state function
pass
def finite_sp_matrix(elements):
# Implementation of finite_sp_matrix function
pass
def super_position_state(p, n):
# Implementatio... | magicoder | python |
You are given an array of integers representing the heights of a series of buildings. Your task is to write a function to calculate the amount of rainwater that can be trapped between the buildings after a rainstorm. The water is trapped within the gaps between the buildings, and it is assumed that the width of each bu... | ```java
public class TrappedWaterCalculator {
public static int calculateTrappedWater(int[] heights) {
int n = heights.length;
if (n < 3) {
return 0; // Not enough buildings to trap water
}
int[] leftMax = new int[n];
int[] rightMax = new int[n];
leftMax... | magicoder | java |
You are tasked with creating a Python function that simulates the behavior of the `run_get_node` function used in the given code snippet. The `run_get_node` function is responsible for executing a `CreateEvaluateWorkChain` workflow by chaining two basic processes and returning the result and node. Your task is to imple... | ```python
def simulate_run_get_node(workflow_factory, create_process, evaluate_process, create_input, output_input_mapping):
"""
Simulates the behavior of the run_get_node function by executing the CreateEvaluateWorkChain workflow.
"""
CreateEvaluateWorkChain = WorkflowFactory(workflow_factory)
... | magicoder | python |
You are tasked with implementing a function that constructs a window and a graphics context for a simple 2D game using the `winit` and `glutin` libraries in Rust. The provided code snippet initializes the window builder and context builder, setting specific OpenGL version and profile requirements.
Your task is to comp... | ```rust
use glutin::{event_loop::EventLoop, window::WindowBuilder, ContextBuilder, GlProfile, GlRequest, Api, PossiblyCurrent, WindowedContext};
fn create_window_and_context(event_loop: &mut EventLoop<()>) -> (WindowedContext<PossiblyCurrent>, WindowedContext<PossiblyCurrent>) {
let window_builder = WindowBuilder:... | magicoder | rust |
You are tasked with creating a custom deserializer for a specific data type in Rust. The data type in question is a URI (Uniform Resource Identifier), which is a string that identifies a resource. The deserializer needs to take a string representation of a URI and convert it into a valid `Uri` type. The `Uri` type is n... | ```rust
use serde::{de, Deserialize, Deserializer};
use std::str::FromStr;
// Assume a custom Uri type is defined elsewhere
struct Uri;
impl FromStr for Uri {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
// Custom parsing logic for Uri type
// Example: parsing th... | magicoder | rust |
You are tasked with creating a TypeScript interface for an authentication service in a web application. The interface should define the structure of the authentication services, including properties for labels, headers, descriptions, and profiles. Your task is to define the interface based on the given code snippet and... | ```typescript
// Define the AuthInterface
interface AuthInterface {
confirmLabel?: string;
header?: string;
description?: string;
failureHeader?: string;
failureDescription?: string;
}
// Define the AuthClickThroughService type
type AuthClickThroughService = IdOrAtId<string> & {
profile: 'http://iiif.io/ap... | magicoder | typescript |
You are working on a text editor application that supports the undo feature. The code snippet provided is a part of the implementation for handling transactions in the editor. The `tr.setMeta('addToHistory', false)` call is used to indicate that the transaction should not be added to the history, and `this.dispatchTran... | ```javascript
class Transaction {
constructor() {
this.history = [];
}
setMeta(key, value) {
this.meta = this.meta || {};
this.meta[key] = value;
}
dispatchTransaction(tr, addToHistory) {
if (addToHistory) {
this.history.push(tr);
}
// Dispatch the transaction
}
undo() {
... | magicoder | javascript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.