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 error handling system for a JSON-LD API in Swift. The provided code snippet shows an enum `JSONLDAPIError` that represents various error cases that can occur when working with the JSON-LD API. Your task is to extend this enum with additional error cases and implement a function... | ```swift
public enum JSONLDAPIError: Error {
case colliding_keywords
case context_overflow
case cyclic_IRI_mapping
case invalid_base_direction
case invalid_base_IRI
case invalid_container_mapping
case invalid_context_entry
case invalid_context_nullification
case invalid_keyword_usage... | magicoder | swift |
You are given a Python code snippet that defines a list of names and a book_tags sequence using the `datasets` module. Your task is to write a function that takes the list of names and the book_tags sequence as input and returns a dictionary containing the count of occurrences of each name in the book_tags sequence.
W... | ```python
def count_name_occurrences(names, book_tags):
name_counts = {name: 0 for name in names} # Initialize the dictionary with 0 counts for each name
for tag in book_tags:
if tag in name_counts:
name_counts[tag] += 1 # Increment the count for the corresponding name
return name_coun... | magicoder | python |
You are tasked with implementing a custom error handling mechanism for a Rust application. The goal is to create a macro similar to the `expect` method provided by the Rust standard library's `Option` and `Result` types. The macro should accept a custom error message and handle it appropriately.
Your task is to create... | ```rust
macro_rules! custom_expect {
($expr:expr, $msg:expr) => {
match $expr {
Some(val) => val,
None => {
eprintln!("Error: {}", $msg);
std::process::exit(1);
}
}
};
}
fn main() {
let error_code = 404;
let with_dummy... | magicoder | rust |
You are tasked with creating a PHP function that processes a given array of post data and generates HTML output based on a specific template structure. The function should iterate through the array and generate HTML output for each post using the provided template. Additionally, the function should increment a counter ... | ```php
<?php
function generatePostHTML($postDataArray) {
$output = ''; // Initialize the output variable
$count = 0; // Initialize the counter variable
foreach ($postDataArray as $post) {
ob_start(); // Start output buffering
include('vc_templates/post/_single.php'); // Include the template... | magicoder | php |
You are tasked with implementing a time utility library in C++ to calculate time differences and provide a bottom description based on a given timestamp.
Your task is to implement the following functions within the `utils::time` namespace:
1. `calculateTimeDifference`: This function should take two `std::time_t` para... | ```cpp
#include <iostream>
#include <ctime>
#include <string>
namespace utils::time {
std::time_t calculateTimeDifference(std::time_t alarmTime, std::time_t currentTime) {
return difftime(alarmTime, currentTime);
}
std::time_t calculateMinutesDifference(std::time_t alarmTime, std::time_t currentTi... | magicoder | cpp |
You are tasked with implementing a protocol-oriented programming problem related to JSON serialization in Swift.
Define a protocol `JSONParcelable` that represents types which can be serialized to JSON. The protocol should require a property `parcelableType` of type `JSONParcelableType`, which indicates the type of th... | ```swift
// Define the JSONParcelableType enum
public enum JSONParcelableType {
case dictionary
case array
}
// Define the JSONParcelable protocol
public protocol JSONParcelable {
var parcelableType: JSONParcelableType { get }
}
// Extend the Dictionary type to conform to JSONParcelable
extension Dictiona... | magicoder | swift |
You are tasked with creating a Python program that interacts with a serial device using the `serial` library. The program should list all available serial ports and allow the user to select a port for communication. Additionally, the program should provide functionality to send and receive data to and from the selected... | ```python
import serial
import serial.tools.list_ports
class SerialCommunicator:
def __init__(self):
self.serial_port = None
def list_available_ports(self):
return [port.device for port in serial.tools.list_ports.comports()]
def select_port(self, port_name):
available_ports = self... | magicoder | python |
You are tasked with creating a script to automate the renewal of SSL/TLS certificates using Let's Encrypt and then reload the Nginx web server to apply the updated certificates. Let's Encrypt is a certificate authority that provides free SSL/TLS certificates for websites. Nginx is a popular web server and reverse proxy... | ```bash
#!/bin/bash
# Set the webroot path and domains
WEBROOT_PATH="/var/www/html"
DOMAINS="example.com www.example.com"
# Renew SSL/TLS certificates using Let's Encrypt
letsencrypt --renew certonly --webroot --webroot-path $WEBROOT_PATH --agree-tos $DOMAINS
# Check the exit status of the letsencrypt command
if [ $... | magicoder | shell |
You are tasked with creating a Java class that utilizes reflection to dynamically instantiate a singleton object using the provided code snippet as a reference. Your class should be able to load a class by its name, check if it is annotated with `@Singleton`, and if so, create a single instance of the class using refle... | ```java
import io.micronaut.context.BeanContext;
import javax.inject.Singleton;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class SingletonInstantiator {
public <T> T createSingleton(String className) {
try {
Class<?> clazz = Class.forName(c... | magicoder | java |
You are tasked with implementing a configuration class in Python that allows for the storage and retrieval of key-value pairs. The class should support setting, getting, and deleting key-value pairs, as well as providing a method to return all key-value pairs as a dictionary. Additionally, the class should have a metho... | ```python
class Configuration:
def __init__(self):
self.data = {}
def set(self, key, value):
self.data[key] = value
def get(self, key):
return self.data.get(key)
def delete(self, key):
if key in self.data:
del self.data[key]
def get_all(self):
... | magicoder | python |
You are working on a project that involves implementing a neural network architecture using PyTorch. As part of this project, you need to create a custom module that handles linear transformations for input and output data. The module should also manage the fusion of channels based on certain configuration parameters. ... | ```python
import torch.nn as nn
class CustomModule(nn.Module):
def __init__(self, SA_cfg, model_cfg):
super(CustomModule, self).__init__()
self.linears_in = nn.ModuleList()
self.linears_out = nn.ModuleList()
self.fusion_channel = sum([x[-1] for x in SA_cfg[model_cfg.FEATURES_SOURCE[... | magicoder | python |
You are tasked with creating a Swift program that utilizes the WebKit framework to display a JSON data in a macOS application. Your program should include a struct called `JSONView` that conforms to the `NSViewRepresentable` protocol, allowing the JSON data to be rendered within a custom view. The `JSONView` struct sho... | ```swift
import SwiftUI
import WebKit
struct JSONView: NSViewRepresentable {
var jsonData: Data
func makeNSView(context: Context) -> WKWebView {
return WKWebView()
}
func updateNSView(_ nsView: WKWebView, context: Context) {
let jsonString = String(data: jsonData, encoding: .utf8) ?? ... | magicoder | swift |
You are tasked with creating a script to automate the training process for a machine learning model. The script should execute several shell commands and process the output to extract relevant information.
Your script should perform the following steps:
1. Execute the `clear_classes_weights.sh` script.
2. Execute the ... | ```bash
#!/bin/bash
# Step 1: Execute clear_classes_weights.sh
./clear_classes_weights.sh
# Step 2: Execute init_classes_weights.sh
./init_classes_weights.sh
# Step 3: Execute train_gpu_classes.sh with the specified number of classes
./train_gpu_classes.sh $1 | awk 'BEGIN{i=0} /^{'\''Accuracy/ {print $0; i++;}'
# E... | magicoder | shell |
You are tasked with implementing a custom input stream class in C++. The class should support reading from a file and provide functionality for reading different data types from the file. Your task is to implement the `MyInputStream` class with the following requirements:
1. The class should have a constructor that ta... | ```cpp
#include <iostream>
#include <fstream>
#include <string>
class MyInputStream {
public:
MyInputStream(const std::string& filename) : is_(filename) {
if (!is_.is_open()) {
throw std::runtime_error("Failed to open file: " + filename);
}
}
int readInt() {
int value;
... | magicoder | cpp |
You are tasked with implementing a plugin loading system for a software application. The system should be able to load multiple plugins based on their names and execute them. Each plugin is represented by a Python function with a specific signature.
You are provided with a `load_plugins` function that takes a list of ... | ```python
# Sample implementation of the load_plugin function
def load_plugin(plugin_name):
if plugin_name == "plugin1":
def plugin1_function():
print("Executing plugin 1")
return plugin1_function
elif plugin_name == "plugin2":
def plugin2_function():
print("Execu... | magicoder | python |
You are tasked with implementing a function that simulates a simplified version of a worker management system. The system is responsible for coordinating workers to perform tasks in a parallelized manner. The provided code snippet is a part of the existing system and demonstrates the usage of a function `gpb_from_func_... | ```python
# Worker Manager Class
class WorkerManager:
def __init__(self):
self.workers = []
def reset(self):
self.workers = []
# gpb_from_func_caller function
def gpb_from_func_caller(func_caller, worker_manager, max_capital, sync_mode, optimization_strategy):
# Implementation of optimizat... | magicoder | python |
You are tasked with creating a unit test for a Python class called `Planner`. The `Planner` class is responsible for managing a set of `Link` objects, which represent connections to other components in a larger system. The test is intended to verify that the `Planner` class correctly handles the lifecycle events of its... | ```python
import unittest
from unittest.mock import patch, Mock
from your_module import Planner, Link # Import the Planner and Link classes from your module
class TestPlanner(unittest.TestCase):
@patch(fqname(Link), spec=Link)
def test_start_order(self, link):
planner = Planner() # Instantiate the Pl... | magicoder | python |
You are tasked with creating a simple iOS application that tracks the time spent on different tasks. The application should have the following functionality:
1. Allow the user to start and stop a timer for each task.
2. Display the total time spent on each task.
3. Allow the user to reset the timer for each task.
To ... | ```swift
import UIKit
class TaskTimer {
private var timers: [String: Timer] = [:]
private var startTime: [String: Date] = [:]
private var totalTime: [String: TimeInterval] = [:]
func startTimer(taskName: String) {
if timers[taskName] == nil {
timers[taskName] = Timer.scheduledTimer... | magicoder | swift |
You are tasked with implementing a Python class for a circular robot, Cbot, which will be used to simulate the movement of a robot in a 2D space. The robot's position is represented by its x and y coordinates, and it has a fixed radius. Your task is to implement the `Cbot` class with the following functionalities:
1. I... | ```python
import cv2
import math
class Cbot:
def __init__(self, x, y, radius):
self.x = x
self.y = y
self.radius = radius
def move_to(self, x, y):
self.x = x
self.y = y
def is_in_collision(self, x, y, obstacle_x, obstacle_y, obstacle_radius):
distance = mat... | magicoder | python |
You are tasked with writing a program to reorder the component spice node sequence based on a user-defined sequence. The input will consist of a spice netlist file containing component spice nodes, and a user-defined sequence for reordering the nodes. The program should read the netlist file, identify the component spi... | ```python
def reorder_spice_nodes(netlist_file):
with open(netlist_file, 'r') as file:
lines = file.readlines()
sequence = None
node_lines = []
for line in lines:
if line.startswith("//"):
continue
if "[SPICE_NODE_SEQUENCE]" in line:
sequence = list(map(i... | magicoder | python |
You are tasked with implementing a user authentication system for a web application. The system should allow users to create new accounts, but only if the currently logged-in user is an admin. The code snippet provided contains some variables and comments related to this task. Your goal is to complete the implementatio... | ```typescript
class UserAuthenticationSystem {
next: string; // url
querySub: Subscription;
initialized = false;
isAdminAuth = false;
defaultHref: string; // default href for the back button
initializeAuthSystem(): void {
this.initialized = true;
}
createUser(username: string, password: string): v... | magicoder | typescript |
You are given a 2D board of letters and a word. Your task is to determine if the word exists in the board. The word can be constructed from letters of sequentially adjacent cells, where "adjacent" cells are those horizontally or vertically neighboring. Each cell may not be used more than once in the word.
You need to ... | ```python
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
def dfs(board, word, i, j, k):
if not (0 <= i < len(board) and 0 <= j < len(board[0]) and board[i][j] == word[k]):
return False
if k == len(word) - 1:
return True
... | magicoder | python |
You are working on a project that involves managing multiple packages and running various commands to deploy and start different services. Your task is to create a script that automates the deployment and startup process for a specific package within the project.
Given the following code snippet as an example of the c... | ```bash
#!/bin/bash
# Navigate to the directory packages/generic/client
cd packages/generic/client || { echo "Error: Unable to navigate to packages/generic/client directory"; exit 1; }
# Set the environment variable REACT_APP_RUN_MODE to PROD
export REACT_APP_RUN_MODE=PROD
# Run the superstatic server to serve the c... | magicoder | shell |
You are tasked with implementing a program to generate a truth tree for a given logical formula and then output the truth tree to a .tex file. The truth tree is a data structure used in logic to determine the validity of a logical formula. Each node in the truth tree represents a subformula of the original formula, and... | ```java
public void outputToFile() {
try {
this.setBufferedReader(new BufferedReader(new FileReader(TEX_TREE_TEMPLATE)));
this.setBufferedWriter(new BufferedWriter(new FileWriter(this.getOutputFile())));
// First copy the template over.
String line;
while ((line = this.getBu... | magicoder | java |
You are tasked with implementing a simplified version of a database query system using Java. The system should be able to store and retrieve objects based on specific criteria.
You are given a code snippet that demonstrates the usage of the `FastSelect` library, which provides a fast and memory-efficient way to query ... | ```java
import java.util.ArrayList;
import java.util.List;
// Define the TestInt class
class TestInt {
private int intValue;
public TestInt(int intValue) {
this.intValue = intValue;
}
public int getIntValue() {
return intValue;
}
}
// Define the Database class
class Database<T> {... | magicoder | java |
You are tasked with creating a Python class that simulates the behavior of a pool monitoring system. The system interacts with an external API to retrieve device information and maintain a connection through periodic keep-alive requests. Your task is to implement the necessary methods and attributes for this class.
Yo... | ```python
import requests
import time
class PoolMonitor:
def __init__(self, username, password):
self.username = username
self.password = password
self.access_token = None
self.last_refresh_time = 0
def login(self):
response = requests.post(AQUALINK_LOGIN_URL, json={"us... | magicoder | python |
You are tasked with implementing a decision tree visualization algorithm for a machine learning model. The given code snippet is a part of a function that builds a visualization of a decision tree using the `pydot` library. The function recursively constructs the decision tree graph by adding nodes and edges based on t... | ```python
import pydot
def build_pydot_tree(graph, root, idx):
node = pydot.Node(idx, label=root.label)
if root.decision.true_child is not None:
true_child = build_pydot_tree(graph, root.decision.true_child, idx + 'T')
true_weight = root.decision.true_child.value / root.value
graph... | magicoder | python |
You are tasked with implementing a simplified version of a callback mechanism using Java. Your goal is to create a class that allows a callback to be triggered when a certain condition is met.
You are provided with a partial code snippet for a class called `BlockCallback` that implements the `PacketCallback` interface... | ```java
import java.util.concurrent.Semaphore;
public class BlockCallback implements PacketCallback {
private Semaphore received;
public BlockCallback() {
received = new Semaphore(0);
}
// Method to set the value of the Semaphore object to a specified integer value
public void setSemaphor... | magicoder | java |
You are tasked with implementing a generic vocabulary builder in Rust. The vocabulary builder should allow adding items and counting their occurrences. Your task is to implement the `VocabBuilder` struct and its associated methods to achieve this functionality.
The `VocabBuilder` struct should have the following metho... | ```rust
struct CountedType<T> {
item: T,
count: usize,
}
pub struct VocabBuilder<T> {
types: Vec<CountedType<T>>,
}
impl<T> VocabBuilder<T> {
pub fn new() -> Self {
VocabBuilder { types: Vec::new() }
}
pub fn count(&mut self, item: T)
where
T: PartialEq,
{
if l... | magicoder | rust |
You are given a Python function `lowpass_downsample` that takes an input bitmap (a NumPy array) and a downsampling factor. The function aims to downsample the input bitmap using Discrete Fourier Transform (DFT) truncation. The DFT is a technique used in signal processing and image compression to transform a signal from... | ```python
import numpy as np
import scipy.fftpack as fft
def lowpass_downsample(bitmap, factor):
"""
Downsample a bitmap via DFT truncation.
:param bitmap: Input bitmap (NumPy array)
:param factor: Downsampling factor
:return: Downsampled bitmap array
"""
# Compute 2D DFT of the input bitm... | magicoder | python |
You are working on a project that involves visualizing meteorological data using the Python library PyNGL (Python interface to the NCAR Graphics Libraries). As part of this project, you need to create a program that generates a streamline map and adds long_name and units annotations to the plot.
The given code snippet... | ```python
import Ngl
def generate_streamline_map(ua, va, long_name, units):
wks = Ngl.open_wks("png", "streamline_map") # Open a workstation for creating the plot
# Create the streamline map
stres = Ngl.Resources()
plot = Ngl.streamline_map(wks, ua[::3, ::3], va[::3, ::3], stres)
# Write variabl... | magicoder | python |
You are tasked with implementing a file upload manager for a cloud storage service. The manager is responsible for handling multipart uploads and ensuring that uploads are properly managed, including aborting uploads in case of unrecoverable errors.
Your task is to create a class that manages the multipart upload proc... | ```csharp
using System;
public class UploadManager
{
private string uploadId;
private string vaultName;
private string accountId;
private string totalFileChecksum;
public UploadManager(string vaultName, string accountId, string totalFileChecksum)
{
this.vaultName = vaultName;
t... | magicoder | csharp |
You are tasked with implementing a self-balancing binary search tree (BST) using the AVL (Adelson-Velsky and Landis) tree rotation operations. AVL trees are a type of self-balancing binary search tree where the balance factor of each node is maintained to be -1, 0, or 1. When a new node is inserted or an existing node ... | ```python
class AVLNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
self.height = 1
class AVLTree:
def __init__(self):
self.root = None
def _height(self, node):
if node is None:
return 0
return node.hei... | magicoder | python |
You are tasked with implementing a custom resolver for a package management system. The resolver will be responsible for resolving package dependencies and versions based on a set of rules. The resolver will need to handle package resolution, versioning, and dependency management.
Your task is to implement the `Custom... | ```rust
use core::errors::Result;
use core::{
CoreFlavor, Range, Resolved, ResolvedByPrefix, Resolver, RpPackage, RpRequiredPackage,
RpVersionedPackage, Version,
};
use naming::Naming;
use relative_path::{RelativePath, RelativePathBuf};
use std::any::Any;
use std::collections::{HashMap, HashSet};
struct Custom... | magicoder | rust |
You are tasked with implementing a Python function that dynamically selects and builds a machine learning model based on the provided model name and keyword arguments. Your task is to complete the function `select_and_build_model` by implementing the logic to select the appropriate model builder function and use it to ... | ```python
import moe
def select_and_build_model(name, kwargs):
if hasattr(moe, f"build_{name}_model"):
build_model = getattr(moe, f"build_{name}_model")
else:
raise ValueError(f"Unknown model name: {name}.")
return build_model(**kwargs)
```
The provided solution implements the `select_and... | magicoder | python |
You are tasked with implementing a simple cryptocurrency trading system. The system consists of two modules: `faucet` and `indexer`. The `faucet` module is responsible for simulating the distribution of new cryptocurrency tokens to users, while the `indexer` module is responsible for tracking and indexing all transacti... | ```rust
// faucet.rs
use crate::indexer;
pub fn distribute_tokens(tokens_to_generate: u32) {
indexer::record_distribution(tokens_to_generate);
}
// indexer.rs
pub struct DistributionRecord {
tokens_distributed: u32,
distribution_history: Vec<u32>,
}
impl DistributionRecord {
pub fn new() -> Distribut... | magicoder | rust |
You are tasked with creating a script to automate the testing of a web application using Cypress. Cypress is a popular JavaScript end-to-end testing framework that allows for easy and effective testing of web applications. The `cypress run` command is used to execute the tests defined in the Cypress test suite.
Your t... | ```javascript
const { exec } = require('child_process');
function runCypressTests() {
return new Promise((resolve, reject) => {
exec('cypress run', (error, stdout, stderr) => {
if (error) {
reject(error);
} else {
resolve(stdout);
}
});
});
}
function parseTestResults(tes... | magicoder | javascript |
You are working on a system that integrates with a Magento e-commerce platform to manage product and category data. The system uses JSON data to load categories and products from Magento and then creates corresponding objects in the local database.
Your task is to implement a function that processes product data from ... | ```python
class Product:
def find_or_create_using_magento_data(product_data):
# Check if the product exists in the local database
existing_product = Product.query.filter_by(magento_id=product_data['id']).first()
if existing_product:
# Update the existing product with the new dat... | magicoder | python |
You are tasked with implementing a Python class that retrieves weather data for a given location using the One Call API. The class should be able to fetch current weather information as well as minutely forecast data. You are provided with a partial code snippet for the `OneCall` class, which includes the constructor m... | ```python
from typing import Union, Optional
from ..commons import exceptions
from ..utils import geo
from .weather import Weather
from ..utils.opendata_cwb import OpendataCWB
class OneCall:
def __init__(self,
lat: Union[int, float],
lon: Union[int, float],
timez... | magicoder | python |
You are tasked with implementing a command-line auto-completion feature for a custom script that interacts with a gist service. The script provides various commands for managing gists, such as editing, describing, archiving, and retrieving information about gists. Your task is to create a function that generates auto-c... | ```bash
__gist() {
local curr=${COMP_WORDS[COMP_CWORD]}
local cmd=${COMP_WORDS[1]}
COMPREPLY=()
case ${cmd} in
edit|description|archive|files|content|clone|info)
if (( ${COMP_CWORD} == 2 )); then
# Auto-completion for commands
local commands="edit description archive files content cl... | magicoder | shell |
You are tasked with implementing a function to create a loading HUD (Heads-Up Display) in an iOS application using Swift. The HUD will be displayed on a given view and will show a loading indicator along with a message. You are provided with a code snippet that includes a function to create a simple HUD with a text mes... | ```swift
static func createLoadingHUD(view: UIView, message: String) -> MBProgressHUD {
let hud = MBProgressHUD.showAdded(to: view, animated: true)
hud.mode = .indeterminate // Set the mode to display an activity indicator
hud.label.text = message // Set the message to be displayed on the HUD
hud.remove... | magicoder | swift |
You are working on a critical system that processes user input to execute commands on the server. Your task is to implement a security check to prevent any potentially harmful commands from being executed. Specifically, you need to filter out any user input that contains the `rm -rf` command, which is notorious for cau... | ```python
def sanitizeInput(input_str):
if "rm -rf" in input_str:
return input_str.replace("rm -rf", "INVALID COMMAND")
else:
return input_str
```
The `sanitizeInput` function checks if the input string contains the `rm -rf` command using the `in` keyword. If it does, the function replaces all ... | magicoder | python |
You are working on a Java Spring Boot application that involves handling authentication and authorization. The code snippet provided is an interface `AuthModuleApiQueryMapper` which is used to query the database for `AuthModuleApi` entities based on the `moduleId` and `status`. The `AuthModuleApi` represents the mappin... | ```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class AuthModuleApiService {
@Autowired
private AuthModuleApiQueryMapper authModuleApiQueryMapper;
public List<... | magicoder | java |
You are working on a project that involves processing images and depth maps. Your task is to implement a function that improves the quality of depth maps based on the corresponding grayscale images. The depth maps are initially read from files and then processed using the `improve_depth` function. The function takes th... | ```python
import cv2
import os
import numpy as np
def improve_depth(gray_img, original_depth, threshold):
# Perform depth map improvement based on the grayscale image and original depth map
# Example implementation using simple thresholding for demonstration purposes
smoothed_depth = np.where(gray_img < th... | magicoder | python |
You are tasked with implementing a custom data structure in Java to efficiently store and retrieve information about categories and their associated items. The data structure should support adding, removing, and retrieving items for a given category, as well as retrieving all categories and their associated items.
You... | ```java
import java.util.*;
public class CategoryItemStore {
private Map<String, List<String>> categoryItemMap;
public CategoryItemStore() {
categoryItemMap = new HashMap<>();
}
public void addItem(String category, String item) {
categoryItemMap.computeIfAbsent(category, k -> new Arra... | magicoder | java |
You are tasked with creating a Python function that navigates through a file system and locates a specific directory. Your function should take the current directory path and the target directory name as input and return the absolute path of the target directory if found, or "Not found" if the directory does not exist.... | ```python
import os
def find_directory(current_path: str, target_directory: str) -> str:
# Change the current directory to the provided path
os.chdir(current_path)
# Check if the target directory exists
if os.path.exists(target_directory) and os.path.isdir(target_directory):
return os.path... | magicoder | python |
You are tasked with implementing a function to fill a 2D matrix with a specified border and then populate the inner region with values parsed from a given input string. The function `parse_as_2d_matrix_with_filled_border` takes three parameters:
1. `input_data`: a string containing the data to be parsed into the inner... | ```rust
use std::str::FromStr;
use std::fmt::Debug;
use ndarray::{Array2, Array, s};
use crate::parse_error::ParseError;
pub fn parse_as_2d_matrix_with_filled_border<T: Clone + FromStr + Debug>(
input_data: &str,
border_size: usize,
border_value: T,
) -> Result<Array2<T>, ParseError> {
let input_data =... | magicoder | rust |
You are tasked with implementing a simplified version of a command pattern in C#. The command pattern is a behavioral design pattern that turns a request into a stand-alone object that contains all information about the request. This allows for parameterizing clients with queues, requests, and operations.
Your task i... | ```csharp
using System;
public class Command : ICommand
{
private Action<object> execute;
private Func<object, bool> canExecute;
public event EventHandler CanExecuteChanged;
public Command(Action<object> execute, Func<object, bool> canExecute = null)
{
this.execute = execute;
this... | magicoder | csharp |
You are tasked with creating a Python class to manage network devices and their configurations. Your class should include methods to add Ethernet interfaces and assign IPv4 addresses to them. Additionally, you need to implement a method to generate a report of all configured IPv4 addresses and their corresponding gatew... | ```python
class NetworkDevice:
def __init__(self, name):
self.name = name
self.ethernets = []
def add_ethernet_interface(self, name):
self.ethernets.append({'name': name, 'ipv4_addresses': []})
def assign_ipv4_address(self, ethernet_name, ipv4_address, gateway):
for etherne... | magicoder | python |
You are tasked with implementing a function to calculate the sum of all prime numbers within a given range. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The function should take two integer parameters, `start` and `end`, representing the inclusive range within... | ```cpp
#include <iostream>
#include <cmath>
bool isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i <= sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
int sumOfPrimesInRange(int start, int end) {
int sum = 0;
for (int i =... | magicoder | cpp |
You are tasked with implementing a function to calculate the weight of a file or directory in a file system. The weight of a file is its size in bytes, and the weight of a directory is the sum of the weights of all the files and directories it contains. Additionally, the weight of a directory is multiplied by a factor ... | ```python
import os
def get_weight(path: str, substring: str) -> int:
if os.path.isfile(path):
return os.path.getsize(path)
elif os.path.isdir(path):
total_weight = 0
for item in os.listdir(path):
item_path = os.path.join(path, item)
if os.path.isfile(item_path):... | magicoder | python |
You are tasked with implementing a function `read_line_looping` that reads the first `count` lines from a file named `file_name` and prints them in a looping manner. If the file contains fewer lines than `count`, the function should start reading from the beginning of the file again until `count` lines are printed.
Th... | ```python
def read_line_looping(file_name: str, count: int) -> None:
with open(file_name, 'r') as file:
lines = file.readlines()
total_lines = len(lines)
for i in range(count):
print(lines[i % total_lines].strip())
```
The `read_line_looping` function opens the file specified by... | magicoder | python |
You are given a code snippet that involves matrix dimensions and memory layout. Your task is to write a function that calculates the total size of a matrix based on its dimensions, considering both row-major and column-major memory layouts.
Write a function `calculate_matrix_size` that takes the following parameters:
... | ```rust
fn calculate_matrix_size(dimensions: &[usize], row_major: bool) -> usize {
if row_major {
dimensions.iter().product()
} else {
dimensions.iter().rev().product()
}
}
```
The `calculate_matrix_size` function takes the dimensions and the memory layout as input. If `row_major` is true, ... | magicoder | rust |
You are tasked with creating a script to automate the generation of SSL/TLS certificates for a server using OpenSSL. Your script should take the following requirements into account:
1. Generate a 1024-bit RSA private key and save it to a file named `server-key.pem`.
2. Create a certificate signing request (CSR) using ... | ```bash
#!/bin/bash
# Generate a 1024-bit RSA private key and save it to server-key.pem
openssl genrsa -out server-key.pem 1024
# Create a certificate signing request (CSR) using the private key and save it to server-csr.pem
openssl req -new -key server-key.pem -out server-csr.pem -subj "/C=US/ST=State/L=City/O=Organ... | magicoder | shell |
You are tasked with implementing a read-only proxy class in Python. A read-only proxy class is a wrapper around an object that allows access to its attributes and methods but prevents any modifications to the object itself. Your task is to create a `ReadOnlyProxy` class that takes an object as input and returns a read-... | ```python
class ReadOnlyProxy:
def __init__(self, obj):
self._obj = obj
def __getattr__(self, name):
if hasattr(self._obj, name):
attr = getattr(self._obj, name)
if callable(attr):
def proxy_method(*args, **kwargs):
return attr(*args, ... | magicoder | python |
You are tasked with creating a custom filtering and serialization mechanism for a Django REST framework view. The view is responsible for managing device information and needs to support filtering, searching, ordering, authentication, and permission control.
The provided code snippet is a partial implementation of the... | ```python
from datetime import timedelta
from django.utils import timezone
from rest_framework import filters, serializers
class LastSeenFilterBackend(filters.BaseFilterBackend):
def filter_queryset(self, request, queryset, view):
last_seen_days = request.query_params.get('last_seen_days')
if last_... | magicoder | python |
You are tasked with implementing a C++ class that represents a game scene node for a level end. The class should inherit from the `SceneNode` class and provide specific functionality related to the end of a game level.
Your task is to complete the implementation of the `LevelEnd` class by adding the necessary member v... | ```cpp
#include "scene/LevelEnd.hpp"
namespace fs::scene
{
class LevelEnd : public SceneNode
{
public:
LevelEnd(/* constructor parameters */)
: SceneNode(/* initialize base class with constructor parameters */)
{
// Initialize any specific member variables related t... | magicoder | cpp |
You are working on a project that involves networking on an embedded system using MicroPython. You need to create a function that determines the protocol type based on the given address family and protocol number. The address family and protocol number are represented by constants defined in the 'usocket' module.
Writ... | ```python
def protocol_type(address_family, protocol_number):
if address_family == 2 and protocol_number == 0:
return "IPv4"
elif address_family == 10 and protocol_number == 0:
return "IPv6"
else:
return "Unknown"
``` | magicoder | python |
You are tasked with implementing a simple asynchronous pump control system in Rust. The system consists of a remote pump and a local pump, both of which are controlled asynchronously. The code snippet provided is a part of the system's control logic.
The code snippet shows a portion of the control logic for the pumps.... | ```rust
use tokio::task;
async fn remote_pump() -> Result<(), Box<dyn std::error::Error>> {
// Implementation of remote pump logic
Ok(()) // Placeholder for successful execution
}
async fn local_pump() -> Result<(), Box<dyn std::error::Error>> {
// Implementation of local pump logic
Ok(()) // Placehol... | magicoder | rust |
You are working on a computer vision project and need to generate anchors for object detection. The code snippet provided is a part of the anchor generation process. The `feature_map_size` is calculated based on the `grid_size` and a downsample factor obtained from the `model_cfg`. The anchors are then generated based ... | ```python
import torch
def generate_anchors(grid_size, model_cfg, target_assigner):
downsample_factor = config_tool.get_downsample_factor(model_cfg)
feature_map_size = [grid_size[0] // downsample_factor, grid_size[1] // downsample_factor, 1][::-1]
anchors = target_assigner.generate_anchors(feature_map... | magicoder | python |
You are tasked with implementing a query parameter validation system for a web API. The system should enforce specific rules regarding the combination of query parameters and their values. The validation rules are as follows:
1. If the query parameter `exclude_fields` is provided, it cannot be combined with `all_field... | ```python
class ValidationError(Exception):
pass
def validate_query_parameters(exclude_fields, all_fields, fields, exclude_default, query_parameter, field):
if exclude_fields and (all_fields or fields or exclude_default):
msg = ("Invalid query parameter combination: 'exclude_fields' "
"c... | magicoder | python |
You are given a function `findMaxScore` that takes in a 2D array `scores` representing the scores of different players in a game. Each row in the 2D array represents a player, and each column represents a different game level. The function is intended to find the maximum total score that can be achieved by selecting on... | ```python
from typing import List
def findMaxScore(scores: List[List[int]]) -> int:
if not scores: # Handle the case where the scores array is empty
return 0
maxScore = 0
for playerScores in scores:
totalScore = 0
for score in playerScores:
totalScore += score
... | magicoder | python |
You are tasked with implementing a program to analyze and manipulate circuit parameters. The given code snippet is part of a larger program that processes a circuit file and prints the number of XOR gates, the number of other gates, the fan-in of XOR gates, and the fan-in of other gates. Your task is to implement the f... | ```python
def parse_circuit(path):
num_xor = 0
num_other = 0
fn_xor = 0
fn_other = 0
with open(path, 'r') as file:
for line in file:
if line.startswith('XOR'):
num_xor += 1
fn_xor = max(fn_xor, len(line.split()) - 1)
else:
... | magicoder | python |
You are tasked with creating a program that reads a dictionary file and performs various operations on it. The dictionary file contains a list of words, with each word on a separate line. The file is located at the path specified in the `DICTIONARY` constant.
Your program needs to accomplish the following tasks:
1. Co... | ```rust
use std::fs::File;
use std::io::{BufRead, BufReader};
struct DictionaryStats {
total_words: usize,
longest_word: String,
average_length: f64,
words_with_z: usize,
}
fn dictionary_stats(dictionary_path: &str) -> DictionaryStats {
let file = File::open(dictionary_path).expect("Failed to open... | magicoder | rust |
You are tasked with creating a Python script that interacts with a Cassandra database using the `pcassandra` library. Your script should prompt the user to input a query, execute the query on the Cassandra database, and then display the results. You are required to handle potential exceptions that may occur during the ... | ```python
from django.core.management.base import BaseCommand
from django.utils.six.moves import input
from pcassandra import connection
from pcassandra import utils
def execute_cassandra_query(query):
try:
# Establish connection to Cassandra database
cassandra_conn = connection.get_connection()
... | magicoder | python |
You are tasked with implementing a simple Lisp interpreter in JavaScript. The interpreter should be able to handle basic operations such as variable assignment and arithmetic operations. The interpreter should support the following operations:
- Variable assignment: `["let", ["variable_name", value], expression]`
- Ari... | ```javascript
class Interpreter {
constructor() {
this.env = {};
}
rep(input) {
const expression = JSON.parse(input);
return this.evaluate(expression, this.env);
}
evaluate(expression, env) {
if (Array.isArray(expression)) {
const [operator, ...operands] = expression;
switch (ope... | magicoder | javascript |
You are tasked with implementing a Graph Attention Network (GAT) layer using PyTorch. The GAT layer is a type of neural network layer designed to operate on graph-structured data, where nodes in the graph represent entities and edges represent relationships between them. The GAT layer uses attention mechanisms to aggre... | ```python
import torch
import torch.nn as nn
import torch.nn.functional as F
class GAT_gate(nn.Module):
def __init__(self, n_in_feature, n_out_feature):
super(GAT_gate, self).__init__()
self.W = nn.Linear(n_in_feature, n_out_feature, bias=False)
self.a = nn.Parameter(torch.zeros(size=(2*n_o... | magicoder | python |
You are tasked with creating a program to navigate a 2D grid based on a series of directions. The directions are provided as a comma-separated string, where each direction represents a movement in the grid. The movements are in the form of cardinal directions: North (N), South (S), East (E), and West (W).
Your task is... | ```python
class Direction:
def __init__(self, direction):
self.direction = direction
def apply(self, position):
x, y = position
if self.direction == 'N':
return x, y + 1
elif self.direction == 'S':
return x, y - 1
elif self.direction == 'E':
... | magicoder | python |
You are tasked with creating a Python function that processes multiple files uploaded via a web request. The function should validate each file, ensuring that it exists, is a .txt file, and is not empty. If any of these conditions are not met, an error message should be returned along with a status code of 500. If all ... | ```python
def process_uploaded_files(request, num_files):
decoded_contents = []
for x in range(1, num_files + 1):
file_key = 'file' + str(x)
if file_key not in request.files:
return 'Error with attached file(s)', 500
if not request.files.get(file_key).filename.split(".")[-1] ... | magicoder | python |
You are working on a web application that manages blog posts. The given code snippet is a part of the HTML template for displaying blog post entries in a table. The PHP code is used to generate dynamic HTML elements based on the blog post data. The snippet includes buttons for editing, viewing details, and sending a po... | ```php
function generatePostHTML($blogPosts) {
$html = '';
if (!empty($blogPosts)) {
foreach ($blogPosts as $val) {
$html .= '<tr>';
$html .= '<td>' . $val['title'] . '</td>';
$html .= '<td>';
$html .= '<a href="' . base_url() . 'post/editpost/' . $val['bl... | magicoder | php |
You are tasked with creating a Python function that modifies foreign key constraints in a database migration script. The function should alter the column type for specific tables and ensure that the `nullable` property is set to `False` for the modified columns.
You are provided with a code snippet that demonstrates t... | ```python
def modify_foreign_keys(migration, op, types, fk_template_id_tables):
for table in fk_template_id_tables:
with migration.modify_foreign_keys_constraint((table,)):
op.alter_column(table, 'template_id', type_=types.Uuid, nullable=False)
```
The `modify_foreign_keys` function iterates thr... | magicoder | python |
You are tasked with creating a Python function that processes a given string and returns a dictionary containing the frequency of each character in the string. The function should ignore case sensitivity and non-alphabetic characters, and should only consider alphabetic characters in the input string.
Your task is to ... | ```python
def character_frequency(input_string):
frequency_dict = {}
for char in input_string:
if char.isalpha():
char = char.lower()
if char in frequency_dict:
frequency_dict[char] += 1
else:
frequency_dict[char] = 1
return frequen... | magicoder | python |
You are tasked with implementing a Swift class that represents a geometric shape. The class should have the ability to calculate its area and perimeter based on its specific shape. Your task is to create a base class `GeometricShape` with two subclasses `Rectangle` and `Circle`, each implementing the necessary methods ... | ```swift
// GeometricShape class
class GeometricShape {
var className: String {
return type(of: self).className
}
func area() -> Double {
fatalError("Subclasses must override this method")
}
func perimeter() -> Double {
fatalError("Subclasses must override this meth... | magicoder | swift |
You are tasked with implementing a Rust function to handle Monero RPC error codes. Monero is a popular cryptocurrency, and the provided code snippet contains a Rust enum `CoreRpcErrorCode` representing various error codes related to Monero RPC server responses. Your task is to write a function that takes an error code ... | ```rust
fn get_error_message(error_code: i32) -> Option<&'static str> {
match error_code {
-1 => Some("WrongParam"),
-2 => Some("TooBigHeight"),
_ => None,
}
}
```
In the solution, the `get_error_message` function uses a `match` statement to map the input error code to the corresponding... | magicoder | rust |
You are tasked with creating a script to automate the deployment process for a Maven project based on certain conditions. The script should check the project version and the current branch name to determine whether to deploy the project. If the project version contains "SNAPSHOT" and the branch is either "master" or a ... | ```bash
#!/bin/bash
PROJECT_VERSION=$(mvn org.apache.maven.plugins:maven-help-plugin:evaluate -Dexpression=project.version -B | grep -v '\[')
BRANCH=$(git rev-parse --abbrev-ref HEAD)
if [[ "$PROJECT_VERSION" =~ .*SNAPSHOT ]] && [[ "${BRANCH}" =~ ^master$|^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
mvn deploy -s .ci.maven.se... | magicoder | shell |
You are given the code snippet for a function that takes four lists of integers `p1`, `p2`, `p3`, and `p4` as input and is expected to return a boolean value. Your task is to implement the function `is_square` that determines whether the given four points form a square in a 2D plane. A square is defined as a quadrilate... | ```python
from typing import List
def distance(p1: List[int], p2: List[int]) -> int:
return (p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2
def is_square(p1: List[int], p2: List[int], p3: List[int], p4: List[int]) -> bool:
distances = [distance(p1, p2), distance(p1, p3), distance(p1, p4), distance(p2, p3), distan... | magicoder | python |
You are tasked with implementing a content caching algorithm for a Road Side Unit (RSU) in a vehicular network. The RSU has a cache with a maximum capacity of `max_cacheR` and is responsible for storing and serving content to vehicles passing through its coverage area. The algorithm aims to optimize content delivery by... | ```python
class ContentCachingAlgorithm:
def __init__(self, max_cacheR, content_size):
self.max_cacheR = max_cacheR
self.content_size = content_size
self.content_label_R = [[None] * (max_cacheR // content_size) for _ in range(self.max_cacheR // self.content_size)]
self.content_label_... | magicoder | python |
You are given a string consisting of only '0's and '1's. Your task is to write a function that finds the length of the longest consecutive sequence of '0's in the string. For example, in the string "100110001", the longest consecutive sequence of '0's is 4.
Write a function `longest_consecutive_zeros` that takes a str... | ```python
def longest_consecutive_zeros(s: str) -> int:
max_zeros = 0
current_zeros = 0
for c in s:
if c == '0':
current_zeros += 1
max_zeros = max(max_zeros, current_zeros)
else:
current_zeros = 0
return max_zeros
```
The function `longest_consecutiv... | magicoder | python |
You are given a list of colors represented by integers. Your task is to implement a function that optimizes the selection of color patches for a design. The function should find the combination of 4 colors that minimizes the cost of the design. The cost of a design is calculated based on the absolute difference between... | ```python
import itertools
def optimize(data):
min_cost = float('inf')
optimized_combination = None
for i, j, k, l in itertools.combinations(range(len(data)), 4):
cost = abs(data[i] - data[j]) + abs(data[j] - data[k]) + abs(data[k] - data[l])
if cost < min_cost:
min_cost = cost
... | magicoder | python |
You are tasked with implementing a class method that sets constraints for a pose optimization problem. The method should remove a specific constraint from the optimization model if a certain flag is set to true. You are given a code snippet as inspiration, which demonstrates the removal of a constraint related to tip d... | ```python
class PoseOptimizationWEIS:
def set_constraints(self, wt_opt):
# Inherit constraints from the superclass method
super(PoseOptimizationWEIS, self).set_constraints(wt_opt)
# Access specific design variables and constraints from the optimization configuration
blade_opt = self... | magicoder | python |
You are tasked with implementing a simple plotting library in Python. Your library should be able to create line plots with customizable features such as title, x-axis label, y-axis label, and legend. The library should also support plotting multiple lines on the same plot and customizing the line styles and colors.
Y... | ```python
import matplotlib.pyplot as plt
class LinePlot:
def __init__(self, title, xlabel, ylabel):
self.title = title
self.xlabel = xlabel
self.ylabel = ylabel
self.lines = []
def add_line(self, x_data, y_data, label, linestyle='-', color='b'):
self.lines.append((x_da... | magicoder | python |
You are tasked with implementing a function that filters an array of objects based on a specific property value and then renders the filtered results in a specific format. The code snippet provided is a part of a React component that renders a list of links based on their state property. The `renderLinks` function is r... | ```javascript
const LinkState = {
AWESOME: 'awesome',
DEFAULT: 'default'
};
function renderLinks(links) {
const renderLink = link => (
<li key={link.id}>
<a href={link.url}>{link.name}</a>
</li>
);
const awesomeLinks = links.filter(link => link.state === LinkState.AWESOME).map(renderLink);
c... | magicoder | javascript |
You are tasked with implementing a custom exception class and a function that utilizes this exception to handle parsing errors in a key-value pair dictionary.
Write a Python function `parse_dict` that takes a dictionary `input_dict` as input and returns a new dictionary where the keys are converted to uppercase and th... | ```python
from typing import Dict
class ParseException(Exception):
def __init__(self, msg: str, kv_pair: Dict, *args: object) -> None:
super().__init__(*args)
self.msg = msg
self.kv_pair = kv_pair
def parse_dict(input_dict: Dict) -> Dict:
result_dict = {}
for key, value in input_di... | magicoder | python |
You are working on a software tool for managing materials in a 3D modeling application. The code snippet provided is a part of a function that aims to clean up the names of materials by removing unorthodox characters and creating unique names for each material. The function `cleanMaterials()` retrieves the list of mate... | ```python
def findNameMaterial(material_name, existing_materials, counter):
clean_name = ''.join(e for e in material_name if e.isalnum() or e.isspace()) # Remove unorthodox characters
unique_name = clean_name
while unique_name in existing_materials: # Check if the name already exists
unique_name =... | magicoder | python |
You are tasked with creating a JavaScript function that processes data from a PHP backend and populates an object with the retrieved information. The PHP code snippet provided is responsible for outputting the JavaScript object's initial state. Your task is to complete the JavaScript function by implementing the `getFi... | ```javascript
// Define the Inline object
var Inline = {
fields: getFieldsWithInlineTag(), // Populate the fields property with data from the getFieldsWithInlineTag method
primaryKey: "<?php echo \REDCap::getRecordIdField(); ?>" // Set the primaryKey property to the value returned by REDCap::getRecordIdField functi... | magicoder | javascript |
You are tasked with implementing a custom data structure that supports the following operations efficiently:
1. `add(obj)`: Add the given object `obj` to the data structure.
2. `remove(obj)`: Remove the given object `obj` from the data structure if it exists.
3. `getRandom()`: Return a random object from the data stru... | ```python
import random
class RandomizedSet:
def __init__(self):
self.val_to_index = {}
self.values = []
def insert(self, val: int) -> bool:
if val in self.val_to_index:
return False
self.val_to_index[val] = len(self.values)
self.values.append(val)
r... | magicoder | python |
You are tasked with creating a custom password field for a user account model in a Django application. The custom password field should be read-only and use a hash for storing the password securely. Your task is to implement the custom password field and ensure that it is integrated correctly with the UserAccount model... | ```python
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.db import models
class CustomUserManager(BaseUserManager):
def create_user(self, email, password=None, **extra_fields):
if not email:
raise ValueE... | magicoder | python |
You are given a list of dictionaries `b`. Each dictionary contains a single key-value pair, where the key is a lowercase letter and the value is an integer. Your task is to write a function `sort_dicts_by_value(b)` that sorts the list of dictionaries based on the integer values in ascending order and returns the sorted... | ```python
def sort_dicts_by_value(b):
return sorted(b, key=lambda x: list(x.values())[0])
# Test the function with the given input
b = [{'b': 2}, {'a': 1}]
print(sort_dicts_by_value(b)) # Output: [{'a': 1}, {'b': 2}]
``` | magicoder | python |
You are tasked with creating a Python function that processes a given string and returns a modified version of the string based on specific rules. The function should take a string as input and perform the following operations:
1. If the input string contains any lowercase letters, convert them to uppercase.
2. If the... | ```python
import re
def process_string(input_string):
modified_string = input_string.upper() # Convert lowercase letters to uppercase
modified_string = re.sub(r'\d', '', modified_string) # Remove digits
modified_string = re.sub(r'[^a-zA-Z\s]', ' ', modified_string) # Replace special characters with spac... | magicoder | python |
You are tasked with implementing a function to validate RGB color values. The function should accept either an RGB color object, a string representation of an RGB color, or a null value. The RGB color object is represented by the following interface:
```typescript
interface RgbColor {
red: number;
green: number;
... | ```typescript
function isValidRgb(value: RgbColor | string | null): boolean {
const rgb = typeof value === 'string' ? parseRgb(value) : value;
if (!rgb) {
return false; // Handle null values
}
if (typeof rgb === 'string') {
return false; // Invalid string format
}
return (
isBetween(rgb.red, 0, ... | magicoder | typescript |
You are tasked with creating a Java class that interacts with the Google Fit API to retrieve and display the user's step count data. The class should handle the setup of a Google API client, request step count data from the Google Fit API, and display the retrieved step count data.
Your task is to complete the impleme... | ```java
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.fitness.Fitness;
import com.google.android.gms.fitness.data.DataSet;
import com.google.android.gms.fitness.data.DataType;
import com.google.android.gms.fitness.request... | magicoder | java |
You are tasked with creating a Python function that evaluates a machine learning model's performance and updates a controller object with the accuracy score. The function should take in a trained model, test data, test labels, and a boolean flag for plotting the confusion matrix. The function should use the model to ma... | ```python
import matplotlib.pyplot as plt
from joblib import load
from sklearn.metrics import accuracy_score, plot_confusion_matrix
def evaluate_and_update_controller(controller, trained_model, test_data, test_labels, plot=True):
predictions = trained_model.predict(test_data)
accuracy = round(accuracy_score(te... | magicoder | python |
You are working on a project that involves analyzing 3D images to identify spots of interest within the image. You have been given a Python function `get_spot_context` that takes in an image, a set of spots, voxel dimensions, and a radius, and is supposed to return the context of each spot within the image. However, th... | ```python
import numpy as np
def get_spot_context(image, spots, vox, radius):
"""
Returns the context of each spot within the image.
Args:
image (ndarray): A 3D image array.
spots (ndarray): An array of shape (N, 3) containing the coordinates of the spots.
vox (float): Voxel dimensions.
ra... | magicoder | python |
You are working on a 3D visualization application that involves manipulating layers and their corresponding visuals. The code snippet provided is a part of a class that manages the interaction between layers and their visuals. The `for` loop iterates through selected layers and their visuals, updating the shading filte... | ```python
import numpy as np
class VisualizationManager:
def __init__(self, selected_layers, selected_layer_visuals, view_direction, viewer):
self.selected_layers = selected_layers
self.selected_layer_visuals = selected_layer_visuals
self.view_direction = view_direction
self._viewer... | magicoder | python |
You are working on a machine learning library and need to implement a class for loading and using different types of models. The code snippet provided demonstrates the usage of the model loading and fitting functionality. Your task is to implement the `load_model` function and the classes `RandomForestClassifier` and `... | ```python
from sklearn.ensemble import RandomForestClassifier as SklearnRandomForestClassifier, RandomForestRegressor as SklearnRandomForestRegressor
class RandomForestBase:
def __init__(self, model_file, cursor, n_estimators):
self.model_file = model_file
self.cursor = cursor
self.n_estima... | magicoder | python |
You are tasked with implementing a function to compute the dominance frontier of a control flow graph. The dominance frontier of a node in a control flow graph is the set of nodes whose immediate dominator is not the node's dominator, but the node's predecessor is. In simpler terms, the dominance frontier of a node con... | ```python
class ControlFlowGraph:
def __init__(self, nodes, edges, dominators, predecessors, successors):
self.nodes = nodes
self.edges = edges
self.dominators = dominators
self.predecessors = predecessors
self.successors = successors
def compute_dominance_frontier(self,... | magicoder | python |
You are given a Python class `PossibilitySpace` that represents a card game's possibility space. The class has been initialized with various attributes related to points and card suits. Your task is to implement a method within this class that calculates the total number of possible card combinations based on the given... | ```python
class PossibilitySpace:
def __init__(self):
self.points = list(range(0, 11))
self.clubs_points = list(range(0, 11))
self.diamonds_points = list(range(0, 11))
self.hearts_points = list(range(0, 11))
self.spades_points = list(range(0, 11))
self.clubs_might = ... | magicoder | python |
You are tasked with creating a program that will parse an HTML snippet and extract the copyright year and the name of the company or individual. The HTML snippet will always contain a `div` element with the class `col-lg-12` that includes the copyright information in the format "Copyright © <NAME> <YEAR>". Your pr... | ```python
import re
def extractCopyrightInfo(htmlSnippet):
pattern = r'Copyright © (.+?) (\d{4})'
match = re.search(pattern, htmlSnippet)
if match:
name = match.group(1)
year = match.group(2)
return (name, year)
else:
return None
```
The `extractCopyrightInfo` func... | magicoder | python |
You are tasked with implementing a data processing pipeline for analyzing particle physics data. The pipeline involves applying a series of selection criteria to the data and then performing specific calculations on the selected events. Your task is to write a Python function that processes the data using the given cod... | ```python
def process_data(input_data, output_file_path):
try:
selected_events = 0
for event in input_data:
if 'Muon_Charge[0]' in event and 'Muon_Charge[1]' in event:
if event['Muon_Charge[0]'] == -1 * event['Muon_Charge[1]']:
selected_events += 1
... | magicoder | python |
You are tasked with creating a Python function that processes a given GitHub repository's metadata to extract relevant information. The metadata is provided in the form of a string, where each line represents a specific piece of information. Your function should extract the number of stars the repository has received a... | ```python
def extract_repo_info(metadata: str) -> dict:
repo_info = {'stars': 0, 'version': ''}
lines = metadata.split('\n')
for i in range(len(lines)):
if lines[i].startswith('<gh_stars>'):
repo_info['stars'] = int(lines[i].split('<gh_stars>')[1])
elif lines[i] == 'from ._versio... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.