query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a Python class that handles the serialization and deserialization of data. The class should be able to process literal parameters and handle the deserialization of JSON data. Your task is to complete the implementation of the `PythonType` class and the `RoomState` class based on the giv... | ```python
import json
class PythonType:
def deserialize(self, value):
return json.loads(value)
class Base:
def process_literal_param(self, value, dialect):
return value
class RoomState(Base):
pass
```
In the `PythonType` class, the `deserialize` method is implemented to use the `json.loa... | magicoder | python |
You are working on a drone control system that interfaces with AirSim, a simulator for drones, cars, and other vehicles. The code snippet provided is a part of a method in the drone control system. The method is responsible for retrieving the orientation angles of the drone from the AirSim environment. The `toEulerianA... | ```python
def calculate_orientation_difference(camera_id):
camera_orientation = AirSimClientBase.toEulerianAngle(self.get_client().getCameraInfo(camera_id).pose.orientation)
drone_orientation = AirSimClientBase.toEulerianAngle(self.mystate_module.get_state().kinematics_true.orientation)
roll_diff = dro... | magicoder | python |
You are working on a deployment script for a web application and need to make some modifications to the configuration file based on certain conditions. Your task is to write a Python function that takes in several parameters and updates a JSON configuration file accordingly. The function should also execute some system... | ```python
import json
import os
def update_config_and_execute(data, aadTenant, aadClientId, webNodeAppSettingsFilePath, password):
data["Authentication"]["JWTSigningCertificate"]["StoreLocation"] = "CurrentUser"
data["Authentication"]["JWTSigningCertificate"]["SubjectName"] = "CN=LOCALHOST"
if aadTenant !... | magicoder | python |
You are tasked with implementing a class that manages a collection of unique integers. The class should provide methods for adding integers to the collection, removing integers from the collection, and checking if a given integer is present in the collection. Additionally, the class should support finding the maximum a... | ```java
import java.util.TreeSet;
public class UniqueIntegerCollection {
private TreeSet<Integer> integers;
public UniqueIntegerCollection() {
integers = new TreeSet<>();
}
public void addInteger(int num) {
integers.add(num);
}
public void removeInteger(int num) {
int... | magicoder | java |
You are tasked with creating a program that simulates a simple client-server interaction using sockets in C. The server will listen on a specified port, and the client will connect to the server using the telnet protocol. Your task is to implement the server-side code that listens for incoming connections and handles c... | ```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#define PORT 9876
#define MAX_CLIENTS 5
#define BUFFER_SIZE 1024
int main() {
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char ... | magicoder | c |
You are tasked with implementing a module resolution system for a JavaScript project. The project has a file structure where modules are organized into different directories, and each module can consume and provide bindings to other modules. The module resolution system needs to handle the import and export of bindings... | ```javascript
const path = require('path');
const fs = require('fs');
function resolveModuleBindings(modulePath) {
const resolvedPath = path.resolve(modulePath);
const moduleDir = path.dirname(resolvedPath);
const moduleContent = fs.readFileSync(resolvedPath, 'utf8');
const consumedBindings = [];
const prov... | magicoder | javascript |
You are tasked with creating a SQL query builder class for managing user roles in a web application. The class should be able to generate SQL queries for various operations related to user roles, such as retrieving roles for a specific user, adding a new role for a user, updating a user's role, and deleting a user's ro... | ```php
namespace App\DB\Providers\SQL\Factories\Factories\UserRole\Gateways;
use App\DB\Providers\SQL\Factories\SQLFactory;
use App\DB\Providers\SQL\Interfaces\SQLFactoriesInterface;
class UserRoleQueryBuilder implements SQLFactoriesInterface
{
public function getAllRolesForUserQuery($userId)
{
return... | magicoder | php |
You are tasked with creating a Rust library for handling text processing. The library should provide functionality for building nodes and working with text units. The code snippet provided includes some initial imports that will be essential for the library.
Your task is to implement the following components:
1. `bui... | ```rust
// node.rs
pub struct Node {
content: SmolStr,
// Other relevant fields
}
// builder.rs
use super::node::Node;
use smol_str::SmolStr;
pub trait Builder {
fn build_node(content: &str) -> Node {
Node {
content: SmjsonStr::from(content),
// Initialize other fields
... | magicoder | rust |
You are given a string containing a series of commands for combining elements. Each command consists of a prefix "-St" followed by a space and a comma-separated list of numbers in increasing order. For example, "-St 0,1,2" or "-St 0" or "-St 1,2". The numbers represent the elements to be combined. Your task is to write... | ```python
from typing import List
def combine_elements(commands: str) -> List[List[int]]:
if not commands:
return []
combined_elements = []
commands_list = commands.split("-St ")[1:]
for command in commands_list:
numbers = [int(num) for num in command.split(",")]
combined_eleme... | magicoder | python |
You are tasked with creating a program that generates a pattern of asterisks in a specific format. The program should take an integer input `n` and print a pattern of asterisks in the form of a diamond with 2n-1 rows. The top half of the diamond should have increasing number of asterisks in each row, while the bottom h... | ```python
def print_diamond_pattern(n):
# Print the top half of the diamond
for i in range(1, n+1):
print(" " * (n-i) + "*" * (2*i-1))
# Print the bottom half of the diamond
for i in range(n-1, 0, -1):
print(" " * (n-i) + "*" * (2*i-1))
# Example usage
n = 3
print_diamond_pattern(n... | magicoder | python |
You are given a string `s` consisting of lowercase English letters. Your task is to find the length of the longest substring without repeating characters.
Write a function `longest_substring_length` that takes in a string `s` and returns the length of the longest substring without repeating characters.
For example, g... | ```python
def longest_substring_length(s: str) -> int:
max_len = 0
l = 0
count = {}
for r in range(len(s)):
if s[r] in count:
l = max(l, count[s[r]] + 1)
count[s[r]] = r
max_len = max(max_len, r - l + 1)
return max_len
```
The `longest_substring_length` function ... | magicoder | python |
You are tasked with creating a program that reads a text file and counts the occurrences of each word in the file. Your program should ignore punctuation and consider words in a case-insensitive manner. Additionally, the program should output the top N most frequently occurring words and their respective counts.
Write... | ```python
from typing import List, Tuple
import string
def top_n_words(file_name: str, n: int) -> List[Tuple[str, int]]:
word_count = {}
with open(file_name, 'r') as file:
for line in file:
words = line.lower().translate(str.maketrans('', '', string.punctuation)).split()
for wor... | magicoder | python |
You are tasked with implementing a simple HTTP server that handles GET and POST requests. The server should respond to a GET request for a specific resource and a POST request to initiate a build process. Your task is to complete the implementation of the server's request handling functions.
You are provided with a Sw... | ```swift
func post(_ path: String, handler: (Request) throws -> Response) {
// Implementation for handling POST requests
do {
let request = Request() // Create a request object
let response = try handler(request) // Call the provided handler function
// Process the response as needed
... | magicoder | swift |
You are tasked with creating a rule validation system for a software application. The system should be able to run rules on a given context and return the result status along with any issues encountered during the validation process.
You are provided with a Python code snippet that demonstrates the execution and asser... | ```python
from enum import Enum
class RuleResultType(Enum):
SUCCESS = 1
FAILURE = 2
class RuleResult:
def __init__(self, status, issues):
self.status = status
self.issues = issues
class Rule:
def run(self, context, _):
# Perform rule validation logic here
# For demonst... | magicoder | python |
You are tasked with creating a Django model for managing time slots and time phases within those slots. The provided code snippet is a part of the model definition and includes a help text, a foreign key relationship, a string representation method, and a clean method.
Your task is to complete the implementation of th... | ```python
from django.db import models
from django.core.exceptions import ValidationError
class TimeSlot(models.Model):
# Define the TimeSlot model fields and methods here
pass
class TimePhase(models.Model):
description = models.CharField(max_length=100)
start_time = models.DateTimeField()
end_tim... | magicoder | python |
You are working on a reinforcement learning algorithm that utilizes PyTorch for neural network computations. The code snippet provided is a part of the algorithm's training process, specifically focusing on selecting the best action based on the Q-values and their corresponding probabilities.
The code involves the fol... | ```python
import torch
import torch.nn.functional as F
def calculate_q_values_and_probs(q_tp1, q_probs_tp1):
FLOAT_MIN = torch.tensor(1e-8) # Define the minimum threshold for Q-values
# Check if any Q-values are greater than FLOAT_MIN
q_tp1_best_mask = q_tp1 > FLOAT_MIN
# Select the best action base... | magicoder | python |
You are tasked with implementing a C++ template class for SPI peripheral configuration. The provided code snippet defines a namespace `hal` with two `spi_d` template instantiations, `spi1` and `spi2`/`spi3`. The `spi_d` template takes a single parameter representing the base address of the SPI peripheral.
Your task is... | ```cpp
#include <cstdint>
// Template class for SPI peripheral configuration
template <std::uint32_t BaseAddress>
class spi_d {
public:
// Constructor for initializing the SPI peripheral
spi_d() {
// Initialize SPI peripheral at the specified base address
// Implementation specific to the targe... | magicoder | cpp |
You are tasked with implementing a method to retrieve options based on a given type from a tracker system. The method `getTrackerOption` takes a string `typeS` as input, which can be one of the following: "@CAT" (category), "@PRC" (process type), or "@DEP" (user department). The method should return an array of strings... | ```java
import java.util.ArrayList;
import java.util.List;
public class TrackerSystem {
// Helper function to retrieve options from the tracker system
public String getStringAttribute(String attribute) {
// Implementation not provided
return ""; // Placeholder return statement
}
// ty... | magicoder | java |
You are tasked with implementing a map scale formatter in Swift. The map scale formatter should take a numerical map scale value and convert it into a formatted string that represents the scale in the format "1:[formatted scale]". The formatted scale should be a string representation of the map scale value, with approp... | ```swift
// Define the map scale formatter function
func scaleFormatter(mapScale: Double) -> String {
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
numberFormatter.maximumFractionDigits = 0
guard let formattedScale = numberFormatter.string(from: NSNumber(value: mapScale)... | magicoder | swift |
You are tasked with simulating a simplified version of the card game "Crazy Eights" between a player and a computer opponent. In this game, the player and the computer take turns playing cards from their hands onto the middle pile. The objective is to be the first to empty their hand of cards.
The game is played with ... | ```java
private Card pickMatchingCardOrJack(Card lastCardOnMiddle, Set<Card> computerCards) {
Card pickedCard = null;
// Check for a matching card in the computer's hand
Card matchingCard = computerCards.stream()
.filter(card -> card.compareRank(lastCardOnMiddle))
.findFirst()
... | magicoder | java |
You are tasked with implementing a PNCounter data structure, which is a variant of a G-Counter used for tracking the number of positive and negative increments. The PNCounter supports increment and decrement operations, and it can be merged with other PNCounters to obtain a combined count.
Your task is to implement th... | ```rust
use std::cmp;
#[derive(Debug, Clone)]
struct PNCounter {
id: u64,
positive: u64,
negative: u64,
}
impl PNCounter {
fn new(id: u64) -> PNCounter {
PNCounter {
id,
positive: 0,
negative: 0,
}
}
fn increment(&mut self) {
self.po... | magicoder | rust |
You are given a list of integers representing the scores of a game. The game has a special rule where if the current score is the same as the previous score, the current score is not counted towards the total score. Your task is to write a function that calculates the total score of the game according to this rule.
Wr... | ```python
from typing import List
def calculate_total_score(scores: List[int]) -> int:
total_score = 0
prev_score = None
for score in scores:
if score != prev_score:
total_score += score
prev_score = score
return total_score
```
The `calculate_total_score` function iterates... | magicoder | python |
You are tasked with implementing a C++ template function that draws graphics using OpenGL. The function `draw` takes in various parameters related to drawing modes and the OpenGL context. Your goal is to complete the implementation of the `draw` function by adding the necessary OpenGL commands to render the graphics ba... | ```cpp
#include <gl/context.h>
#include <gfx/depth_mode.h>
#include <gfx/stencil_mode.h>
template <class DrawMode>
void draw(gl::Context& context,
DrawMode drawMode,
gfx::DepthMode depthMode,
gfx::StencilMode stencilMode,
/* Add necessary parameters for drawing */
) {
... | magicoder | cpp |
You are tasked with writing a Python function that takes a JSON string as input and returns a modified JSON string with specific transformations. The input JSON string will represent a person's information, including their name, age, birthday, and a nested field. Your task is to implement the function `transform_json` ... | ```python
import json
def transform_json(person_json: str) -> str:
person_data = json.loads(person_json)
# Transformation 1: Uppercase the name
person_data["name"] = person_data["name"].upper()
# Transformation 2: Convert age to string and append " years"
person_data["age"] = str(person_d... | magicoder | python |
You are tasked with creating a Python function that processes hyperparameters for a machine learning model. The function should take in a dictionary of default hyperparameters, a machine learning model, and a list of module names to exclude from the hyperparameter processing. The function should create a new set of hyp... | ```python
import copy
def process_hyperparameters(defaults, model, exclude_modules):
hyperparameters = copy.copy(defaults)
for module_name, param in model.named_parameters():
if any(module in module_name for module in exclude_modules):
hyperparameters.pop(module_name, None)
return hyper... | magicoder | python |
You are tasked with implementing a class that validates the properties of a web page. The class should check if the index URI is valid and if the page content meets certain criteria.
You are given a partial code snippet for the validation class:
```csharp
public class WebPageValidator
{
public string IndexUri { ... | ```csharp
public void Validate()
{
if (string.IsNullOrEmpty(IndexUri) ||
!Uri.IsWellFormedUriString(IndexUri, UriKind.Absolute))
{
throw new ArgumentException("Invalid index URI");
}
if (string.IsNullOrEmpty(PageContent))
{
throw new ArgumentException("Page content is empty"... | magicoder | csharp |
You are tasked with implementing a denoising neural network using the Chainer library in Python. The provided code snippet initializes a denoiser model using Chainer's Chain class and defines multiple linear layers for the neural network.
Your task is to complete the implementation of the denoiser model by adding the ... | ```python
import chainer
import chainer.functions as F
import chainer.links as L
from chainer import optimizers, training
from chainer.training import extensions
class Denoiser(chainer.Chain):
def __init__(self):
super(Denoiser, self).__init__()
with self.init_scope():
self.l0 = L.Linea... | magicoder | python |
You are tasked with implementing a Python function that converts a Python list or dictionary (which represents a JSON-like object with single quotes as string delimiters) into a JSON string with double quotes as string delimiters and escaped double quotes. The function should take the Python object as input and return ... | ```python
import json
from typing import Union
def pythonObj_to_jsonStr(obj: Union[dict, list]) -> str:
jsonStr = json.dumps(obj)
return jsonStr
```
The solution defines the function `pythonObj_to_jsonStr`, which uses the `json.dumps` method to convert the input Python object into a JSON string. The resulting... | magicoder | python |
You are tasked with implementing a data handling system for a space station's communication and resource management. The system involves saving and loading data related to antenna information and Morijio management. Your task is to create a class that handles the saving and loading of this data.
You are provided with ... | ```java
// Implementation of TfAntennaInfoHandler class
public class TfAntennaInfoHandler {
public void saveAntennaData(TfAntennaInfoHandler handler) {
// Implement the logic to save antenna data
// Example: Serialize the antenna data and save it to a file or database
}
}
// Implementation of M... | magicoder | java |
You are tasked with creating a new authentication module for a web application using NestJS, a popular Node.js framework. The provided code snippet is a part of the NestJS module configuration. The `AuthModule` is responsible for handling authentication-related functionality. It declares the providers, controllers, and... | ```typescript
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-local';
import { AuthService } from './auth.service';
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(pri... | magicoder | typescript |
You are working on a computer vision project and need to implement a function to calculate the Intersection over Union (IoU) for a set of bounding boxes. The IoU is a measure of the overlap between two bounding boxes and is commonly used in object detection tasks. Given two sets of bounding boxes, your task is to imple... | ```python
import tensorflow as tf
class BoundingBoxCalculator:
def broadcast_iou(self, box_1, box_2):
# broadcast boxes
box_1 = tf.expand_dims(box_1, -2) # shape: (..., 1, 4)
box_2 = tf.expand_dims(box_2, 0) # shape: (1, N, 4)
# calculate intersection coordinates
interse... | magicoder | python |
You are tasked with implementing a function that processes data from a collection view in a Swift application. The function is responsible for updating the selected cell in the collection view based on certain conditions. The collection view supports infinite scrolling, and the function needs to handle this scenario ap... | ```swift
private func updateSelectedCellIfNeeded(collectionView: UICollectionView) {
guard isInfiniteScrolling else { return }
guard let selectedItems = collectionView.indexPathsForSelectedItems else { return }
guard let selectedIndex = selectedItems.first else { return }
let selectedIndexInOr... | magicoder | swift |
You are tasked with implementing a class that simulates a simple fill algorithm for a 2D grid. The grid is represented by a 2D array of integers, where each cell contains a color value. The fill algorithm starts at a given cell and changes the color of that cell and all connected cells of the same color to a new color.... | ```cpp
#include <vector>
class CFill {
private:
std::vector<std::vector<int>> grid;
int rows;
int cols;
void fillHelper(int x, int y, int oldColor, int newColor) {
if (x < 0 || x >= rows || y < 0 || y >= cols || grid[x][y] != oldColor) {
return;
}
grid[x][y] = newC... | magicoder | cpp |
You are tasked with implementing a function to process trips and plot them on a graph using Python and the NetworkX library. The function `process_trips` takes three parameters: a graph `G`, a list of trips `trips`, and a heuristic function `heuristic`. Each trip in the `trips` list is represented as a tuple of two nod... | ```python
import networkx as nx
import matplotlib.pyplot as plt
def process_trips(G, trips, heuristic):
"""
Processes trips and plots them on the graph.
Parameters: (G, trips, heuristic)
G - networkx.graph()
trips - [trips]
heuristic - Callable
trip - (node, node)
"""
... | magicoder | python |
You are working on a medical image processing project and need to implement a patch cropping algorithm for two 3D medical images. The given code snippet shows the transformation and cropping of patches from the transformed images. Your task is to implement a function to calculate the normalized cross-correlation (NCC) ... | ```python
import numpy as np
def calculate_ncc(patchA, patchB):
mean_patchA = np.mean(patchA)
mean_patchB = np.mean(patchB)
numerator = np.sum((patchA - mean_patchA) * (patchB - mean_patchB))
denominator = np.sqrt(np.sum((patchA - mean_patchA)**2)) * np.sqrt(np.sum((patchB - mean_patchB)**2))
... | magicoder | python |
You are tasked with implementing a Python class to represent a cryptographic key, with specific attributes and methods. The class should be able to print the key, its version, depth, parent fingerprint, and child number with a tick.
Your task is to complete the implementation of the `XKey` class by adding the necessar... | ```python
class XKey:
def __init__(self, version, depth, parent_fp, child_number):
self.version = version
self.depth = depth
self.parent_fp = parent_fp
self.child_number = child_number
def child_number_with_tick(self):
return str(self.child_number) + "✓"
def __str__... | magicoder | python |
You are tasked with implementing a function that processes a given string to extract specific information. The input string represents a Swift class or struct, and the function should extract and return the names of all the methods defined within the class or struct.
The input string will be formatted as follows:
- Th... | ```swift
func extractMethodNames(_ input: String) -> [String] {
var methodNames: [String] = []
if let startIndex = input.firstIndex(of: "{"),
let endIndex = input.lastIndex(of: "}") {
let classContent = input[startIndex...endIndex]
let methodRegex = try! NSRegularExpression(pattern: "func... | magicoder | swift |
You are tasked with implementing a function to calculate the total damage caused by a grenade explosion in a game. The function takes in the number of grenades thrown and the damage caused by each grenade. The game has a maximum limit on the number of grenades that can be thrown. If the number of grenades specified is ... | ```cpp
#include <iostream>
#include <vector>
#include <string>
const int maxGrenades = 5; // Maximum limit on the number of grenades
enum ParseResult {
PA_ERROR = -1,
PA_SUCCESS = 0
};
int calculateTotalDamage(int numGrenades, int damagePerGrenade, const std::vector<std::string>& targets) {
if (targets.e... | magicoder | cpp |
You are tasked with creating a form validation function for a web application. The form contains two input fields: "ten" for the name and "diaChi" for the address. The function should validate the input values based on the following criteria:
1. The "ten" field should not be empty and should contain only letters, space... | ```javascript
function validateForm(ten, diaChi) {
const nameRegex = /^[a-zA-Z\s-]+$/;
const addressRegex = /^[a-zA-Z0-9\s,-]+$/;
const errors = [];
if (!ten.trim()) {
errors.push("Name is required");
} else if (!nameRegex.test(ten)) {
errors.push("Invalid name format");
} else {
errors.push("... | magicoder | javascript |
You are tasked with creating a program that parses an SVG path data string and calculates the total length of the paths. The SVG path data string consists of a series of commands and parameters that define the path to be drawn. Each command is a single character, followed by a series of parameters. For this problem, we... | ```javascript
function calculatePathLength(svgPath) {
const pathSegments = svgPath.split('M').filter(Boolean); // Split the path into segments based on 'M' command
let totalLength = 0;
for (const segment of pathSegments) {
const subPaths = segment.split('Z').filter(Boolean); // Split each segment into subpat... | magicoder | javascript |
You are given a text file containing a software license agreement. Your task is to write a program that counts the occurrences of each unique word in the agreement and then prints the top N most frequently occurring words along with their counts.
Your program should consider the following rules:
- Words are case-insen... | ```python
import re
from collections import Counter
def count_words_in_file(file_path, n):
with open(file_path, 'r') as file:
text = file.read().lower() # Convert the text to lowercase for case-insensitive comparison
words = re.findall(r'\b\w+\b', text) # Extract words using regular expression
... | magicoder | python |
You are tasked with creating a script to manage and organize files in a directory. The script should generate a unique folder name based on the current date and time, and then create a corresponding Condor submission file for job scheduling.
Write a shell script that accomplishes the following tasks:
1. Generate a uni... | ```bash
#!/bin/bash
inputFolder="inputFolderName" # Replace with the actual input folder name
SCRIPTDIR="/path/to/script/directory" # Replace with the actual script directory path
USER=$(whoami)
datestamp=$(date +"%m%d%y_%H%M%S" | tr -d '/:')
inputFolder2="$inputFolder"__"$datestamp"
condorFile="$SCRIPTDIR/submit... | magicoder | shell |
You are tasked with implementing a Python decorator that adds functionality to a web framework. The decorator should be designed to expose a function as a web endpoint when used with the CherryPy web framework.
Your task is to create a decorator function called `template` that, when applied to a function, sets the `ex... | ```python
import cherrypy
import types
def template():
def decorator(func):
func.exposed = True # Set the exposed attribute to True
return cherrypy.expose(func) # Expose the function as a web endpoint
return decorator
# Usage examples
class Example:
@template()
def endpoint_with_pare... | magicoder | python |
You are tasked with creating a Python class that generates a dynamic list of prime numbers within a given range. Your class should have a method that takes in a start and end value and returns a list of prime numbers within that range. Additionally, you need to implement a method that calculates the sum of the prime nu... | ```python
class PrimeNumberGenerator:
def generate_primes(self, start, end):
primes = []
sieve = [True] * (end + 1)
sieve[0:2] = [False, False] # 0 and 1 are not prime numbers
for num in range(2, int(end ** 0.5) + 1):
if sieve[num]:
for multiple in range... | magicoder | python |
You are tasked with creating a Python function that determines whether a given file path has an extension based on the environment's PATH and PATHEXT variables. The PATH variable contains a list of directories to search for executable files, while the PATHEXT variable contains a list of file extensions to append to exe... | ```python
import os
def has_valid_extension(path):
# Extract the file extension from the path
_, file_extension = os.path.splitext(path)
# Check if the file has an extension
if file_extension:
# Extract the valid extensions from the environment variable PATHEXT
valid_extensions = [... | magicoder | python |
You are tasked with implementing a system for managing game entities in a game engine. The game engine uses the ECS (Entity-Component-System) architecture, where entities are composed of various components and systems operate on entities based on their components. Your goal is to create a system that handles the loadin... | ```rust
// Define the system to manage loading and unloading of assets
fn manage_assets_system(
loaders: ReadStorage<'a, Loader>,
loadables: ReadStorage<'a, Loadable>,
unloaded: WriteStorage<'a, Unloaded>,
hidden: WriteStorage<'a, Hidden>,
) {
// Iterate over entities with Loader and Loadable compon... | magicoder | rust |
You are tasked with creating a script to automate the configuration of a CMake build for a machine learning framework. The script should take into account various build options and directory paths to ensure a successful build process. Your task is to write a Python function that generates the necessary CMake command ba... | ```python
def generate_cmake_command(WITH_MKL: bool, WITH_GPU: bool, USE_TENSORRT: bool, LIB_DIR: str, CUDNN_LIB: str, CUDA_LIB: str) -> str:
cmake_command = "cmake .. -DPADDLE_LIB={} -DWITH_MKL={} -DWITH_GPU={} -DWITH_STATIC_LIB=OFF".format(LIB_DIR, "ON" if WITH_MKL else "OFF", "ON" if WITH_GPU else "OFF")
if... | magicoder | python |
You are tasked with implementing a custom error type and associated functions for handling errors related to string manipulation. The error type, `NameError`, should encompass specific error cases, and the functions should provide ways to create and handle these errors.
Your task is to complete the implementation of t... | ```rust
use std::convert::TryFrom;
// Define the NameError type to represent errors related to the Name type
#[derive(Debug, PartialEq)]
enum NameError {
ContainsNul(usize),
}
// Implement the Name type, representing a string with constraints
struct Name(String);
impl TryFrom<&str> for Name {
type Error = Na... | magicoder | rust |
You are tasked with implementing a Python function that preprocesses a given list of sequences for input into a neural network model. The function should perform the following tasks:
1. Truncate longer sequences to a specified maximum length and pad shorter sequences with a given padding value.
2. Initialize an embeddi... | ```python
import numpy as np
from typing import List, Tuple
def preprocess_sequences(sequences: List[List[int],
max_seq_length: int,
padding_value: int,
learning_rate: float,
emb_matrix: np.ndarray,
... | magicoder | python |
You are tasked with implementing a Python function that processes geographical data and returns a GeoDataFrame. The function takes a list of Point objects, a list of corresponding names, a number of decimal places, and a coordinate reference system (CRS) as input. It then creates a new GeoDataFrame with the rounded y-c... | ```python
from shapely.geometry import Point
import geopandas as gpd
def process_geographical_data(points, names, decimals, crs):
new_points = []
for point in points:
y = round(point.y, decimals)
new_points.append(Point(point.x, y))
df = gpd.GeoDataFrame(geometry=new_points, crs=crs)
... | magicoder | python |
You are tasked with implementing a Python class that extends the functionality of the provided `BaseJobSchema` class. The `BaseJobSchema` class is a part of a larger system for managing job metadata in a job scheduling application. Your task is to create a subclass called `ExtendedJobSchema` that adds new fields and fu... | ```python
class ExtendedJobSchema(BaseJobSchema):
priority = fields.Int()
experiment_name = fields.Str(dump_only=True)
def calculate_cost(self, hours):
hourly_rate = 10 # Example hourly rate
return hours * hourly_rate
```
In the solution, we create a subclass `ExtendedJobSchema` that inher... | magicoder | python |
You are tasked with creating a Python function that simulates a quiz question feature for a chatbot. The function `add_quiz_question` takes four parameters: `update`, `context`, and `response`. The `update` and `context` parameters are objects used in the Telegram Bot API, and `response` is an object containing informa... | ```python
from telegram import Poll
def add_quiz_question(update, context, response):
chat_id = get_chat_id(update, context)
message = context.bot.send_poll(chat_id=chat_id, question=response.question,
options=response.answers, type=Poll.QUIZ,
... | magicoder | python |
You are tasked with implementing a caching mechanism for network responses in a Swift application. The provided code snippet shows a `NetworkCache` class that conforms to the `CachedResponseHandler` protocol. Your goal is to complete the implementation of the `dataTask(_:willCacheResponse:completion:)` method to handle... | ```swift
public final class NetworkCache: CachedResponseHandler {
public func dataTask(_ task: URLSessionDataTask, willCacheResponse response: CachedURLResponse, completion: @escaping (CachedURLResponse?) -> Void) {
// Check if caching is allowed based on response or task properties
let shouldCacheR... | magicoder | swift |
You are tasked with implementing a function to calculate the B-spline curve given a set of control points and a knot vector. B-splines are a type of piecewise polynomial function commonly used in computer graphics and geometric modeling. The B-spline curve is defined by a set of control points and a knot vector, and it... | ```python
import numpy as np
def calculate_bspline_curve(control_points, knot_vector, u):
p = len(control_points) - 1 # Degree of the B-spline curve
n = len(control_points) # Number of control points
m = len(knot_vector) # Number of knots
def basis_function(i, j, u):
if j == 0:
... | magicoder | python |
You are tasked with simulating a particle system in a 2D space. The system consists of a specified number of particles, each with a random position and density. The density of a particle is a measure of how many neighboring particles are within a certain distance. Your goal is to implement a function that calculates th... | ```python
import random
def calculate_average_density(number_of_particles: int, density_min: int, density_max: int) -> float:
total_density = 0
for _ in range(number_of_particles):
particle_x = random.uniform(0, 100) # Random x-coordinate within a 100x100 space
particle_y = random.uniform(0, 1... | magicoder | python |
You are tasked with implementing a simplified version control system that supports the `git reset` and `git commit` commands. Your system should handle the following operations:
1. `git reset --soft HEAD~$2`: This command resets the current branch's HEAD pointer to the specified commit, while keeping the changes stage... | ```python
from typing import List
class VersionControl:
def __init__(self):
self.commits = []
def reset(self, num_commits: int) -> None:
if num_commits <= len(self.commits):
self.commits = self.commits[:-num_commits]
def commit(self, message: str) -> None:
self.commits... | magicoder | python |
You are given a set of movement instructions for a robot on a grid. The robot can move in four directions: up, down, left, and right. Each movement instruction consists of a direction (up, down, left, or right) and a distance to move in that direction. The grid starts at the origin (0, 0), and the robot's position is u... | ```python
def calculate_final_position(instructions):
x, y = 0, 0
for instruction in instructions:
direction, distance = instruction.split()
distance = int(distance)
if direction == "forward":
y += distance
elif direction == "down":
y -= distance
e... | magicoder | python |
You are tasked with creating a rocket launch tracking system for SpaceX rockets. The system will retrieve information about a specific rocket's next and past launches and present it in a structured format. You are given a code snippet from the existing system, which uses reactive programming with Project Reactor's Flux... | ```java
public Mono<RocketLaunchInfo> getRocketLaunchInfo(String rocketId) {
return spacexClient.findRocket(rocketId)
.zipWith(findNextRocketLaunches(rocketId), Converters::toRocketResponseWithNextLaunches)
.zipWith(pastLaunchesResponse, Converters::toRocketResponseWithPastLaunches)
... | magicoder | java |
You are tasked with implementing a Swift class that represents a 2D control point with a label, value, and control type. The class should provide methods to calculate the distance between two control points and to check if a given point lies within the bounds of the control point.
You are given the following code snip... | ```swift
public enum ControlType {
case unknown
case button
case slider
case knob
}
public class ControlPoint {
public var label: String
public var value: simd_float2
public var controlType: ControlType
public var minX: Float
public var maxX: Float
public var minY: Float
pub... | magicoder | swift |
You are tasked with implementing a simple class hierarchy for rendering passes in a graphics rendering engine. The provided code snippet is a part of a larger system and represents a base class for an antialiasing pass. Your task is to extend this class hierarchy by creating a subclass for a specific antialiasing techn... | ```python
class FXAAPass(RenderPass):
def __init__(self):
RenderPass.__init__(self)
def getID(self):
return "FXAAPass"
def applyFXAA(self, rendered_image):
# Implement FXAA antialiasing effect on the rendered image
# Pseudocode for FXAA implementation
# ...
... | magicoder | python |
You are tasked with creating a Python script for Blender that will analyze a 3D object and report the number of evaluated vertices in the object's mesh. The script should utilize Blender's API to access the evaluated vertices and output the count as an informational message.
Given the code snippet provided, you need t... | ```python
import bpy
class OBJECT_OT_evaluated_example(bpy.types.Operator):
bl_idname = "object.evaluated_example"
bl_label = "Evaluated Example"
def execute(self, context):
obj = context.object
depsgraph = context.evaluated_depsgraph_get()
# Access the evaluated mesh of the objec... | magicoder | python |
You are given a JavaScript object representing a game state. The object contains properties for styling, game data, score, and user information. Your task is to write a function that updates the game data based on a given move and returns the updated game state.
The game state object is structured as follows:
```javas... | ```javascript
function updateGameState(gameState, move) {
const { row, col, value } = move;
const updatedState = { ...gameState };
const updatedShowData = gameState.ShowData.map(row => [...row]);
if (updatedShowData[row][col] === 0) {
updatedShowData[row][col] = value;
} else {
// H... | magicoder | javascript |
You are tasked with creating a Python function that parses a given file and extracts the copyright information from it. The copyright information is typically found in the header of source code files and includes the year and the copyright holder's name.
Write a function called `extract_copyright_info` that takes a fi... | ```python
import re
def extract_copyright_info(file_path):
copyright_info = []
with open(file_path, 'r') as file:
for line in file:
match = re.search(r'Copyright (\d{4}) - (.+?)[\.\n]', line)
if match:
year = int(match.group(1))
holder = match.gro... | magicoder | python |
You are tasked with implementing a class that manages time spans for specific days. The class, `DayTimeSpanModel`, should support adding and removing time spans for given days. Each time span is defined by a start time (`since`) and an end time (`until`).
Your task is to implement the `DayTimeSpanModel` class with the... | ```cpp
#include <vector>
#include <algorithm>
#include <QDate>
#include <QTime>
class DayTimeSpan {
public:
QDate day;
QTime since;
QTime until;
// Other necessary members and methods
};
class DayTimeSpanModel {
private:
std::vector<DayTimeSpan> timeSpans;
public:
void setSince(const QTime &s... | magicoder | cpp |
You are given a list of integers `nums` and a list of indices `non_zeros` representing the positions of non-zero elements in `nums`. Your task is to modify the list `nums` in-place such that all non-zero elements are placed at the beginning of the list, and the remaining elements are filled with zeroes.
Write a functi... | ```python
from typing import List
def move_zeros(nums: List[int], non_zeros: List[int]) -> None:
nz = len(non_zeros)
nums[:nz] = [nums[i] for i in non_zeros] # Place non-zero elements at the beginning
nums[nz:] = [0] * (len(nums) - nz) # Fill the remaining elements with zeroes
```
The `move_zeros` funct... | magicoder | python |
You are tasked with implementing a class that represents a query builder for a database. The class should allow users to construct SQL queries in a fluent and readable manner. The provided code snippet is a part of the class, and it seems to be a method that returns the query builder instance. Your task is to complete ... | ```php
class QueryBuilder
{
private $query;
public function __construct()
{
$this->query = '';
}
public function select(...$columns): QueryBuilder
{
$this->query .= 'SELECT ' . implode(', ', $columns);
return $this;
}
public function from($table): QueryBuilder
... | magicoder | php |
You are tasked with implementing a simple URL shortening service. Your goal is to create a function that takes a long URL as input and returns a shortened version of the URL. The shortened URL should be unique and should redirect to the original long URL when accessed.
You need to implement a function `shorten_url(lon... | ```python
import random
import string
url_mapping = {} # Dictionary to store the mapping between shortened URLs and original long URLs
def shorten_url(long_url):
while True:
short_code = ''.join(random.choices(string.ascii_letters + string.digits, k=6)) # Generate a 6-character alphanumeric code
... | magicoder | python |
You are tasked with creating a Python function that processes data from a CSV file and generates a list of image URLs based on the information in the file. The CSV file contains data related to room bookings, and each row represents a booking with the following columns: "lid" (location ID), "gid" (booking ID), "name" (... | ```python
import csv
from typing import List
def generate_image_urls(csv_file_path: str) -> List[str]:
image_urls = []
with open(csv_file_path) as data:
reader = csv.reader(data)
next(reader) # Skip header row
for row in reader:
lid, gid, _, _ = row # Unpack relevant valu... | magicoder | python |
You are tasked with creating a Python function that extracts information from HTML soup objects representing online advertisements. The function should parse the HTML and return specific details such as the advertisement description and services offered.
You are provided with a code snippet from a test suite that asse... | ```python
from bs4 import BeautifulSoup
def _get_ad_description(soup):
# Assuming the advertisement description is contained within a specific HTML tag or class
ad_description_tag = soup.find('div', class_='ad-description')
ad_description = ad_description_tag.text.strip() if ad_description_tag else "Descri... | magicoder | python |
You are tasked with creating a program that retrieves and loads assemblies from a given directory. The program should be able to filter out non-assembly files and load valid assemblies into memory.
Write a function `GetAssemblies` that takes no parameters and returns an array of loaded assemblies. The function should ... | ```csharp
// Define the IsAssembly method to check if a file type represents an assembly
private static bool IsAssembly(string fileType)
{
// Assuming the file type for an assembly is ".dll"
return fileType == ".dll";
}
// Define the LoadAssembly method to load an assembly into memory
private static Assembly L... | magicoder | csharp |
You are tasked with implementing a simple memory management system for a custom framework called CoVi. The framework provides a protocol `CoViDisposable` that allows objects to be disposed of when they are no longer needed. The protocol has two methods: `disposed(by:)` and `dispose()`. The `disposed(by:)` method takes ... | ```swift
import Foundation
public protocol CoViDisposable {
func disposed(by bag: CoViDisposeBag)
func dispose()
}
public class CoViDisposeBag {
private var disposables: [CoViDisposable] = []
deinit {
dispose()
}
func dispose() {
disposables.forEach { $0.dispose() }
d... | magicoder | swift |
You are working on a game development project and need to implement a method to retrieve a random cube asset ID based on a given block type. The cube assets are stored in a list, and each asset has an associated key. You are provided with a partial code snippet for the asset retrieval process.
You are required to impl... | ```csharp
public int GetRandomCubeId(MonoBlock.BlockType type)
{
List<int> matchingIds = new List<int>();
// Find all cube asset IDs that match the given block type
for (int i = 0; i < CubeAssetList.Count; i++)
{
if (CubeAssetList[i].BlockType == type)
{
matchingIds.Add(i);
... | magicoder | csharp |
You are given a list of coordinates representing points on a map. Each coordinate is represented as a pair of latitude and longitude values. Your task is to write a function that calculates the distance between two given coordinates using the Haversine formula. The Haversine formula is used to calculate the distance be... | ```python
import math
def calculate_distance(lat1, lon1, lat2, lon2):
R = 6371 # Radius of the Earth in kilometers
lat1_rad = math.radians(lat1)
lon1_rad = math.radians(lon1)
lat2_rad = math.radians(lat2)
lon2_rad = math.radians(lon2)
dlat = lat2_rad - lat1_rad
dlon = lon2_rad - lon1_rad
... | magicoder | python |
You are tasked with implementing a function that will parse a given HTML snippet and extract the team names from a list of items. The HTML snippet will contain an unordered list (`<ul>`) with list items (`<li>`) representing the team names. Your task is to write a function that takes the HTML snippet as input and retur... | ```java
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TeamNameExtractor {
public static List<String> extractTeamNames(String htmlSnippet) {
List<String> teamNames = new ArrayList<>();
Pattern pattern = Pattern.compile... | magicoder | java |
You are given a 2D matrix representing a maze. The matrix contains 0s and 1s, where 0 represents an open cell and 1 represents a blocked cell. Your task is to write a function `isMazeValid` that takes the matrix as input and determines if it represents a valid maze. A valid maze is defined as a matrix where there is a ... | ```java
public boolean isMazeValid(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
boolean[][] visited = new boolean[m][n];
return isPathValid(matrix, 0, 0, visited, m, n);
}
private boolean isPathValid(int[][] matrix, int i, int j, boolean[][] visited, int m, int n) {
if (i < 0 ... | magicoder | java |
You are tasked with implementing a class that simulates an XML writer. The XMLWriter class should provide methods for creating XML tags, adding data to the tags, and inserting comments within the XML structure. Your goal is to create the XMLWriter class and its methods to produce a valid XML string based on the provide... | ```python
import io
class XMLWriter:
def __init__(self, file_handle):
self.file_handle = file_handle
self.indent_level = 0
def tag(self, tag_name):
self.file_handle.write(f"{' ' * self.indent_level}<{tag_name}>")
self.indent_level += 1
return TagContextManager(self, ta... | magicoder | python |
You are tasked with creating a Python class that manages game data for different players. The class should have methods to retrieve specific information from the game data. You are provided with a code snippet that partially implements the class. Your task is to complete the class by implementing the missing methods an... | ```python
class GameData:
def __init__(self, player_id, date_birth, company):
self.player_id = player_id
self.date_birth = date_birth
self.company = company
class GameDataManager:
def __init__(self, save_data):
self.save_data = save_data # Assume save_data is a dictionary-like ... | magicoder | python |
You are tasked with creating a Python program that securely encrypts and decrypts sensitive data using GnuPG (GPG). Your program should provide command-line functionality to encrypt a file, decrypt a file, and list the keys available for encryption. The program should utilize the `gnupg` library for GPG operations and ... | ```python
import json
import sys
from argparse import ArgumentParser
from typing import Any, Dict, List, NoReturn, TextIO
import gnupg
def encrypt_file(file_path: str, recipient_key: str) -> None:
gpg = gnupg.GPG()
with open(file_path, 'rb') as f:
encrypted_data = gpg.encrypt_file(f, recipient_key)
... | magicoder | python |
You are tasked with creating a Python class that processes a given source code file and extracts information about the test cases present in the file. Your class should be able to generate an XML report containing details about the test cases found in the source code.
You are provided with a partial code snippet that ... | ```python
class TestCasesXMLGenerator:
def __init__(self, file_path):
self.file_path = file_path
self.test_cases = []
def parse_test_cases(self):
# Implement test case parsing logic here
# Example: Identify test cases and store relevant information in self.test_cases
pas... | magicoder | python |
You are tasked with implementing a function to calculate the total transaction fees for a blockchain network. The function should take into account a base fee and a coefficient for each transaction, as well as the total number of transactions. Additionally, the function should handle stake distribution for a given epoc... | ```rust
// Function to calculate total transaction fees
fn calculate_transaction_fees(base_fee: u64, coefficient: u64, transaction_amount: u64) -> u64 {
base_fee + coefficient * transaction_amount
}
// Function to calculate initial funds for the stake pool
fn calculate_initial_funds(initial_funds_per_account: u64,... | magicoder | rust |
You are given a 2D array representing a grid of cells. Each cell can be either alive (denoted by 1) or dead (denoted by 0). Your task is to write a function to simulate the next state of the grid according to the following rules:
1. Any live cell with fewer than two live neighbors dies, as if by underpopulation.
2. Any... | ```swift
func nextGeneration(_ grid: [[Int]]) -> [[Int]] {
let rows = grid.count
let cols = grid[0].count
var nextGrid = Array(repeating: Array(repeating: 0, count: cols), count: rows)
let directions = [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, -1), (1, -1), (-1, 1)]
func countLiveNeighbors(_... | magicoder | swift |
You are tasked with implementing a custom decoding format style in Swift. The goal is to create a structure that can decode a string input into a specific output type using a block-based format style.
Your task is to complete the implementation of the `StringMapDecodingFormatStyle` structure, which conforms to the `De... | ```swift
// MARK: - Decoding
/// A structure to decode string to output using block based format style.
public struct StringMapDecodingFormatStyle<Output>: DecodingFormatStyle {
private let decode: (String) throws -> Output?
fileprivate init(_ decode: @escaping (String) throws -> Output?) {
self.decod... | magicoder | swift |
You are tasked with creating a Python program that processes a configuration file and extracts specific information based on the provided code snippet. The configuration file contains key-value pairs, where the keys correspond to Pygments token names and the values represent the associated color codes. Your program sho... | ```python
# Read the configuration file and extract token names and color codes
with open("pygments_config.txt", "r") as file:
config_data = file.readlines()
token_color_map = {}
for line in config_data:
key, value = line.strip().split(": ")
token_color_map[key] = value
# Sort the token names alphabetical... | magicoder | python |
You are tasked with implementing a simple event handling system in PHP using anonymous functions and closures. Your goal is to create a class that can register event handlers and trigger those handlers when the corresponding event occurs.
You are provided with a partial code snippet that demonstrates the usage of the ... | ```php
class EventEmitter
{
private $eventHandlers = [];
public function on($event, $handler)
{
if (!isset($this->eventHandlers[$event])) {
$this->eventHandlers[$event] = [];
}
$this->eventHandlers[$event][] = $handler;
}
public function emit($event, ...$args)
... | magicoder | php |
You are working on a class method for a sensor data processing module. The method `calculate` takes in four parameters: `pressure_raw` (integer), `temperature_raw` (integer), `oss` (integer), and `eeprom` (dictionary). The `pressure_raw` and `temperature_raw` parameters represent raw sensor readings for pressure and te... | ```python
@classmethod
def calculate(cls, pressure_raw, temperature_raw, oss, eeprom):
pressure_comp = pressure_raw + cls.calculate_temperature_compensation(temperature_raw, eeprom) - cls.calculate_pressure_offset(oss, eeprom) + cls.calculate_pressure_sensitivity(oss, eeprom)
return pressure_comp
@classmethod
... | magicoder | python |
You are tasked with creating a Python function that processes a given dataset to identify peaks using the `peakutils` library and logs the results using the `logging` module. The function should read data from a CSV file, identify peaks, and log the peak indices and values using a specified logger configuration.
You a... | ```python
import peakutils
import logging
import csv
def process_and_log_peaks(data_file, logger_name):
# Configure the logger
logger = logging.getLogger(logger_name)
# Read data from the CSV file
x_values = []
y_values = []
with open(data_file, 'r') as file:
reader = csv.reader(file)
... | magicoder | python |
You are tasked with implementing a Python decorator that ensures the uniqueness of the return values of a given function. The decorator should raise a `ValueError` if the function returns a value that has already been returned before. Your task is to complete the implementation of the `@unique` decorator and apply it t... | ```python
from enum import Enum
def unique(func):
seen = set()
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
if result in seen:
raise ValueError("Value already exists")
seen.add(result)
return result
return wrapper
@unique
def sample_function(x):
... | magicoder | python |
You are tasked with creating a Java program that utilizes reflection to retrieve information about the fields of a given class. Your program should prompt the user to input the fully qualified class name, and then display a list of all the declared fields within that class. The program should handle any potential excep... | ```java
import java.lang.reflect.Field;
import java.util.Scanner;
public class FieldReflection {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the fully qualified class name: ");
String className = scanner.nextLine();
try... | magicoder | java |
You are tasked with implementing a program to parse and extract HTML comments from a given HTML file. HTML comments are enclosed within `<!--` and `-->` tags and can span multiple lines. Your program should be able to identify and extract all the HTML comments present in the input HTML file.
Write a function or method... | ```python
import re
def extractHTMLComments(html_content):
comment_pattern = r'<!--(.*?)-->'
comments = re.findall(comment_pattern, html_content, re.DOTALL)
return [comment.strip() for comment in comments]
```
The `extractHTMLComments` function uses the `re.findall` method to find all occurrences of HTML ... | magicoder | python |
You are tasked with implementing a generic field operations library in Rust. The library should provide support for both finite field arithmetic and prime field arithmetic. Your task is to implement the necessary operations for both types of fields.
For the finite field (field_n), you need to implement addition, subtr... | ```rust
// Implementation for finite field operations
pub mod field_n {
use std::ops::{Add, Sub, Mul, Div};
pub struct FieldN<T> {
modulus: T,
}
impl<T> FieldN<T>
where
T: Copy + Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Div<Output = T> + PartialEq,
{
pub fn... | magicoder | rust |
You are tasked with implementing a custom data structure in Swift that mimics the behavior of a stack with an additional method. The stack should support the usual push and pop operations, as well as a method that efficiently returns the maximum element in the stack at any given time. You need to design the data struct... | ```swift
class MaxStack {
private var stack: [(value: Int, max: Int)] = []
func push(_ value: Int) {
let currentMax = stack.last.map { max($0.max, value) } ?? value
stack.append((value, currentMax))
}
func pop() -> Int? {
return stack.popLast()?.value
}
func max() -> I... | magicoder | swift |
You are working as a system administrator for a company that uses a Linux-based server environment. Your task is to create a script that ensures the inclusion of a specific configuration file in the sudoers file. The sudoers file is used to specify which users or groups are allowed to execute commands with elevated pri... | ```bash
#!/bin/bash
# Check if sudo command is available
command -v sudo >/dev/null 2>&1 || { echo "sudo command not found, exiting" >&2; exit 1; }
# Check if /etc/sudoers.d directory exists, create if not and set permissions
if [ ! -d /etc/sudoers.d ]; then
mkdir /etc/sudoers.d
chmod 0750 /etc/sudoers.d
fi
... | magicoder | shell |
You are tasked with creating a GraphQL resolver for managing asynchronous jobs. The resolver should handle querying the status of a job, creating a new job, and subscribing to job status updates. The job status can be one of the following: "PENDING", "IN_PROGRESS", "COMPLETED", or "FAILED".
Your task is to implement t... | ```typescript
import { Args, Mutation, Query, Resolver, Subscription } from '@nestjs/graphql';
@Resolver()
export class AsyncJobResolver {
// Mock data for demonstration purposes
private asyncJobs: AsyncJob[] = [];
@Query(() => AsyncJobResponse)
async queryAsyncJobStatus(@Args('jobId') jobId: string): Promise... | magicoder | typescript |
You are working on a project that involves implementing a Hidden Markov Model (HMM) for a speech recognition system. In this scenario, you are given the following parameters:
- `n_mix_hidden`: an integer representing the number of hidden states in the HMM.
- `p_observation`: a float representing the probability of obs... | ```python
def generate_hmm_transition_matrix(n_mix_hidden, p_observation, p_ck_noise):
transition_matrix = [[0.0 for _ in range(n_mix_hidden)] for _ in range(n_mix_hidden)]
for i in range(n_mix_hidden):
for j in range(n_mix_hidden):
if i == j:
transition_matrix[i][j] = 1... | magicoder | python |
You are tasked with creating a secure configuration file for a Django web application. The configuration file contains sensitive information and settings that need to be protected. Your goal is to write a Python function that generates a secure Django settings file with a randomly generated secret key and appropriate s... | ```python
import random
import string
def generate_secure_settings():
# Generate a random secret key
secret_key = ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits + string.punctuation) for _ in range(50))
# Create the secure settings file
settings_file = f"""
# Secure Django s... | magicoder | python |
You are tasked with implementing a simple visitor pattern for processing source file items. The code snippet provided is a part of the visitor pattern implementation in Java. The `visit` method is used to process different types of source file items, and it takes the item to be processed and a context object as paramet... | ```java
// Base class for source file items
class SrcFileItem {
public Object accept(Visitor visitor, Object ctx) {
return visitor.visit(this, ctx);
}
}
// Class representing a class in the source file
class ClassItem extends SrcFileItem {
public Object accept(Visitor visitor, Object ctx) {
... | magicoder | java |
You are tasked with implementing a custom memory management system for a specific class in Python. The class, `CustomClass`, has a custom destructor method `__del__(self)` that needs to be implemented to release any resources held by instances of the class. Your task is to create a memory management system that ensures... | ```python
import weakref
class CustomClass:
_instances = set()
def __init__(self, resource):
self.resource = resource
self._instances.add(weakref.ref(self, self._remove_instance))
def _remove_instance(self, ref):
self._instances.discard(ref)
def release_resource(self):
... | magicoder | python |
You are tasked with implementing a custom magnitude-scaling relationship class for seismic hazard analysis. The class should inherit from the `BaseMSRSigma` class and be decorated with the `with_slots` decorator from the `openquake.baselib.slots` module. The purpose of this custom class is to define a magnitude-scaling... | ```python
from openquake.hazardlib.scalerel.base import BaseMSRSigma
from openquake.baselib.slots import with_slots
@with_slots
class PeerMSR(BaseMSRSigma):
"""
Magnitude-Scaling Relationship defined for PEER PSHA test cases.
See "Verification of Probabilistic Seismic Hazard Analysis Computer
Programs... | magicoder | python |
You are tasked with implementing a class hierarchy for a strategy pattern in a PHP application. The provided code snippet is the beginning of a namespace declaration for an abstract strategy class. Your task is to complete the implementation of the abstract strategy class and create concrete strategy classes that exten... | ```php
namespace Rocketeer\Abstracts\Strategies;
abstract class AbstractStrategy
{
abstract public function initialize(); // Abstract method to be implemented by concrete strategy classes
abstract public function execute(); // Abstract method to be implemented by concrete strategy classes
}
class ConcreteS... | magicoder | php |
You are tasked with implementing a simple reference counting system in C++ for managing the lifetime of objects. The reference counting system should include functions for adding and releasing references, as well as a mechanism for automatically deleting the object when the reference count reaches zero.
You are provid... | ```cpp
#include <iostream>
// Declaration of the base class for reference counted objects
struct cef_base_ref_counted_t {
int ref_count;
cef_base_ref_counted_t() : ref_count(1) {}
virtual ~cef_base_ref_counted_t() {
std::cout << "Object deleted" << std::endl;
}
};
// Function to increment th... | magicoder | cpp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.