query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a service distribution system that efficiently updates and rebuilds the distribution whenever a profile is updated. The system should be able to reuse existing services from the prior state to minimize resource usage.
You are given a list of services and their corresponding profiles. ... | To solve this problem, we can use a data structure such as a set or a map to store the existing services in the prior state. When the profile is updated, we can iterate through the updated profile and check if each service already exists in the prior state. If a service exists, we can reuse it; otherwise, we add the up... | magicoder | python |
You are tasked with creating a function to visualize persons detected in an image using OpenCV in Python. The function should take an input image and a list of dictionaries, where each dictionary represents a person's bounding box and label. The function should draw bounding boxes around each person and label them with... | ```python
import cv2
import numpy as np
def visualize_persons(img, person_dicts):
for person in person_dicts:
bbox = person['bbox']
label = person['label']
x_min, y_min, x_max, y_max = bbox
color = (0, 255, 0) # BGR color for bounding box (green in this case)
thickness = 2 ... | magicoder | python |
You are tasked with creating a password validation function for a user registration system. The function should take in two passwords, a name, a list of modes, a homepage URL, an API URL, a MIPTA URL, a phone number, and an email address. The function should perform the following validations:
1. Check if the two passwo... | ```python
import re
def validate_registration(password1, password2, name, modes, homepage, api_url, miptaurl, phone, email):
# Check if the two passwords match
if password1 != password2:
return "Passwords do not match"
# Ensure that the password meets the criteria
if not re.match(r'^(?=.*[A-Z]... | magicoder | python |
You are tasked with implementing a class `ArbitraryIntervals` that supports the following operations on a set of arbitrary intervals:
1. `add_interval(start, end)`: Add a new interval `[start, end]` to the set. If the new interval overlaps with existing intervals, merge them into a single interval.
2. `remove_interval... | ```python
class ArbitraryIntervals:
def __init__(self):
self.intervals = []
def add_interval(self, start, end):
new_interval = [start, end]
merged_intervals = []
for interval in self.intervals:
if interval[1] < new_interval[0] or interval[0] > new_interval[1]:
... | magicoder | python |
You are tasked with implementing a custom exception class in C++. Your exception class should inherit from the standard `std::exception` class and provide a custom error message. Additionally, you need to create a function that throws an instance of your custom exception class and handle the exception in the main progr... | ```cpp
#include <iostream>
#include <exception>
class CustomException : public std::exception {
public:
CustomException(const char* message) : errorMessage(message) {}
const char* what() const noexcept override {
return errorMessage;
}
private:
const char* errorMessage;
};
void throwCustomEx... | magicoder | cpp |
You are tasked with implementing a generic dependency injection framework in Swift. The framework should allow the user to define providers for different types and then use these providers to create instances of elements. The providers are responsible for providing the necessary dependencies to the element factories.
... | ```swift
// Define the Provider type
class Provider<T> {
private let instance: T
init(instance: T) {
self.instance = instance
}
func get() -> T {
return instance
}
}
// Define the Element type
class Element<Argument, Output> {
private let factory: (Argument) -> Output
... | magicoder | swift |
You are tasked with creating a leaderboard system for a coding competition. The competition is hosted by GNOME, and the leaderboard will display the top contributors based on their points earned through project contributions. Each contributor has a name and a point total associated with their contributions.
You need t... | ```python
class Leaderboard:
def __init__(self):
self.contributors = {} # Dictionary to store contributors and their points
def add_contributor(self, name, points):
if name in self.contributors:
raise ValueError("Contributor already exists")
self.contributors[name] = points... | magicoder | python |
You are given an array `a` of length `n`. Your task is to find the maximum element to the left of each element in the array. You need to store these maximum values in an array `lmax` such that `lmax[i]` contains the maximum element in the subarray `a[0:i]` (inclusive).
For example, if the input array `a` is `[3, 1, 5,... | ```python
from typing import List
def find_left_max(a: List[int]) -> List[int]:
n = len(a)
lmax = [0]*n
lmax[0] = a[0]
for i in range(1, n):
lmax[i] = max(lmax[i-1], a[i])
return lmax
``` | magicoder | python |
You are tasked with creating a program that processes SQL template strings to extract specific information. The SQL template string follows a specific format and contains placeholders for variables. Your task is to write a function that takes the SQL template string as input and returns a dictionary containing the extr... | ```python
import re
def extract_sql_info(sql_template):
selected_columns = re.findall(r'Select (.*?) FROM', sql_template, re.IGNORECASE)[0].split(', ')
table_names = re.findall(r'FROM (.*?) WHERE', sql_template, re.IGNORECASE)[0].split(', ')
where_conditions = re.findall(r'WHERE (.*)', sql_template, re.IGN... | magicoder | python |
You are tasked with designing a Python class that manages contract event loggers for Ethereum smart contracts. The class should handle the retrieval of new entries from logs for transfer and approval events. You are provided with a code snippet that initializes an empty list called `approval_tasks` and iterates through... | ```python
class ContractEventManager:
def __init__(self, addresses_to_contracts, contract_event_loggers):
self._addresses_to_contracts = addresses_to_contracts
self._contract_event_loggers = contract_event_loggers
def retrieve_new_transfer_entries(self, block_hashes):
transfer_tasks = [... | magicoder | python |
You are tasked with implementing a Python class for a color sensor device. The class should include a method to calculate the color currently being viewed based on the sensor readings. The color is determined by comparing the sensor readings to baseline values obtained during initialization.
Your task is to complete t... | ```python
class ColorSensor(I2CDevice):
def __init__(self):
I2CDevice.__init__(self, 1, 0x00, config='tcs3472_i2c.yaml')
self.get_baseline()
@property
def color(self):
"""Actual color currently being viewed."""
current_readings = self.get_sensor_readings() # Obtain current ... | magicoder | python |
You are working on a quantum chemistry software project and are tasked with implementing a function to calculate the kernel of a many-body perturbation (MP) theory. The kernel function takes several arguments, including the molecular orbitals (mo_coeff), orbital energies (mo_energy), and electron repulsion integrals (e... | ```python
def kernel(mp, mo_energy=None, mo_coeff=None, eris=None, with_t2=WITH_T2, verbose=logger.NOTE):
if mp.mo_energy is None or mp.mo_coeff is None:
mo_coeff_init = mp._scf.mo_coeff # Initialize mo_coeff_init with the molecular orbitals from the mean-field calculation
mo_coeff = mp._scf.mo_coe... | magicoder | python |
You are tasked with implementing a simple module system in a JavaScript application. The module system should allow for the export and import of modules between different files. The code snippet provided is an example of an export statement in JavaScript, which exports the `Dock` module from a file called "Dock.js".
Y... | ```javascript
function importModule(moduleName, filePath) {
// Simulate file loading and module extraction
const fileContent = loadFile(filePath); // Assume this function loads the content of the file
const moduleExports = {};
const moduleScope = {
exports: moduleExports
};
const moduleFunction = new Fu... | magicoder | javascript |
You are tasked with creating a Python function that utilizes the TensorFlow library to build a custom neural network model for image classification. Your function should take in the number of classes for the classification task and return a compiled neural network model with specific architecture and configurations.
W... | ```python
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import GlobalAveragePooling2D, Dense, Dropout
from tensorflow.keras.applications import VGG16
def create_image_classifier_model(num_classes):
# Load the pre-trained VGG16 model without the top layers
b... | magicoder | python |
You are tasked with implementing a search function for a custom search engine using C#. The function should take in a search text, a boolean flag indicating whether to use wildcards, a LuceneSearcher provider, and an index type. The function should return a XPathNodeIterator containing the search results.
Your task is... | ```csharp
internal static XPathNodeIterator Search(string searchText, bool useWildcards, LuceneSearcher provider, string indexType)
{
// Construct the query based on the search text and wildcards flag
string query = useWildcards ? $"*{searchText}*" : searchText;
// Use the LuceneSearcher provider to perfor... | magicoder | csharp |
You are tasked with simulating the behavior of a cellular automaton known as Conway's Game of Life. In this game, a grid of cells evolves through discrete time steps based on a set of rules. Each cell can be in one of two states: alive or dead. The rules for the evolution of the grid are as follows:
1. Any live cell wi... | ```python
from typing import List
def game_of_life(board: List[List[bool]]) -> None:
rows, cols = len(board), len(board[0])
directions = [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, -1), (1, -1), (-1, 1)]
def count_live_neighbors(row, col):
count = 0
for dr, dc in directions:
... | magicoder | python |
You are tasked with simulating a simple thread management system for a multi-threaded application. The system is responsible for creating, executing, and tracking the elapsed time of threads. Each thread is associated with a specific task and is executed sequentially.
You are provided with a code snippet that demonstr... | ```python
import time
class Thread:
def __init__(self, name):
self.name = name
self.start_time = None
self.end_time = None
def read(self, source, data):
# Simulate reading data with a time delay
time.sleep(1)
print(f"Thread '{self.name}' read data: {hex(data)}")... | magicoder | python |
You are tasked with implementing a DNS tracing tool that follows the chain of authority to resolve a domain name. The tool will perform DNS queries starting at the root Internet name servers and continue following the specified authorities until it finds an answer.
Your task is to implement the `trace` function that t... | ```rust
use trust_dns::client::{Client, SyncClient};
use trust_dns::op::Message;
use trust_dns::rr::{DNSClass, Name, RecordType};
use trust_dns::udp::UdpClientConnection;
fn trace(domain: &str) -> Result<String, String> {
let root_servers = vec!["198.41.0.4", "192.228.79.201", "192.33.4.12", "199.7.91.13", "192.20... | magicoder | rust |
You are tasked with creating a program to assist in the process of merging and editing datasets. The program should take an existing "silver" dataset with binary accept/reject annotations and merge the annotations to find the best possible analysis given the constraints defined in the annotations. After merging, the pr... | ```python
from typing import List, Optional
def merge_and_edit_dataset(
silver_dataset: List[str],
annotations: Optional[List[str]] = None
) -> List[str]:
"""
Merge the annotations with the existing "silver" dataset to find the best possible analysis given the constraints defined in the annotations,
... | magicoder | python |
You are tasked with implementing a custom data structure to represent a directed graph. The graph will consist of nodes and edges, where each node can have multiple outgoing edges to other nodes. Your task is to create a class `DirectedGraph` that supports the following operations:
1. `addNode(nodeId)`: Adds a new node... | ```java
import java.util.*;
class DirectedGraph {
private Map<String, List<String>> adjacencyList;
public DirectedGraph() {
this.adjacencyList = new HashMap<>();
}
public void addNode(String nodeId) {
if (!adjacencyList.containsKey(nodeId)) {
adjacencyList.put(nodeId, new ... | magicoder | java |
You are tasked with creating a program that simulates a simple banking system. The system should be able to create and manage bank accounts, allowing users to deposit, withdraw, and check their balance. Additionally, the program should support transferring funds between accounts.
Your task is to implement the `Bank` s... | ```rust
struct Account {
holder_name: String,
account_number: u32,
balance: f64,
}
impl Account {
fn new(holder_name: String, account_number: u32) -> Account {
Account {
holder_name,
account_number,
balance: 0.0,
}
}
fn deposit(&mut self, amo... | magicoder | rust |
You are tasked with creating a role-based access control system for a web application. The application has two user roles: "Admin" and "Employee". You need to implement a method that checks whether a given user has the necessary role to access a specific feature.
You are provided with a class `CustomRole` that contain... | ```csharp
using System;
namespace Workers.Web.Infrastructure.Constants
{
public class CustomRole
{
public const string Admin = "Admin";
public const string Employee = "Employee";
public static bool CheckUserRole(string userRole, string requiredRole)
{
if (userRole =... | magicoder | csharp |
You are tasked with implementing a Python class that handles the serialization of synthetic enzyme data. The class should provide methods for both standard and long-form serialization, as well as the ability to log the serialization process to a JSON file.
Your task is to create a class `SynthaseSerializer` with the f... | ```python
import logging
class SynthaseSerializer:
_json_loaded = False
def __init__(self, synthases):
self.synthases = synthases
def to_standard(self, long_form=False, output=None):
if long_form:
print(self.synthases.to_long(), flush=True, file=output)
else:
... | magicoder | python |
You are tasked with creating a class decorator in TypeScript that validates the length and non-empty nature of a property. The decorator should ensure that the property is a string, not empty, and does not exceed a specified maximum length. Your task is to implement the class decorator `ValidateStringProperty` that can... | ```typescript
// Define the StatusCode enum for context codes
enum StatusCode {
IS_NOT_EMPTY = 'IS_NOT_EMPTY',
MAX_LENGTH = 'MAX_LENGTH',
}
// Create the ValidateStringProperty decorator
function ValidateStringProperty(maxLength: number) {
return function (target: any, propertyKey: string) {
let value: strin... | magicoder | typescript |
You are tasked with creating a Java class that represents a product with various attributes. The class should be designed to be serialized to JSON using the Jackson library. Below is a partial code snippet for the product class:
```java
import com.fasterxml.jackson.annotation.JsonProperty;
public class Product {
... | ```java
import com.fasterxml.jackson.databind.ObjectMapper;
public class Product {
@JsonProperty("name")
private String name = null;
@JsonProperty("currency_id")
private String currencyId = null;
@JsonProperty("cost")
private Integer cost = null;
// Constructor, getters, setters, and any... | magicoder | java |
You are tasked with creating a Python program that simulates a simplified web page fetching and processing system using asyncio. The program will fetch multiple web pages concurrently, wait for their completion, and then process the responses. Your goal is to implement the necessary functions and logic to achieve this.... | ```python
import asyncio
async def fetch_page(url):
# Simulate fetching the web page content asynchronously
# For demonstration purposes, we'll use a simple sleep to simulate the fetch operation
await asyncio.sleep(1) # Simulate fetching the page content
return f"Content of {url}" # Simulated fetched... | magicoder | python |
You are tasked with implementing a simplified version of a mail system in Python. Your goal is to create a class that represents an email message and a mail system that can send and receive these messages. The `Mail` class should have the following functionalities:
- A method `send_mail` that takes a `Message` object a... | ```python
class Mail:
def __init__(self, app):
self.mailbox = {}
self.app = app
def send_mail(self, message):
if message.recipient in self.mailbox:
self.mailbox[message.recipient].append(message)
else:
self.mailbox[message.recipient] = [message]
def ... | magicoder | python |
You are working on a neuroimaging data analysis pipeline using the AFNI software suite. As part of the pipeline, you need to write a script to apply cluster results to each output file and then perform the same operation on NIfTI files with a liberal threshold.
You have a code snippet that uses various AFNI commands a... | ```bash
#!/bin/bash
# Obtain FWHM values from blur_est.1D
fxyz=( `tail -1 blur_est.1D` )
# Perform cluster simulation
3dClustSim -both -NN 123 -mask mask.nii.gz -fwhmxyz ${fxyz[@]:0:3} -prefix ClustSim
# Apply cluster results to each output file
for cname in "${contrasts[@]}"; do
# Apply cluster results using 3dre... | magicoder | shell |
You are tasked with implementing a custom logging system for a Python application. The logging system should support different log levels and be able to write log messages to a file. You are provided with a basic logger module called `easy_logger`, which contains the following functions:
1. `set_log_level(level)`: Thi... | ```python
from .easy_logger import set_log_level, log_message
class CustomLogger:
def __init__(self, log_file):
self.log_file = log_file
def debug(self, message):
set_log_level("DEBUG")
log_message(f"[DEBUG] {message}", "DEBUG")
def info(self, message):
set_log_level("INFO... | magicoder | python |
You are tasked with creating a Python script that automates the process of setting up a new Anaconda environment on a Linux system. The script should install Anaconda, create a new conda environment, and activate it. Your script should take the following inputs:
- `install_dir`: The directory where Anaconda will be ins... | ```python
import os
import subprocess
def setup_conda_environment(install_dir, env_name):
if not os.path.exists(install_dir):
# Download and install Anaconda
anaconda_installer_url = 'https://repo.anaconda.com/archive/Anaconda3-2020.11-Linux-x86_64.sh'
subprocess.run(['wget', anaconda_insta... | magicoder | python |
You are tasked with implementing a program to extract linguistic constructions from a given UCCA corpus. The UCCA (Uniform CoNstructional Annotation) corpus is a linguistic resource that annotates text with a graph-based representation of its grammatical structure. The program should take as input the corpus in the for... | ```python
import argparse
import constructions # Assuming the constructions module is available
from ucca_corpus_reader import read_files_and_dirs # Assuming the ucca_corpus_reader module is available
def main():
argparser = argparse.ArgumentParser(description="Extract linguistic constructions from UCCA corpus."... | magicoder | python |
You are tasked with implementing a method to set the positions of objects in a 2D space. The method should take a list of objects and arrange them in a grid-like pattern, ensuring that no two objects occupy the same position. The objects should be positioned in a way that minimizes the total distance between them.
You... | ```java
public void SetPosiciones(List<Object> objects) {
int n = objects.size();
List<Object> sortedObjects = new ArrayList<>(objects);
sortedObjects.sort(Comparator.comparingInt(o -> o.X * n + o.Y));
int[] dx = {0, 0, 1, -1};
int[] dy = {1, -1, 0, 0};
boolean[][] occupied = new boolean[n * 2... | magicoder | java |
You are tasked with implementing a photo editing feature that allows users to crop images within a specified rectangular overlay. The provided code snippet is part of a larger photo editing application and contains methods related to image cropping and manipulation.
Your task is to implement the `crop()` method and th... | ```swift
// Implementing the crop() method
func crop() {
// Calculate the new image rectangle based on the overlay rectangle and image ratio
let newImageRect = convertToImageRect(CGRect(origin: CGPoint(x: overlayRect.origin.x - leftPadding, y: overlayRect.origin.y - topPadding), size: overlayRect.size), ratio: ... | magicoder | swift |
You are tasked with implementing a simple buffered output system in Rust. The system should allow for writing to a buffer and then flushing the buffer to the standard output. You are provided with a code snippet that sets up the initial infrastructure for the buffered output system using Rust's standard library.
Your ... | ```rust
use std::io::{self, Write};
use std::sync::{Mutex, Arc};
lazy_static::lazy_static! {
static ref BUFFER: Mutex<Vec<u8>> = Mutex::new(Vec::new());
pub static ref LINE_STDOUT: Arc<Mutex<io::LineWriter<io::Stdout>>> = {
let stdout = io::stdout();
Arc::new(Mutex::new(io::LineWriter::new(stdo... | magicoder | rust |
You are tasked with creating a Python class that simulates a simple banking system. The class should have methods for depositing funds, withdrawing funds, checking the balance, and displaying the account information. Additionally, the class should incorporate basic security features to prevent unauthorized access.
You... | ```python
import random
class BankAccount:
def __init__(self, initial_balance):
self.account_number = random.randint(100000, 999999)
self.balance = initial_balance
self.is_locked = False
def deposit(self, amount):
if not self.is_locked:
self.balance += amount
... | magicoder | python |
You are tasked with implementing a GUI-based encryption tool using Python's tkinter library. The provided code snippet is a part of the GUI setup for the encryption tool. The snippet includes event bindings for the "Return" key, configuration settings for disabled elements, and window position adjustment.
Your task is... | ```python
def encrypt(data, root, combo_mode, combo_key_type, entry_key, combo_iv_type, entry_iv):
# Obtain the selected encryption mode, key type, and IV type from the GUI elements
selected_mode = combo_mode.get()
selected_key_type = combo_key_type.get()
selected_iv_type = combo_iv_type.get()
... | magicoder | python |
You are tasked with creating a Python function that processes and splits a dataset into training and testing sets. The dataset consists of features and corresponding classes, and the function should perform the following steps:
1. Concatenate three sets of features (DatasetFeatures1, DatasetFeatures2, DatasetFeatures3... | ```python
import json
import random
def process_and_split_dataset(DatasetFeatures1, DatasetFeatures2, DatasetFeatures3, DatasetClasses1, DatasetClasses2, DatasetClasses3, iterator):
# Concatenate features and classes
DatasetFeatures = DatasetFeatures1 + DatasetFeatures2 + DatasetFeatures3
DatasetClasses = ... | magicoder | python |
You are tasked with creating a program that simulates a simple network client-server interaction. The server is listening on localhost at port 9090, and upon receiving a specific message, it performs an operation and sends back a response. The client program needs to send the message to the server and display the hexad... | ```bash
#!/bin/bash
# Function to send message to server and display hexadecimal dump of response
send_message() {
echo -e '\x04\x00\x00\x00\x4D\x3C\x2B\x1AABCD' | nc localhost 9090 | hd
}
# Loop to send message to server 10 times concurrently
for ((i=0; i<10; i++)); do
send_message &
done
# Wait for all con... | magicoder | shell |
You are tasked with implementing a function that extracts the class names from a given HTML code snippet. The function should take the HTML code as input and return a list of unique class names found within the code.
Write a function `extract_class_names(html_code: str) -> List[str]` that takes a string `html_code` re... | ```python
from bs4 import BeautifulSoup
import re
def extract_class_names(html_code: str) -> List[str]:
class_names = set()
soup = BeautifulSoup(html_code, 'html.parser')
for tag in soup.find_all(attrs={'class': re.compile(r'\b')}):
class_names.update(tag.get('class', []))
return list(class_nam... | magicoder | python |
You are tasked with implementing a Python function to perform image augmentation using the imgaug library. Image augmentation is a common technique used in machine learning and computer vision to artificially expand the size of a training dataset by applying various transformations to the original images. The imgaug li... | ```python
import imgaug.augmenters as iaa
import numpy as np
def aug_out_scale(img):
seq = iaa.Sequential([iaa.Affine(scale={"x": (0.8, 1.2), "y": (0.8, 1.2)})])
img = seq.augment_image(img)
img = img.astype('float32') / 255.0
return img
def aug_out_featurewise_tr(img):
seq = iaa.Sequential([iaa.S... | magicoder | python |
You are tasked with implementing a custom adapter class for a list of accounts in an Android application. The adapter will be used to display the accounts in a RecyclerView and allow for drag-and-drop functionality. The provided code snippet is the constructor of the adapter class, which takes an instance of a ToolbarA... | ```java
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.Collections;
import java.util.List;
public class AdapterAccounts extends RecyclerView.Adapter<AdapterAccounts.AccountViewHolder> implements ItemTouchHelpe... | magicoder | java |
You are tasked with implementing a simple game where a player navigates through a grid-based maze. The maze is represented as a 2D grid, where each cell can be either empty (denoted by '0') or blocked (denoted by '1'). The player can move up, down, left, or right, but cannot move into blocked cells. The player starts a... | ```python
from typing import List
def canReachEnd(maze: List[List[int]]) -> bool:
rows, cols = len(maze), len(maze[0])
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
def dfs(row, col):
if row < 0 or row >= rows or col < 0 or col >= cols or maze[row][col] == 1:
return False
if ... | magicoder | python |
You are tasked with implementing a simple virtual machine that can perform arithmetic operations on integers of various sizes. The virtual machine operates on a stack-based architecture and supports four basic arithmetic operations: addition, subtraction, multiplication, and division. Additionally, the virtual machine ... | ```rust
#[derive(Debug)]
enum OperandSize {
Byte,
Word,
Dword,
Qword,
}
fn execute_arithmetic_operation(stack: &mut Vec<i64>, operation_code: u8, operand_size: Option<OperandSize>) {
if stack.len() < 2 {
return; // Not enough elements on the stack to perform the operation
}
let ope... | magicoder | rust |
You are tasked with implementing a custom validation system for a MongoDB database using the Java MongoDB driver. The `ValidationOptions` class provides a way to configure validation rules for a collection in MongoDB. Your goal is to create a program that sets up validation options for a collection and then retrieves t... | ```java
import org.bson.conversions.Bson;
import com.mongodb.client.model.ValidationOptions;
import com.mongodb.client.model.ValidationLevel;
import com.mongodb.client.model.ValidationAction;
import org.bson.Document;
public class MongoDBValidationExample {
public static void main(String[] args) {
// Creat... | magicoder | java |
You are tasked with optimizing the execution of a Java application running on a cloud server. The provided code snippet is a Bash script used to start the Java application in a detached screen session. The script specifies various JVM options to optimize the application's performance and memory usage. Your goal is to a... | ```bash
#!/bin/bash
screen -S cloud java -XX:+UseG1GC -XX:+UseStringDeduplication -XX:MaxGCPauseMillis=20 -XX:G1HeapRegionSize=4M -XX:MaxHeapSize=512m -XX:InitialHeapSize=256m -XX:+UnlockExperimentalVMOptions -XX:G1NewSizePercent=20 -XX:G1MaxNewSizePercent=50 -jar runner.jar
```
Explanation:
1. `-XX:+UseG1GC`: Enables... | magicoder | shell |
You are tasked with implementing a function that validates and parses a given input to produce a specific output. The input consists of a sequence ID and a dot-bracket structure. The sequence ID is a string representing an identifier, and the dot-bracket structure is a string containing a sequence of characters, where ... | ```typescript
/**
* Represents the parsed and validated dot-bracket structure.
* This is a placeholder for the actual data structure used to represent the structure.
*/
type Structure = any; // Replace 'any' with the actual data structure type
/**
* Represents the input object containing sequenceId and dotBracket.... | magicoder | typescript |
You are tasked with implementing a parser for a specific file format that contains account numbers. Each account number is represented as a series of lines, where each line contains a sequence of characters that form a digit. Your goal is to write a parser that takes the raw lines as input and returns an array of accou... | ```python
class AccountNumberParser:
def __init__(self):
pass
def parse(self, raw_lines):
account_numbers = []
for i in range(0, len(raw_lines), 3):
account_number = ""
for j in range(9):
digit = ""
for k in range(3):
... | magicoder | python |
You are tasked with creating a Python function that merges batches of data from a specified folder using multiprocessing. Your task is to implement the `mergeBatches` function, which takes in several parameters to perform the merging operation efficiently.
The function signature is as follows:
```python
def mergeBatch... | ```python
import os
import multiprocessing
import pandas as pd
def mergeBatches(dataFolder, extractionFunc, extractionKwargs, ncpus, testsamples, testbatch, outFile, metaCols=None, filters=None, useFeather=False):
# Function to apply extraction logic to a single batch
def process_batch(batch_file):
# A... | magicoder | python |
You are tasked with creating a database migration for an event booking system using Laravel's Eloquent ORM. The database schema should include fields for event booking entries, such as event code, membership type, contact person, registration type, member number, names, ID number, and registration number.
Your task i... | ```php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateEventBookingEntryTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create... | magicoder | php |
You are tasked with implementing a function to reverse a singly linked list. You are given the definition of a ListNode class as follows:
```cpp
template <typename T>
class ListNode
{
public:
T value;
ListNode<T>* next = nullptr;
~ListNode() { delete next; }
};
```
You need to implement the following func... | ```cpp
template <typename T>
ListNode<T>* reverseList(ListNode<T>* head) {
ListNode<T>* prev = nullptr;
ListNode<T>* curr = head;
ListNode<T>* next = nullptr;
while (curr != nullptr) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev... | magicoder | cpp |
You are tasked with creating a script to validate the existence and executability of a list of executables. The script should iterate through the list of executables and check if each one exists and is executable. If an executable is not found or is not executable, an error message should be printed to the standard err... | ```bash
#!/bin/bash
EXECUTABLES="executable1 executable2 executable3"
################################################################################
# check executables exist and are executable
################################################################################
for exec in $EXECUTABLES; do
if [[ ! -f... | magicoder | shell |
You are tasked with implementing a throttle controller for an autonomous vehicle. The vehicle's throttle, brake, and steering commands are determined based on the cross-track error (cte), sample time, linear velocity, current velocity, deceleration limit, vehicle mass, and wheel radius. The throttle controller is respo... | ```python
def throttle_controller_step(self, cte, sample_time):
throttle = 0
brake = 0
if linear_velocity == 0 and current_velocity < 0.1:
throttle = 0
brake = 400
elif throttle < 0.1 and cte < 0:
throttle = 0
decel = max(cte, self.decel_limit)
brake = abs(de... | magicoder | python |
You are tasked with implementing a user management system for a web application. The system has three types of users: regular users, admins, and super-admins. Each user has the ability to delete other users based on their role. The following rules apply:
- Regular users can only delete themselves.
- Admins can delete o... | ```javascript
import { request } from '../base'
function deleteUser(deletingUser, userToDelete) {
return new Promise((resolve, reject) => {
if (deletingUser.id === userToDelete.id) {
resolve("You cannot delete yourself.");
} else if (deletingUser.role === 'regular' && deletingUser.id !== userToDelete.i... | magicoder | javascript |
You are tasked with creating a JavaScript function that processes date ranges and retrieves case numbers from local storage. The function should perform the following tasks:
1. Check the current month and format it with a leading zero if it is less than 10.
2. Set the `date_range` object with a start date of January 1s... | ```javascript
function processDateAndCases() {
let mes = (new Date().getMonth() + 1 < 10) ? '0' + (new Date().getMonth() + 1) : (new Date().getMonth() + 1);
let date_range = {
start: new Date().getFullYear() + '-01-01',
end: new Date().getFullYear() + '-' + mes + '-' + new Date().getDate()
};
if (localS... | magicoder | javascript |
You are tasked with creating a Swift function that interacts with a web service to retrieve and process JSON data. The function should handle the response from the web service and decode the JSON data into a specific Swift struct. Your task is to implement the function that accomplishes this.
You are provided with the... | ```swift
import Foundation
func retrieveAndDecode(url: URL, completion: @escaping (Result<Gist, Error>) -> Void) {
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
completion(.failure(error))
return
}
guard l... | magicoder | swift |
You are tasked with creating a shell script that automates the process of initializing a new Git repository and setting up a remote origin. The script should take the following steps:
1. Determine the absolute path of the directory containing the script and navigate to its parent directory.
2. Extract the base name of... | ```bash
#!/bin/bash
# Step 1: Determine the absolute path of the directory containing the script and navigate to its parent directory
SCRIPT_DIR=$(cd $(dirname $0) && pwd)
cd $SCRIPT_DIR/..
# Step 2: Extract the base name of the parent directory
REPO_NAME=$(basename $(pwd))
# Step 3: Initialize a new Git repository ... | magicoder | shell |
You are tasked with implementing a custom hook for form handling in a React application. The hook should provide functions for handling changes, blur events, and form submissions. Additionally, the hook should integrate with a custom components hook to access specific components for a sign-up form.
Your task is to cre... | ```javascript
// useFormHandlers.js
import { useState } from 'react';
const useFormHandlers = () => {
const [formData, setFormData] = useState({});
const handleChange = (e) => {
const { name, value } = e.target;
setFormData((prevData) => ({
...prevData,
[name]: value,
}));
};
const ha... | magicoder | javascript |
You are tasked with creating a Swift package that simulates a mock URLSession for testing network requests in iOS applications. Your goal is to implement a `MockURLSession` class that mimics the behavior of URLSession, allowing developers to define and verify expected network requests and responses in their unit tests.... | ```swift
import Foundation
// Define a struct to represent a network request
struct NetworkRequest {
let url: URL
let method: String
let body: Data?
}
// Define a struct to represent a network response
struct NetworkResponse {
let statusCode: Int
let body: Data?
}
// Define a class to simulate a ... | magicoder | swift |
You are tasked with creating a Bash script to automate the process of capturing webcam photos using the `fswebcam` command-line tool. The script should check if the `fswebcam` tool is installed, create a directory to store the photos if it does not exist, and then capture a photo using the webcam.
Your script should p... | ```bash
#!/bin/bash
photo_path="/home/swpi/webcam_photo"
# Check if fswebcam is available
if [[ -f `which fswebcam` ]]; then
# Check if the photo directory exists
if ! [[ -d $photo_path ]]; then
# Create the photo directory if it does not exist
mkdir -p $photo_path
fi
# Capture a phot... | magicoder | shell |
You are tasked with implementing a Python class for executing star operations on a query. The class `Star` inherits from `QueryCommand` and has an `execute` method that sends a PATCH request to star a specific query. The `execute` method catches any `RequestError` and raises a `BusinessError` with a custom error messag... | ```python
class QueryCommand:
def __init__(self, connection):
self.connection = connection
class PatchRequest:
def __init__(self, connection, context):
self.connection = connection
self.context = context
def execute(self):
# Implement the PATCH request logic to star a query... | magicoder | python |
You are given an array of integers `a` of size `n`. You need to perform `q` queries on this array. Each query consists of an integer `x`. For each query, you have to find the number of elements in the array `a` that are less than `x`.
Write a function or method that takes in the array `a`, its size `n`, an array of qu... | ```cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> countElementsLessThanX(int a[], int n, int queries[], int q) {
vector<int> result;
sort(a, a + n); // Sort the array to perform binary search
for (int i = 0; i < q; i++) {
int count = upper_bound(a,... | magicoder | cpp |
You are given a Python code snippet that involves manipulating quantum states using Pauli operators. Your task is to create a function that simulates the action of a Pauli operator on a quantum state and returns the resulting state and the corresponding coefficient.
You need to implement the `compute_action` function,... | ```python
import numpy as np
def compute_action(basis_state, pauli_term, length):
if pauli_term == 'sX':
new_basis_state = basis_state.copy()
new_basis_state[length - 1] ^= 1 # Bit-flip operation on the last qubit
coeff = 1 # Coefficient for sX is 1
elif pauli_term == 'sY':
ne... | magicoder | python |
You are tasked with implementing a database client factory function in Python. The function should dynamically load and instantiate the appropriate database client based on the provided database provider and connection configuration. Additionally, the function should validate the availability of the specified database ... | ```python
class InvalidDatabaseProvider(Exception):
pass
def load_db_client(db_provider):
try:
module_name = f"db_clients.{db_provider.lower()}_client"
module = __import__(module_name, fromlist=[''])
client = getattr(module, f"{db_provider}Client")
return client
except (Modu... | magicoder | python |
You are tasked with creating a PHP script that reads environment variables from a `.env` file using the `vlucas/phpdotenv` library and establishes a database connection using the configuration details from the `.env` file.
Your task is to complete the PHP script by implementing the following steps:
1. Load the environ... | ```php
<?php
// Load environment variables from the .env file
require "vendor/autoload.php";
$dotenv = Dotenv\Dotenv::create(__DIR__);
$dotenv->load();
// Include the database configuration file
require "App/database/config.php";
// Use the environment variables to establish a database connection
$host = $_ENV['DB_HO... | magicoder | php |
You are tasked with creating a function that processes a given string to extract specific information based on a predefined pattern. The pattern consists of a series of commands enclosed in curly braces, each command representing a specific action to be performed on the input string. Your task is to implement the funct... | ```swift
func processString(_ input: String, pattern: String) -> String {
var processedString = input
for command in pattern {
switch command {
case "U":
processedString = processedString.uppercased()
case "L":
processedString = processedString.lowercased()
... | magicoder | swift |
You are tasked with creating a Python program to manage a queue of tasks using multithreading and serial communication. The program should utilize the `serial` library to communicate with an external device and manage a queue of tasks using multithreading.
Your program should have the following functionalities:
1. Ini... | ```python
import serial
import sys
import threading
import time
import argparse
import struct
import queue
class TaskManager:
def __init__(self, serial_port):
self.serial_port = serial_port
self.task_queue = queue.Queue()
self.serial_connection = serial.Serial(serial_port, baudrate=9600, ti... | magicoder | python |
You are tasked with creating a custom tab bar controller for a mobile application. The tab bar controller should consist of two tabs: "Balance" and "Transactions". Each tab should be associated with a navigation controller and a corresponding view controller. The "Balance" tab should display the `BalanceController` and... | ```swift
import UIKit
class BalanceController: UIViewController {
// Implement the BalanceController view controller
// ...
}
class TransactionsController: UIViewController {
// Implement the TransactionsController view controller
// ...
}
class CustomTabBarController: UITabBarController {
overri... | magicoder | swift |
You are tasked with creating a custom exception handler for a Python web application framework. Your goal is to implement a function that raises a specific exception when a template file is not found during the rendering process.
You are provided with a basic code snippet that uses the `pytest` library to test the exc... | ```python
class TemplateNotFoundError(Exception):
pass
class View:
def render(self, template):
# Check if the template file exists
if not os.path.exists(template):
raise TemplateNotFoundError(f"Template file '{template}' not found")
# Render the template
# ... (other... | magicoder | python |
You are tasked with implementing a Java method that scales a list of Android `View` objects using the `ExpectAnim` library. The `ExpectAnim` library provides a way to create smooth and flexible animations for Android views. Your task is to complete the implementation of the `scale` method in the `Scale` class within th... | ```java
package com.github.florent37.expectanim.core.scale;
import android.view.View;
import com.github.florent37.expectanim.ExpectAnim;
import java.util.List;
public class Scale {
public static void scale(List<View> views, float scaleX, float scaleY, long duration, long delay) {
ExpectAnim expectAnim =... | magicoder | java |
You are given a code snippet that manipulates vectors in a 3D space using a custom `Vector3` class. The code snippet is part of an orthonormal basis (ONB) construction process, where three mutually perpendicular unit vectors `onb.u`, `onb.v`, and `onb.w` are being computed.
The `onb` object represents the orthonormal ... | ```java
class Vector3 {
double x, y, z;
public Vector3(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
public void normalize() {
double length = Math.sqrt(x * x + y * y + z * z);
if (length != 0) {
x /= length;
y /= ... | magicoder | java |
You are tasked with implementing a custom Polynomial class in C++. The Polynomial class should support addition, subtraction, and output operations. The class should be able to handle polynomials of any degree and should provide appropriate operator overloading for the operations.
Your task is to complete the implemen... | ```cpp
#include <iostream>
#include <vector>
class Polynomial {
private:
std::vector<double> coefficients;
public:
Polynomial(int degree) : coefficients(degree + 1, 0) {}
void setCoefficient(int degree, double coefficient) {
coefficients[degree] = coefficient;
}
double getCoefficient(int degree) const... | magicoder | cpp |
You are tasked with creating a Python function that processes the response from a REST API and extracts specific information based on the response status code and other conditions. The function should handle scenarios where a project does not exist, the response status code is 200, and certain conditions related to App... | ```python
import requests
def process_api_response(r, branch):
result = {}
if r.status_code == 404:
result["deleted"] = True
elif r.status_code == 200:
has_appveyor = _has_appveyor_any_branch(branch)
result["has_appveyor"] = has_appveyor
if has_appveyor:
appveyor... | magicoder | python |
You are tasked with creating a JavaScript function that interacts with the Ethereum blockchain using the Web3 library. Your function should send a specified amount of Ether from one Ethereum account to another. You will need to handle any potential errors and ensure that the transaction is successfully executed.
Your ... | ```javascript
import Web3 from 'web3';
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR_INFURA_API_KEY');
function sendEther(senderAddress, receiverAddress, amount) {
return new Promise((resolve, reject) => {
web3.eth.getBalance(senderAddress, (err, balance) => {
if (err) {
reject('Error g... | magicoder | javascript |
You are tasked with implementing a class for generating SQL statements based on specified parameters. The class, `Items`, takes in arguments for date range, type group, order by, and number of items to retrieve. The `write_statement` method of the class should construct and return an SQL statement based on the provided... | ```python
class Items:
def __init__(self, date_range, type_group, order_by, num_items):
self.date_range = date_range
self.type_group = type_group
self.order_by = order_by
self.num_items = num_items
def write_statement(self):
sql_statement = "SELECT * FROM items WHERE "
... | magicoder | python |
You are tasked with implementing a function that extracts class-balanced patches from full images. The function should take in full images and return class-balanced patches with a specified shape and number of channels.
You are given the following function signature and documentation:
```python
def extract_class_bala... | ```python
import numpy as np
from typing import Tuple
def extract_class_balanced_patches(full_images: np.ndarray, patch_shape: Tuple[int, int], num_channels: int) -> Tuple[np.ndarray, np.ndarray]:
"""
Extracts class-balanced patches from full images.
Args:
full_images (np.ndarray): input full imag... | magicoder | python |
You are tasked with implementing a function to calculate the virial radius of a dark matter halo in a cosmological simulation. The virial radius is defined as the radius within which the average density is a certain multiple (denoted by `odelta`) of the critical density of the universe at the redshift of the halo. The ... | ```python
import math
def calculate_virial_radius(concentration, halo_mass, odelta, critical_density):
pi = math.pi
virial_radius = (3 * halo_mass / (4 * pi * odelta * critical_density * concentration**3))**(1/3)
return virial_radius
# Example usage
concentration = 5.0
halo_mass = 1e12 # 1 trillion solar... | magicoder | python |
You are working on an image processing project and need to implement a specific set of operations on an input image using the OpenCV library in Python. Your task is to write a function that takes an input image and performs the following operations in sequence:
1. Apply a thresholding operation to the input image usin... | ```python
import cv2
import numpy as np
def image_processing(img_rec_red2):
# Apply thresholding
ret, th = cv2.threshold(img_rec_red2, 10, 255, cv2.THRESH_BINARY)
# Create a 5x5 kernel
kernel = np.ones((5, 5), np.uint8)
# Perform dilation
th = cv2.dilate(th, kernel)
# Apply G... | magicoder | python |
You are tasked with simulating a multi-agent system to navigate through a grid-based environment with obstacles. Each agent must find the shortest path from a start point to a goal point while avoiding the obstacles. The agents can move in four directions: up, down, left, and right. The goal is to determine the average... | ```python
import numpy as np
import random
from queue import PriorityQueue
import copy
# Function to generate the grid-based environment
def generate_environment(rows, cols, num_obstacles):
grid = np.full((rows, cols), '.')
grid[0][0] = 'S' # Start point
grid[rows - 1][cols - 1] = 'G' # Goal point
f... | magicoder | python |
You are tasked with implementing a function that processes a list of strings and returns a boolean value based on certain conditions. The function should iterate through the list and return True if any string contains the word 'No', and False otherwise. However, the function should also handle exceptions gracefully and... | ```python
from typing import List
def check_for_no(strings: List[str]) -> bool:
try:
for s in strings:
if 'No' in str(s):
return True
except Exception:
pass
return False
```
The `check_for_no` function iterates through the input list of strings. It checks if the ... | magicoder | python |
You are tasked with implementing a class `Tester` that has a method `test` which takes a function as an argument and returns the result of executing that function. Additionally, you need to create a program that utilizes the `Tester` class to test various functions.
Your task is to implement the `Tester` class and wri... | ```python
class Tester:
def test(self, func):
"""
Executes the given function and returns the result.
Args:
func: A function to be executed.
Returns:
The result of executing the given function.
"""
return func()
# Example usage of the Tester class
d... | magicoder | python |
You are tasked with implementing a feature flag system for a software library. The library has various features that can be enabled or disabled using feature flags. The code snippet provided is a simplified representation of the feature flag system using the Rust programming language.
The `has_xcb_xinerama_query_scree... | ```rust
// Define the feature flag "xcb_xinerama"
#[cfg(feature = "xcb_xinerama")]
mod xcb_xinerama {
// Define the symbol for the feature
pub fn xcb_xinerama_query_screens_reply() {
// Implementation for xcb_xinerama_query_screens_reply
}
}
// Define the has_sym! macro to check for the availabilit... | magicoder | rust |
You are tasked with implementing a simple panic handler for a bare-metal Rust application. The provided code snippet is a part of the panic handler function, which is called when the application encounters a panic. The `panic` function takes a reference to `PanicInfo` and returns a never type (`!`), indicating that it ... | ```rust
// Import necessary dependencies
use core::panic::PanicInfo;
// Define the PanicInfo type
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
if let Some(location) = info.location() {
serial_println!("Panic in file '{}' at line {}", location.file(), location.line());
} else {
serial_prin... | magicoder | rust |
You are tasked with implementing a class that represents a running session. The class should have a method to calculate the total number of run cycles completed during the session. A run cycle is defined as the combination of alternating periods of running and walking. The class should also have methods to record the d... | ```java
public class RunningSession {
private int runCycles;
private boolean isRunning;
public RunningSession() {
this.runCycles = 0;
this.isRunning = false;
}
public void startRunning() {
if (!isRunning) {
isRunning = true;
}
}
public void stop... | magicoder | java |
You are tasked with implementing a Python class method that returns a string representation of an object. The method should return a string that, when evaluated by Python, would produce an equivalent object. Your task is to complete the implementation of the `test_repr` method in the given Python class.
```python
clas... | ```python
class MyClass:
def __init__(self, name, age):
self.name = name
self.age = age
def test_repr(self):
return f'MyClass("{self.name}", {self.age})'
# Example usage
obj = MyClass("Alice", 25)
print(obj.test_repr()) # Output: 'MyClass("Alice", 25)'
```
In the solution, the `test_r... | magicoder | python |
You are tasked with implementing a custom logging system for a software application. The logging system should support different log levels (e.g., DEBUG, INFO, WARNING, ERROR) and be able to output log messages to various destinations such as the console, a file, or a network socket.
Your task is to design and impleme... | ```cpp
#include <iostream>
#include <fstream>
#include <vector>
enum class LogLevel { DEBUG, INFO, WARNING, ERROR };
class Logger {
public:
void setLogLevel(LogLevel level) {
logLevel = level;
}
void addOutputDestination(std::ostream& output) {
outputDestinations.push_back(&output);
}... | magicoder | cpp |
You are tasked with creating a function to analyze ice hockey player pairings and line combinations. The function will take in the season, game, and homeroad parameters, and then perform various manipulations on the data to extract relevant information. Specifically, the function will retrieve line combinations, player... | ```python
def analyze_player_combinations(season, game, homeroad):
# Step 1: Retrieve line combinations
combos = manip.get_line_combos(season, game, homeroad)
# Step 2: Retrieve player pairings
pairs = manip.get_pairings(season, game, homeroad)
# Step 3: Retrieve TOI data for forwards
... | magicoder | python |
You are tasked with developing a program to analyze a given signal and identify the peaks in the signal using Python's scientific computing libraries. The signal processing involves using various functions from libraries such as `cv2`, `imalgo`, `sys`, `plotting`, `matplotlib.pylab`, and `scipy`. Your task is to implem... | ```python
import numpy as np
from scipy.signal import find_peaks, savgol_filter
from scipy.optimize import curve_fit
def find_signal_peaks(signal):
# Smooth the signal using Savitzky-Golay filter
smoothed_signal = savgol_filter(signal, 5, 2)
# Find peaks in the smoothed signal
peaks, _ = find_peaks(sm... | magicoder | python |
You are tasked with creating a script to automate the installation and usage of a code coverage tool for a Rust project. The code snippet provided is a part of the script and checks for the existence of the `grcov` command, installs it if it's not available, and then uses it to generate code coverage reports.
Your tas... | ```bash
#!/bin/bash
# Check if grcov is installed
if ! [ -x "$(command -v grcov)" ]; then
# Install grcov using cargo
cargo +nightly install grcov
fi
# Generate code coverage reports using grcov
grcov ./target/debug/ -s . -t html --llvm --branch --ignore-not-existing -o ./target/debug/coverage/
```
The provided ... | magicoder | shell |
You are tasked with creating a Python function that extracts the version information from a given module and returns it in a specific format. The module contains version-related variables and a tuple conversion function. Your task is to implement the function `extract_version_info` that takes the module as input and re... | ```python
from distutils.version import LooseVersion
import types
def extract_version_info(module: types.ModuleType) -> str:
if hasattr(module, '__version__'):
return module.__version__
else:
raise AttributeError("Module does not contain __version__ attribute")
# Test the function with the giv... | magicoder | python |
You are tasked with creating a program that reads and processes 3D model data from a Wavefront OBJ file. The Wavefront OBJ file format is a simple text-based format for representing 3D models, including vertices, normals, texture coordinates, and faces. Your program should read the OBJ file, extract relevant data, and ... | ```rust
use std::fs;
use std::io;
use std::io::BufRead;
fn calculate_surface_area(obj_file_path: &str) -> Result<f64, String> {
let file_content = match fs::read_to_string(obj_file_path) {
Ok(content) => content,
Err(_) => return Err("Error reading file".to_string()),
};
let mut vertices: ... | magicoder | rust |
You are tasked with creating a Python function that generates a scatter plot with a line plot overlay. The scatter plot should display real data points, while the line plot should represent predictions made by a neural network (NN). Your function should take in the real data points (`x` and `y`), the predicted data poi... | ```python
import matplotlib.pyplot as plt
def plot_real_vs_predicted(x, y, test_x, test_y, scatter_label, line_label):
fig, ax1 = plt.subplots()
ax1.scatter(x, y, s=5, c='b', marker="o", label=scatter_label)
ax1.plot(test_x, test_y, c='r', label=line_label)
plt.legend()
plt.show()
# Example u... | magicoder | python |
You are tasked with implementing a program to process and analyze location data. The input consists of a 2D array `loc` containing location coordinates. Each row of the array represents a location, and each column represents a coordinate (e.g., latitude, longitude, altitude, etc.). The code snippet provided is a part o... | ```cpp
#include <vector>
#include <sstream>
using namespace std;
vector<double> processLocations(vector<vector<double>>& loc, int line) {
vector<double> averages(6, 0.0);
for (int j = 0; j < line; ++j) {
string loc_0, loc_1, loc_2, loc_3, loc_4, loc_5;
stringstream ss_0;
ss_0.clear();... | magicoder | cpp |
You are given a code snippet that appears to be a partial and corrupted implementation of a generic function in an unknown programming language. Your task is to analyze the code and reconstruct the missing parts to complete the function.
The code snippet is as follows:
```
({})
}
f
e)
func f<g>() -> (g, g -> g) -> g {... | The missing parts of the function `f` can be reconstructed based on the provided code snippet. The complete and correct implementation of the function `f` is as follows:
```swift
func f<g>() -> (g, (g) -> g) -> g {
return { arg1, arg2 in
// Implementation logic for the function f
// ...
}
}
```... | magicoder | swift |
You are tasked with creating a RESTful API endpoint for a code judging platform using Flask. The API endpoint should accept a POST request with a JSON payload containing code, language, and problem ID. The code snippet provided is a partial schema for the JSON payload that the API endpoint expects.
Your task is to com... | ```python
from flask import Flask, jsonify, request
from flask_expects_json import expects_json
app = Flask(__name__)
judge_schema = {
'type': 'object',
'properties': {
'code': {'type': 'string'},
'language': {'type': 'string'},
'problem_id': {'type': 'integer'}
},
'required': ... | magicoder | python |
You are tasked with implementing a file encryption and decryption program using the Advanced Encryption Standard (AES) in Python. The program should allow users to encrypt a file using a given key and initialization vector (IV), and subsequently decrypt the encrypted file using the same key and IV.
Your task is to com... | ```python
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
import os
__all__ = ["encrypt", "decrypt", "main"]
MODE = AES.MODE_CTR
BS = AES.block_size
KS = AES.key_size[-1]
def _pad_bytes(byte_str, size):
pad_len = size - len(byte_str) % size
return byte_str + bytes([pad_len] * pad_le... | magicoder | python |
You are tasked with creating a Python program to process and split dataframes for training and validation. The program should calculate the time taken to load the dataframes and then split them into training and validation sets. The time taken to load the dataframes is given in minutes and seconds, and the program shou... | ```python
def process_dataframes(load_time, dataframes, split_ratio):
load_min = load_time // 60 # Calculate minutes
load_sec = load_time % 60 # Calculate remaining seconds
print('Dataframes loaded in {} minutes {} seconds! Splitting for train and validation...\n'.format(load_min, load_sec))
# Split... | magicoder | python |
You are tasked with implementing a shopping cart feature for an online music store. The code snippet provided is a function that populates a view with album information. Your task is to extend this functionality by creating a ShoppingCart class that allows users to add albums to their cart, calculate the total price, a... | ```swift
struct Album {
let title: String
let band: String
let price: Double
}
class ShoppingCart {
private var albums: [Album] = []
func addAlbum(_ album: Album) {
albums.append(album)
}
func removeAlbum(_ album: Album) {
if let index = albums.firstIndex(where: { $0.title... | magicoder | swift |
You are tasked with implementing a memo tracking system for a company. The system should allow users to create memos, update their status, and track the history of memo activities. The code snippet provided is a part of the memo system and is responsible for marking a memo as obsolete, recording the activity, and savin... | ```python
from datetime import datetime
from enum import Enum
class MemoActivity(Enum):
Obsolete = 1
# Add other memo activities here
class User:
# Assume necessary attributes and methods for user representation
class Memo:
def __init__(self):
self.obsolete_date = None
def obsolete(self,... | magicoder | python |
You are working on a command-line interface (CLI) application that manages commands and their permissions. The application has a function `get_command` that retrieves a command by name and a function `set_command_permission` that updates the permission for a given command. The `get_command` function attempts to retriev... | ```python
from typing import Optional
class CommandManager:
def __init__(self):
self.commands = {}
def add_command(self, name: str, permission: Optional[str]) -> None:
self.commands[name] = permission
def get_command(self, name: str) -> Optional[str]:
return self.commands.get(name... | magicoder | python |
You are tasked with implementing a Python function that processes a JSON object and sorts its keys in a specific manner. The function should take a JSON object as input and return a string representation of the sorted JSON object with indentation.
The function signature should be:
```python
def custom_json_sort(json_o... | ```python
import json
def custom_json_sort(json_obj: dict) -> str:
sorted_json = json.dumps(json_obj, indent=4, sort_keys=True)
return sorted_json
```
The `custom_json_sort` function takes a JSON object as input, sorts its keys in ascending order, and returns a string representation of the sorted JSON object ... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.