query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a custom convolutional neural network (CNN) for image classification using PyTorch. The provided code snippet initializes the CNN model, moves it to the GPU if available, sets up the optimizer and loss function, and includes a forward pass through the model. Your task is to complete the... | ```python
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Conv2d(3, 16, 3)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(16... | magicoder | python |
You are tasked with creating a SwiftUI view that displays a list of articles along with their images. The `ArticlesViewModel` class is responsible for managing the articles and fetching their images. The `ArticleRow` is a custom view for displaying individual articles. When an article is about to appear in the list, th... | ```swift
import SwiftUI
struct Article {
let id: Int
let title: String
var image: UIImage?
}
class ArticlesViewModel: ObservableObject {
@Published var articles: [Article] = []
func fetchImage(for article: Article) {
guard let index = articles.firstIndex(where: { $0.id == article.id }) el... | magicoder | swift |
You are tasked with creating a script to automate the tagging and building of Docker images for a software project. The script should utilize the current date to generate a unique tag for the Docker image and then execute the necessary Docker commands to build and tag the image.
Your task is to write a shell script th... | ```bash
#!/bin/bash
set -x # Enable command tracing
docker_tag="chronograf-$(date +%Y%m%d)" # Define docker_tag with current date
# Build Docker image and tag it with docker_tag
docker build --rm=false -f etc/Dockerfile_build -t builder:$docker_tag .
# Tag the built Docker image with a repository on Quay.io using... | magicoder | shell |
You are tasked with implementing a performance profiling tool for a Fibonacci function. The tool should measure the execution time of the Fibonacci function and display it using a specific library. Your task is to create a Rust program that utilizes the `microprofile` library to profile the execution time of a recursiv... | ```rust
use std::time::Instant;
// Define the Test trait
trait Test {
fn fibonacci(&self, n: u32) -> u32;
}
// Implement the Test trait for Microprofile
struct Microprofile {}
impl Test for Microprofile {
fn fibonacci(&self, n: u32) -> u32 {
microprofile::scope!("foo", "fibonacci"); // Start profiling... | magicoder | rust |
You are tasked with implementing a dynamic library loading mechanism in C++ to load and utilize functions from an external DLL. The code snippet provided demonstrates the loading of a DLL and the retrieval of specific function pointers from it. Your task is to complete the implementation by creating a class that encaps... | ```cpp
#include <iostream>
#include <windows.h>
// Define the function pointer types
typedef int (*StartHookProc)();
typedef int (*StopHookProc)();
class DynamicLibraryLoader {
private:
HMODULE dll_;
public:
DynamicLibraryLoader(const char* dllPath) {
dll_ = LoadLibrary(dllPath);
if (dll_ == ... | magicoder | cpp |
You are tasked with implementing a simple object container class in Python. The class should have the following methods:
1. `addObject(self, name, object_:object)`: This method should add an object to the container with the given name.
2. `hasObject(self, name)`: This method should return `True` if an object with the... | ```python
class ObjectContainer:
def __init__(self):
self._container = {}
def addObject(self, name, object_: object):
self._container[name] = object_
def hasObject(self, name):
return name in self._container
def getObject(self, name) -> object:
return self._container.g... | magicoder | python |
You are tasked with implementing a function to parse and process transaction data in a blockchain system. The given code snippet is part of a larger function that constructs a string representation of a transaction. The `transaction` object contains information about the transaction, including `extraData` and an array ... | ```javascript
function parseTransaction(transaction) {
let str = "Transaction:\n";
if (transaction.extraData) {
str += `extraData ${transaction.extraData.toString("hex")}\n`;
}
transaction.inputs.forEach(({ prevout, script, sequence }, i) => {
str += `input ${i}:\n`;
str += `prevout ${prevout.toStri... | magicoder | javascript |
You are tasked with implementing a function that processes a list of dictionaries representing data points and generates a plot based on the data. Each dictionary in the list contains keys "x" and "y" representing the x and y coordinates of a data point. The function should allow for customization of the plot appearanc... | ```python
import matplotlib.pyplot as plt
def generate_plot(data_points, title, x_label, y_label, show_plot=False, output_path=None):
x_values = [point["x"] for point in data_points]
y_values = [point["y"] for point in data_points]
plt.scatter(x_values, y_values)
plt.title(title)
plt.xlabel(x_labe... | magicoder | python |
You are tasked with creating a simple movie API using Python's Flask framework. The API should allow users to perform basic CRUD (Create, Read, Update, Delete) operations on a collection of movies. Each movie will have attributes such as title, director, genre, and release year. Your task is to implement the endpoints ... | ```python
from flask import Flask, jsonify, request
app = Flask("movies_api")
movies = []
@app.route('/movies', methods=['GET'])
def get_movies():
return jsonify(movies)
@app.route('/movies', methods=['POST'])
def add_movie():
new_movie = request.json
movies.append(new_movie)
return jsonify({"message... | magicoder | python |
You are tasked with implementing a simplified version of a global controller for a stitching application. The global controller is responsible for managing the creation and deletion of individual stitching controllers for different devices. The provided code snippet shows a part of the implementation for the global con... | ```cpp
class StitcherController {
// Class representing the stitching controller
};
class GlobalControllerImpl {
public:
StitcherController* getController() const {
return controller;
}
void createController(int device) {
// Create a new stitching controller for the specified device
... | magicoder | cpp |
You are tasked with implementing a function to parse and extract information from a custom log format used in a Vep-Container system. The log format consists of two different log lines, each containing specific information about the Vep-Container.
The first log line contains information about the Vep-Container identif... | ```c
#include <stdio.h>
#include <string.h>
typedef struct {
char prefix[20];
char identifier[50];
char validity[8];
unsigned int version;
char type[20];
int typeValue;
unsigned char flags;
unsigned int headerSize;
unsigned int dataSize;
unsigned short crc;
unsigned int numP... | magicoder | c |
You are tasked with implementing a simplified version of a command-line text editor's key binding functionality. The given code snippet represents a set of key bindings for a command-line text editor, where certain key combinations are associated with specific actions. The key bindings are represented using the `bindke... | ```python
class KeyBinding:
def __init__(self):
self.bindings = {
"^A": "beginning-of-line",
"^E": "end-of-line",
"^B": "vi-backward-word",
"^F": "vi-forward-word",
"^W": "vi-backward-kill-word",
"^[": "vi-cmd-mode"
}
def p... | magicoder | python |
You are tasked with creating a program that manages the generation and storage of PDF files. The given code snippet is a part of a larger program that creates a PDF document using a library such as PDF-lib in a Node.js environment. The code sets various properties for the PDF, such as the height, font size, font type, ... | ```javascript
const { PDFDocument, rgb } = require('pdf-lib');
const fs = require('fs');
const path = require('path');
const { v4: uuidv4 } = require('uuid');
async function generateAndSavePDF(height, fontSize, fontType, color, filePath) {
const pdfDoc = await PDFDocument.create();
const timesRomanFont = await pdf... | magicoder | javascript |
You are tasked with creating a program that analyzes a given text to identify and count the occurrences of specific words. Your program should be able to handle large text inputs efficiently.
Write a function `countWordOccurrences(text: str, words: List[str]) -> Dict[str, int]` that takes in a string `text` representi... | ```python
from typing import List, Dict
def countWordOccurrences(text: str, words: List[str]) -> Dict[str, int]:
word_counts = {}
text = text.lower() # Convert the text to lowercase for case-insensitive comparison
words = [word.lower() for word in words] # Convert the words to lowercase for case-insensit... | magicoder | python |
You are tasked with creating a program that analyzes a given text file to count the occurrences of specific words. The program should read the text file, tokenize the words, and then count the occurrences of each word. Additionally, the program should ignore any words that are included in a provided list of common stop... | ```python
from typing import List, Dict
import re
def count_word_occurrences(file_path: str, stop_words: List[str]) -> Dict[str, int]:
word_counts = {}
with open(file_path, 'r') as file:
text = file.read()
words = re.findall(r'\b\w+\b', text)
for word in words:
word = word.l... | magicoder | python |
You are tasked with creating a Node.js function that handles email template compilation and sends emails. The function should read a template file, compile it using Handlebars, and then send the compiled email using a mailing service. However, the function should also check if mailing is enabled before proceeding with ... | ```javascript
const path = require('path');
const util = require('util');
const readFile = util.promisify(require('fs').readFile);
async function compileAndSendEmail(options) {
try {
if (this._mailingEnabled === false) {
logger.debug('Mailing disabled', { data: options });
return; // Mailing is disab... | magicoder | javascript |
You are tasked with implementing a Python module that simulates a simple banking system. The module should provide functionality for creating bank accounts, depositing and withdrawing funds, and transferring funds between accounts. Additionally, the module should support the retrieval of account balances and transactio... | ```python
from typing import List, Union
from datetime import datetime
class BankAccount:
def __init__(self, account_number: int, name: str, initial_balance: float):
self.account_number = account_number
self.name = name
self.balance = initial_balance
self.transaction_history = []
... | magicoder | python |
You are tasked with implementing a Python script to automate the process of obtaining OAuth credentials for accessing Google Calendar API. The script should guide the user through the OAuth authorization flow and update a file with the obtained credentials. Your task is to write a Python function that accomplishes this... | ```python
import os
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
import json
def get_google_calendar_credentials():
# Load client secret file
client_secret_file = 'client_secret.json'
if not os.pa... | magicoder | python |
You are tasked with implementing a file compression algorithm that takes a directory and compresses its contents into a zip file. You are given a code snippet that uses a stack-based approach to traverse the directory and add its contents to the zip file. Your task is to complete the implementation of the file compress... | ```java
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Stack;
public class FileCompression {
... | magicoder | java |
You are tasked with implementing a parallelized matrix operation using OpenMP. Given a matrix `in` of dimensions `rows x cols`, and two arrays `alpha` and `beta` of length `cols`, you need to perform the following operation in parallel:
```plaintext
out[i][j] = alpha[j] * in[i][j] + (beta ? beta[j] : 0)
```
Where `ou... | ```cpp
#include <vector>
#include <omp.h>
std::vector<std::vector<float>> parallelMatrixOperation(const std::vector<std::vector<float>>& in, const std::vector<float>& alpha, const std::vector<float>& beta, int rows, int cols) {
std::vector<std::vector<float>> out(rows, std::vector<float>(cols, 0.0f));
#pragma... | magicoder | cpp |
You are tasked with implementing a module that combines functionality from two different libraries, `tree_storage` and `merkle_tree`. The code snippet provided imports all items from the `abc` module of both libraries using the `pub use` statement. Your task is to create a new module that utilizes the functionalities i... | ```rust
mod merkle_operations {
use tree_storage::abc::*;
use merkle_tree::abc::*;
pub fn calculate_merkle_hash(data: &[&str]) -> Result<String, String> {
// Create a new tree for storing the data
let mut tree = Tree::new();
// Store the data items in the tree
for item in d... | magicoder | rust |
You are tasked with implementing a command-line tool for parsing and processing WKT (Well-Known Text) geometries. WKT is a text markup language for representing vector geometry objects. The tool should support listing all available rules for parsing WKT and providing trace information during the parsing process.
Your ... | ```python
import argparse
import sys
import re
class ListRules(argparse.Action):
def __call__(self, parser, namespace, values, option_string):
print('Rules:')
for r in WktParser.rule_list():
print(r)
print()
sys.exit(0)
class ParseWKT(argparse.Action):
def __call__(... | magicoder | python |
You are tasked with automating the deployment of various Kubernetes resources using a script. The script provided below contains a series of `kubectl` commands and comments. Your goal is to write a Python script that parses this input and extracts the Kubernetes resource names and types being created or applied. Additi... | ```python
import re
def parse_kubectl_script(script):
resources = []
dashboard_url = ""
secret_name = ""
for line in script.split('\n'):
if line.startswith('#'):
continue
if line.startswith('kubectl create -f') or line.startswith('kubectl apply -f'):
resource_ty... | magicoder | python |
You are tasked with implementing a CUDA-accelerated matrix operation using the cudamat library. The goal is to perform a specific computation on two matrices and compare the results to ensure correctness.
You are given the following code snippet as a starting point:
```python
m = 256
n = 128
c_targets = np.array(np.r... | ```python
import numpy as np
import pycuda.autoinit
import pycuda.gpuarray as gpuarray
import skcuda.linalg as linalg
linalg.init()
def mult_by_sigmoid_deriv(g_targets, g_acts):
# Perform element-wise multiplication of g_targets and g_acts
g_acts.mult(g_targets)
# Apply the sigmoid derivative to g_acts
... | magicoder | python |
You are tasked with implementing a function to detect whether a given ciphertext has been encrypted using the Electronic Codebook (ECB) mode in Advanced Encryption Standard (AES) encryption. ECB mode is known for its vulnerability to certain types of attacks due to its deterministic nature.
You are provided with the f... | ```python
def detect_aes_ecb(ciphertext):
blocks = [ciphertext[i:i+16] for i in range(0, len(ciphertext), 16)]
unique_blocks = set(blocks)
if len(blocks) != len(unique_blocks):
return True # If there are duplicate blocks, it's likely ECB mode
else:
return False # Otherwise, it's likely... | magicoder | python |
You are tasked with implementing a method to concatenate two byte arrays. The method should take two byte arrays as input and return a new byte array containing the concatenated elements of the input arrays. If either of the input arrays is null or empty, the method should return a copy of the non-null or non-empty arr... | ```java
public class ByteArrayConcatenator {
public static byte[] concat(byte[] arr1, int start1, int length1, byte[] arr2, int start2, int length2) {
if (arr1 == null || length1 == 0) {
return (arr2 != null) ? arr2.clone() : new byte[0];
}
if (arr2 == null || length2 == 0) {
... | magicoder | java |
You are tasked with creating a Python function that interacts with a REST API to perform a batch import operation. The function will take in various parameters and make a POST request to the API endpoint. Your task is to implement the function according to the given specifications.
Function Signature:
```python
def pe... | ```python
import requests
def perform_batch_import(options, accessToken, files):
parameters = {
'itemType': options['itemType'],
'merge': options['merge'],
'headerRow': options['headerRow']
}
resp = requests.post(
f"{options['hostUrl']}/ls/api/batch/import".format(options['c... | magicoder | python |
You are tasked with creating a URL routing system for a web application using Python's Django framework. Your goal is to define URL patterns that map specific URLs to corresponding views.
Given the code snippet provided, you need to extend the URL routing configuration to include a new URL pattern for a "referral det... | To achieve the new URL pattern for the "referral detail" view, you can extend the existing URL routing configuration in the Django application's `urls.py` file. Here's the code to accomplish this:
```python
from django.conf.urls import url
from . import referrals
urlpatterns = [
url(r'^referrals/$', referrals.Ref... | magicoder | python |
You are tasked with implementing a JavaScript module bundler that can handle the export and import statements commonly used in ES6 modules. Your module bundler should be able to resolve and bundle the dependencies of a given entry module.
You are given a code snippet representing a set of named exports from different ... | ```javascript
function bundleModules(namedExports) {
// Resolve and bundle the dependencies of the named exports
let bundledCode = '// Bundled code\n';
for (const exportName in namedExports) {
const moduleName = namedExports[exportName];
bundledCode += `const ${exportName} = require('./${moduleName}');\n`... | magicoder | javascript |
You are tasked with creating a program that manages a library of PHP books. The program should allow users to add new books to the library and retrieve information about the books. Each book has a title, author, and category. The program should also provide the functionality to search for books by category and display ... | ```php
class PHPBook {
private $title;
private $author;
private $category;
public function __construct($title, $author, $category) {
$this->title = $title;
$this->author = $author;
$this->category = $category;
}
public function getTitle() {
return $this->title;
... | magicoder | php |
You are tasked with implementing a custom logging system in C++. The system should allow for the output of various types of events to a specified output stream. Each event will have a specific value associated with it, and the logging system should be able to handle different types of events.
Your task is to create a ... | ```cpp
#include <iostream>
#include <fstream>
// Define the Event class for custom event types
class Event {
// Define the properties and methods of the Event class
};
class Logger {
public:
// Overload for logging integer events
void log(std::ostream& os, int event) {
os << "Integer event: " << e... | magicoder | cpp |
You are tasked with creating a custom validation function for a Flask web application. The function should validate a file upload form field to ensure that the file extension matches the allowed image extensions specified in the Flask application configuration. If the file extension is not allowed, the validation funct... | ```python
from werkzeug.utils import secure_filename
from wtforms.validators import ValidationError
import flask
def validator(form, field):
allowed_extensions = flask.current_app.config.get('IMAGE_EXTENSIONS', [])
filename = secure_filename(field.data.filename)
if '.' in filename:
file_extension =... | magicoder | python |
You are tasked with implementing a ZlibStreamCompressor class that can compress an input IOBuf chain using the Zlib compression algorithm. The class provides a method, `compress`, which can be called multiple times to compress the input data incrementally. After the final call to `compress`, the Zlib stream must be syn... | ```cpp
#include <zlib.h>
#include <folly/io/IOBuf.h>
#include <folly/io/Cursor.h>
class ZlibStreamCompressor {
public:
ZlibStreamCompressor() {
// Initialize Zlib stream
memset(&stream_, 0, sizeof(stream_));
deflateInit(&stream_, Z_DEFAULT_COMPRESSION);
}
~ZlibStreamCompressor() {
// Clean up Zl... | magicoder | cpp |
You are tasked with implementing a custom convolutional neural network (CNN) layer in Python using the PyTorch library. Your goal is to create a class that defines a specific convolutional layer followed by a max pooling operation. The convolutional layer should have a 7x7 kernel size, and the max pooling operation sho... | ```python
import torch
import torch.nn as nn
import torch.nn.functional as F
class Conv7x7(nn.Module):
def __init__(self, in_channels, out_channels, norm=True, act=True):
super(Conv7x7, self).__init__()
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=7)
self.norm = norm
... | magicoder | python |
You are tasked with creating a program that simulates a simple 2D bouncing ball animation using the OpenGL library. The code snippet provided initializes the GLFW window with a forward compatibility hint for OpenGL.
Your task is to complete the program by implementing the ball animation using OpenGL. The ball should m... | ```c
#include <GLFW/glfw3.h>
#include <OpenGL/gl3.h>
#include <iostream>
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
glfwSetWindowShouldClose(window, GLFW_TRUE);
}
}
int main() {
if (!glfwInit()) {
... | magicoder | c |
You are tasked with implementing a C++ class that manages callable objects and delegates. The class, named `DelegateManager`, should provide functionality to store and execute callable objects and delegates of various types.
Your task is to complete the implementation of the `DelegateManager` class by adding the follo... | ```cpp
#include <functional>
// Define the types used for the delegate and callable objects
using Callable = std::function<void()>;
template <typename ReturnType, typename... Args>
using DelegateType = std::function<ReturnType(Args...)>;
class DelegateManager
{
public:
// Store a callable object of type std::func... | magicoder | cpp |
You are tasked with implementing a class that simulates the behavior of a service application. The class, `TestAppService`, is responsible for managing the execution of a work function and handling any exceptions that may occur during its execution. The class has the following key methods and properties:
- `Start()`: ... | ```csharp
using System;
public class TestAppService
{
public delegate void WorkFunction(Action handle);
public delegate void LogFunction(Exception ex);
public event EventHandler StartedEvent;
public WorkFunction WorkFunc { get; set; }
public LogFunction LogFunc { get; set; }
public void Start... | magicoder | csharp |
You are tasked with creating a utility function to extract unique package names from a given list of import statements in a JavaScript/TypeScript file. The import statements follow the ES6 module syntax and may include named imports, default imports, and namespace imports.
You need to implement a function `extractPack... | ```javascript
function extractPackageNames(importStatements) {
const packageNames = importStatements.map(statement => {
const matches = statement.match(/from\s+["']([^"']+)["']/);
return matches ? matches[1] : null;
});
return Array.from(new Set(packageNames.filter(Boolean)));
}
// Test the function
con... | magicoder | javascript |
You are tasked with creating a Python function that generates an EPUB (Electronic Publication) file from a list of content. EPUB is a standard e-book format that can be read on various devices. Your function should take in a list of content, where each item represents a chapter or section of the e-book, and produce a v... | ```python
from ebooklib import epub
from typing import List
def generate_epub(content: List[str], title: str, author: str, output_file: str) -> None:
book = epub.EpubBook()
# Set metadata
book.set_identifier('id123456')
book.set_title(title)
book.set_language('en')
book.add_author(author)
... | magicoder | python |
You are tasked with creating a C# program to manage communication with a serial port. The program should include a class for managing the serial port connection and a separate thread for reading data from the port. Your task is to implement the missing parts of the program to achieve this functionality.
You are provid... | ```csharp
using System;
using System.IO.Ports;
using System.Threading;
public class SerialPortManager
{
static SerialPort _serialPort;
static Thread _readThread;
static bool _continueReading;
public Settings settings { get; private set; }
public SerialPortManager(Settings portSettings)
{
... | magicoder | csharp |
You are tasked with implementing a simplified version of a DOM (Document Object Model) interface for handling XML documents. The provided code snippet shows a partial implementation of a class that represents an element in an XML document. Your task is to complete the implementation by adding the missing method `getAtt... | ```java
@Override
public Attr getAttributeNodeNS(String namespaceURI, String localName) {
if (attributes != null) {
for (Attr attr : attributes.values()) {
if (attr.getNamespaceURI().equals(namespaceURI) && attr.getLocalName().equals(localName)) {
return attr;
}
... | magicoder | java |
You are tasked with implementing a function to parse a listen address into a specific format. The listen address is in the form of `<ip_address>:<port>`, and the function should convert it into a string of the format `'tcp:<port>:interface=<ip_address>'`. The function should handle both IPv4 and IPv6 addresses.
Write ... | ```python
import re
def parse_listen_addr(listen_addr):
ip_pattern = r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|(\[?[0-9a-fA-F:]+\]?)'
port_pattern = r'(\d{1,5})'
pattern = re.compile(f'({ip_pattern}):({port_pattern})')
match = pattern.match(listen_addr)
if match:
ip = match.group(1) if match.... | magicoder | python |
You are tasked with implementing a memory configuration class in Python. The class should allow for the configuration of various memory parameters such as size, speed, and type. Additionally, the class should provide methods for retrieving and updating these configuration parameters.
Your task is to complete the imple... | ```python
class MemoryConfig:
def __init__(self, size, speed, memory_type):
self.size = size
self.speed = speed
self.memory_type = memory_type
def get_size(self):
return self.size
def set_size(self, size):
self.size = size
def get_speed(self):
return se... | magicoder | python |
You are tasked with implementing a simple observer pattern in C++. The observer pattern is a behavioral design pattern that defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. In this problem, you will create a simplified ver... | ```cpp
#include <iostream>
#include <vector>
class Tweak; // Forward declaration
class NodeWindow {
public:
void addObserver(Tweak* observer) {
observers.push_back(observer);
}
void removeObserver(Tweak* observer) {
observers.erase(std::remove(observers.begin(), observers.end(), observer... | magicoder | cpp |
You are tasked with implementing a simplified version of the Schnorr signature algorithm. The Schnorr signature scheme is a digital signature algorithm known for its simplicity and security. In this problem, you will focus on the key generation and signature generation steps of the algorithm.
The Schnorr signature alg... | ```rust
use num_bigint::BigUint;
use num_traits::{One, Zero};
use sha2::{Digest, Sha256};
fn key_generation(p: &BigUint, g: &BigUint, x: &BigUint) -> BigUint {
g.modpow(x, p)
}
fn signature_generation(p: &BigUint, g: &BigUint, x: &BigUint, m: &str) -> (BigUint, BigUint) {
let k = BigUint::from(12345u32); // R... | magicoder | rust |
You are tasked with creating a Python class that simulates a job scheduling system for a computing cluster. The system should be able to allocate a variable number of workers to perform calculations and manage the distribution of tasks across these workers. The class should also be capable of tracking the status of eac... | ```python
import heapq
class JobScheduler:
def __init__(self, minimum_number_of_workers, maximum_number_of_workers):
self.min_workers = minimum_number_of_workers
self.max_workers = maximum_number_of_workers
self.workers = []
self.tasks = []
self.completed_tasks = set()
... | magicoder | python |
You are tasked with implementing a Python generator function that processes different types of work units and yields record envelopes. The work units can be of three types: `DataWorkUnit`, `MetadataWorkUnit`, and `UsageStatsWorkUnit`. Each work unit type has specific validation and record envelope creation logic.
Your... | ```python
# Sample usage of the process_workunit function
data_workunit = DataWorkUnit(1, "sample data")
metadata_workunit = MetadataWorkUnit(2, "sample metadata")
usage_stats_workunit = UsageStatsWorkUnit(3, "sample usage stats")
workunits = [data_workunit, metadata_workunit, usage_stats_workunit]
for record_envelop... | magicoder | python |
You are tasked with creating a Python script to automate the setup of a Jupyter Notebook server on a remote machine. The script should generate a Jupyter Notebook configuration file, set a password for the server, and then start the Jupyter Lab server with specific configurations.
Your script should perform the follow... | ```python
import subprocess
# Step 1: Generate Jupyter Notebook configuration file
try:
subprocess.run(["jupyter", "notebook", "--generate-config"], check=True)
print("Jupyter Notebook configuration file generated successfully.")
except subprocess.CalledProcessError as e:
print(f"Error generating Jupyter N... | magicoder | python |
You are tasked with implementing a custom security system for a web application. The system should allow for the definition of access control rules based on user roles and permissions. To achieve this, you need to create a class that manages the configuration attributes and provides a way to check if a given authentica... | ```java
import java.util.ArrayList;
import java.util.List;
public class CustomSecurityManager implements ConfigAttributeDefinition {
private List<ConfigAttribute> configAttributes;
public CustomSecurityManager() {
this.configAttributes = new ArrayList<>();
}
public void addConfigAttribute(Con... | magicoder | java |
You are tasked with implementing a program that simulates a simple banking system. The program should allow users to create accounts, deposit and withdraw funds, and check their balance. Each account should have a unique account number, and the program should support multiple accounts. The program should also be able t... | ```python
class Account:
def __init__(self, account_number: int):
self.account_number = account_number
self.balance = 0
def deposit(self, amount: float):
self.balance += amount
def withdraw(self, amount: float):
if self.balance >= amount:
self.balance -= amount
... | magicoder | python |
You are tasked with implementing a parser for a simplified programming language syntax using the provided code snippet as a reference. The snippet defines functions and their parameters using a custom syntax. Your goal is to write a Python function that can parse function declarations and their parameters based on the ... | ```python
import re
def parse_function_declaration(code):
pattern = r'function\s+(\w+)\s*\(([^)]*)\)'
match = re.match(pattern, code)
if match:
function_name = match.group(1)
parameters = [param.strip() for param in match.group(2).split(',') if param.strip()]
return {"function_name"... | magicoder | python |
You are tasked with creating a function to process reminders and generate HTML content for display. The function should take an array of reminder objects as input and produce a formatted HTML list of reminders. Each reminder should be displayed as a list item with details such as user name, date, note, and next follow-... | ```php
function generateReminderList(array $reminders): string {
$details = "<ul class='media-list media-list-divider m-0'>";
foreach ($reminders as $row) {
$details .= "<li class='media followup_details'>
<div class='media-body'>
<div class='media-hea... | magicoder | php |
You are working on a project that involves serializing and deserializing data in a Python application using Django and Django REST framework. You need to create a serializer for a model called `Term` and its related model `Meaning`. The `Term` model has fields `id`, `slug`, `pali`, `wordClass`, `gender`, `def_in_PLS_di... | ```python
from rest_framework import serializers
class MeaningSerializer(serializers.ModelSerializer):
class Meta:
model = Meaning
fields = ('id', 'est', 'eng', 'root', 'rootLang', 'rootDescription', 'expl', 'further', 'example_set')
class SingleTermSerializer(serializers.ModelSerializer):
mea... | magicoder | python |
You are tasked with creating a web application that allows users to update their profile information, including their profile image. The backend of the application is written in PHP using the Laravel framework. The code snippet provided is a part of the update functionality for a user's profile. The `$data['image']` va... | ```php
class UserController extends Controller
{
public function updateProfile(Request $request, $id)
{
// Validate the incoming request data
$validatedData = $request->validate([
'name' => 'required|string',
'email' => 'required|email',
'image' => 'image|mime... | magicoder | php |
You are tasked with implementing a parser for a simple domain-specific language (DSL) using the provided code snippet as a reference. The DSL consists of blocks, stanzas, and statements, each with specific syntax and semantics.
A block is defined by a begin block token (BeginBlock), followed by multiple statements (St... | ```python
from parsy import string, regex, seq, alt, opt, eof, success
# Define the tokens and parsers
BeginBlock = string("BEGIN")
EndBlock = string("END")
Name = regex(r'[a-zA-Z_][a-zA-Z0-9_]*')
Value = regex(r'[a-zA-Z0-9_]+')
Comment = string("#")
WS = regex(r'\s*')
# Define the parsers for the DSL
Block = seq(Beg... | magicoder | python |
You are tasked with implementing a video player class in Python that simulates the playback of a video. The class should support functionalities such as starting, pausing, and seeking through the video frames. Your task is to implement the `VideoPlayer` class with the following methods:
1. `__init__(self, speed)`: Ini... | ```python
from time import time
from select import select
class VideoPlayer:
def __init__(self, speed):
self.speed = speed
self.start = 0
self.prev_ts = 0
self.position = 0
self.pause = False
self.stdin = 0 # Replace with actual file descriptor for standard input
... | magicoder | python |
You are tasked with implementing a custom router for a Django REST framework application. The router should handle the registration of viewsets for different URL patterns. The provided code snippet demonstrates the registration of two viewsets with specific URL patterns using the `SimpleRouter` class.
Your task is to ... | ```python
from rest_framework.routers import SimpleRouter, Route
class CustomRouter(SimpleRouter):
def __init__(self):
super().__init__()
def register_nested(self, prefix, viewset, base_name, parent_field):
routes = [
Route(
url=fr'^{{prefix}}/(?P<{parent_field}>[^/... | magicoder | python |
You are working on a machine learning project and need to implement a data preprocessing pipeline for image data. The pipeline involves calculating the mean values of the image channels, splitting the data into training and testing sets, and specifying the path to the data. You are given a code snippet that initializes... | ```python
import os
import numpy as np
from sklearn.model_selection import train_test_split
def preprocess_image_data(channel_means, train_test_split, data_path):
# Load image data and labels from the specified path
# Assume data is loaded into X and y variables
# Normalize the image data by subtracti... | magicoder | python |
You are tasked with simulating a simple GPIO (General Purpose Input/Output) interface for a microcontroller. The provided code snippet is a part of a Python program that interacts with a GPIO interface. The `GPIO_seq_point` function is used to create a GPIO sequence point, which is then written to a FIFO (First In, Fir... | ```python
class GPIOSequencePoint:
def __init__(self, address, time, output):
self.address = address
self.time = time
self.output = output
def GPIO_seq_point(address, time, output):
return GPIOSequencePoint(address, time, output)
def write_point(fifo, point):
fifo.append(point)
de... | magicoder | python |
You are tasked with implementing a logistic regression model for a binary classification problem. The logistic regression model is a fundamental algorithm in machine learning used for binary classification tasks. In this problem, you will need to create a Python class that represents a logistic regression model and imp... | ```python
import numpy as np
# Sample usage of the LogisticRegression class
# Assume X_train, y_train, X_test are available
# Create an instance of LogisticRegression
model = LogisticRegression(learning_rate=0.01, num_iterations=1000)
# Train the model
model.fit(X_train, y_train)
# Make predictions
predictions = mo... | magicoder | python |
You are tasked with implementing a fraud detection system for a financial institution. The system needs to process a large amount of transaction data and identify potentially fraudulent activities. To achieve this, you need to develop a program that performs data processing and analysis to detect any suspicious pattern... | ```python
def detect_fraudulent_transactions(transactions):
flagged_transactions = []
for transaction in transactions:
if transaction["amount"] > 10000.0:
flagged_transactions.append(transaction)
elif is_high_frequency(transactions, transaction["account"], transaction["timestamp"]):
... | magicoder | python |
You are tasked with creating a SwiftUI application that simulates a simple audio control interface. The application should have a toggle switch to control the state of the microphone output to the headphones. Additionally, there should be a text message providing instructions on how to change the output device from hea... | ```swift
import SwiftUI
struct AudioControlView: View {
@StateObject var viewModel = AudioControlViewModel()
var body: some View {
NavigationView {
Form {
Section {
Toggle(isOn: $viewModel.isRunning) {
Text("Microphone to headphon... | magicoder | swift |
You are tasked with implementing a Python function that calculates the number of occurrences of a specific word in a given text. The function should be able to handle both case-sensitive and case-insensitive searches.
You are given the following code snippet as a starting point:
```python
def word_counter(text, word, ... | ```python
def word_counter(text, word, case_sensitive=True):
if not text or not word:
return 0
if case_sensitive:
return text.split().count(word)
else:
return text.lower().split().count(word.lower())
```
The `word_counter` function first checks for empty input text or word and retu... | magicoder | python |
You are tasked with creating a Python class that manages the downloading of booking data from a remote server. The class should be able to handle authentication, retrieve the data, and store it locally. Additionally, the class should be able to handle potential errors that may occur during the download process.
Your t... | ```python
class AuthenticationError(Exception):
pass
class NetworkError(Exception):
pass
class ServerUnavailableError(Exception):
pass
class BookingDownload:
def __init__(self):
self.authenticated = False
def authenticate(self, username, password):
# Simulate authentication proce... | magicoder | python |
You are tasked with creating a function that processes a configuration file for a Container project. The function should handle parsing the configuration file, validating its contents, and returning a specific error message if the file is invalid.
The configuration file is expected to be in JSON format and may contain... | ```javascript
const parseJsonFromStringOrFile = async (jsonString) => {
try {
return JSON.parse(jsonString);
} catch (e) {
throw new Error('Invalid JSON format');
}
};
const processConfigFile = async (containerPath, extra) => {
if (!containerPath.startsWith('/Container/')) {
throw new Error(`Make s... | magicoder | javascript |
You are tasked with implementing a simplified version of a task scheduler in a multi-threaded environment. The task scheduler is responsible for executing a series of tasks concurrently. Each task is represented by an object with a `run` method that performs the task's functionality. Your goal is to design a task sched... | ```java
import java.util.List;
public class Task {
public void run() {
// Perform the task's functionality
}
}
public class TaskScheduler {
public void schedule(List<Task> tasks) {
for (Task task : tasks) {
Thread thread = new Thread(task::run);
thread.start();
... | magicoder | java |
You are tasked with implementing a PIN update system for a banking application. The system should prompt the user to enter their previous PIN and the new PIN they wish to set. If the previous PIN is different from the new PIN, the system should check if the previous PIN exists in the user database. If it does, the syst... | ```python
def update_pin(users: dict):
previous_pin_inp = int(input('Please Enter previous PIN: '))
new_pin_inp = int(input('Please Enter new PIN: '))
if previous_pin_inp != new_pin_inp:
if previous_pin_inp in users:
users[int(new_pin_inp)] = users.pop(int(previous_pin_inp))
... | magicoder | python |
You are tasked with creating a Python class that calculates the minimum path sum in a grid. The grid is represented as a 2D list of integers, where each element represents the cost to traverse that cell. You need to implement the `minPathSum` method in the class to find the minimum path sum from the top-left cell to th... | ```python
from typing import List
import heapq
class MinPathSum:
def __init__(self, grid: List[List[int]]):
self.grid = grid
def minPathSum(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
distance = [[float('inf')] * (n + 1) for _ in range(m + 1)]
distance[0... | magicoder | python |
You are tasked with creating a Python function that retrieves air quality data from a specific monitoring station using the UK Air Quality API. The function should take a station ID as input and return the air quality data for that station.
The UK Air Quality API provides access to air quality monitoring data for vari... | ```python
from urllib.request import Request, urlopen
from urllib.error import URLError
import json
def get_air_quality_data(station_id):
url = 'https://uk-air.defra.gov.uk/sos-ukair/api/v1/stations/' + str(station_id)
request = Request(url)
try:
response = urlopen(request)
data = response... | magicoder | python |
You are tasked with implementing a simplified version of a concurrent programming pattern using channels and a selector. The goal is to create a program that simulates the synchronization and communication between multiple concurrent processes.
You are provided with the following classes:
1. `Channel`: A class represe... | ```python
from channel import Channel
from selector import Selector
from wg import WaitGroup
import time
def process1(channel):
time.sleep(1)
channel.send("Hello from Process 1")
def process2(channel):
time.sleep(2)
channel.send("Hello from Process 2")
def main():
channel1 = Channel()
channel... | magicoder | python |
You are tasked with implementing a class method for managing BIOS configuration attributes. The class, `Manager`, is part of the `sdbusplus::xyz::openbmc_project::BIOSConfig::Common::Error` namespace. The method, `setAttribute`, takes two parameters: `attribute` of type `AttributeName` and `value` of type `AttributeVal... | ```cpp
void Manager::setAttribute(AttributeName attribute, AttributeValue value)
{
// Access the pendingAttributes function from the base class
auto pendingAttrs = Base::pendingAttributes();
// Perform operations to set the attribute with the given value
// Example: Assuming pendingAttributes returns a... | magicoder | cpp |
You are working on a project that involves optimizing convolution operations using the cuDNN library for deep learning applications. As part of this project, you need to develop a program that finds the most efficient convolution forward algorithm for a given set of input and filter tensors.
Your task is to write a fu... | ```cpp
int findMostEfficientConvolutionAlgorithm(cudnnHandle_t cudnn_handle,
cudnnTensorDescriptor_t tensor_desc_0,
cudnnFilterDescriptor_t filter_desc,
cudnnConvolutionDescriptor_t conv_desc,
... | magicoder | cpp |
You are tasked with implementing a cache management system for a data processing application. The system involves multiple cache services that store and manage different types of data. The provided code snippet contains verification calls for the cache management operations using the Mockito framework in Java.
Your ta... | ```java
// Cache Service Interfaces
public interface EvictQueryTemplateCacheService {
void evictByDatamartName(String datamartName);
}
public interface MaterializedViewCacheService {
void forEach(Consumer<Object> action);
}
public interface EntityCacheService {
void removeIf(Predicate<Object> filter);
}
... | magicoder | java |
You are tasked with creating a Python class that manages a database connection. The class should handle potential errors that may occur during the connection process. Your task is to implement the `DatabaseManager` class with the following requirements:
1. The class should have a method `connect` that takes a database... | ```python
import some_database_library
class DatabaseManager:
def __init__(self):
self.conn = None
def connect(self, database_url):
try:
# Attempt to establish a connection to the database
self.conn = some_database_library.connect(database_url)
except RuntimeErr... | magicoder | python |
You are tasked with implementing a class for managing player achievements and expedition data in a game. The provided code snippet is a part of the class `SaveData`, which contains properties for accessing the achievement manager and player, as well as a method for retrieving an expedition seed.
Your task is to comple... | ```python
from random import randint
class AchievementManager:
def __init__(self):
self.achievements = {} # Initialize achievements as an empty dictionary
def unlock_achievement(self, achievement_name):
# Implement logic to unlock the specified achievement
self.achievements[achievemen... | magicoder | python |
You are tasked with implementing a function that constructs a J1939 identifier based on the given inputs. The J1939 identifier is a 29-bit value used in the SAE J1939 standard for vehicle network communications. The identifier is composed of the Parameter Group Number (PGN), Destination Address, Priority, and other fie... | ```cpp
#include <iostream>
// Constants for J1939 identifier construction
const int J1939_DST_ADDR_MASK = 0xFF;
const int J1939_DST_ADDR_OFFSET = 8;
const int J1939_PGN_MASK = 0x3FFFF;
const int J1939_PGN_OFFSET = 8;
const int J1939_PRIORITY_OFFSET = 26;
// Enum for PDU format group
enum PDUFormatGroup {
PDU_FORM... | magicoder | cpp |
You are tasked with implementing a rail fence cipher encryption algorithm. The rail fence cipher is a transposition cipher that rearranges the plaintext letters by writing them in a zigzag pattern down and up the rails of a fence. The number of "rails" or lines used for the zigzag pattern is determined by the input par... | ```python
def rail_fence(plaintext, n):
plaintext_length = len(plaintext)
line_size = -(-plaintext_length // n) # Equivalent to int(np.ceil(plaintext_length/n))
ciphertext = ""
for i in range(n):
for j in range(line_size):
if j * n + i < plaintext_length:
ciphertext... | magicoder | python |
You are tasked with creating a Python function that simulates a temporary file management system. The function should create temporary files, perform operations on them, and then delete them once the process is complete.
Write a Python function called `manage_temp_files` that takes in two parameters:
1. `num_files` (i... | ```python
import os
import random
def manage_temp_files(num_files, operations):
deleted_files = []
temp_files = [f"temp_file_{i}" for i in range(1, num_files + 1)]
for operation in operations:
if operation == "read":
file_to_read = random.choice(temp_files)
if os.path.exist... | magicoder | python |
You are working on a project that involves subscribing to an MQTT (Message Queuing Telemetry Transport) broker hosted on AWS IoT. The code snippet provided initializes an MQTT client and sets up the necessary configurations for secure communication with the broker.
Your task is to write a Python function that subscrib... | ```python
import paho.mqtt.client as paho
import ssl
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe(topic)
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
def subscribe_to_mqtt_broker(topic: str) -> None:
mqttc =... | magicoder | python |
You are tasked with implementing a class that simulates a shooting scheme for a given number of trials. The shooting scheme involves a certain number of steps for each trial, and the number of steps can vary based on the type of shooting being performed. Your task is to create a Python class `ShootingScheme` with a met... | ```python
from __future__ import division
class ShootingScheme:
def n_steps_for_trials(self, shooting_type, num_trials):
if shooting_type == 'shooting':
return 400.0 / 3.0
else:
# Custom formula for calculating steps based on the shooting type
# Replace the follo... | magicoder | python |
You are tasked with implementing a custom data structure in Rust that simulates a simple stack with the ability to push, pop, and get the minimum element in constant time. You need to design the data structure to support these operations efficiently.
Your task is to implement the `MinStack` struct with the following m... | ```rust
struct MinStack {
stack: Vec<(i32, i32)>, // (value, current_min)
}
impl MinStack {
fn new() -> Self {
MinStack { stack: Vec::new() }
}
fn push(&mut self, val: i32) {
let min = if let Some(&(_, min)) = self.stack.last() {
val.min(min)
} else {
va... | magicoder | rust |
You are tasked with implementing a parser for a simplified programming language that supports lambda expressions. The language includes the ability to define simple lambda arguments and tuple lambda arguments. A simple lambda argument consists of a single variable name, while a tuple lambda argument consists of multipl... | ```rust
#[derive(Debug, Clone)]
pub(crate) enum LambdaArg<'a> {
Simple(String),
Tuple(Vec<&'a str>),
}
impl<'a> Expression<'a> {
pub(crate) fn parse(parser: &'a Parser<'a>, pos: usize) -> ParseResult<'a> {
let (expr, mut pos) = Expression::parse_dollar_func_call_expr(parser, pos)?;
if parse... | magicoder | rust |
You are tasked with creating a Java program that interacts with an API to retrieve file metadata and perform specific operations based on the retrieved information. The program should take command-line arguments and utilize the Gson library for JSON parsing.
Your program should accomplish the following tasks:
1. Retri... | ```java
import com.google.gson.Gson;
import com.google.gson.JsonObject;
public class FileMetadataRetriever {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: java FileMetadataRetriever <file_id>");
return;
}
String fileId = ... | magicoder | java |
You are tasked with implementing a function that parses HTML code to extract information about form elements and their attributes. Specifically, you need to extract the label text, input type, input name, and whether the input is checked (if it's a checkbox).
You are given a sample HTML code snippet as follows:
```
... | ```python
import re
def parseFormElements(html):
form_elements = re.findall(r'<label>(.*?)<\/label>.*?<input type="(.*?)" name="(.*?)"(?: checked)?>', html, re.DOTALL)
parsed_elements = []
for element in form_elements:
label, input_type, name = element
checked = True if 'checked' in element... | magicoder | python |
You are tasked with implementing a custom router for a Django REST framework application. The router should be able to register multiple viewsets with distinct prefixes and basenames, and then generate a list of corresponding URLs.
Your task is to create a Python class `CustomRouter` that allows for the registration o... | ```python
class CustomRouter:
def __init__(self):
self.routes = []
def register(self, prefix, viewset, basename):
self.routes.append((prefix, basename))
def urls(self):
return [f'{prefix}/{basename}/' for prefix, basename in self.routes]
# Usage
router = CustomRouter()
router.regi... | magicoder | python |
You are given a graph with N nodes and M edges. Each node is labeled from 0 to N-1. The graph is represented as an adjacency list, where graph[i] contains a list of nodes that are adjacent to node i.
Your task is to write a function that returns the maximum depth of the graph starting from a given node. The depth of a... | ```python
from typing import List
def max_depth(graph: List[List[int]], N: int, M: int, target_node: int) -> int:
visited = [False] * N
depth = [0] * N
def dfs(node, d):
visited[node] = True
depth[node] = d
for neighbor in graph[node]:
if not visited[neighbor]:
... | magicoder | python |
You are tasked with creating a Python program to manage and monitor a network of IoT devices. The program should utilize asynchronous programming to handle multiple tasks concurrently. One of the devices in the network is a Sense HAT, which provides environmental data and user input capabilities. The program needs to c... | ```python
import asyncio
async def senseHatTask():
# Implement the functionality for the Sense HAT task
await asyncio.sleep(5) # Placeholder for actual Sense HAT task
async def listeners():
# Implement the functionality for the listeners task
await asyncio.sleep(3) # Placeholder for actual listeners... | magicoder | python |
You are tasked with creating a system for a 2D game engine using the Bevy game engine framework. The game engine uses the ECS (Entity-Component-System) architecture, where entities are composed of components and systems operate on entities with specific components. Your goal is to implement a system that updates the po... | ```rust
pub fn bg_position_system(
mut windows: ResMut<Windows>,
mut cam: Query<&MainCam>,
mut bg_tiles: Query<(&mut Transform, With<Tile>)>,
) {
if let Some(window) = windows.get_primary() {
if let Ok(camera) = cam.single() {
for (mut transform, _) in bg_tiles.iter_mut() {
... | magicoder | rust |
You are tasked with implementing a banking application that provides account summaries for a list of bank accounts. Each account summary should include the account holder's name, account number, account type, and current balance. You are given an interface with a method signature as follows:
```java
public List<Accoun... | ```java
import java.util.List;
import java.util.ArrayList;
public class BankingApplication implements AccountSummaryProvider {
// Assume the presence of a database connection and necessary setup
@Override
public List<AccountSummary> getAccountSummaries() {
// Assume the database query to fetch acc... | magicoder | java |
You are tasked with creating a Python class that simulates a simple banking system. The class should have methods for depositing funds, withdrawing funds, and checking the account balance. Additionally, the class should have a method for transferring funds to another account.
Your task is to implement the `BankAccount... | ```python
class BankAccount:
def __init__(self):
self.balance = 0
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if self.balance >= amount:
self.balance -= amount
else:
print("Insufficient funds")
def get_balance(s... | magicoder | python |
You are tasked with creating a script to automate the build process for a software project. The build process involves using the `stack` tool to build the project with specific options. Your script should execute the `stack build` command with the following options:
- `--no-test`: This option skips running the test sui... | ```python
import subprocess
def build_project():
try:
# Construct the command with specified options
command = ["stack", "build", "--no-test", "--profile", "--no-haddock"]
# Execute the command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PI... | magicoder | python |
You are tasked with creating a Rust program that dynamically loads a library and provides an interface to its functionality. Specifically, you need to implement a struct `XcbScreensaver` that represents a dynamically loaded `libxcb-screensaver` library. The struct should contain a field `lib` of type `NamedLibrary` and... | ```rust
use crate::ffi::*;
use crate::lazy::*;
/// A dynamically loaded `libxcb-screensaver`.
pub struct XcbScreensaver {
pub(crate) lib: NamedLibrary,
pub(crate) screensaver: XcbScreensaverScreensaver,
}
impl XcbScreensaver {
// Define any additional fields or methods here
// Example method to demon... | magicoder | rust |
You are tasked with implementing a function to benchmark the performance of a given function using a specific input value. The function `benchmark` takes two parameters: `unit_vector` (a function) and `value` (an input value). Your goal is to measure the execution time of the `unit_vector` function when it is called wi... | ```python
import time
def benchmark(unit_vector, value):
start_time = time.time()
unit_vector(value)
end_time = time.time()
elapsed_time_ms = (end_time - start_time) * 1000
return elapsed_time_ms
```
In the solution, the `benchmark` function uses the `time` module to measure the execution time of ... | magicoder | python |
You are tasked with implementing a class that generates transition instructions for a 2D diamond animation. The class, `DiamondsTransition2D`, takes an integer parameter `diamondSize` in its constructor, representing the width of the diamonds. The constructor throws an `IllegalArgumentException` if the `diamondSize` is... | ```java
public class DiamondsTransition2D {
private int diamondSize;
public DiamondsTransition2D(int diamondSize) {
if (diamondSize <= 0)
throw new IllegalArgumentException("size (" + diamondSize + ") must be greater than 0");
this.diamondSize = diamondSize;
}
public Transi... | magicoder | java |
You are tasked with implementing a function that determines the data type of a given value. The function should return a string representing the data type of the input value. The data types to be considered are Int, UInt8, UInt16, UInt32, UInt64, Float, and String. The function should handle both primitive data types a... | ```swift
func determineType(_ value: Any) -> String {
if let _ = value as? Int {
return "Int"
} else if let _ = value as? UInt8 {
return "UInt8"
} else if let _ = value as? UInt16 {
return "UInt16"
} else if let _ = value as? UInt32 {
return "UInt32"
} else if let _ =... | magicoder | swift |
You are tasked with implementing a function to load a dynamic library in a cross-platform manner. The function should handle loading the library based on the platform it is running on. For Android, the function should construct the library path based on the current app name obtained from the command line. For other pla... | ```cpp
#include <memory>
#include <string>
#ifdef ANDROID
#include <android/log.h>
#include <fstream>
#endif
class LibraryHandle {
// Define the necessary members for library handling
};
std::unique_ptr<LibraryHandle> loadLibrary(const char* name) {
#ifdef ANDROID
// Read the current app name from cmdline
... | magicoder | cpp |
You are tasked with creating a Python function to visualize a 3D sigma plot using the given code snippet as a reference. The function `sigma_visualize_3d` takes in parameters `T` (transformation matrix) and `sigma` (covariance matrix), with optional parameters `N` and `K` set to default values of 100 and 1 respectively... | ```python
import matplotlib.colors
from numpy.linalg import cholesky
import numpy as np
def get_axis_points(T, sigma, N, K, axis_index, A):
# Implementation of get_axis_points function
pass # Placeholder for actual implementation
def sigma_visualize_3d(T, sigma, N=100, K=1):
colors = list(matplotlib.colo... | magicoder | python |
You are tasked with implementing a class that simulates a simplified version of a web browser's tab management system. The class should allow for the creation, deletion, and switching of tabs, as well as the ability to close the entire browser.
Your task is to implement the `BrowserTabManager` class with the following... | ```java
import java.util.ArrayList;
import java.util.List;
public class BrowserTabManager {
private List<String> openTabs;
public BrowserTabManager() {
openTabs = new ArrayList<>();
}
public void openTab(String url) {
openTabs.add(url);
}
public void closeTab(int index) {
... | magicoder | java |
You are tasked with implementing a class hierarchy for managing fields in a data structure. The base class `DataStructure` is provided, which contains a property for the name of the data structure and a list of fields it contains. Your task is to create derived classes and implement additional functionality.
You need ... | ```csharp
public class Database : DataStructure
{
public string ConnectionString { get; set; }
public override void AddField(Field field)
{
Fields.Add(field);
}
}
public class Form : DataStructure
{
public string SubmissionUrl { get; set; }
public override void AddField(Field field)
... | magicoder | csharp |
You are tasked with creating a Rust program that dynamically includes a generated file at compile time. The generated file, `policykit_cr.rs`, contains code related to policy kit functionality. Your task is to write a Rust program that includes this generated file and uses the functionality provided within it to perfor... | ```rust
// main.rs
include!(concat!(env!("OUT_DIR"), "/policykit_cr.rs"));
fn main() {
let user_id = 123; // Replace with actual user ID
let action = "read"; // Replace with actual action
if has_permission(user_id, action) {
println!("User has permission to perform the action");
} else {
... | magicoder | rust |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.