query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a cost model for task continuations in a scheduling system. The system manages tasks with unique identifiers and requires a cost model to determine the cost of continuing a specific task. The cost model is represented by the `VoidCostModel` class, which contains a method `TaskContinuati... | ```cpp
#include <iostream>
// Define the ArcDescriptor class to encapsulate cost information
class ArcDescriptor {
public:
// Define attributes to represent cost details
double costValue;
// Other relevant attributes can be added here
};
// Define the VoidCostModel class
class VoidCostModel {
public:
... | magicoder | cpp |
You are tasked with implementing a Python class for managing image data for a machine learning project. The class should include methods for splitting a dataset into training and validation sets, as well as for reading and converting images from BGR to RGB format.
You need to implement the following methods in the cla... | ```python
import cv2
import numpy as np
class ImageDataManager:
def __init__(self, driving_log, record_count):
self.driving_log = driving_log
self.record_count = record_count
def train_valid_split(self, ratio=0.8):
np.random.shuffle(self.driving_log)
n_train = int(ratio * self... | magicoder | python |
You are tasked with creating a script to automate the deployment of a Snap package to a remote server using SSH. The script should handle the building of the Snap package, staging it, and then transferring it to the remote server. The script should be able to run on a local machine and transfer the Snap package to the ... | ```bash
#!/bin/bash
SNAPPYVM=../snappy-vm
SNAPSRC=`pwd`
SNAPNAME=node-red_1.0_amd64.snap
cd $SNAPSRC
snapcraft clean
snapcraft stage --force
snapcraft
cd $SNAPPYVM
scp -P 2222 -i .vagrant/machines/default/virtualbox/private_key $SNAPSRC/$SNAPNAME ubuntu@127.0.0.1:~/
```
The provided script sets the necessary vari... | magicoder | shell |
You are tasked with creating a Python class method that handles the confirmation of a setup token for integrating with Google Drive API. The method should compare the current authorization code with the previous one stored in the system, and if they differ, it should generate a refresh token using a provided service.
... | ```python
class GoogleDriveIntegration:
def __init__(self, env, google_drive_authorization_code):
self.env = env
self.google_drive_authorization_code = google_drive_authorization_code
def confirm_setup_token(self):
params = self.env['ir.config_parameter'].sudo()
authorization_co... | magicoder | python |
You are tasked with creating a script that automates the cleanup of temporary files in a specified directory. The script should take a directory path as input and remove all temporary files within that directory. Temporary files are identified by their file extensions, which include `.tmp`, `.temp`, and `.bak`.
Your t... | ```bash
# GLOBAL VARIABLES
CWD=$(pwd)
function cleanup {
local dir_path=$1
if [ -d "$dir_path" ]; then # Check if the directory exists
cd "$dir_path" || return # Change to the specified directory
for file in *.{tmp,temp,bak}; do # Iterate through files with temporary extensions
[... | magicoder | shell |
You are tasked with creating a Python script that automates the process of deleting Kubernetes resources using the `kubectl` command-line tool. Your script should take a YAML file containing the resource definitions as input and execute the deletion command for each resource specified in the file.
Your Python script s... | ```python
import sys
import subprocess
import yaml
def delete_kubernetes_resources(yaml_file):
with open(yaml_file, 'r') as file:
resources = list(yaml.safe_load_all(file))
for resource in resources:
resource_type = resource.get('kind')
resource_name = resource.get('metadata... | magicoder | python |
You are tasked with creating a Python function that processes chemical reactions and calculates the overall change in the number of atoms for each element involved. The function should take in a list of reaction equations and return a dictionary mapping each element to its net change in quantity across all reactions.
... | ```python
from typing import List, Dict
def calculate_element_changes(reactions: List[str]) -> Dict[str, int]:
element_changes = {}
for reaction in reactions:
reactants, products = reaction.split('->')
reactants = reactants.strip().split('+')
products = products.strip().split('+')
... | magicoder | python |
You are tasked with creating a program to manage messages for a sports team. The program needs to write messages to individual files for each player, using a specific filename format. The messages will be generated based on a predefined structure and the player's information. Your task is to implement the function `mak... | ```python
def make_filename(player_name):
"""
Generates a filename for the player based on the given name.
Args:
player_name (str): The name of the player.
Returns:
str: The filename in the format "playername.txt".
"""
formatted_name = player_name.lower().replace(' ', '_') + '.txt'
... | magicoder | python |
You are tasked with implementing a stack data structure using a singly linked list. You need to create a class `Stack` with the following methods:
1. `push(self, x: int) -> None`: This method should add an element `x` to the top of the stack.
2. `pop(self) -> int`: This method should remove and return the element at t... | ```python
class Stack:
class Node:
def __init__(self, val, min_val, next):
self.val = val
self.min_val = min_val
self.next = next
def __init__(self):
self.head = None
def push(self, x: int) -> None:
if self.head == None:
self.head = s... | magicoder | python |
You are tasked with implementing a Base58 encoding and decoding algorithm. Base58 is a binary-to-text encoding scheme that is commonly used in Bitcoin and other cryptocurrencies to represent large numbers as alphanumeric strings. The Base58 encoding uses a set of 58 characters, excluding characters that are easily mist... | ```swift
func base58Encode(_ data: [UInt8]) -> String {
let alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
let base = BigInt(58)
var x = BigInt(data)
var result = ""
while x > 0 {
let (quotient, remainder) = x.quotientAndRemainder(dividingBy: base)
resul... | magicoder | swift |
You are working on a project that involves processing and manipulating data using PyTorch, a popular machine learning library. As part of your task, you need to implement a function that performs a specific operation on tensor data. The function takes in several input parameters and is responsible for concatenating two... | ```python
import torch
def process_and_save_data(feats, spectral_emb, emb_path, load):
if spectral_emb is not None:
feats = torch.cat([feats, spectral_emb], dim=1)
in_feats = feats.size(1)
if load and emb_path:
torch.save(feats, emb_path)
return feats, in_feats
```
The `pro... | magicoder | python |
You are tasked with implementing a custom hook in a React application. The hook, `useRowSpan`, is intended to be used in a table component to handle row spanning logic. The provided code snippet shows the initial implementation of the `useRowSpan` hook, which takes an array of hooks and pushes a `useInstance` hook into... | ```javascript
const useRowSpan = (hooks) => {
hooks.useInstance.push(useInstance);
// Logic to calculate and apply row spanning
// Assuming tableData is the data used in the table component
const applyRowSpan = (tableData) => {
// Your row spanning logic here
// Example: Identifying rows to span based ... | magicoder | javascript |
You are tasked with implementing a program that simulates a simple file system. The program should support creating, deleting, and listing files and directories, as well as changing the current working directory. The program should also handle relative and absolute paths.
Your task is to implement the `p` command, whi... | ```python
def resolve_path(current_path, input_path):
if input_path.startswith('|'):
current_path = '|'
input_path = input_path[1:]
paths = input_path.split('/')
for path in paths:
if path == '.':
continue
elif path == '..':
if current_path != '|':
... | magicoder | python |
You are tasked with implementing a Python dictionary using a custom storage mechanism. The dictionary should support basic operations such as adding, updating, and retrieving key-value pairs. Additionally, you need to implement a method to find the key with the maximum value in the dictionary.
Your task is to complete... | ```csharp
using System;
using System.Collections.Generic;
namespace IronPython.Runtime {
public class CustomPythonDictionary {
private Dictionary<string, int> storage;
public CustomPythonDictionary() {
storage = new Dictionary<string, int>();
}
public void __setitem__(... | magicoder | csharp |
You are tasked with creating a machine learning model evaluation function. Given a code snippet that trains a predictor and evaluates its accuracy, your goal is to implement a function that calculates the mean accuracy of the predictor over multiple train-test splits.
You are provided with the following information:
-... | ```python
def mean_accuracy(X, Y, train_id, test_id, flags):
total_accuracy = 0.0
num_splits = len(train_id)
for i in range(num_splits):
X_train, X_test = X[train_id[i]], X[test_id[i]]
y_train, y_test = Y[train_id[i]], Y[test_id[i]]
# Initialize the predictor
pp = policy_ne... | magicoder | python |
You are working on a project that involves processing and analyzing data from a sensor network. The code snippet provided is a part of a data processing module that deals with observed and unobserved targets. The code uses NumPy for array manipulation and logical operations.
Your task is to implement a function that t... | ```python
import numpy as np
def process_targets(obs_target, diff_targets, ind1, ind2, ind3, target_observed, r2_targets, obs_rad2, target_unobserved):
# Reshape the observed targets and update the obs_target array
for i in range(obs_target.shape[1] // 2):
obs_target[:, i * 2:(i + 1) * 2] = np.reshape(... | magicoder | python |
You are tasked with implementing a function that processes a given UTF-8 encoded string according to a specific set of rules. The function should remove leading and trailing whitespace from the input string, and if the resulting string is not empty, it should be converted to a native string format. The native string fo... | ```javascript
function processString(utf8) {
// Remove leading and trailing whitespace
let trimmedString = utf8.trim();
// If the resulting string is empty, return an empty string
if (trimmedString === "") {
return "";
}
// Convert the trimmed string to native string format
let nativeString = tr... | magicoder | javascript |
You are tasked with creating a function that interacts with an external service to fetch details of a service order for a specific equipment. The function takes an access token as a parameter and should return the details of the service order.
The function signature is as follows:
```javascript
/**
* Function to fetc... | ```javascript
const fetch = require('node-fetch');
/**
* Function to fetch details of a service order for the equipment
* @param {string} accessToken - valid access token
* @param {string} equipmentId - ID of the equipment for which service order details are to be fetched
* @returns {Promise<object>} - A promise t... | magicoder | javascript |
You are tasked with simulating a game called "Marble Mania." In this game, players take turns placing marbles in a circular arrangement of cups. The objective is to score points by strategically placing marbles and removing specific marbles based on certain rules.
The game is played with a specific set of rules:
1. Th... | ```rust
fn marble_mania(players: u32, last_marble: u32) -> u32 {
let mut circle = vec![0];
let mut scores = vec![0; players as usize];
let mut current_player = 0;
let mut current_marble = 0;
for marble in 1..=last_marble {
if marble % 23 == 0 {
let remove_index = (current_marble... | magicoder | rust |
You are tasked with implementing a custom view controller in a Swift iOS application. The view controller will display information about a user's saved state in a game, including the title of the saved game, the timestamp of the save, and the core details of the save. The view controller contains several outlets for UI... | ```swift
weak var saveState: PVSaveState? {
didSet {
if let saveState = saveState {
titleLabel.text = saveState.title
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM d, h:mm a"
timeStampLabel.text = dateFormatter.string(from: saveState.time... | magicoder | swift |
You are tasked with implementing a program that processes a list of software licenses and extracts the license identifiers along with their corresponding license types. Each license is represented by a comment in the source code, adhering to the SPDX License Identifier format. The SPDX License Identifier is a unique st... | ```python
from typing import List, Dict
def extract_license_info(code_lines: List[str]) -> Dict[str, str]:
license_info = {}
for line in code_lines:
if line.strip().startswith('# SPDX-License-Identifier:'):
license_identifier = line.strip().split(':')[-1].strip()
if license_iden... | magicoder | python |
You are tasked with creating a Python function that validates and processes database configuration settings for a Django application. The function should take a dictionary representing the database configuration and perform the following tasks:
1. Check if the 'default' key exists in the dictionary.
2. If the 'default'... | ```python
def process_database_config(config: dict) -> str:
if 'default' in config:
default_config = config['default']
if 'ENGINE' in default_config and default_config['ENGINE'] == 'django.db.backends.postgresql_psycopg2':
return default_config['NAME']
return ""
```
The `process_dat... | magicoder | python |
You are given a 2D matrix represented as a list of lists. Your task is to write a Python function that transposes the given matrix. Transposing a matrix involves converting its rows into columns and vice versa.
Write a function `transpose_matrix(matrix)` that takes a 2D matrix `matrix` as input and returns its transpo... | ```python
def transpose_matrix(matrix):
# Get the number of rows and columns in the original matrix
rows = len(matrix)
cols = len(matrix[0]) # Assuming all rows have the same number of elements
# Create a new matrix to store the transposed elements
transposed = [[0 for _ in range(rows)] for _ in r... | magicoder | python |
You are tasked with creating a Java program that utilizes Groovy scripting to dynamically load and execute a Groovy script. Your program should be able to load a Groovy script from a file, instantiate a class from the script, and set a property on the instantiated object. Your task is to implement the necessary Java co... | ```java
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import java.io.File;
public class GroovyScriptExecutor {
public static void main(String[] args) throws Exception {
String filepath = "path/to/YourGroovyScript.groovy"; // Replace with the actual file path
ClassLoader p... | magicoder | java |
You are tasked with implementing a function that prints information about octree levels and their dimensions. An octree is a tree data structure in which each internal node has exactly eight children. The function should take a list of OctreeLevel objects and an integer representing the starting level index. The functi... | ```python
from typing import List, Tuple
from ...._vendor.experimental.humanize.src.humanize import intword
class OctreeLevel:
def __init__(self, dimensions: Tuple[int, int]):
self.dimensions = dimensions
def _dim_str(dim: Tuple[int, int]) -> str:
return f"({dim[0]}, {dim[1]}) = {intword(dim[0] * dim[... | magicoder | python |
You are given a code snippet from a Python script that appears to be part of a parser implementation. The code snippet contains some errors and inconsistencies. Your task is to analyze the code and identify the issues, then propose the correct code to fix the problems.
Given the code snippet:
```
print str(nod... | The code snippet contains several issues that need to be addressed:
1. The `sys` module is used without being imported.
2. The variable `small` is used without being defined.
3. There is a typo in the variable name `nodes[o]` instead of `nodes[0]`.
4. The `parser.parse` function is used without being imported.
Here's... | magicoder | python |
You are tasked with implementing a simple dependency injection container in C#. A dependency injection container is a design pattern used to manage the dependencies between objects. The code snippet provided is an interface `IContainerBuilder` that outlines the methods required to build a dependency injection container... | ```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public interface IComponentContainer
{
T Resolve<T>();
object Resolve(Type type);
}
public class ComponentContainer : IContainerBuilder, IComponentContainer
{
private Dictionary<Type, Type> _typeMappings;... | magicoder | csharp |
You are tasked with writing a script to automate the process of copying files from one directory to another. The script should use the environment variables `test` and `main` to determine the source and destination directories for the file copy operation. The script should also handle any errors that may occur during t... | ```bash
#!/bin/bash
# Check if source directory exists
if [ ! -d "$test" ]; then
echo "Source directory does not exist: $test"
exit 1
fi
# Check if destination directory exists, create if not
if [ ! -d "$main" ]; then
mkdir -p "$main"
fi
# Copy files from source to destination
cp -r "$test"/* "$main"
# Check ... | magicoder | shell |
You are tasked with implementing a thread-safe random number storage class in C++. The given code snippet is a part of the `ct_RndStore` class, which is responsible for storing and swapping random number data between two instances of the class. The class uses a mutex (`co_Mutex`) to ensure thread safety when swapping d... | ```cpp
#include <mutex>
#include <random>
class ct_RndStore {
private:
std::mutex co_Mutex;
int so_Data;
public:
// Constructor to initialize so_Data with a random number
ct_RndStore() {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<int> dis(1, 10... | magicoder | cpp |
You are tasked with implementing a C++ header file guard generator. Header file guards are used to prevent a header file from being included multiple times in the same translation unit, which can lead to redefinition errors. The guard typically takes the form of `#ifndef`, `#define`, and `#endif` directives, with a uni... | ```cpp
#include <string>
#include <cctype>
std::string generateHeaderGuard(const std::string& fileName) {
std::string guardIdentifier = "INCLUDED_";
for (char c : fileName) {
if (std::isalnum(c)) {
guardIdentifier += std::toupper(c);
} else {
guardIdentifier += '_';
... | magicoder | cpp |
You are tasked with implementing a class that manages properties of JavaScript objects in a Java environment. The `TestHelper` class provides a method `property` that retrieves a property from a given JavaScript object. The method takes a `JSObject` and a property name as input and returns the corresponding `Property` ... | ```java
import jdk.nashorn.api.scripting.JSObject;
import java.lang.reflect.Field;
public class PropertyManager {
public void addProperty(JSObject jsObject, String propertyName, Object value) {
try {
Field field = TestHelper.class.getDeclaredField("jsObject");
field.setAccessible(tr... | magicoder | java |
You are tasked with creating a Python program that simulates a simple game of rock-paper-scissors. The program should prompt the user to enter their choice (rock, paper, or scissors), generate a random choice for the computer, determine the winner, and display the result. The program should then ask the user if they wa... | ```python
import random
def determine_winner(user_choice, computer_choice):
if user_choice == computer_choice:
return "It's a tie!"
elif (user_choice == "rock" and computer_choice == "scissors") or (user_choice == "scissors" and computer_choice == "paper") or (user_choice == "paper" and computer_choice... | magicoder | python |
You are given an array of characters `arr`. Write a function `reverseAndPrint` that takes the array as input and prints the characters in reverse order, separated by a space.
The function signature is:
```swift
func reverseAndPrint(_ arr: [Character])
```
For example, given the input `['a', 'b', 'c', 'd']`, the funct... | ```swift
func reverseAndPrint(_ arr: [Character]) {
for char in arr.reversed() {
print(char, separator: "", terminator:" ")
}
}
``` | magicoder | swift |
You are tasked with implementing a memory allocation system for a custom data structure. The system should allocate memory in fixed-size chunks and handle the case where a user attempts to allocate more memory than is available.
You are given a code snippet that includes a test function for converting a string to a la... | ```rust
struct MemoryAllocator {
slab_size: usize,
}
impl MemoryAllocator {
fn new(slab_size: usize) -> Self {
MemoryAllocator { slab_size }
}
fn allocate_memory(&self, size: usize) -> Result<String, &'static str> {
if size <= self.slab_size {
// Simulating memory allocatio... | magicoder | rust |
You are tasked with implementing a Python decorator that can be used to temporarily modify a specific setting within a given settings object while a function is being executed. The decorator should ensure that the original setting is restored after the function completes, regardless of whether the function raises an ex... | ```python
def modify_setting(name, value, settings):
def decorator(fn):
def wrapper(*args, **kwargs):
original = getattr(settings, name)
setattr(settings, name, value)
try:
return fn(*args, **kwargs)
finally:
setattr(settings, n... | magicoder | python |
You are given a code snippet that involves the use of the angr symbolic execution framework to analyze a binary file. The code snippet includes the creation of an angr project, the definition of vtable sizes, and the extraction and validation of vtables from the binary file.
Your task is to create a programming proble... | The solution will be provided once the problem description is created. | magicoder | python |
You are tasked with creating a program that analyzes a given text file to determine the frequency of each word in the file. Your program should ignore punctuation and consider words regardless of their case (i.e., "Hello" and "hello" should be considered the same word). Additionally, the program should exclude common E... | ```python
import re
from collections import Counter
# Read the input text from the file
with open('input.txt', 'r') as file:
text = file.read()
# Define the list of stop words
stop_words = ["the", "and", "of", "to", "in", "a", "is", "it", "that", "as", "on", "with", "for", "at", "by", "this", "we", "you", "not", ... | magicoder | python |
You are tasked with implementing a program that processes a series of commands to manipulate a list of integers. The commands include adding, removing, and finding elements in the list. Your task is to implement the program to handle these commands efficiently.
You are given a code snippet that imports modules and ini... | ```python
import re
import sys
commands = []
for line in sys.stdin:
commands.append(line.strip())
result = []
for command in commands:
if command.startswith("A"):
_, x = command.split()
result.append(int(x))
elif command.startswith("R"):
_, x = command.split()
x = int(x)
... | magicoder | python |
You are tasked with implementing a logic gate simulator that can handle various types of logic gates and different grid sizes. The logic gates to be implemented are And, NAnd, Or, NOr, XOr, and NXOr. The grid size is defined by its height and width, and the logic gates will be applied to the grid cells.
Your task is t... | ```python
def apply_logic_gate(op, height, width):
def apply_gate(x, y):
if op == "And":
return x and y
elif op == "NAnd":
return not (x and y)
elif op == "Or":
return x or y
elif op == "NOr":
return not (x or y)
elif op == "XOr... | magicoder | python |
You are given a 2D grid filled with non-negative integers representing the cost of moving through each cell. You need to find the minimum sum of a path from the top-left cell to the bottom-right cell, moving only right or down.
Write a function `minPathSum(grid)` that takes in a 2D grid as input and returns the minimu... | ```python
def minPathSum(grid):
m, n = len(grid), len(grid[0])
dp = [[0] * n for _ in range(m)]
# Initialize the first cell
dp[0][0] = grid[0][0]
# Initialize the first column
for i in range(1, m):
dp[i][0] = dp[i-1][0] + grid[i][0]
# Initialize the first row
for j... | magicoder | python |
You are tasked with creating a program that processes DNA sequencing data from a given BAM file and generates a pileup file for further analysis. The input BAM file contains aligned sequencing reads, and the output pileup file will provide information about the coverage and variation at each genomic position.
Your pro... | ```python
import subprocess
def generate_pileup(bam_file, track_name):
pileup_file = f"{track_name}.pileup"
command = f"samtools mpileup -f reference_genome.fa {bam_file} > {pileup_file}"
subprocess.run(command, shell=True, check=True)
# Example usage
bam_file_path = "path/to/input.bam"
desired_track_name... | magicoder | python |
You are tasked with creating a web form for a CRUD (Create, Read, Update, Delete) application using the Yii PHP framework. The provided code snippet is a part of the view file for the form. The variables `$this`, `$model`, and `$form` are used to interact with the Yii framework for rendering the form elements and handl... | ```php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\Crud */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="crud-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'attribute1')->textInput(['maxlength' => true]) ?>
... | magicoder | php |
You are given a Python function `predict_transform` that takes in five parameters: `prediction` (a tensor representing predictions), `inp_dim` (input dimension), `anchors` (a list of anchor boxes), `num_class` (number of classes), and `CUDA` (a boolean indicating whether to use CUDA). The function returns a transformed... | ```python
def calculate_iou(wh1, wh2):
"""
Calculate the Intersection over Union (IoU) for two bounding boxes.
Args:
wh1 (tuple, list): width and height pair for the first box
wh2 (tuple, list): width and height pair for the second box
Returns:
iou (float): intersection/union f... | magicoder | python |
You are tasked with creating a Rust program that processes a list of environment variables and performs specific operations based on their values. Your program should handle potential errors and provide appropriate error messages.
You are given a code snippet that attempts to access an environment variable and encount... | ```rust
use std::env;
fn main() {
match env::var("10") {
Ok(val) => {
if let Ok(num) = val.parse::<i32>() {
println!("{}", num * num);
} else {
println!("{}", val.len());
}
}
Err(_) => println!("Environment variable not fou... | magicoder | rust |
You are working on a Django REST framework project and need to implement a custom viewset for a specific model. The code snippet provided is a part of a Django REST framework viewset and contains decorators and method overrides. Your task is to complete the implementation of the custom viewset by adding the necessary m... | ```python
from rest_framework import viewsets, permissions
from rest_framework.decorators import action
from rest_framework.response import Response
from .models import MyModel
from .serializers import MyModelSerializer
class MyModelViewSet(viewsets.ModelViewSet):
queryset = MyModel.objects.all()
serializer_c... | magicoder | python |
You are given a list of strings representing a hierarchical structure. Each string consists of a sequence of elements separated by a delimiter (in this case, a hyphen). The indentation level of each element indicates its position in the hierarchy. Your task is to write a function that sorts the elements based on their ... | ```python
from typing import List
def sort_hierarchy(input_list: List[str]) -> List[str]:
def parse_hierarchy(input_list, level=0):
result = []
for item in input_list:
name, indent = item.strip(), item.count(' ')
if indent == level:
result.append(name)
... | magicoder | python |
You are tasked with creating a program that manages the installation of library dependencies for a microcontroller project. The program should be able to handle the installation of various libraries from different sources using a command-line interface. Your task is to design a class that represents the library install... | ```python
import subprocess
class LibraryManager:
def install_library(self, name):
try:
subprocess.run(["platformio", "lib", "--global", "install", name])
print(f"Library '{name}' installed successfully.")
except subprocess.CalledProcessError as e:
print(f"Error ... | magicoder | python |
You are given a snippet of HTML code representing a simple web page structure. Your task is to write a function that extracts the content within the `<div>` tags and returns it as a string. The function should handle cases where there are multiple nested `<div>` tags and any amount of whitespace or newlines within the ... | ```python
import re
def extractDivContent(html: str) -> str:
match = re.search(r'<div>([\s\S]*?)</div>', html)
if match:
return match.group(1)
else:
return ""
```
The `extractDivContent` function uses regular expressions to search for the content within the `<div>` tags. The `([\s\S]*?)` p... | magicoder | python |
You are tasked with implementing a simplified version of a callback handling system in C++. The system involves managing callbacks and draining sequences for a parent-child relationship.
You are given the following classes and functions:
```cpp
class Callback {
public:
void AsStdFunction() {
// Implementa... | ```cpp
#include <functional>
#include <iostream>
#include <vector>
class Callback {
public:
void AsStdFunction() {
// Implementation not shown
}
};
class Child {
private:
std::vector<std::function<void()>> drainCloseCallbacks;
public:
auto addOnDrainCloseCb(const std::function<void()>& callba... | magicoder | cpp |
You are working on a project that involves integrating with the Google Cloud Document AI service. Your task is to write a Python function that makes a POST request to the Document AI service endpoint to process a document and extract information from it. The function should take the document content and the API key as ... | ```python
import requests
def process_document(image_content: str, api_key: str) -> dict:
document = {"content": image_content, "mime_type": "application/pdf"}
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json; charset=utf-8"
}
endpoint = "https://eu-d... | magicoder | python |
You are tasked with creating a script to automate the process of generating customized ISO files for different models of ultra-mobile personal computers (UMPCs). The script should take an input ISO file and the UMPC model as parameters, and then create a new ISO file with the UMPC model appended to its name. If the out... | ```bash
#!/bin/bash
# Check if the required parameters are provided
if [ $# -ne 2 ]; then
echo "Usage: $0 <input_iso_file> <umpc_model>"
exit 1
fi
ISO_IN=$1
UMPC=$2
echo "Making ${ISO_IN} for ${UMPC}"
ISO_OUT=$(basename "${ISO_IN}" | sed "s/\.iso/-${UMPC}\.iso/")
# Check if the output ISO file already exists
if... | magicoder | shell |
You are tasked with creating a Python function that simulates a simple game of dice. The game involves rolling two dice and summing the values obtained. The function should take in the number of rounds to play and return the frequency of each possible sum from 2 to 12 after the specified number of rounds.
The code sni... | ```python
import random
import config as cnf
def simulate_dice_game(rounds):
frequencies = {i: 0 for i in range(2, 13)} # Initialize frequencies for sums 2 to 12
for _ in range(rounds):
dice1 = random.randint(1, 6) # Simulate roll of first dice
dice2 = random.randint(1, 6) # Simulate roll of... | magicoder | python |
You are tasked with implementing a Python class that interacts with a testbench system for job polling and reporting. The class, named `JobReporter`, has two methods: `report` and `poll`. The `report` method is responsible for reporting the job result to the testbench system, while the `poll` method is used to check fo... | ```python
import testbench
class JobReporter:
def __init__(self, job_id: str):
self.job_id = job_id
self.report_tmp_name = None
def report(self) -> str:
try:
# Report the job result to the testbench system using self.job_id
# Assume the report_tmp_name is obtain... | magicoder | python |
You are tasked with creating a TypeScript function that validates the input arguments for constructing an EngineModel resource. The function should ensure that the required properties are provided and that the values adhere to specific constraints.
The `EngineModelArgs` interface is used to define the set of arguments... | ```typescript
/**
* Validates the input arguments for constructing an EngineModel resource.
* @param args The object of type EngineModelArgs to be validated.
* @returns true if all validations pass, false otherwise.
*/
function validateEngineModelArgs(args: EngineModelArgs): boolean {
if (!args.project || typeo... | magicoder | typescript |
You are tasked with creating a World of Warcraft (WoW) addon that provides information about the player's current shapeshift form and totem status. You have access to a set of predefined functions and constants to achieve this. Your goal is to implement a function that returns the number of active totems for the player... | ```typescript
function GetNumActiveTotems(): number {
if (!IsLoggedIn()) {
return 0; // Player is not logged in, return 0
}
let numActiveTotems = 0;
for (let slot = 1; slot <= 4; slot++) {
const totemInfo = GetTotemInfo(slot);
if (totemInfo && totemInfo[1]) {
numActiveTotems++; // Increment c... | magicoder | typescript |
You are given a set of points in a 2D plane. Your task is to implement a function that constructs the Relative Neighborhood Graph (RNG) for the given set of points. The Relative Neighborhood Graph is a graph where each point is connected to all other points that are not closer to it than any other point. In other words... | ```python
from math import sqrt
def distance(p1, p2):
return sqrt((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2)
def constructRNG(points):
rng = {}
for p in points:
rng[p] = []
for q in points:
if p != q:
is_neighbor = True
for r in points:
... | magicoder | python |
You are tasked with implementing a simple strategy pattern in Python for a stock trading application. The application should allow users to define different trading strategies and apply them to make buy or sell decisions based on certain conditions.
Your task is to create a `Strategy` class with a method `execute_str... | ```python
class Strategy:
def execute_strategy(self, stock_price):
pass # Abstract method to be implemented by subclasses
class MovingAverageStrategy(Strategy):
def __init__(self, short_term_window, long_term_window):
self.short_term_window = short_term_window
self.long_term_window = ... | magicoder | python |
You are tasked with designing a task scheduling system for a cryptocurrency exchange platform. The platform needs to execute various tasks related to registering and updating tokens on the exchange. The tasks are scheduled to be executed asynchronously using a task queue system like Celery.
You are provided with a cod... | To address the task scheduling and execution requirements for the cryptocurrency exchange platform, a robust solution can be designed using Celery, a distributed task queue system. Celery provides the necessary features to handle asynchronous task execution, reliability, scalability, and fault tolerance.
1. **Task Sch... | magicoder | python |
You are tasked with creating a command-line utility that simulates the behavior of the `mv` command in Unix-like operating systems. The `mv` command is used to move or rename files and directories. Your task is to implement a simplified version of this command that handles the following scenarios:
1. Moving a file fro... | ```python
import os
import shutil
def mv_command(source, destination, interactive=False):
if not os.path.exists(source):
return f"Error: Source '{source}' does not exist."
if os.path.isdir(destination):
destination = os.path.join(destination, os.path.basename(source))
if os.path.exists(de... | magicoder | python |
You are tasked with implementing a class hierarchy to manage attribute information for a software system. The base class `AttributeInformation` represents general attribute information, and the derived class `AttributeInformationDetailed` provides additional details specific to detailed attribute information.
The `Att... | ```csharp
public class AttributeInformation
{
public string AttributeName { get; set; }
}
public class AttributeInformationDetailed : AttributeInformation
{
public int NumberOfCalls { get; set; }
public IEnumerable<StepDetails> GeneratedStepDefinitions { get; set; }
public static int GetTotalStepDefin... | magicoder | csharp |
You are tasked with implementing a Bayesian optimization algorithm to optimize a given objective function. The objective function is defined as a black-box function that takes a set of input parameters and returns a single scalar value representing the performance of the system under those parameters. The Bayesian opti... | ```python
def perform_bayesian_optimization(objective_function, search_space, num_iterations):
# Import necessary modules
from BayesOpt import BO
from BayesOpt.Surrogate import RandomForest
from BayesOpt.SearchSpace import ContinuousSpace, OrdinalSpace, NominalSpace
from BayesOpt.base import Solutio... | magicoder | python |
You are tasked with simulating a Brownian particle system using parallel computing. The code snippet provided initializes the simulation parameters and generates data for validation testing. Your task is to implement a parallel simulation of Brownian particles and process the generated data for further analysis.
Your ... | ```python
# Import necessary libraries
import torch
import numpy as np
import mpi4py
from mpi4py import MPI
# Initialize MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
# Define the Brownian particle simulator class
class BrownianParticle:
def __init__(self, dt, gamma, kT, initial, prefix,... | magicoder | python |
You are tasked with creating a program that processes text data using various natural language processing (NLP) techniques. Your task is to implement a function that tokenizes a given input text using the SentencePiece library and then extracts specific parts of speech using the MeCab library. The function should take ... | ```python
import MeCab
import sentencepiece as spm
class NLPProcessor:
def __init__(self, context_aware_sentencepiece_model):
self.context_aware_sentencepiece_model = context_aware_sentencepiece_model
def load(self):
# Load necessary resources for NLP processing
pass
def process_t... | magicoder | python |
You are tasked with creating a Python program to organize images into separate folders based on their category. The program should read a list of image file paths from a text file, create a new directory for each category, and move the images to their respective category folders.
You are given a code snippet that read... | ```python
import os
import shutil
test_list = [line.rstrip('\n') for line in open('./food-101/meta/test.txt')]
os.mkdir('./food-101/test')
source_base = './food-101/images/'
target_base = './food-101/test/'
for item in test_list:
category = item.split('/')[0]
source_path = os.path.join(source_base, item)
... | magicoder | python |
You are tasked with implementing a simplified version of the MD5 hashing algorithm. The MD5 algorithm takes as input a message of arbitrary length and produces a 128-bit "fingerprint" or "message digest" of the input. The algorithm consists of several logical functions, bitwise operations, and constant values.
Your ta... | ```rust
fn md5_i(a: u32, b: u32, c: u32, d: u32, x: u32, s: u32, t: u32) -> u32 {
((b & c) | ((!b) & d)).wrapping_add(a).wrapping_add(x).wrapping_add(t).rotate_left(s)
}
struct MD5 {
state: [u32; 4],
}
impl MD5 {
fn process_block(&mut self, block: &[u8]) {
let mut x = [0u32; 16];
for i in ... | magicoder | rust |
You are tasked with implementing a password hashing and verification system using the scrypt algorithm. The scrypt algorithm is a key derivation function designed to be secure against hardware brute-force attacks. Your goal is to create a function that takes a password and a salt as input, hashes the password using the... | ```javascript
const scrypt = require('scrypt'); // Import the scrypt library
async function test(value, password) {
const salt = Buffer.from(value.s, 'base64'); // Decode the base64-encoded salt
const hashParams = {
N: value.p[0], // CPU/memory cost parameter
r: value.p[1], // block size parameter
p: v... | magicoder | javascript |
You are tasked with creating a web routing system for a simple web application. The application should support registering routes for different HTTP methods and handling those routes with appropriate callbacks. Your task is to implement a class that manages the registration and handling of these routes.
You need to cr... | ```python
class Route:
def __init__(self):
self.routes = {
'GET': {},
'POST': {},
'PUT': {},
'DELETE': {}
}
def registerGetRoute(self, path, callback):
self.routes['GET'][path] = callback
def registerPostRoute(self, path, callback):
... | magicoder | python |
You are given a list of tuples, where each tuple contains a string and an integer. Your task is to write a Python function that takes this list as input and prints the string and integer values of each tuple in reverse order, sorted by the integer value in descending order.
The function signature is:
```python
def pri... | ```python
from typing import List, Tuple
def print_sorted_tuples(sorted_eles: List[Tuple[str, int]]) -> None:
for e in sorted_eles[::-1]:
print(e[0], e[1])
# Test the function
sorted_eles = [('apple', 3), ('banana', 2), ('cherry', 5)]
print_sorted_tuples(sorted_eles)
```
When the `print_sorted_tuples` fu... | magicoder | python |
You are tasked with implementing a class for managing invitations to an event. The class should have methods to check if an invitation has been accepted and if it has expired.
You are provided with a partial code snippet for the Invitation class. The class has two properties: `accepted_at` and `created_at`, and a cons... | ```python
from datetime import datetime, timedelta
INVITATION_EXPIRY = timedelta(days=7) # Example: Invitations expire after 7 days
class Invitation:
def __init__(self, created_at, accepted_at=None):
self.created_at = created_at
self.accepted_at = accepted_at
@property
def accepted(self)... | magicoder | python |
You are tasked with implementing a C++ class that handles asynchronous work using Nan and Gemfire. The provided code snippet outlines the skeleton of the `GemfireWorker` class, which is responsible for executing Gemfire-related tasks asynchronously. Your task is to complete the implementation of the `GemfireWorker` cla... | ```cpp
#include <nan.h>
#include <string>
class GemfireWorker : public Nan::AsyncWorker {
public:
explicit GemfireWorker(Nan::Callback * callback) :
Nan::AsyncWorker(callback),
errorName() {}
void Execute() {
try {
ExecuteGemfireWork();
} catch (const std::exception& e) {
SetError("Gem... | magicoder | cpp |
You are tasked with implementing a loss function for a computer vision model that detects objects in an image. The model predicts bounding box coordinates, centerness scores, and other related information for each object. The loss function is designed to penalize inaccurate predictions and encourage the model to priori... | ```python
import torch
import torch.nn.functional as F
def centerness_weighted_iou_loss(flatten_centerness, pos_inds, num_pos, flatten_bbox_targets, flatten_points, flatten_strides, pos_bbox_preds):
pos_centerness = flatten_centerness[pos_inds]
if num_pos > 0:
pos_bbox_targets = flatten_bbox_targets[p... | magicoder | python |
You are tasked with creating a Python script to automate the process of copying specific directories and running tests for a software project. Your script should perform the following tasks:
1. Copy the 'lit' directory from 'llvm-project/llvm/utils/lit' to a specified destination path.
2. Copy the 'bin', 'lib', 'test'... | ```python
import subprocess
import os
destinationPath_ = '/path/to/destination' # Replace with the actual destination path
llvm_project = 'llvm-project'
build_llvm_clang = 'build_llvm_clang'
build = 'build'
# Copy specific directories to the destination path
subprocess.call(['cp', '--parent', f'{llvm_project}/llvm/u... | magicoder | python |
You are tasked with implementing a function to calculate the volume of a 3D object represented by a quaternary FOM (Figure of Merit) stacked ternary grid. The grid is defined by the `make10ternaxes()` function, which returns the axes and step length for the grid. The variable `gridi` represents the number of grid point... | ```python
import numpy as np
def calculate_volume(axes, step_length, grid_points):
# Calculate the volume of the 3D object represented by the grid
x_axis, y_axis, z_axis = axes
x_step, y_step, z_step = step_length
x_points, y_points, z_points = grid_points
# Create a meshgrid for the axes
x_va... | magicoder | python |
You are tasked with creating a Python function that simulates a simplified version of a resource management system. The function should handle the allocation and deallocation of resources, while also providing error handling for resource allocation failures.
You are provided with a class `ResourceManager` that contain... | ```python
class InsufficientResourcesError(Exception):
def __init__(self, requested_resources, total_resources):
self.requested_resources = requested_resources
self.total_resources = total_resources
super().__init__(f"Insufficient resources. Requested: {requested_resources}, Available: {tota... | magicoder | python |
You are tasked with creating a Python class to represent hourly data for medical facilities. The class should have attributes to store information about the facility, installation, and various patient-related statistics. Additionally, the class should include methods to calculate and retrieve specific patient-related m... | ```python
from datetime import datetime, timedelta
class HourlyData:
def __init__(self, facility_name, installation_name, license, extracted_at, updated_at, model_created_at, model_updated_at, stretchers=None, patients=None, patients_24=None, patients_48=None):
self.facility_name = facility_name
se... | magicoder | python |
You are tasked with implementing a custom error handling system in Rust. Your goal is to create a macro that defines custom error types with a built-in tracer for debugging purposes. The macro should allow the user to define multiple suberrors with optional arguments and sources, as well as custom formatting for error ... | ```rust
#[macro_export]
#[doc(hidden)]
macro_rules! define_error_with_tracer {
( $tracer:ty;
$derive:tt $name:ident;
{
$(
$suberror:ident
$( { $( $arg_name:ident : $arg_type:ty ),* $(,)? } )?
$( [ $source:ty ] )?
| $formatter_arg:pat | $formatter:expr
... | magicoder | rust |
You are tasked with implementing a distributed training setup for a deep learning model using PyTorch's Distributed Data Parallel (DDP) framework. The given code snippet is a part of this setup and contains initialization of the process group, setting up data loaders for training and evaluation, device allocation, and ... | ```python
def _get_optimizers(self):
optimizers = []
for param in self.parameters():
optimizer = torch.optim.Adam(param, lr=self.config['learning_rate'])
optimizers.append(optimizer)
return optimizers
```
In the `_get_optimizers` method, we iterate through the model's parameters and create a... | magicoder | python |
You are tasked with creating a Python function that simulates a simplified version of the `math.frexp` function. The `math.frexp` function returns the mantissa and exponent of a given number when represented in the form `m * 2^e`, where `0.5 <= abs(m) < 1.0`. Your task is to implement a function `custom_frexp` that tak... | ```python
import math
def custom_frexp(x: float) -> (float, int):
if x == 0.0:
return (0.0, 0)
# Extracting the sign, exponent, and mantissa from the floating-point representation
sign, exponent, mantissa = math.frexp(x)
# Handling the special case when x is a subnormal number
if exponent... | magicoder | python |
You are tasked with creating a TypeScript function that processes an array of objects and returns a new object based on certain conditions. The function should take an array of objects and a key as input and return a new object where the keys are unique values from the specified key in the input objects, and the values... | ```typescript
function groupBy<T>(arr: T[], key: string): { [key: string]: T[] } {
return arr.reduce((acc, obj) => {
const keyValue = obj[key];
if (acc[keyValue]) {
acc[keyValue].push(obj);
} else {
acc[keyValue] = [obj];
}
return acc;
}, {});
}
const data = [
{ id: 1, name: 'Alic... | magicoder | typescript |
You are tasked with implementing a transformer class in Java that converts AttributeValues to Byte objects based on certain conditions. The AttributeValue class represents an attribute value in Amazon DynamoDB, and the transformer class needs to handle the conversion logic for different types of AttributeValues.
Your ... | ```java
import software.amazon.awssdk.enhanced.dynamodb.AttributeValue;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTag;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
public class AttributeTransformer ex... | magicoder | java |
You are tasked with creating a C++ macro that checks the platform and throws a compilation error if the platform is unknown. The macro should be able to handle both Windows and non-Windows platforms.
Your task is to define a macro `CHECK_PLATFORM` that, when used in a C++ program, checks if the platform is Windows or ... | ```cpp
#ifdef _WIN32
# define CHECK_PLATFORM
#else
# error "Unknown platform!"
#endif
```
The solution defines the macro `CHECK_PLATFORM` using conditional compilation directives. If `_WIN32` is defined, indicating a Windows platform, the macro is defined as empty. If `_WIN32` is not defined, indicating a non-Windows ... | magicoder | cpp |
You are working on a project that involves organizing files and directories. Your task is to write a Python function that simulates the creation of directories based on a given input string. The input string represents a series of directory creation commands. Each command consists of the "mkdir" command followed by a s... | ```python
def simulate_directory_creation(input_str):
directories = {}
commands = input_str.split("\n")
for command in commands:
if command.startswith("mkdir -p"):
directories_list = command.split(" ")[2:]
current_dir = directories
for directory in directories_lis... | magicoder | python |
You are tasked with implementing a Morse code decoder. Morse code is a method used in telecommunication to encode text characters as sequences of two different signal durations, called dots and dashes, or dits and dahs. In this problem, you are given a string `arg` containing Morse code characters separated by spaces, ... | ```python
import re
def morse_decode(arg: str) -> str:
morse_mapping = {
'.-': 'A', '-...': 'B', '-.-.': 'C', '-..': 'D', '.': 'E', '..-.': 'F',
'--.': 'G', '....': 'H', '..': 'I', '.---': 'J', '-.-': 'K', '.-..': 'L',
'--': 'M', '-.': 'N', '---': 'O', '.--.': 'P', '--.-': 'Q', '.-.': 'R',
... | magicoder | python |
You are tasked with implementing a Python class method for creating a NURBS (Non-Uniform Rational B-Splines) curve from a set of given points. The NURBS curve is a mathematical model commonly used in computer graphics and design for creating smooth curves and surfaces. Your task is to write a method that takes a set of... | ```python
from compas_occ import OCCNurbsCurve
from compas.plugins import plugin
class NURBSCurveFactory:
@plugin(category='factories', requires=['compas_occ'])
def new_nurbscurve_from_interpolation(cls, points, degree=3, weights=None, knots=None):
"""
Create a NURBS curve from given points.
... | magicoder | python |
You are tasked with implementing a simple database management system in Python. The system should support creating tables with specified columns and data types, inserting records into the tables, and querying the records based on certain conditions.
Your task is to implement the `Database` class with the following met... | ```python
class NotAllowed(Exception):
"""Raised when attempting to change class.id"""
class DatabaseException(Exception):
"""Raised for database errors"""
class ColumnTypeUnknown(Exception):
"""Raised when an unknown column type is specified"""
class Database:
def __init__(self):
self.__t... | magicoder | python |
You are tasked with implementing a function that takes an array of objects and returns a new array containing only the objects that have a specific property with a certain value.
You are given the following code snippet as a starting point:
```javascript
const data = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bo... | ```javascript
function filterObjects(arr, prop, value) {
return arr.filter(obj => obj.hasOwnProperty(prop) && obj[prop] === value);
}
```
The `filterObjects` function takes an array `arr`, a property `prop`, and a value `value` as input. It uses the `filter` method to create a new array containing only the objects t... | magicoder | javascript |
You are tasked with implementing a Python class for a simple dynamic linear model (DLM) to perform time series analysis. The DLM class should have the following functionalities:
1. Initialization: The class should be initialized with the state equation and observation equation matrices.
2. State Update: Implement a me... | ```python
import numpy as np
class DynamicLinearModel:
def __init__(self, state_transition_matrix, control_input_matrix, observation_matrix):
self.state_transition_matrix = state_transition_matrix
self.control_input_matrix = control_input_matrix
self.observation_matrix = observation_matrix
... | magicoder | python |
You are tasked with implementing a Python class that generates architecture based on InfoGAN. InfoGAN is a type of generative adversarial network (GAN) that incorporates additional information into the generative process. Your task is to create a class called `InfoGANGenerator` that inherits from an abstract class call... | ```python
from abc import ABC, abstractmethod
class AbstractGenerator(ABC):
@abstractmethod
def generate(self):
pass
class InfoGANGenerator(AbstractGenerator):
def __init__(self, info_params):
self.info_params = info_params
# Initialize InfoGAN specific parameters and architecture ... | magicoder | python |
You are given a list of strings `ss` and a code snippet that uses the `SequenceMatcher` class to compare pairs of strings in the list. Your task is to write a function that takes the list of strings as input and returns the pair of strings with the highest similarity score based on the `SequenceMatcher` comparison.
Yo... | ```python
from difflib import SequenceMatcher
def find_highest_similarity_pair(ss):
max_similarity = 0
max_pair = ()
for i in range(len(ss)):
x = ss[i]
for j in range(i+1, len(ss)):
y = ss[j]
s = SequenceMatcher(None, x, y)
similarity = s.ratio()
... | magicoder | python |
You are given two arrays, `isl180` and `isr180`, which represent the left and right sides of a 180-degree image. The `isl180` array contains the pixel values for the left side of the image, while the `isr180` array contains the pixel values for the right side of the image. The task is to merge these arrays to form the ... | ```python
def merge180Image(isl180, isr180):
complete_image = isl180 + isr180[::-1] # Merge the arrays by concatenating the left side with the reversed right side
return complete_image
```
The `merge180Image` function takes the left and right side arrays as input and concatenates them to form the complete 180... | magicoder | python |
You are tasked with implementing a function that takes in a string representing a markup language and returns the parsed markup. The markup language consists of tags enclosed in angle brackets, where each tag can have attributes in the form of key-value pairs. The tags can be nested within each other, and the attribute... | ```python
def parseMarkup(markup):
stack = []
result = {}
current = result
i = 0
while i < len(markup):
if markup[i] == '<':
if markup[i+1] == '/':
stack.pop()
current = stack[-1]
i += 2
else:
tag, attrs,... | magicoder | python |
You are tasked with creating a script to compare two sets of files and count the differences between them. Your script should take two directory paths as input and compare the files in these directories. For each pair of files with the same name, your script should check if their contents are identical. If there is a d... | ```bash
#!/bin/bash
# Check if two directory paths are provided as arguments
if [ $# -ne 2 ]; then
echo "Usage: $0 <directory1> <directory2>"
exit 1
fi
# Initialize error count
ERROR_COUNT=0
# Iterate through files in the first directory
for FILE1 in "$1"/*; do
# Extract the filename
FILENAME=$(basen... | magicoder | shell |
You are tasked with implementing a builder pattern for a custom input type in Rust. The `SwapEnvironmentCNAMEs` module provides a builder method and a new method for creating a new `SwapEnvironmentCNAMEs` operation. Additionally, it implements the `ParseStrictResponse` trait from the `aws_smithy_http` crate. Your task ... | ```rust
// Define the SwapEnvironmentCNAMEsInput struct
pub struct SwapEnvironmentCNAMEsInput {
environment_names: Vec<String>,
cnames: Vec<String>,
// Add any other relevant fields here
}
// Implement the builder struct for SwapEnvironmentCNAMEsInput
pub struct SwapEnvironmentCNAMEsInputBuilder {
inpu... | magicoder | rust |
You are tasked with creating a Python function that processes a list of dependencies and operations related to database migrations. The function should analyze the dependencies and operations to determine the final sequence of migration operations that need to be executed in order to update the database schema.
The in... | ```python
def process_migrations(dependencies, operations):
dependency_graph = {}
for dependency in dependencies:
if dependency[1] not in dependency_graph:
dependency_graph[dependency[1]] = []
dependency_graph[dependency[1]].append(dependency[0])
def dfs(node, visited, result):
... | magicoder | python |
You are tasked with creating a program that simulates a simple templating engine for a web application. The program should be able to parse a given template and replace placeholders with actual values.
Your task is to implement a function `renderTemplate(template, data)` that takes a template string and a data object ... | ```javascript
function renderTemplate(template, data) {
const placeholderRegex = /{{(.*?)}}/g;
return template.replace(placeholderRegex, (match, placeholder) => data[placeholder.trim()]);
}
// Test the function
const template = `
@section('title')
Linc | {{pageTitle}}
@endsection
@section('header')
@include('{{he... | magicoder | javascript |
You are tasked with implementing a Java method that finds the odd one out in a given array of integers. The odd one out is the integer that appears an odd number of times in the array, while all other integers appear an even number of times. If there are multiple integers that fit this criteria, the method should retur... | ```java
import java.util.HashMap;
import java.util.Map;
public class OddManOut {
public static int findOddManOut(int[] numbers) {
Map<Integer, Integer> countMap = new HashMap<>();
for (int num : numbers) {
countMap.put(num, countMap.getOrDefault(num, 0) + 1);
}
... | magicoder | java |
You are tasked with implementing a polling system for input devices in a game engine. The game engine supports polling input from both a mouse and gamepads. The provided code snippet shows a partial implementation of the polling system, with the mouse polling section commented out. Your task is to complete the implemen... | ```cpp
// poll mouse
//...
void pollMouse() {
// Your implementation to poll the mouse for input goes here
// Example:
// Check for mouse movement and button presses
}
// poll gamepads
//...
void pollGamepads() {
// Your implementation to poll the gamepads for input goes here
// Example:
// Che... | magicoder | cpp |
You are tasked with implementing a pop-up menu view controller in Swift. The pop-up menu should be presented from a given view controller and should provide a list of options for the user to choose from. Your task is to create a custom pop-up menu view controller that can be easily integrated into any iOS app.
Your cu... | ```swift
class PopupMenuViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var options: [String] = []
var optionSelectionHandler: ((String) -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
// Configure the table view to display the options
let ... | magicoder | swift |
You are given a Swift code snippet that contains incomplete code for a protocol and a struct. Your task is to complete the code by defining the missing parts and ensuring that the code compiles successfully.
Complete the code by defining the missing parts of the protocol and struct to satisfy the requirements and cons... | ```swift
protocol b {
associatedtype b: B<T>
}
class T {
struct B<T>: b {
typealias b = T
}
}
```
In the solution, we complete the code by defining the missing associated type in the protocol `b` and implementing the struct `B` with a generic type `b` conforming to the protocol `b`. The struct `B`... | magicoder | swift |
You are tasked with creating a program to calculate the vertical field of view (FOV) for a camera and a projector. The FOV is calculated using the formula: FOV = 2 * arctan(sensor_height / (2 * focal_length)), where sensor_height is half the height of the sensor or projection and focal_length is the distance from the s... | ```python
import math
# Calculate and display the vertical FOV for the camera
a = float(input('Enter the sensor height of the camera (in cm): '))
b = float(input('Enter the focal length of the camera (in cm): '))
camera_vertical_fov = math.degrees(math.atan(a / b))
print('The Vertical FOV of your camera is approximate... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.