query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are working on a data processing pipeline that involves moving and converting files between different directories. Your task is to write a Python function that takes a list of file paths and moves them from a temporary landing zone to a persistent processing zone. Additionally, the function should convert the files... | ```python
from hdfs import InsecureClient
import os
TEMPORAL_ZONE_DIR = '../data/raw'
TEMP_CONVERTED_DIR = '../data/processedTemp'
PERSISTENT_ZONE_DIR = '../data/processed/'
HDFS_DIR = './data/processed'
client = InsecureClient('http://10.4.41.82:9870', user='bdm') # this IP should be changed to your personal VM
def... | magicoder | python |
You are tasked with implementing a Python decorator that will be used to register classes as blocks in a block diagram system. The decorator should validate that the decorated class is a subclass of a `Block` class and then add it to a global list of block classes. Your task is to complete the implementation of the `bl... | ```python
class Block:
pass # Placeholder for the Block class definition
blocklist = [] # Global list to store block classes
def block(cls):
if issubclass(cls, Block):
blocklist.append(cls) # Append class to the global list
else:
raise ValueError('@block used on non Block subclass')
... | magicoder | python |
You are tasked with implementing a custom proxy for the `random.Random` class in Python. The proxy should intercept and modify calls to the `randint` method to ensure that the returned values follow a specific pattern. Your task is to create a `ProxyRandom` class that achieves this behavior.
Your `ProxyRandom` class s... | ```python
import random
class ProxyRandom(random.Random):
def __init__(self, rng):
super().__init__()
self._rng = rng
self._pattern = [1, 2]
self._pattern_index = 0
def randint(self, a, b):
if self._pattern_index >= len(self._pattern):
self._pattern_index = ... | magicoder | python |
You are given a set of numbers representing the base and exponent of a power operation. Your task is to write a program that calculates the result of raising the base to the power of the exponent for each given pair of numbers.
Write a function or program that takes in pairs of numbers (base and exponent) and outputs ... | ```c
#include <stdio.h>
#include <math.h>
int main() {
double n, p, k;
while (scanf("%lf %lf", &n, &p) != EOF) {
k = pow(p, 1 / n);
printf("%0.lf\n", k);
}
return 0;
}
```
The solution reads pairs of numbers from the input until the end-of-file (EOF) is reached. For each pair, it calcu... | magicoder | c |
You are tasked with creating a program to generate random SAT problem instances in Conjunctive Normal Form (CNF) for the purpose of testing SAT solvers. A CNF formula is a conjunction of clauses, where each clause is a disjunction of literals. The program should take the following inputs:
- `n`: The number of variables... | ```python
import random
def generate_cnf_formula(n, m):
with open(f'./data/{m}/uf{n}-{m}.cnf', 'w') as file:
file.write(f'p cnf {n} {m}\n')
for _ in range(m):
clause = ' '.join(str(random.choice([-1, 1]) * random.randint(1, n)) for _ in range(random.randint(3, 5)))
file.writ... | magicoder | python |
You are tasked with implementing a pagination mechanism for a robot application listing service. The `listRobotApplicationsPaginator` function takes in a request object of type `ListRobotApplicationsRequest` and provides a closure `onPage` to be called with each block of entries. The closure returns a boolean indicatin... | ```swift
public func listRobotApplicationsPaginator(
_ input: ListRobotApplicationsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListRobotApplicationsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
func listApplicat... | magicoder | swift |
You are tasked with implementing a binary tree data structure and its associated methods. The binary tree should support the following operations: creating a binary tree from an iterator, clearing the binary tree, and converting the binary tree to a vector.
You are given a code snippet that demonstrates the usage of t... | ```rust
// Define the BinaryTree struct
struct BinaryTree<T> {
root: Option<Box<Node<T>>>,
}
// Define the Node struct
struct Node<T> {
value: T,
left: Option<Box<Node<T>>>,
right: Option<Box<Node<T>>>,
}
impl<T> BinaryTree<T> {
// Create a new binary tree from an iterator
fn from_iter<I>(iter... | magicoder | rust |
You are tasked with implementing a Python script that processes a list of import statements and their associated import parts. An import statement in Python allows you to import a module or specific parts of a module into your current namespace. Each import statement can have multiple import parts, which are the specif... | ```python
class ImportAsPart:
def __init__(self, module_name, alias, comment=None):
self.module_name = module_name
self.alias = alias
self.comment = comment
class ImportStatement:
def __init__(self, module_name, import_parts):
self.module_name = module_name
self.import_p... | magicoder | python |
You are tasked with creating a web application that allows users to manage their to-do lists. The application should have a dashboard page that displays the user's to-do items. You are given a code snippet from the dashboard view file, which uses a Blade template in Laravel framework.
The code snippet is as follows:
`... | ```php
@extends('layouts.app')
@section('content')
<div class="page-title">
<h3>Dashboard</h3>
<div class="todo-list">
@foreach($todos as $todo)
<div class="todo-item">
<input type="checkbox" id="todo-{{ $todo['id'] }}" {{ $todo['completed'] ? 'checked' : '' }}>
... | magicoder | php |
You are tasked with implementing a delegate protocol and a method to handle photo editing in a photo editing application. The `PhotoToolbox` class provides a static method `editPhoto(_:presentingViewController:)` that presents the UI for editing a photo. The method takes in a `UIImage` object representing the photo to ... | ```swift
// Define the PhotoToolboxDelegate protocol
public protocol PhotoToolboxDelegate: AnyObject {
func canceledEditing()
}
// Implement the PhotoToolbox class
public class PhotoToolbox {
/**
Presents the UI for editing a photo.
- Parameter photo: The UIImage to be edited.
... | magicoder | swift |
You are tasked with implementing a credit card validation algorithm for a payment gateway system. The system receives credit card information in the form of a string, and your task is to validate whether the credit card number is potentially valid based on a set of rules.
The credit card information is provided as a s... | ```python
def validateCreditCard(credit_card_number):
# Rule 1: Check if the credit card number consists of 16 digits in the format "XXXX-XXXX-XXXX-XXXX"
if len(credit_card_number) != 19 or not credit_card_number.replace("-", "").isdigit():
return False
# Rule 2: Check if the first digit of the... | magicoder | python |
You are working on a multilingual web application that needs to support different languages for its user interface. You have been tasked with implementing a language translation feature for the application. Your task is to write a function that takes a language key and returns the corresponding translated value based o... | ```php
function translate(array $translations, string $key): string {
return isset($translations[$key]) ? $translations[$key] : $key;
}
``` | magicoder | php |
You are tasked with creating a Python web application that utilizes the Flask framework to build a simple RESTful API for managing a collection of books. Your application should include endpoints for retrieving all books, retrieving a specific book by its ID, adding a new book, updating an existing book, and deleting a... | ```python
from flask import Flask, Blueprint, jsonify, request
app = Flask(__name__)
api = Blueprint('api', __name__)
books = [
{"id": 1, "title": "Book1", "author": "Author1", "publication_year": 2020},
{"id": 2, "title": "Book2", "author": "Author2", "publication_year": 2019}
]
@api.route('/books', methods... | magicoder | python |
You are tasked with creating a Python class that simulates a live dashboard for monitoring Slurm job statuses. Slurm is an open-source workload manager designed for Linux clusters. The class should utilize the Rich library for creating a visually appealing and dynamic dashboard. The provided code snippet serves as a st... | ```python
from rich.live import Live
from rich.table import Table
from rich import print
class SlurmDashboard:
def __init__(self):
self._rich_live = None
def start(self):
self._rich_live = Live(refresh_per_second=16)
self._rich_live.start()
return self
def __exit__(self, *... | magicoder | python |
You are tasked with implementing a class that manages the saving of chunks in a game world. The provided code snippet is a method from this class, which is responsible for saving chunks. The method signature is as follows:
```java
public boolean saveChunks(boolean p_73151_1_, IProgressUpdate p_73151_2_)
```
The metho... | ```java
public boolean saveChunks(boolean p_73151_1_, IProgressUpdate p_73151_2_) {
if (p_73151_1_) {
// Logic to save chunks based on the game world environment
// Use the provided IProgressUpdate instance to track the progress
// Update progress using p_73151_2_.setLoadingProgress(progress... | magicoder | java |
You are tasked with implementing a function that utilizes pre-trained neural network models to create a custom deep learning architecture. The function should take advantage of existing model classes and their functionalities to construct a new architecture for image processing tasks.
You are provided with a code snip... | ```python
from models.vgg import VGGNet
from models.fcn import ResNextDecoderAtt
from models.resnext import ResNeXt101 # Assuming ResNeXt101 is defined in resnext module
def resskspp():
# Initialize the pre-trained ResNeXt101 model
pretrained_model = ResNeXt101(pretrained=True)
# Create an instance of Re... | magicoder | python |
You are tasked with creating a Python module that simulates a simple banking system. The module should include classes for BankAccount and SavingsAccount, each with specific functionalities. The BankAccount class should have methods for deposit, withdraw, and get_balance, while the SavingsAccount class should inherit f... | ```python
class BankAccount:
def __init__(self, balance=0):
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
else:
print("Insufficient funds")
... | magicoder | python |
You are tasked with creating a Python class that processes a dataset containing information about the spread of a disease in different regions. The dataset is structured as a list of dictionaries, where each dictionary represents a region and contains the keys 'Confirmed', 'Deaths', and 'Recovered', along with their re... | ```python
class DiseaseDataProcessor:
def __init__(self, data):
self.data = data
def group_and_calculate_totals(self, key):
data_grouped = {}
for region in self.data:
group_key = region.get(key)
if group_key not in data_grouped:
data_grouped[group... | magicoder | python |
You are tasked with implementing a cross-platform thread-local storage mechanism for a multi-threaded application. The given code snippet includes conditional compilation directives for including platform-specific thread-local storage headers. Your task is to create a class that provides a unified interface for thread-... | ```cpp
// Platform-specific includes
#ifdef __unix__
#include "Unix/ThreadLocal.inc"
#elif defined(_WIN32)
#include "Windows/ThreadLocal.inc"
#else
#warning Neither LLVM_ON_UNIX nor _WIN32 set in Support/ThreadLocal.cpp
#endif
template <typename T>
class ThreadLocalStorage {
public:
void set(const T& value) {
... | magicoder | cpp |
You are given a binary tree data structure and are required to implement a function that calculates the average value of each level in the tree. The tree is represented using a standard node structure with left and right pointers. The function should return a vector of doubles, where each element represents the average... | ```cpp
#include <vector>
#include <queue>
vector<double> averageOfLevels(TreeNode* root) {
vector<double> result;
if (root == nullptr) {
return result;
}
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int sz = q.size();
double sum = 0;
for (int ... | magicoder | cpp |
You are tasked with implementing a custom dataset class for sequential data processing. The dataset class, named `seq_dataset`, is designed to handle sequential data stored in a specified directory. The class should be able to load and preprocess the sequential data for further processing.
Your task is to complete the... | ```python
import pickle
import pdb
import os
import cv2
from torch.utils.data import Dataset
import numpy as np
class seq_dataset(Dataset):
"""seq_dataset"""
def __init__(self, data_dir, resize=(64, 64)):
self.data_dir = data_dir
self.resize = resize
self.data_files = [f for f in os.lis... | magicoder | python |
You are tasked with implementing a function to convert a given time duration in microseconds to the equivalent duration in system ticks. The system ticks are represented as a 64-bit integer value. The function should take the time duration in microseconds as input and return the equivalent duration in system ticks.
Yo... | ```c
_Use_decl_annotations_
LONGLONG
TiMicrosecondsToTicks(ULONGLONG microseconds)
{
// Assuming the system frequency in ticks per second
const ULONGLONG ticksPerSecond = 10000000ULL; // For a system with 100-nanosecond ticks
// Calculate the equivalent ticks using a 64-bit integer to avoid overflow
L... | magicoder | c |
You are tasked with implementing a currency exchange rate caching system in Python. The system should utilize a caching mechanism to store and retrieve currency exchange rates to improve performance and reduce the need for frequent external API calls.
You are provided with a code snippet that includes a function `Curr... | ```python
import requests
def Currency_Change_Rate(user_currency):
r_key = f'currency:{user_currency}'
cached = cache.get(r_key)
if cached:
current_app.logger.info(f'{user_currency} exchange rate is cached: {cached}')
else:
api_url = f'https://api.exchangeratesapi.io/latest?base=USD&sym... | magicoder | python |
You are tasked with implementing a Snake game using object-oriented programming in Python. The game consists of a snake that moves around a grid, consuming food to grow in length and score points. The provided code snippet includes a part of the test suite for the game, which checks the length and score of the snake af... | ```python
class SnakeGame:
def __init__(self, grid_size, initial_position, initial_direction):
self.grid_size = grid_size
self.snake = [initial_position]
self.direction = initial_direction
self.food = self.generate_food()
self.score = 0
def move(self):
head = sel... | magicoder | python |
You are working on a project that involves processing and manipulating multidimensional arrays. Your task is to implement a function that performs a specific type of cropping operation on a given input array.
You are given a 4-dimensional array `x0` of shape `(a, b, c, d)` and a 3-dimensional array `y0` of shape `(a, ... | ```python
import numpy as np
def crop(arr, n):
"""
Crop the input array by removing n elements from each edge along each dimension.
Args:
arr: Input array of shape (a, b, c, d) or (a, b, c)
n: Number of elements to remove from each edge along each dimension
Returns:
cropped_arr: Cropped a... | magicoder | python |
You are tasked with simulating the behavior of a RIOT (Ram, Input/Output, Timer) chip, which was used in the Atari 2600 gaming console. The RIOT chip has a timer that decrements at a fixed rate and can trigger an interrupt when it reaches zero. Your goal is to implement a simplified version of the RIOT chip's timer fun... | ```rust
#[derive(Default)]
struct Riot {
timer_value: u8,
timer_reset: bool,
timer_interrupt: bool,
}
impl Riot {
fn set(&mut self, value: u8) {
self.timer_value = value;
}
fn tick(&mut self, decrement_amount: u8) {
if self.timer_value > 0 {
self.timer_value = self.... | magicoder | rust |
You are tasked with implementing a function that takes in a string of HTML code and returns the count of unique HTML tags present in the string. For the purpose of this problem, an HTML tag is defined as any substring enclosed within angle brackets, such as `<div>`, `<p>`, or `<img src="image.jpg">`. Tags with the same... | ```javascript
function countUniqueHTMLTags(htmlString) {
const tagSet = new Set();
let tag = '';
let inTag = false;
for (let i = 0; i < htmlString.length; i++) {
if (htmlString[i] === '<') {
inTag = true;
tag = '<';
} else if (htmlString[i] === '>') {
inTag = false;
tag += '>';
... | magicoder | javascript |
You are tasked with implementing a function to remove a specific ragdoll joint from a physics setup associated with an actor in a game engine. The provided code snippet is a part of a larger system and demonstrates the beginning of the implementation of the `Execute` function for the `CommandRemoveRagdollJoint` class. ... | ```cpp
bool CommandRemoveRagdollJoint::Execute(const MCore::CommandLine& parameters, AZStd::string& outResult)
{
AZ_UNUSED(parameters);
Actor* actor = GetActor(this, outResult);
if (!actor)
{
return false;
}
const AZStd::shared_ptr<PhysicsSetup>& physicsSetup = actor->GetPhysicsSetup()... | magicoder | cpp |
You are tasked with implementing a Python class that performs thresholding on a given numerical value. The class should have a method `threshold(num, threshold)` that takes a numerical value `num` and a threshold value `threshold` in the range [0, 1]. The method should return `True` if the fractional part of `num` is g... | ```python
class Threshold:
def threshold(self, num, threshold):
if not (0 <= threshold < 1):
raise ValueError('Threshold input must be in the range [0, 1]')
fractional = num - int(num)
return fractional >= threshold
```
The solution provides a Python class `Threshold` w... | magicoder | python |
You are tasked with implementing a function that validates and processes input arguments for creating variables in a programming language. The function should take a dictionary of input arguments and a variable type, and then validate and process the input according to the available arguments and their requirements.
Y... | ```python
class MissingArgumentException(Exception):
pass
class InvalidArgumentException(Exception):
pass
def process_variable_input(variable_dict_input, variable_type, available_args):
processed_input = {}
for arg, details in available_args.items():
if arg in variable_dict_input:
... | magicoder | python |
You are tasked with creating a command-line utility that processes and stores command history from a shell session. The utility, named "mcfly," is designed to capture the text of the last command executed in the shell and save it to a database. The provided code snippet is a part of a Zsh shell function that integrates... | To implement the "mcfly" utility, you can create a script or program that interacts with the shell environment to capture command history and store it in a database. Below is a high-level solution outline for the functionality described in the problem:
1. Capture the last executed command and its exit code:
- Acces... | magicoder | shell |
You are tasked with creating a custom button component for a user interface. The button should have specific properties and behaviors, and you need to implement the necessary code to achieve this.
Your task is to create a custom button class in C# that meets the following requirements:
- The button should have a prope... | ```csharp
using System.Drawing;
using System.Windows.Forms;
public class CustomButton : Button
{
public CustomButton()
{
this.TabStop = false;
this.BorderRadius = 20;
this.CheckedState.Parent = this;
this.CustomImages.Parent = this;
this.Font = new Font("Mark", 9.75F, Fo... | magicoder | csharp |
You are tasked with creating a Python command-line application that utilizes the `typer` library to interact with a custom module called `windshader`. The `windshader` module provides utilities for processing wind data. Your application should have commands to perform various operations on wind data, such as fetching, ... | ```python
import typer
from windshader import utils
app = typer.Typer()
@app.command()
def fetch_wind_data(location: str):
"""
Fetch wind data from the specified location.
"""
# Call the fetch_wind_data function from the windshader module
wind_data = utils.fetch_wind_data(location)
typer.echo(... | magicoder | python |
You are tasked with creating a Python function that simulates a simple web template rendering process similar to Django's template rendering. Your function should take a template string and a dictionary of context variables as input, and return the rendered template with the context variables replaced.
Your function s... | ```python
def render_template(template: str, context: dict) -> str:
from jinja2 import Template # Using Jinja2 for template rendering
# Create a Jinja2 template object from the input template string
jinja_template = Template(template)
# Render the template with the provided context variables
rend... | magicoder | python |
You are tasked with implementing a chess move evaluation algorithm using the Alpha-Beta pruning algorithm. The given code snippet provides a partial implementation of the algorithm in Rust. Your task is to complete the implementation of the `update_pv` and `depth` functions for the `AlphaBetaSearchParams` and `NullWind... | ```rust
impl<E: Eval> SearchParams<E> for AlphaBetaSearchParams<E> {
fn update_pv(&mut self, chess_move: ChessMove, other: AlphaBetaSearchParams<E>) {
self.pv.push(chess_move);
self.pv.extend(other.pv);
}
fn depth(&self) -> i16 {
self.depth
}
}
impl<E: Eval> SearchParams<E> for... | magicoder | rust |
You are tasked with creating a Python script that automates the process of checking for outdated packages in a virtual environment and then generates a report of the outdated packages. Your script should utilize the `pip list` command to retrieve the list of installed packages and then display the outdated packages in ... | ```python
import subprocess
# Step 1: Retrieve the list of installed packages using pip list
installed_packages = subprocess.check_output(['pip', 'list']).decode('utf-8').split('\n')
# Step 2: Identify the outdated packages
outdated_packages = [package.split()[0] for package in installed_packages[2:] if '==' in packa... | magicoder | python |
You are tasked with implementing a simple CPU simulator that executes a series of instructions and updates the state of the registers and memory. The provided code snippet is a part of the execution loop of the simulator. The `execute` function takes an instruction, the current register state, and the program counter a... | ```python
# Define the execute function
def execute(instruction, register_state, program_counter):
# Implement the execution logic for each instruction
# Update the register state, program counter, and return the execution result
# Example:
# execute ADD instruction
if instruction.startswith('ADD'):... | magicoder | python |
You are tasked with implementing a function to parse and aggregate log data from a server response. The server response is in the form of a JSON object containing a list of log entries. Each log entry is represented as a dictionary with keys "timestamp" and "message". Your task is to write a function that takes this se... | ```python
def aggregate_logs(server_response: dict) -> dict:
logs = server_response.get("logs", [])
aggregated_logs = {}
for log in logs:
timestamp = log.get("timestamp")
message = log.get("message")
if timestamp in aggregated_logs:
aggregated_logs[timestamp].append(messa... | magicoder | python |
You are tasked with implementing a test case for a data store dispatch method in a Swift application. The method under test is responsible for ensuring that the payload sent to a hub accurately represents the incoming synchronization data. The code snippet provided is a placeholder for the test case, indicating that it... | ```swift
import XCTest
class DataStoreTests: XCTestCase {
func testDataStoreDispatchesCreateToHub() {
// Given
let dataStore = DataStore() // Instantiate the data store
let mockHub = MockHub() // Create a mock hub for testing
// Define the incoming synchronization data
let ... | magicoder | swift |
You are tasked with implementing a custom React alert component that can be closed by clicking on a button. The component should accept various props and render different types of alerts based on the `type` prop. Additionally, the component should call an `onClose` callback function when the alert is closed.
Your task... | ```jsx
import React, { useState, useRef } from 'react';
import classnames from 'classnames';
const Alert = ({ type, onClose, className, ...restProps }) => {
const [alertStatus, setAlertStatus] = useState(true);
const prefixCls = 'alert';
const closeAlert = (event) => {
setAlertStatus(false);
onClose?.(e... | magicoder | jsx |
You are working on a machine learning project using TensorFlow and have encountered a debugging scenario. You are using TensorFlow's `tf_debug` module to debug the gradients during the training process. The code snippet provided is a part of your TensorFlow graph construction.
Given the code snippet, you need to compl... | ```python
import tensorflow as tf
from tensorflow.python import debug as tf_debug
# Assume x is a placeholder or input tensor
x = tf.placeholder(tf.float32)
# Define the operation y = x + x
y = tf.add(x, x)
# Create a GradientsDebugger instance
grad_debugger = tf_debug.GradientsDebugger()
# Identify the gradient of... | magicoder | python |
You are tasked with creating a program that analyzes a given HTML file to extract and count the unique URLs of CSS files and background images used in the file. The HTML file contains various elements, including links to CSS files and inline styles with background images. Your program should be able to identify and cou... | ```python
import re
def extractUrls(html):
css_urls = set(re.findall(r'href="([^"]+\.css)"', html))
background_image_urls = set(re.findall(r'url\(([^)]+)\)', html))
return {
"css": len(css_urls),
"background_images": len(background_image_urls)
}
```
The `extractUrls` function uses regu... | magicoder | python |
You are tasked with creating a custom JSON converter for a specific class in a C# application. The class `OgmoValueDefinition` represents a definition for a value used in the Ogmo Editor, a level design tool. Your goal is to implement the custom JSON converter to serialize and deserialize instances of the `OgmoValueDef... | ```csharp
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
namespace Ash.Ogmo.JsonConverters
{
public class OgmoValueDefinitionConverter : JsonConverter<OgmoValueDefinition>
{
public override OgmoValueDefinition ReadJson(JsonReader reader, Type objectType, OgmoValueDefinition existingVa... | magicoder | csharp |
You are given a mapping of digits to a set of letters as follows:
```
{
2: ['a', 'b', 'c'],
3: ['d', 'e', 'f'],
4: ['g', 'h', 'i'],
5: ['j', 'k', 'l'],
6: ['m', 'n', 'o'],
7: ['p', 'q', 'r', 's'],
8: ['t', 'u', 'v'],
9: ['w', 'x', 'y', 'z']
}
```
Write a function `letterCombinations` t... | ```python
def letterCombinations(digits):
dic = {
'2': ['a', 'b', 'c'],
'3': ['d', 'e', 'f'],
'4': ['g', 'h', 'i'],
'5': ['j', 'k', 'l'],
'6': ['m', 'n', 'o'],
'7': ['p', 'q', 'r', 's'],
'8': ['t', 'u', 'v'],
'9': ['w', 'x', 'y', 'z']
}
def ba... | magicoder | python |
You are given a weighted directed graph with V vertices and E edges. Each edge is represented as a triple (source, destination, weight), where source and destination are vertices and weight is the edge's weight. The task is to find the shortest distances from a given source vertex to all other vertices in the graph usi... | ```java
public int[] bellmanFord(int[][] graph, int V, int E, int source) {
int[] dis = new int[V];
for (int i = 0; i < V; i++) {
dis[i] = Integer.MAX_VALUE;
}
dis[source] = 0;
for (int i = 0; i < V - 1; i++) {
for (int j = 0; j < E; j++) {
int u = graph[j][0];
... | magicoder | java |
You are tasked with creating a program to simulate a simple stack data structure using a linked list. The stack should support the following operations: push, pop, and peek. Additionally, you need to implement a method to find the minimum element in the stack in constant time.
You are given the following class definit... | ```csharp
public class Stack
{
private Node top;
public void Push(int value)
{
if (top == null)
{
top = new Node { Value = value, MinValue = value, Next = null };
}
else
{
var newNode = new Node { Value = value, Next = top, MinValue = Math.Min... | magicoder | csharp |
You are tasked with implementing a shell script function that converts a device name in a specific format to its corresponding device identifier using the `blkid` command. The function should handle device names in the form of UUID=xxxx or LABEL=xxxx, where xxxx represents the actual UUID or label of the device.
You n... | ```bash
to_dev_name() {
local dev="${1//\"/}" # Remove surrounding double quotes from the input device name
case "$dev" in
UUID=*)
dev=`blkid -U "${dev#UUID=}"` # Retrieve device identifier based on UUID
;;
LABEL=*)
dev=`blkid -L "${dev#LABEL=}"` # Retrieve device identifier ... | magicoder | shell |
You are tasked with creating a Python function that generates a specific file structure for a drone control system. The function `fileStructure` takes four parameters: `ip` (string), `port` (int), `drones` (list of strings), and `leds` (list of strings). The function should construct a string representing the file stru... | ```python
def fileStructure(ip, port, drones, leds):
file_structure = f'<rosparam>\n <param name="ip" value="{ip}" />\n <param name="port" value="{port}" />\n <node>\n'
drone_args = []
for drone_number in range(len(drones)):
drone_args.append(f' <arg name="uri{drone_number}" default="radi... | magicoder | python |
You are tasked with implementing a Python function to parse a BUSCO (Benchmarking Universal Single-Copy Orthologs) output file and extract a list of duplicated genes. BUSCO is a widely used tool for assessing the completeness of genome assemblies and annotations. The output file contains information about identified or... | ```python
def parse_busco_file(busco):
"""Parses the BUSCO output file and returns a list of duplicated genes."""
duplicated_list = []
with open(busco) as handle:
for line in handle:
if 'D:1%' in line: # Assuming 'D:1%' indicates a duplicated gene
mode_index = line.find(... | magicoder | python |
You are given a program that reads input to construct a directed graph. The input consists of a series of pairs of integers, each pair representing a directed edge in the graph. The program also maintains an array `p` to count the number of incoming edges for each vertex and a 2D array `res` to represent the direction ... | ```cpp
#include <vector>
#include <utility>
#include <unordered_map>
using namespace std;
vector<int> findMissingEdge(int n, vector<pair<int, int>> edges) {
unordered_map<int, int> p;
vector<vector<int>> res(n + 1, vector<int>(n + 1, 0));
for (auto edge : edges) {
int x = edge.first;
int ... | magicoder | cpp |
You are tasked with creating a custom data model field in a Django application that sanitizes user input to prevent cross-site scripting (XSS) attacks. To achieve this, you need to utilize the `django_bleach` library, which provides a `BleachField` for sanitizing HTML content. Your goal is to implement a custom model f... | To implement the custom model field using `django_bleach` for sanitizing user input, you can define a new model field class that extends `django.db.models.Field` and utilizes the `django_bleach.models.BleachField`. Below is a sample implementation of the custom model field and the corresponding migration:
```python
fr... | magicoder | python |
You are tasked with creating a Python script to process and merge data from multiple Dota 2 match results into a single CSV file. Each match result is stored in a separate file, and the script should merge the results based on the specified classes and save the merged data to a CSV file.
The script should accept comma... | ```python
import argparse
import os
import pandas as pd
import json
def merge_dota_results(srcpath, classes, dstpath='result.csv'):
# Read match result files from the source path
match_results = []
for filename in os.listdir(srcpath):
if filename.endswith('.json'):
with open(os.path.joi... | magicoder | python |
You are tasked with creating a program that generates a responsive web layout using the given code snippet as a starting point. The `.frame(maxWidth: .infinity)` part of the code snippet is from the SwiftUI framework, which is used for building user interfaces across Apple platforms. In this context, it sets the maximu... | ```python
# Python program to generate HTML and CSS for a responsive web layout
def generate_responsive_layout():
html_code = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css... | magicoder | python |
You are tasked with creating a function that calculates the total score of a game based on the scores obtained in different levels. The game consists of multiple levels, and the score for each level is calculated based on the level number and the time taken to complete the level. The scoring system is as follows:
- The... | ```swift
func calculateTotalScore(levels: [(level: Int, time: Double)]) -> Int {
var totalScore = 0
for level in levels {
var score = level.level * Int(level.time)
if level.level % 2 == 0 {
score *= 2
}
if level.level % 3 == 0 {
score += 50
}
... | magicoder | swift |
You are given a string representing a snippet of C++ code. The code snippet is incomplete and contains an unbalanced number of opening and closing curly braces (`{` and `}`). Your task is to write a function to determine the minimum number of opening or closing curly braces that need to be added to balance the code sni... | ```cpp
#include <iostream>
#include <stack>
#include <string>
int minBracesToAdd(const std::string& codeSnippet) {
std::stack<char> bracesStack;
int openBraces = 0;
int closeBraces = 0;
for (char c : codeSnippet) {
if (c == '{') {
bracesStack.push(c);
} else if (c == '}') {... | magicoder | cpp |
You are tasked with implementing a CoAP (Constrained Application Protocol) message parser in C. The CoAP message parser is responsible for parsing incoming CoAP messages and extracting relevant information from them. The provided code snippet is a part of the CoAP message parser implementation and sets up the expected ... | ```c
void parse_coap_message(const uint8_t *coap_message, uint16_t message_length, sn_coap_hdr_s *parsed_message) {
// Extract message ID from the CoAP message
parsed_message->msg_id = (coap_message[2] << 8) | coap_message[3];
// Extract options list from the CoAP message
// Assuming options list start... | magicoder | c |
You are tasked with implementing a function that simulates a simple text-based adventure game. The game will involve navigating through a series of interconnected rooms, each with its own description and possible exits. The player will be able to move between rooms and interact with objects within the rooms.
Your task... | ```swift
class AdventureGame {
var gameMap: [String: (String, [String: String])]
var currentRoom: String
init(gameMap: [String: (String, [String: String])]) {
self.gameMap = gameMap
self.currentRoom = "start"
}
func move(_ direction: String) -> String {
if let nextR... | magicoder | swift |
You are tasked with creating a function that parses a given HTML code snippet and extracts all the hyperlinks (anchor tags) present in the code. The function should return a list of all the URLs found in the anchor tags.
Write a function `extract_links(html_code: str) -> List[str]` that takes a string `html_code` repr... | ```python
from typing import List
import re
def extract_links(html_code: str) -> List[str]:
# Regular expression pattern to match the href attribute in anchor tags
href_pattern = r'href="([^"]+)"'
# Find all matches of the href attribute using the pattern
href_matches = re.findall(href_pattern, html_c... | magicoder | python |
You are tasked with understanding and utilizing Swift's concurrency features. In this problem, you will be working with the `UnsafeCurrentTask` type and its associated functions.
Your goal is to create a function that checks a property of the `UnsafeCurrentTask` instance and returns a boolean value based on the compa... | ```swift
@available(SwiftStdlib 5.5, *)
func checkProperty(_ task: _Concurrency.UnsafeCurrentTask) -> Bool {
return task.someProperty == "123"
}
@available(SwiftStdlib 5.5, *)
func performTask(_ task: _Concurrency.UnsafeCurrentTask) {
// Implementation for performing the task goes here
// This function doe... | magicoder | swift |
You are tasked with creating a custom serializer class in Python using the Django REST framework. The provided code snippet is a starting point for the serializer class, but it lacks the necessary fields and attributes. Your goal is to complete the serializer class by adding the required fields and implementing the nec... | ```python
from rest_framework import serializers
from .models import Peer
class PeerSerializer(serializers.ModelSerializer):
class Meta:
model = Peer
fields = ['id', 'name', 'ip_address', 'port', 'status']
def validate_name(self, value):
if self.instance and self.instance.name == value... | magicoder | python |
You are tasked with implementing a function that calculates the skewness of a dataset. Skewness is a measure of the asymmetry of the probability distribution of a real-valued random variable about its mean. A skewness value of 0 indicates a symmetrical distribution, while positive and negative values indicate right-ske... | ```python
from typing import List
def calculate_skewness(data: List[float]) -> float:
n = len(data)
mean = sum(data) / n
variance = sum((x - mean) ** 2 for x in data) / n
std_dev = variance ** 0.5
skewness = (n / ((n - 1) * (n - 2))) * sum(((x - mean) / std_dev) ** 3 for x in data)
return skew... | magicoder | python |
You are tasked with creating a middleware function for a web application. The middleware function needs to perform authentication and authorization checks for incoming requests. The function should be designed to work with the Django framework and should be implemented in Python.
Your task is to implement the `check_a... | ```python
# Import necessary modules
from django.shortcuts import redirect
from django.urls import reverse
def check_authentication(get_response):
# Define the middleware function
def middleware(request):
# Check if the user is authenticated
if not request.user.is_authenticated:
# R... | magicoder | python |
You are tasked with implementing a Python class that processes terminal output using regular expressions. The class, `TerminalModule`, is a subclass of `TerminalBase` and contains a list of regular expressions used to match specific patterns in terminal output.
Your task is to complete the implementation of the `Termi... | ```python
from typing import List
import re
class TerminalBase:
pass # Placeholder for the base class
class TerminalModule(TerminalBase):
terminal_stdout_re = [
re.compile(br"[\r\n]?[\w+\-\.:\/\[\]]+(?:\([^\)]+\)){,3}(?:>|#) ?$"),
re.compile(br"\[\w+\@[\w\-\.]+(?: [^\]])\] ?[>#\$] ?$")
]
... | magicoder | python |
You are tasked with implementing a Python class that represents a sequence of paths. The class should be able to handle path manipulation and filtering based on certain criteria.
Your task is to complete the implementation of the `SequencePath` class, which is a subclass of `Gaffer.Path`. The `SequencePath` class shou... | ```python
import IECore
import Gaffer
class SequencePath(Gaffer.Path):
def __init__(self, path, root="/", minSequenceSize=1, filter=None):
super(SequencePath, self).__init__(root)
self.__path = path
self.__minSequenceSize = minSequenceSize
self.__filter = filter
def getSequence... | magicoder | python |
You are tasked with creating a Python function that validates version numbers according to the Semantic Versioning (SemVer) specification. Semantic Versioning is a standard for versioning software that uses a three-part version number: MAJOR.MINOR.PATCH. Each part is a non-negative integer, and the version number must ... | ```python
import re
def validate_semantic_version(version):
pattern = r"^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$"
return bool(re.match(pattern, version))
```
The `validate_semantic_version` function uses a regular expression pattern to match the input version string against the Semantic Versioning specifica... | magicoder | python |
You are tasked with implementing a simplified version of a query planner for a graph database system. The given code snippet is part of a Rust program that involves constructing a query plan and executing a graph query.
The `PlanBuilder` is a struct that provides methods for building query plans and graph templates. T... | ```rust
// Define the Encoder and Algebra types
struct Encoder;
struct Algebra;
// Define the Variables and Plan types
struct Variables;
struct Plan;
// Define the Construct and GraphTemplate types
struct Construct;
struct GraphTemplate;
// Define the Error type
struct Error;
// Implement the PlanBuilder struct
str... | magicoder | rust |
You are tasked with implementing a Sudoku solver using the given `MySolver` class and its associated methods. The `MySolver` class provides a method `solveBoard(Board)` that takes a `Board` object as input and returns a list of `Move` objects representing the solution to the Sudoku puzzle.
Your task is to create a pro... | ```java
import java.util.List;
public class SudokuSolver {
public static int[][] solveSudoku(int[][] board) {
Board sudokuBoard = new Board(board);
MySolver solver = new MySolver();
List<Move> solution = solver.solveBoard(sudokuBoard);
for (Move move : solution) {
... | magicoder | java |
You are tasked with implementing a simplified version of a packet capture (pcap) system in Rust. The given code snippet is part of a larger program and is responsible for initializing a pcap dump object. The `Subject` enum is defined in the `pcap` module and has a variant `AutoFirstSource`. The `PcapDump` struct is als... | ```rust
mod pcap {
pub enum Subject {
AutoFirstSource,
// other variants if present
}
pub struct PcapDump {
subject: Subject,
start_at: u64, // assuming start time is in seconds
end_at: u64, // assuming end time is in seconds
}
impl PcapDump {
pub ... | magicoder | rust |
You are tasked with implementing a function that simulates a simple file system navigation system. The function should take in a list of commands and return the final directory path after executing all the commands. The commands can include navigating to a parent directory (".."), navigating to a child directory ("dir_... | ```swift
func navigateFileSystem(commands: [String]) -> String {
var stack: [String] = ["/"]
for command in commands {
if command == ".." {
if stack.count > 1 {
stack.removeLast()
}
} else if command != "." {
stack.append(command)
... | magicoder | swift |
You are tasked with implementing a simple command-line utility that simulates a basic calculator. The utility should accept a mathematical expression as input and then evaluate and display the result. The mathematical expression can contain the four basic arithmetic operations: addition (+), subtraction (-), multiplica... | ```python
def evaluateExpression(expression: str) -> int:
stack = []
num = 0
sign = '+'
for i in range(len(expression)):
if expression[i].isdigit():
num = num * 10 + int(expression[i])
if (not expression[i].isdigit() and expression[i] != ' ') or i == len(expression) - 1:
... | magicoder | python |
You are tasked with implementing a generic class called `GkTuple` that represents a tuple containing a single value of type `T`. The class should have a method `CompareTo` that allows comparing two `GkTuple` objects based on their contained values. The `CompareTo` method should return a value indicating the relative or... | ```csharp
public class GkTuple<T> : IComparable
{
private T v;
public GkTuple(T value)
{
v = value;
}
public int CompareTo(object obj)
{
if (obj == null) return 1;
GkTuple<T> other = obj as GkTuple<T>;
if (other == null)
throw new ArgumentException(... | magicoder | csharp |
You are tasked with creating a Python function that calculates the average score for a given video based on the scores provided by users. You will be given a list of `VideoScore` objects, each containing the `video_id` and `score` attributes. Your task is to implement a function `calculate_average_score` that takes the... | ```python
def calculate_average_score(video_scores):
video_sum = {}
video_count = {}
for score in video_scores:
if score.video_id in video_sum:
video_sum[score.video_id] += score.score
video_count[score.video_id] += 1
else:
video_sum[score.video_id] =... | magicoder | python |
You are tasked with implementing a simple event handling system for a live page update feature in a web application. The system consists of a `live_page_update` object that manages the live updates and a list of `receivers` that are responsible for handling the updates. The code snippet provided is a part of the event ... | ```python
class Receiver:
def __init__(self, id):
self.id = id
class LivePageUpdate:
def __init__(self):
self.receivers = []
def add_receiver(self, receiver):
self.receivers.append(receiver)
def disconnect(self, receiver):
if receiver in self.receivers:
sel... | magicoder | python |
You are tasked with implementing a class method for a data validation and saving process. The method should perform validation, update the validation status and errors, send a validation message, and save the data. Your task is to complete the implementation of the `validate_and_save` method in the given class.
```pyt... | ```python
class DataProcessor:
def __init__(self, data):
self.data = data
self.validated = False
self.validation_errors = []
def validate(self):
# Perform data validation and return a tuple (is_valid, validation_text)
# is_valid is a boolean indicating whether the data i... | magicoder | python |
You are working on a web application that allows users to edit comments on specific processes and files. The application uses PHP to handle the server-side logic. The code snippet provided below is a part of the server-side script that processes the user input.
```php
$codProcesso = $_GET["cdp"];
$CodArq=$_GET["ca"];
... | ```php
function sanitizeInput($input) {
// Remove leading and trailing whitespace
$input = trim($input);
// Convert special characters to HTML entities
$input = htmlspecialchars($input, ENT_QUOTES, 'UTF-8');
// Use prepared statements or parameterized queries to prevent SQL injection
/... | magicoder | php |
You are working on a project that requires interacting with a salt management system. The salt management system provides a set of libraries for managing and controlling systems. You need to write a Python function that uses the salt libraries to retrieve information about the minions (systems) connected to the salt ma... | ```python
import salt.client
def get_minion_info(master_address, master_port, auth_creds):
local = salt.client.LocalClient()
minions = local.cmd('*', 'grains.items', tgt_type='compound', expr_form='compound', port=master_port, timeout=10, username=auth_creds["username"], password=auth_creds["password"], master... | magicoder | python |
You are tasked with implementing a CPU feature detection algorithm using the CPUID instruction. The CPUID instruction is used to determine the features and capabilities of the CPU. In this problem, you will be focusing on detecting the support for SSE2, AVX, and AVX2 instruction sets.
Your task is to complete the impl... | ```cpp
#include <iostream>
// Define the CPU feature detection class
class CPUFeatureDetection {
public:
bool HW_SSE2;
bool HW_AVX;
bool HW_AVX2;
// Function to retrieve CPU feature information using CPUID instruction
void cpuid(int info[4], int function_id) {
__asm__ __volatile__(
... | magicoder | cpp |
You are tasked with creating a Python class that checks whether all data stored in an Amazon ElastiCache Replication Group is securely encrypted at rest. Your task is to implement the `ElasticacheReplicationGroupEncryptionAtRest` class, which inherits from the `BaseResourceCheck` class. The `ElasticacheReplicationGroup... | ```python
class ElasticacheReplicationGroupEncryptionAtRest(BaseResourceCheck):
def __init__(self):
name = "Ensure all data stored in the Elasticache Replication Group is securely encrypted at rest"
id = "CKV_AWS_29"
supported_resources = ['AWS::ElastiCache::ReplicationGroup']
catego... | magicoder | python |
You are given a Python function that processes a 2D grid and returns a count. The function contains three sets: `col_blacklist`, `major_blacklist`, and `minor_blacklist`. Your task is to implement a program that populates these sets based on certain conditions and then calculates the count returned by the function.
Th... | ```python
from typing import List
def process_grid(grid: List[List[int]]) -> int:
n = len(grid)
col_blacklist = set()
major_blacklist = set()
minor_blacklist = set()
for i in range(n):
for j in range(n):
if grid[i][j] == 0:
col_blacklist.add(j)
m... | magicoder | python |
You are tasked with creating a PHP function that retrieves and processes data from a MySQL database. The function should take a user ID as input and return an array containing statistical information, account details, and a list of distinct system IDs associated with the user.
The database contains three relevant tabl... | ```php
function getUserData($userID) {
$output = [];
// Retrieve statistical information
$query = 'SELECT logins, lastLogin FROM user_stats WHERE userID = :userID';
$stmt = $mysql->prepare($query);
$stmt->bindValue(':userID', $userID);
$stmt->execute();
if ($results = $stmt->fetchObject()) ... | magicoder | php |
You are tasked with implementing a timestamp encoding and decoding algorithm for a custom data format. The timestamp is represented as a combination of seconds and nanoseconds, and it needs to be encoded into a byte buffer using a specific format. Your task is to write a function that takes the timestamp as input and e... | ```rust
use byteorder::{BigEndian, ByteOrder};
#[derive(Debug)]
enum Error {
EndOfBuffer,
}
fn encode_timestamp(seconds: u64, nanoseconds: u32) -> Result<Vec<u8>, Error> {
let x = (u64::from(nanoseconds) << 34) | seconds as u64;
if x & 0xffff_ffff_0000_0000_u64 == 0 {
let mut buf = vec![0; 6];
... | magicoder | rust |
You are given a code snippet from a PHP function that is responsible for inserting data into a database table named `review`. The data to be inserted consists of multiple rows, each containing values for the columns `rate_id`, `proj_id`, `user_id`, `approved`, `created_at`, `comment`, and `rating_count`. The `run` func... | ```php
function generateInsertQuery(array $data): string {
$columns = implode(', ', array_keys($data[0])); // Get the column names
$values = [];
foreach ($data as $row) {
$rowValues = [];
foreach ($row as $value) {
if ($value === NULL) {
$rowValues[] = 'NULL';
... | magicoder | php |
You are tasked with implementing a custom stack data structure in C++. The stack should support the standard push, pop, and top operations, as well as an additional operation to retrieve the minimum element in constant time. You are not allowed to use any built-in stack or data structure from the standard library.
You... | ```cpp
#include <stack>
class MinStack {
private:
std::stack<int> dataStack;
std::stack<int> minStack;
public:
void push(int x) {
dataStack.push(x);
if (minStack.empty() || x <= minStack.top()) {
minStack.push(x);
}
}
void pop() {
if (dataStack.top() ==... | magicoder | cpp |
You are tasked with implementing a text formatting system that supports various text attributes such as underline, reverse, and custom RGB color. The system should take input commands and return the corresponding text formatting attributes.
You are given the following code snippet as a starting point for implementing ... | ```python
class ACC:
UNDERLINE = "underline"
NO_UNDERLINE = "no underline"
REVERSE = "reverse"
NO_REVERSE = "no reverse"
@staticmethod
def customrgb(r, g, b):
return f"custom RGB: ({r}, {g}, {b})"
def hex_to_rgb(hex_code):
hex_code = hex_code.lstrip('#')
return tuple(int(hex_co... | magicoder | python |
You are tasked with creating a script to automate the setup of a Linux desktop environment. The script should start several background processes for various utilities and services. Your task is to write a Bash script that accomplishes this.
Your script should start the following processes in the background:
1. Start t... | ```bash
#!/bin/bash
# Start picom compositor
picom -c -b &> /dev/null &
# Launch dunst notification daemon with custom configuration
dunst -conf $HOME/.config/dunst/dunstrc &> /dev/null &
# Start lxpolkit authentication agent
lxpolkit &> /dev/null &
# Initialize ibus-daemon for input method support
ibus-daemon -drx... | magicoder | shell |
You are tasked with creating a program that processes a file containing words and their associated boolean values. Each line in the file represents a word followed by a boolean value. However, the file may be corrupt, containing errors such as missing boolean values or empty files. Your task is to implement a function ... | ```rust
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
#[derive(Debug, Fail)]
pub enum MyError {
#[fail(display = "Corrupt words file! Line {} in \"{}\" doesn't have boolean prefix.", _1, _0)]
Corrupt(String, usize),
#[fail(display = "Corrupt words file! File {} is empty!", _0)]... | magicoder | rust |
You are tasked with implementing a loss function for a machine learning model. The loss function calculates the mean squared difference between the average pixel values of input images and their corresponding labels. The function takes a dictionary `batch` containing input images and their labels, and a target value `t... | ```python
import numpy as np
import pytest
class ShapeError(Exception):
pass
def loss(batch, target):
if not isinstance(batch, dict) or 'imgs' not in batch or 'labels' not in batch:
raise ValueError("Input batch should be a dictionary containing 'imgs' and 'labels' keys")
imgs = batch['imgs']
... | magicoder | python |
You are tasked with implementing a service for sending welcome emails to special members using Kafka and a SMTP server. The service needs to be integrated with a Dropwizard application and should be tested using JUnit rules for Kafka and SMTP server.
Given the provided code snippet, you are required to complete the im... | ```java
private static final Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private static final String INTEGRATION_YML = resourceFilePath("integration.yml");
private static final String KAFKA_HOST = "localhost";
private static final int KAFKA_PORT = 9092;
private static final String SPECIA... | magicoder | java |
You are tasked with implementing a custom autograd function in PyTorch for adaptive parameterization. The function should alternate between two different operations based on a boolean flag `is_first`. When `is_first` is `True`, the function should apply a custom operation `AP1` to the input tensor and update the gradie... | ```python
import torch
import torch.nn as nn
import torch.nn.functional as F
class AP1Function(torch.autograd.Function):
@staticmethod
def forward(ctx, input, grad):
ctx.save_for_backward(input, grad)
return input # Placeholder operation for AP1
@staticmethod
def backward(ctx, grad_ou... | magicoder | python |
You are tasked with creating a Python program to manage employee information. The program should prompt the user to input the employee's name, year of birth, and whether they have a work permit. Based on this information, the program should calculate the employee's age and, if applicable, prompt for additional informat... | ```python
def employee_info():
print('===== EMPLOYEE INFORMATION =====')
from datetime import datetime
employee = {}
employee['name'] = str(input('Name: '))
birth_year = int(input('Year of Birth: '))
employee['age'] = datetime.now().year - birth_year
ctps = int(input('Carteira de Trabalho (0... | magicoder | python |
You are tasked with creating a program to simulate a network stress test by opening multiple TCP connections and sending a packet to each connection. Your goal is to implement a function that opens a specified number of TCP connections to a given host and port, and then sends a packet of a specified size to each connec... | ```cpp
#include <iostream>
#include <vector>
#include <cstring>
#include <acl/CoreSocket.h>
void networkStressTest(const std::string& host, int port, size_t numSockets, size_t packetSize) {
std::cout << "Testing connecting " << numSockets << " sockets..." << std::endl;
std::vector<acl::CoreSocket::SOCKET> sock... | magicoder | cpp |
You are tasked with implementing a program to manipulate a hierarchical structure of tasks. Each task can have subtasks, forming a tree-like structure. Your program should support adding new tasks at any level, editing values of existing tasks, querying values of tasks, assigning responsible individuals to tasks, gener... | ```java
import java.util.HashMap;
import java.util.Map;
class TaskManager {
private Map<Integer, Map<String, String>> tasks;
public TaskManager() {
tasks = new HashMap<>();
}
public void addTask(int level, String taskName) {
tasks.computeIfAbsent(level, k -> new HashMap<>()).put(taskN... | magicoder | java |
You are tasked with implementing a function to return the data model for a controller in a software system. The data model is a structured representation of the data and its relationships that the controller manages. The function should return the data model in a suitable format.
You are given the following code snipp... | ```c
#include <stdio.h>
// Define the structure for representing the data model
typedef struct {
// Define the data model structure here
// Example:
// int someData;
// char someString[20];
// struct Relationship *relatedData;
// ...
} DataModel;
// Define the function to return the data model... | magicoder | c |
You are tasked with implementing a custom JSON serialization and memory size calculation for a simplified JSON-like data structure. The data structure consists of a boolean flag `is_awesome`, a list of heterogeneous elements `heterogeneous_list`, and a dynamic key-value pair with the key being a dynamic key and the val... | ```rust
use serde_json; // Assuming the use of serde_json for JSON serialization
fn main() {
let json_val = serde_json::json!({
"is_awesome": true,
"heterogeneous_list": [1, "two", 3.0],
"dynamic_key": "world"
});
println!("json: {}", json_val.to_string()); // Serialize the data st... | magicoder | rust |
You are tasked with implementing a program that utilizes a computer vision detector to identify and track objects within a given bounding box. The `bbox` module provides functionality for creating and manipulating bounding boxes, while the `detector` module contains the `ComputerVisionDetector` class for object detecti... | ```python
from typing import List, Dict
from bbox import BoundingBox
from detector import ComputerVisionDetector
def track_objects(bounding_boxes: List[BoundingBox]) -> Dict[BoundingBox, str]:
detector = ComputerVisionDetector() # Instantiate the ComputerVisionDetector
results = {}
for box in bounding_box... | magicoder | python |
You are tasked with implementing a session management system for a web application. The session management system should be able to track and modify session data for each user. In this scenario, the code snippet provided is a part of a Python Django view function that handles session modification. The `request.session.... | ```python
class SessionManager:
def __init__(self):
self.session_data = {}
self.modified = False
def set_session(self, key, value):
self.session_data[key] = value
self.modified = True
def get_session(self, key):
return self.session_data.get(key, None)
def is_mo... | magicoder | python |
You are tasked with implementing a simple Java program to simulate a lottery game. The program should generate a set of random numbers as the winning lottery numbers and allow players to enter their chosen numbers. The program should then compare the player's numbers with the winning numbers and determine the prize bas... | ```java
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
class LotteryGame {
private int[] winningNumbers;
public void generateWinningNumbers() {
winningNumbers = new int[6];
Random random = new Random();
for (int i = 0; i < 6; i++) {
int num;
... | magicoder | java |
You are tasked with implementing a Python function to communicate with a LoRa module over a serial connection. The function should retrieve the current address of the LoRa module and return it as a string. The LoRa module communicates using a specific protocol, and the address retrieval process involves sending a comma... | ```python
def get_current_address(serial_connection, variables):
# Execute the command to retrieve the address
serial_connection.execute_command(serial_connection.str_to_bytes(variables.GET_ADDR))
# Get the response from the LoRa module
addr = serial_connection.response_q.get(variables.COMMAND_VERI... | magicoder | python |
You are tasked with creating a Python script to automate the setup of molecular dynamics simulations using the GROMACS software suite. The script will take command-line arguments to specify the system, simulation step, properties file, input structure PDB file, output GRO file, and output topology ZIP file. The propert... | ```python
import sys
from settings import YamlReader
from simulation import Pdb2gmx
def main():
if len(sys.argv) != 7:
print("Usage: python setup_simulation.py <system> <step> <properties_file> <input_structure_pdb_path> <output_gro_path> <output_top_zip_path>")
return
system = sys.argv[1]
... | magicoder | python |
You are tasked with implementing a data structure to efficiently store and query a set of strings. The data structure should support the following operations:
1. `add(string)`: Add the given string to the data structure.
2. `query(string)`: Check if the given string is present in the data structure.
You need to imple... | ```python
class Trie:
CHAR_START = ord('a')
def __init__(self):
self.n = 0
self.s = []
self.len = [0] * 1000
self.fail = [0] * 1000
self.node = [[0] * 26 for _ in range(1000)]
def new_node(self, length):
self.len[self.n] = length
self.fail[self.n] = ... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.