query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a simple bot that can perform basic arithmetic operations. The bot should be able to handle addition, subtraction, multiplication, and division of two numbers. Your task is to create a class `Bot` with methods to perform these operations. The class should have the following methods:
- `... | ```python
class Bot:
@staticmethod
def add(a, b):
return a + b
@staticmethod
def subtract(a, b):
return a - b
@staticmethod
def multiply(a, b):
return a * b
@staticmethod
def divide(a, b):
if b == 0:
return "Error: Division by zero"
... | magicoder | python |
You are tasked with creating a program that processes a series of commands to manipulate a list of integers. Each command is represented by a single character and may be followed by an optional integer parameter. The initial list of integers is empty. The commands and their corresponding operations are as follows:
- 'I... | ```python
class IntegerList:
def __init__(self):
self.integers = []
def insert(self, n):
self.integers.append(n)
def delete(self):
if self.integers:
self.integers.pop()
def print_list(self):
print(' '.join(map(str, self.integers)))
def calculate_sum(se... | magicoder | python |
You are tasked with implementing a program to calculate the shortest route between two points on a map using Dijkstra's algorithm. The map is represented as a weighted graph, where each node corresponds to a location and each edge represents a road between two locations with a corresponding distance. Your task is to wr... | ```java
public static List<String> calculateShortestRoute(Map<String, Map<String, Integer>> map, String start, String destination) {
Map<String, Integer> distances = new HashMap<>();
Map<String, String> previous = new HashMap<>();
PriorityQueue<String> queue = new PriorityQueue<>(Comparator.comparingInt(dis... | magicoder | java |
You are tasked with creating a Python function that manages software package conflicts and generates configuration arguments based on specified options. The function should handle conflicts between different MPI (Message Passing Interface) implementations and produce appropriate configuration arguments for enabling or ... | ```python
class SoftwarePackage:
def __init__(self, spec):
self.spec = spec
conflicts_list = []
@staticmethod
def conflicts(mpi_implementation, condition):
SoftwarePackage.conflicts_list.append((mpi_implementation, condition))
def configure_args(self):
args = []
if... | magicoder | python |
You are given a Python code snippet that involves manipulating financial data and performing assertions on the expected rank of values. Your task is to create a programming problem based on this code snippet.
Write a function that takes in a dictionary of stock data and a dictionary of groups, and performs the followi... | ```python
import pandas as pd
def calculate_expected_ranks(data: dict, groups: dict) -> dict:
expected_ranks = {}
for stock, stock_data in data.items():
closing_prices = stock_data['close']
group_value = groups[stock]
grouped_data = pd.Series(closing_prices).groupby(group_value)
... | magicoder | python |
You are tasked with implementing a function that calculates the exterior length of a polygon given its vertices. The function should take a list of 2D points representing the vertices of the polygon and return the total exterior length of the polygon. The points are represented as pairs of x and y coordinates. The exte... | ```python
import math
def calculate_exterior_length(points):
if len(points) < 2:
return 0 # Not enough points to form a polygon
total_length = 0
for i in range(len(points)):
x1, y1 = points[i]
x2, y2 = points[(i + 1) % len(points)] # Wrap around to the first point for the last ed... | magicoder | python |
You are tasked with implementing a Python program that simulates inter-process communication using pipes. The program will create a parent process and a child process, and the two processes will communicate by writing and reading data through a pipe.
Your task is to complete the `parent` function, which will create a ... | ```python
import os
def parent():
r, w = os.pipe() # create a pipe
pid = os.fork() # fork a child process
if pid > 0: # parent process
os.close(w) # close the write end of the pipe
r = os.fdopen(r, 'r') # open the read end of the pipe
message = r.read() # read the message writ... | magicoder | python |
You are tasked with creating a custom test framework for UI testing in a mobile application. The framework should be able to run tests for each target application UI configuration. To achieve this, you need to implement a class `PreworkUITestsLaunchTests` that inherits from `XCTestCase` and overrides a property `runsFo... | ```swift
import XCTest
class PreworkUITestsLaunchTests: XCTestCase {
override class var runsForEachTargetApplicationUIConfiguration: Bool {
return true
}
}
```
In the solution, we create a class `PreworkUITestsLaunchTests` that inherits from `XCTestCase`. We then override the property `runsForEac... | magicoder | swift |
You are given a seating layout represented by a grid of seats. Each seat can be either empty (L), occupied (#), or floor (.). The seating layout is initially provided in a file, and you need to process it to simulate people's behavior following certain rules.
You are also given a Python function `get_seat_layout_from_... | ```python
from typing import List
import itertools
def get_seat_layout_from_file(file_path="../../resources/year2020_day11_input.txt"):
with open(file_path) as f:
return string_to_seat_layout(f.read())
def simulate_seating(seat_layout: List[List[str]]) -> List[List[str]]:
directions = [pos for pos in ... | magicoder | python |
You are tasked with implementing a FieldConverterFactory interface that creates FieldConverter instances for different field types. The FieldConverterFactory interface has a method to create a new FieldConverter for a given type. Your task is to create a concrete implementation of the FieldConverterFactory interface an... | ```java
import nl.qbusict.cupboard.convert.FieldConverter;
public class CustomFieldConverterFactory implements FieldConverterFactory {
@Override
public FieldConverter<?> createFieldConverter(String fieldType) {
switch (fieldType) {
case "integer":
return new IntegerFieldCon... | magicoder | java |
You are working on a project that involves processing chemical compounds using the RDKit library in Python. Your task is to create a program that reads a ligand file in SDF (Structure Data File) format, assigns bond orders from a template molecule, and then converts the modified molecule to a PDB (Protein Data Bank) fi... | ```python
import rdkit.Chem as rdk
from rdkit.Chem import AllChem
def process_ligand(ligand, lig_name, outname, template2, format='sdf'):
if format == 'sdf':
# Read the input ligand file in SDF format
mol = rdk.Chem.MolFromMolFile(ligand)
if mol is not None:
# Assign bond order... | magicoder | python |
You are given a C++ code snippet that involves the manipulation of points and projections. Your task is to create a program that calculates the distance between a given point and a set of projections in a 2D space.
You are given the following information:
- The code snippet provided is part of a larger program that de... | ```cpp
#include <iostream>
#include <vector>
#include <cmath>
struct Point {
int x;
int y;
};
std::vector<double> calculateDistances(const Point& point, const std::vector<std::pair<int, int>>& projections) {
std::vector<double> distances;
for (const auto& proj : projections) {
double dx = std:... | magicoder | cpp |
You are tasked with creating a Python function that generates an interactive Altair chart displaying the suicide rate by year for selected regions. The function should take a list of regions as input and return an Altair chart object representing the interactive plot.
The function signature should be:
```python
def ge... | ```python
import altair as alt
import pandas as pd
from typing import List
# Sample data (replace with actual data retrieval)
data = {
'year': [2010, 2011, 2012, 2013, 2014],
'region': ['Region A', 'Region A', 'Region B', 'Region B', 'Region C'],
'suicide_rate': [10, 12, 8, 9, 11]
}
df = pd.DataFrame(data)... | magicoder | python |
You are tasked with creating a Git workflow simulator program. The program should simulate a simplified version of the Git version control system, focusing on the `commit`, `push`, and `checkout` commands.
Your program should support the following commands:
1. `git commit -m "<message>"`: This command should create a ... | ```python
class GitWorkflowSimulator:
def __init__(self):
self.current_branch = "master"
self.local_commits = {}
self.remote_commits = {}
def execute_command(self, command):
if command.startswith("git commit -m"):
message = command.split('"')[1]
self.loca... | magicoder | python |
You are tasked with creating a Python function that handles HTTP requests and returns the status code and content of the response. However, the function should also handle exceptions and print error messages using the `traceback` module. Your task is to complete the function `handle_http_request` by filling in the miss... | ```python
import requests
import traceback
def handle_http_request(url):
try:
response = requests.get(url)
return response.status_code, response.content
except Exception as err:
traceback.print_exc()
print('Error {}'.format(err))
else:
pass
```
In the solution, the ... | magicoder | python |
You are tasked with implementing a Python function that processes an image using a specific object detection algorithm and displays the result using the OpenCV library. The function should take an input image and a label as parameters, apply the object detection algorithm to the image, overlay the detected objects with... | ```python
import cv2
def process_and_display(input_image, label):
# Apply object detection algorithm to the input image
processed_image = detector(input_image, label)
# Draw bounding boxes and labels on the processed image
# Assuming the detector returns the processed image with bounding boxes and lab... | magicoder | python |
You are tasked with implementing a Python class that manages a queue with a limited capacity. The class should have the following functionalities:
1. `__init__(self, capacity)`: Initializes the queue with the given capacity.
2. `enqueue(self, item)`: Adds an item to the queue if there is space available. If the queue i... | ```python
class QueueFullException(Exception):
pass
class QueueEmptyException(Exception):
pass
class LimitedQueue:
def __init__(self, capacity):
self.capacity = capacity
self.queue = []
def enqueue(self, item):
if len(self.queue) < self.capacity:
self.queue.append(... | magicoder | python |
You are tasked with implementing a custom property decorator in Python that mimics the behavior of the `@property` decorator. The custom decorator should allow for the creation of a property with a getter function that retrieves a value from a dictionary-like object using the `pulumi.get` method.
Your task is to creat... | ```python
def custom_property(key):
def decorator(func):
def wrapper(self):
return pulumi.get(self._data, key)
return property(wrapper)
return decorator
class CustomResource:
def __init__(self, data):
self._data = data
def custom_property(key):
def decorator... | magicoder | python |
You are tasked with optimizing a network packet forwarding function in a high-performance networking application. The function `l2fwd` is responsible for forwarding incoming packets from one network interface to another. The code snippet provided is a part of this function and uses the Data Plane Development Kit (DPDK)... | To optimize the packet processing loop within the `l2fwd` function, we can utilize parallel processing and efficient memory management techniques. Below is a sample optimized packet processing loop using DPDK APIs:
```cpp
#include <rte_mbuf.h>
// Define the number of packets to process in each burst
constexpr size_t ... | magicoder | cpp |
You are tasked with creating a Python class that represents a package in a package manager system. Your task is to implement a class called `PyScikitLearnExtra` that inherits from the `PythonPackage` class. The `PyScikitLearnExtra` class should have attributes and methods to represent a Python package for machine learn... | ```python
from spack.package import *
class PyScikitLearnExtra(PythonPackage):
"""A set of useful tools compatible with scikit-learn
scikit-learn-extra is a Python module for machine learning that extends
scikit-learn. It includes algorithms that are useful but do not satisfy the
scikit-learn inclusio... | magicoder | python |
You are tasked with implementing a simple neural network training loop using PyTorch. The provided code snippet is part of a larger training loop and shows the conditional execution of training steps for a generator and a discriminator. The `optimizer_idx` variable is used to determine which part of the network to trai... | ```python
# Solution for generator_step method
def generator_step(self, x):
# Assuming self.generator is the generator model and self.generator_optimizer is the optimizer for the generator
self.generator_optimizer.zero_grad() # Clear the gradients
generated_output = self.generator(x) # Forward pass to gen... | magicoder | python |
You are given a list of lists containing integers. Each inner list represents a row of a 2D grid. The integers in each inner list represent the heights of the cells in that row. Your task is to write a function that calculates the volume of water that can be trapped in the grid after a rainstorm.
For example, given th... | ```python
def trapped_water_volume(grid):
if not grid or not grid[0]:
return 0
rows, cols = len(grid), len(grid[0])
left_max = [0] * rows
right_max = [0] * rows
water_volume = 0
for j in range(cols):
cur_left_max = 0
cur_right_max = 0
for i in range(rows):
... | magicoder | python |
You are tasked with implementing a function that checks if a given Elasticsearch index has been modified and if a specified pattern is no longer present in the index. You are provided with a Python class `Test` that inherits from `BaseTest`. Within this class, there is a method `test_index_modified` which contains a do... | ```python
from elasticsearch import Elasticsearch
from elasticsearch.exceptions import NotFoundError
import time
class Test(BaseTest):
def test_index_modified(self, index_name, pattern):
"""
Test that beat stops in case elasticsearch index is modified and pattern not
"""
# Connect... | magicoder | python |
You are tasked with creating a program that parses a given copyright notice and extracts the copyright year and the name of the entity. The copyright notice is provided as a string in the following format:
```
* @copyright Copyright <YEAR> <NAME>.
* @license Licensed under the Apache License, Version 2.0 (the "Lice... | ```python
import re
def parseCopyrightNotice(notice: str) -> dict:
pattern = r'@copyright\s+Copyright\s+(\d{4})\s+(.*?)\.'
match = re.search(pattern, notice)
if match:
year = match.group(1)
name = match.group(2)
return {'year': year, 'name': name}
else:
return {}
```
Th... | magicoder | python |
You are tasked with developing a script to process DNA sequencing data using the Trimmomatic tool and then remove duplicate reads from the resulting files. Trimmomatic is a popular tool for quality trimming of Illumina NGS data. The provided code snippet demonstrates the usage of Trimmomatic to perform paired-end read ... | ```python
import subprocess
import os
# Paths and filenames
rdata_path = "/path/to/input/files"
read1 = "input_read1.fq"
read2 = "input_read2.fq"
TRIM_PATH = "/path/to/trimmomatic-0.36.jar"
pref = "output_prefix"
# Execute Trimmomatic
trim_cmd = f"java -jar {TRIM_PATH} PE -phred33 {os.path.join(rdata_path, read1)} {o... | magicoder | python |
You are tasked with creating a Python function that processes an image file and applies various transformations to it. The function should take the input image file path, output file path, scaling factor, mirror option, and background color as input parameters. The function should then apply the specified transformatio... | ```python
import os
import time
from PIL import Image, ImageOps
def start_imoji(input_file: str, output_file: str, scale: float, mirror: bool, background: str) -> str:
try:
# Load the input image from the specified input file path
input_image = Image.open(input_file)
# Apply the specified ... | magicoder | python |
You are tasked with creating a function to determine the minimum number of invalid parentheses that need to be removed from a given string in order to make it a valid sequence. Invalid parentheses are defined as any closing parentheses without a corresponding opening parentheses, or any opening parentheses without a co... | ```python
def count_invalid_parenthesis(string):
stack = []
invalid_count = 0
for char in string:
if char == '(':
stack.append(char)
elif char == ')':
if stack:
stack.pop()
else:
invalid_count += 1
invalid_count += len... | magicoder | python |
You are tasked with creating a hierarchical data structure for a file management system. The system should allow users to create folders and subfolders, and each folder can contain files and subfolders. You need to implement a function that calculates the total size of a given folder and all its subfolders and files.
... | The `calculate_total_size` function recursively calculates the total size of a given folder and all its subfolders and files. It starts by adding the size of the current folder to the `total_size` variable. Then, it retrieves all subfolders of the current folder using the `Folder.objects.filter` method and iterates thr... | magicoder | python |
You are tasked with implementing a simplified version of the International Data Encryption Algorithm (IDEA) in Rust. IDEA is a symmetric key block cipher that operates on 64-bit blocks of data and uses a 128-bit key. The algorithm consists of a series of modular arithmetic operations, including addition, multiplication... | ```rust
// File: idea.rs
// Implement the IDEA algorithm here
pub struct Idea;
impl cipher::BlockCipher for Idea {
fn block_size(&self) -> usize {
8
}
fn encrypt_block(&self, block: &mut [u8]) {
// Implement IDEA encryption algorithm here
// Use the 128-bit key to encrypt the 64-... | magicoder | rust |
You are tasked with creating a custom permission class for a Django REST framework viewset. The permission class should restrict the ability to create new instances based on a specific condition. You are given a code snippet from a Django viewset that includes the `perform_create` method, which is responsible for creat... | ```python
from rest_framework import permissions, exceptions
class CanModifyPriceObjectPermission(permissions.BasePermission):
def has_permission(self, request, view):
# Implement the logic to check whether the user has permission to modify the price object
# You can access the request.user and per... | magicoder | python |
You are tasked with creating a program that processes data from a MySQL database using PHP and MySQLi. The program should retrieve information about exercises from the database and perform specific operations on the data.
You are given a MySQL database connection object `$conexao` and a SQL query string `$sql` that re... | ```php
function processExerciseData($conexao, $sql) {
$result = mysqli_query($conexao, $sql);
$exercises = mysqli_fetch_all($result, MYSQLI_ASSOC);
$totalExercises = count($exercises);
$totalDuration = 0;
$longestExercise = null;
foreach ($exercises as $exercise) {
$totalDuration += $... | magicoder | php |
You are given a list of integers representing the scores of a game. Your task is to write a function that calculates the average score of the game, excluding the highest and lowest scores.
Write a function `calculateAverage` that takes in a list of integers and returns the average score, rounded to the nearest whole n... | ```python
from typing import List
def calculateAverage(scores: List[int]) -> int:
if len(scores) <= 2:
return round(sum(scores) / len(scores))
scores.sort()
return round(sum(scores[1:-1]) / (len(scores) - 2))
```
The `calculateAverage` function first checks if the list has 2 or fewer elements,... | magicoder | python |
You are tasked with implementing a plugin system for a rendering engine. The given code snippet is a part of the plugin registration process. The `MOUS_DEF_PLUGIN` macro is used to register a plugin of type `Renderer` with the provided information and implementation.
Your task is to create a class hierarchy for differ... | ```cpp
#include <iostream>
#include <map>
#include <memory>
#include <dlfcn.h>
// Base class for plugins
class Plugin {
public:
virtual void initialize() = 0;
virtual void render() = 0;
virtual ~Plugin() {}
};
// Derived classes for specific types of plugins
class RendererPlugin : public Plugin {
public:
... | magicoder | cpp |
You are tasked with implementing a function to parse a series of directives from a given input string. Each directive is represented as a string and is prefixed by a specific directive name. The input string is formatted as follows:
- Directives are separated by spaces.
- Each directive consists of a directive name fol... | ```cpp
#include <iostream>
#include <vector>
#include <map>
#include <sstream>
#include <algorithm>
void StringToLowerASCII(std::string* str) {
std::transform(str->begin(), str->end(), str->begin(), ::tolower);
}
std::map<std::string, std::vector<std::string>> parseDirectives(const std::string& input) {
std::map<... | magicoder | cpp |
You are tasked with implementing a simple game interface for creating heroes and monsters. The interface provides two methods, `criaHeroi()` and `criaMonstro()`, which are responsible for creating instances of the `Heroi` and `Monstro` classes, respectively. Your goal is to implement the `Heroi` and `Monstro` classes a... | ```java
import java.util.Random;
public class Jogo {
public static void main(String[] args) {
Heroi heroi = criaHeroi();
Monstro monstro = criaMonstro();
heroi.atacar(monstro);
monstro.atacar(heroi);
}
public static Heroi criaHeroi() {
return new Heroi("Heroi", 100... | magicoder | java |
You are tasked with creating a program to analyze and visualize data from a web application. The application uses SVG elements to display statistics on the number of registered users and total earnings. Your task is to write a Python function that parses the SVG elements and extracts the relevant data for further proce... | ```python
import re
def parse_svg_data(svg_code: str) -> dict:
total_users_match = re.search(r'<text.*?>(\d+)</text>', svg_code)
total_earnings_match = re.search(r'<text.*?>(\$[\d,]+\.\d+)</text>', svg_code)
total_users = int(total_users_match.group(1))
total_earnings = float(total_earnings_match.grou... | magicoder | python |
You are tasked with creating a Python function that utilizes the `pytest` library to write a test case for a function that uses patching and fixtures. The function to be tested is `run_all_forever` from the `tickit.cli` module. Additionally, the test case should patch the `asyncio` module to mock its behavior.
Write a... | ```python
import pytest
from unittest.mock import patch, Mock
from typing import Iterable
# Function to be tested
def run_all_forever():
# Implementation of run_all_forever function
pass
# Test case function
def test_run_all_forever(patch_run_all_forever: Iterable[Mock], patch_asyncio: Iterable[Mock]):
# ... | magicoder | python |
You are tasked with implementing a reaction filter system for a messaging application. The `ReactionFilter` class is responsible for allowing or denying reactions to messages based on certain criteria. The `allow_reaction` method is called when a user reacts to a message, and it determines whether the reaction should b... | ```python
from typing import Optional
from discord import Message, Reaction, Member
class ReactionFilter:
def __init__(self, reaction_filter: Optional["ReactionFilter"] = None):
self.inner_filter: ReactionFilter = reaction_filter
async def _allow_reaction(self, message: Message, reaction: Reaction, m... | magicoder | python |
You are tasked with creating a function that can parse and extract information from a Blade template used in a Laravel application. Blade is the templating engine used by Laravel, and it allows developers to embed PHP code within the HTML markup. Your task is to write a function that can extract the names of included t... | ```python
import re
def extractIncludedTemplates(blade_template):
included_templates = re.findall(r"@include\(['\"](.*?)['\"]\)", blade_template)
return included_templates
```
The `extractIncludedTemplates` function uses the `re.findall` method to search for all occurrences of the `@include` directive followe... | magicoder | python |
You are working on a project that involves building a deep learning model using TensorFlow. As part of the model architecture, you need to implement a custom layer that combines Batch Normalization, Dropout, and a Dense layer. The custom layer should also include a GlobalMaxPool2D layer for feature extraction. Your tas... | ```python
import tensorflow as tf
class CustomLayer(tf.keras.layers.Layer):
def __init__(self, **kwargs):
super(CustomLayer, self).__init__(**kwargs)
self.batch_norm = tf.keras.layers.BatchNormalization(momentum=0.9)
self.dropout = tf.keras.layers.Dropout(0.5)
self.dense = tf.keras.... | magicoder | python |
You are tasked with implementing a function to parse a date string in RFC 3339 format and convert it to a Python `datetime.date` object. The RFC 3339 format represents dates and times using the Gregorian calendar and the UTC time zone. The format for a date is "YYYY-MM-DD".
You need to implement the `parse_rfc3339` fu... | ```python
from datetime import datetime
def parse_rfc3339(string):
try:
date_obj = datetime.strptime(string, "%Y-%m-%d").date()
return date_obj
except ValueError:
raise ValueError("Invalid RFC 3339 date format")
```
The `parse_rfc3339` function uses the `datetime.strptime` method to pa... | magicoder | python |
You are tasked with creating a simple terminal emulator in Rust. The terminal emulator should support basic functionalities such as printing text, receiving input, and handling simple commands. You are provided with a `terminal` module that contains the `Terminal` struct and its associated methods. Your task is to impl... | ```rust
mod terminal {
use std::io;
pub struct Terminal;
impl Terminal {
pub fn new() -> Terminal {
Terminal
}
pub fn print(&self, text: &str) {
println!("{}", text);
}
pub fn read_input(&self) -> String {
let mut input = String... | magicoder | rust |
You are tasked with implementing a Python decorator that enforces post-conditions for methods in a class. The decorator should verify certain conditions on the return value of the method and raise an exception if the conditions are not met.
Your task is to complete the implementation of the `post_conditions` decorator... | ```python
class PostConditionError(Exception):
pass
def post_conditions(conditions):
def decorator(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
for condition, check in conditions.items():
if not check(result):
raise Post... | magicoder | python |
You are tasked with creating a script to automate the process of adding an alias command to a user's home directory file. The script should check for read and write permissions before attempting to add the alias command. If the permissions are sufficient, the alias command should be appended to the specified file. If n... | ```bash
#!/bin/bash
# Check if the file exists
if [ -e ~/$file ]; then
# Check for read and write permissions
if [ -r ~/$file ] && [ -w ~/$file ]; then
# Add the alias
/bin/echo -n $ALIAS_COMMAND >> ~/$file
else
echo "Skipping adding alias command to ~/$file since we don't have read and write permissions"
fi... | magicoder | shell |
You are tasked with creating a function that processes and filters data from a blog post API. The API returns an array of post objects, each containing various properties such as slug, created_at, title, and content. Your function should parse the content of each post using the `matter` function and return a filtered a... | ```typescript
import matter from 'gray-matter'; // Assuming the matter function is imported from 'gray-matter'
interface IPostData {
slug: string;
created_at: Date;
title: string;
// Other properties as required
}
async function processPostData(): Promise<IPostData[]> {
const data = await Posts.getAll(); //... | magicoder | typescript |
You are tasked with creating a Python function that simulates a simplified version of the `shell_pipe` function. The `shell_pipe` function takes a command string as input and returns the output of executing the command through a series of shell commands. The command string may contain multiple commands separated by the... | ```python
import subprocess
import shlex
def shell_pipe(command: str) -> str:
commands = command.split('|')
output = None
for cmd in commands:
popen_kw = {
'stdout': subprocess.PIPE,
'stderr': subprocess.PIPE,
'stdin': subprocess.PIPE,
}
command_s... | magicoder | python |
You are tasked with implementing a class for visualizing attention weights in a neural network. The given code snippet is part of the class method responsible for setting up the visualization of attention weights. The method takes care of adding a color bar to the plot, setting the x and y ticks, and defining the defau... | ```python
import numpy as np
import matplotlib.pyplot as plt
class AttentionVisualizer:
def __init__(self, ax, x_label_toks, y_label_toks, chosen_head=None):
self.ax = ax
self.x_label_toks = x_label_toks
self.y_label_toks = y_label_toks
self.chosen_head = chosen_head
def plot_a... | magicoder | python |
You are tasked with creating a program to manage issues in a software development project. Each issue has various attributes, such as the user who created it, its state (open or closed), whether it is locked, the issue body, comment count, assignee, assignees, milestone, creation date, last update date, and closed date... | ```python
from datetime import datetime, timedelta
class Issue:
def __init__(self, user, state, isLocked, body, commentCount, assignee, assignees, milestone, createdAt, updatedAt, closedAt):
self.user = user
self.state = state
self.isLocked = isLocked
self.body = body
self.c... | magicoder | python |
You are given an array of integers. A "majorant" element in an array is defined as an element that appears more than half the length of the array. Your task is to write a function to find the majorant element in the given array, if it exists.
Write a function `FindMajorantElement` that takes in an array of integers an... | ```csharp
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static int FindMajorantElement(int[] array)
{
var dict = array.GroupBy(x => x).ToDictionary(gr => gr.Key, gr => gr.Count());
var majElement = array.FirstOrDefault(x => dict[x] >= array.Len... | magicoder | csharp |
You are given a graph represented as a collection of edges, where each edge is a tuple of the form (source, destination, weight). Your task is to implement a Python function that finds the minimum spanning tree (MST) of the given graph using Kruskal's algorithm.
Kruskal's algorithm is a greedy algorithm that finds a m... | ```python
class DisjointSet:
def __init__(self, vertices):
self.parent = {v: v for v in vertices}
self.rank = {v: 0 for v in vertices}
def find(self, v):
if self.parent[v] != v:
self.parent[v] = self.find(self.parent[v])
return self.parent[v]
def union(self, v1,... | magicoder | python |
You are tasked with creating a Python unit test for a class method that converts a pandas DataFrame to a JSON string, loads it back into a dictionary, and then performs assertions on the dictionary. Your task is to complete the unit test by implementing the missing `expected_dict` method and ensuring that the assertion... | ```python
import json
import pandas as pd
import unittest
class TestDataFrameConversion(unittest.TestCase):
def setUp(self):
# Create a sample DataFrame for testing
data = {'OID': ['ODM.F.VS'], 'Value': [42]}
self.fd = pd.DataFrame(data)
def expected_dict(self):
# Implement the... | magicoder | python |
You are tasked with implementing a text alignment utility in Python. Your goal is to create a class `Align` that can align a given string of text to the left, right, or center within a specified width. The `Align` class should have the following methods:
- `__init__(self, text: str, alignment: str, width: int)`: Initia... | ```python
class Align:
def __init__(self, text: str, alignment: str, width: int):
self.text = text
self.alignment = alignment
self.width = width
def renderable(self) -> str:
if self.alignment == "left":
return self.text.ljust(self.width)
elif self.alignment =... | magicoder | python |
You are tasked with implementing a function that initializes specifications type buttons in an application. The function is part of a larger codebase for a software tool used in data analysis. The code snippet provided is a part of the implementation of this function. The function is responsible for setting up and conf... | ```cpp
void ActorFrame::initializeSpecificationsTypeButtons()
{
// Assuming the existence of UI elements such as sasDataGridTableWidget and actorComboBox
// Create a new QTableWidgetItem with the appropriate headerItem
QTableWidgetItem *item = new QTableWidgetItem(headerItem);
// Insert a new row in t... | magicoder | cpp |
You are tasked with creating a Swift protocol for managing additional XML-formatted information that can be included in the Unattend.xml file used by Windows Setup. The protocol should define the structure for including content by setting the name, component name, and the pass in which the content is applied.
Your tas... | ```swift
// Define the AdditionalUnattendContent structure conforming to AdditionalUnattendContentProtocol
struct AdditionalUnattendContent: AdditionalUnattendContentProtocol {
var name: String
var componentName: String
var pass: String
// Initializer to set the properties
init(name: String, compon... | magicoder | swift |
You are tasked with implementing a custom view hierarchy in a Swift iOS application. Your goal is to create a custom view container that conforms to the `Element` protocol and provides specific functionality for rendering and describing its backing view.
Your task is to complete the implementation of the `TestContaine... | ```swift
import UIKit
struct ElementContent {
let intrinsicSize: CGSize
}
protocol ViewDescription {
// Define the properties and methods for the ViewDescription protocol
}
protocol ViewDescriptionContext {
// Define the properties and methods for the ViewDescriptionContext protocol
}
protocol Element {... | magicoder | swift |
You are tasked with implementing a session management system for a web application. The given code snippet is a part of a method that associates a user's session ID with their user ID and user information in a cache. The CacheUtil class provides methods for interacting with the cache, and the Constants class contains v... | ```java
import java.util.*;
public class SessionManager {
public static Tuple getUserInfoFromSession(String sessionId) {
String userIdKey = Constants.CacheNamespaceEnum.SESSION_USER_ID.value() + sessionId;
String userKey = Constants.CacheNamespaceEnum.SESSION_USER.value() + sessionId;
Stri... | magicoder | java |
You are tasked with implementing a function that performs a regex-based string replacement. Your task is to create a function that takes in a string, a regular expression pattern, and a replacement template, and returns a new string with all the matching substrings replaced with the template.
You are given the followi... | ```swift
func replaceMatches(in input: String, pattern: String, withTemplate template: String) -> String {
do {
let regex = try NSRegularExpression(pattern: pattern, options: [])
let nsstring = NSString(string: input)
let range = NSRange(location: 0, length: nsstring.length)
... | magicoder | swift |
You are tasked with creating a Rust function that interacts with the Garmin API to retrieve and process fitness data. The function should utilize the provided code snippet as a starting point and incorporate the necessary components to achieve this goal.
Your task is to implement a function called `fetch_and_process_f... | The `fetch_and_process_fitness_data` function takes in the `GarminCliOptions` and `PgPool` as input parameters. It creates a new `GarminCli` instance using the provided options and then uses it to fetch fitness data from the Garmin API. The fetched data is then processed using the `GarminParse` module to extract releva... | magicoder | rust |
You are tasked with implementing a program that utilizes Apache Avro to serialize and deserialize data using a specific schema. Apache Avro is a data serialization system that provides rich data structures and a compact, fast, binary data format. Your task is to create a Java program that defines an Avro schema, serial... | ```java
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.DatumWriter;
import org.apache.avro.io.Decoder;
import org.apache.avro.io.DecoderFactory;
import org.apache.avro.io.Encoder;
i... | magicoder | java |
You are tasked with implementing a queue management system for a distributed worker application. The system should handle the queuing and processing of tasks across multiple workers. Each task is associated with a queue and is processed by a worker. The system should also track the status of each task, whether it is qu... | ```python
class Task:
NOT_QUEUED = ("worker",)
QUEUED = ("queued_at", "exchange", "routing_key", "queue", "client",)
def __init__(self):
self.status = "not_queued"
self.queue = None
self.worker = None
def enqueue(self, queue_name):
if self.status == "not_queued":
... | magicoder | python |
You are tasked with implementing a parser for a custom markup language that uses XML-like tags. The parser needs to identify and extract specific attributes from the tags.
Given a string containing multiple XML-like tags, you need to extract the values of the "type" attribute from all the `<alert>` tags and store the... | ```python
from typing import List
import re
def extractAlertTypes(xmlString: str) -> List[str]:
alert_types = re.findall(r'<alert type="([^"]+)"', xmlString)
return alert_types
```
The `extractAlertTypes` function uses the `re.findall` method to extract all occurrences of the "type" attribute from the `<alert... | magicoder | python |
You are tasked with implementing a function that processes a list of dictionaries containing key-value pairs. The function should extract a specific key from each dictionary, convert its value to an integer, and return a list of the converted values. If any dictionary does not contain the specified key or if the value ... | ```python
from typing import List, Dict, Any, Union
def process_dicts(dicts: List[Dict[str, Any]], key: str) -> Union[List[int], bool]:
converted_values = []
for d in dicts:
if key in d:
try:
converted_values.append(int(d[key]))
except ValueError:
... | magicoder | python |
You are working as a software developer at a tech company, and you have been tasked with automating the code formatting process for a large codebase. The company uses the Go programming language, and the codebase is stored in a repository named `joostvdg/cmg`. Your task is to create a script that will format all the Go... | ```bash
#!/bin/bash
# Clone the repository
git clone https://github.com/joostvdg/cmg.git
cd cmg
# Format all Go source files using gofmt
gofmt -s -w -l **/*.go
# Commit the changes
git add .
git commit -m "Automated code formatting using gofmt"
git push origin master
```
This script automates the code formatting pr... | magicoder | shell |
You are tasked with implementing a parallelized algorithm for processing a collection of nodes in a tree structure. Each node in the tree contains a certain value, and the algorithm aims to transform these values in parallel using the Rayon library in Rust.
You are given a Rust code snippet that demonstrates the usage... | ```rust
use rayon::prelude::*;
// Define the Node type
struct Node {
value: i32,
// Other node properties
}
impl Node {
// Define any methods relevant to Node transformation
fn transform(&mut self) {
// Transformation logic for the node value
self.value *= 2; // Example transformation:... | magicoder | rust |
You are tasked with implementing a simplified version of a graphics library's SwapChain class in C++. The SwapChain class is responsible for managing the presentation of images to the screen in a graphics application. Your goal is to create a class that can create a SwapChain object with specific settings and provide a... | ```cpp
#include <iostream>
#include <vector>
// Assume the Window and Image classes, as well as the ImageFormat enum, are defined elsewhere
class SwapChain {
public:
struct Settings {
Ptr<Window> window;
ImageFormat format;
};
virtual ~SwapChain() {}
static Ptr<SwapChain> create(cons... | magicoder | cpp |
You are tasked with implementing a generic data structure that simulates a simplified version of a BTreeSet. The BTreeSet is a sorted set data structure that uses a B-tree for storage. In this problem, you will create a Rust program to implement a simplified version of the BTreeSet using a binary search tree.
You are ... | ```rust
use std::cmp::Ord;
struct Node<T> {
value: T,
left: Option<Box<Node<T>>>,
right: Option<Box<Node<T>>>,
}
impl<T: Ord> Node<T> {
fn new(value: T) -> Self {
Node {
value,
left: None,
right: None,
}
}
fn insert(&mut self, value: T) {
... | magicoder | rust |
You are tasked with implementing a Python class that interacts with a TV show database. The class should have methods for searching and retrieving TV show information based on various parameters. Your task is to complete the implementation of the `TVShowDatabase` class by adding the missing methods and ensuring that th... | ```python
class TVShowDatabase:
def __init__(self, api_key):
self.api = TVShowDatabaseAPI(api_key)
def search_by_title(self, title):
try:
return self.api.search_by_title(title)
except Exception as e:
return f"Error occurred during title search: {e}"
def sear... | magicoder | python |
You are tasked with implementing a simplified version of a 2D texture class in C++. The class should support the creation of a texture object and provide a method for resetting its properties. Your task is to complete the implementation of the `Texture2D` class by adding the `Reset` method and ensuring that the class f... | ```cpp
#include <memory>
enum class Texture2DFilterHint { NEAREST, LINEAR };
struct RawBitmap {
// Definition not provided for brevity
};
class INativeGraphics {
// Definition not provided for brevity
};
class Texture2D {
public:
Texture2D() : nativeGraphics_(nullptr), textureFlags_(0) {}
Texture2D(... | magicoder | cpp |
You are tasked with creating a custom widget for visualizing and manipulating 2D arrays in a Jupyter notebook using ipywidgets and traitlets in Python. Your custom widget should allow users to input a 2D array, visualize it as a grid of input fields, and dynamically update the array based on user input.
Your custom wi... | ```python
import ipywidgets as widgets
from traitlets import Unicode, List, observe
from traittypes import Array
class ArrayWidget(widgets.DOMWidget):
value = Array().tag(sync=True)
def __init__(self, value, **kwargs):
super().__init__(**kwargs)
self.value = value
self._create_arra... | magicoder | python |
You are tasked with creating a Python program that can analyze a given file path and determine the file's encoding. The program should be able to handle various file encodings and provide the correct encoding for a given file path.
Your task is to implement a function `get_file_encoding(file_path)` that takes a file p... | ```python
import chardet
def get_file_encoding(file_path):
with open(file_path, 'rb') as file:
raw_data = file.read()
encoding_info = chardet.detect(raw_data)
return encoding_info['encoding']
# Test the function
file_path = "/usr/lib/python2.7/encodings/gb2312.py"
print(get_file_encoding(f... | magicoder | python |
You are tasked with implementing a Python class for managing game pieces in a board game. The class should handle drawing the pieces on the game board and moving them to new positions. The provided code snippet shows two methods of the class: `draw_pieces` and `move_pieces`.
The `draw_pieces` method is responsible for... | ```python
class GamePiece:
def __init__(self, x, y, piece_color, padding, outline, piece_king=False):
self.x = x
self.y = y
self.piece_color = piece_color
self.padding = padding
self.outline = outline
self.piece_king = piece_king
self.board_row = 0 # Initiali... | magicoder | python |
You are given a code snippet that involves the use of PyTorch tensors and a hypothetical function `model.species_to_tensor()`. Your task is to create a function that takes in the `coordinates` tensor and the `species` tensor, and computes the pairwise distances between each pair of points in the `coordinates` tensor fo... | ```python
import torch
def pairwise_distances(coordinates, species):
# Expand dimensions to enable broadcasting
expanded_coordinates = coordinates.unsqueeze(1)
expanded_species = species.unsqueeze(2)
# Mask to filter out distances for different species
species_mask = expanded_species == expanded_s... | magicoder | python |
You are given a code snippet that represents a function for multiplying a dense matrix by the transpose of a sparse matrix. Your task is to implement a function that performs this matrix multiplication and returns the result.
You are provided with the following information:
- The code snippet represents a function `Mu... | ```cpp
#include <iostream>
#include <vector>
template <class T>
class SparseMatrix {
// Implementation of the sparse matrix class
};
template <class T>
class DenseMatrix {
// Implementation of the dense matrix class
public:
void MultiplyMMTranspose(DenseMatrix<T> &Result, const SparseMatrix<T> &M) {
... | magicoder | cpp |
You are working on a project that involves processing environmental data stored in NetCDF files. You need to write a Python function to extract and process specific data from a NetCDF file using the given code snippet as a reference.
Write a function `extract_and_process_data` that takes in the following parameters:
-... | ```python
import numpy as np
from netCDF4 import Dataset
def extract_and_process_data(file_path, variable_name):
try:
# Open the NetCDF file
with Dataset(file_path, 'r') as nc_file:
# Extract the variable data
variable_data = nc_file.variables[variable_name][:]
... | magicoder | python |
You are tasked with implementing a simple stack data structure in Swift using a generic type. A stack is a last-in, first-out (LIFO) data structure, where elements are added and removed from the same end, known as the top. Your implementation should include the following functionalities:
1. `push`: Add an element to th... | ```swift
public typealias Response = Void
public class Stack<T> {
private var elements: [T] = []
// Add the element to the top of the stack
public func push(_ element: T) {
elements.append(element)
}
// Remove and return the element at the top of the stack
public func pop() -> T? {
... | magicoder | swift |
You are tasked with implementing a custom comparison method for a class representing a geometric shape. The class `GeometricShape` has a method `CompareTo` that compares the current shape with another shape and returns an integer based on their relative positions. The method returns a negative value if the current shap... | ```csharp
public class GeometricShape
{
public virtual int CompareTo(GeometricShape other)
{
// Default implementation for generic geometric shapes
throw new NotImplementedException("Comparison not implemented for generic geometric shapes.");
}
}
public class Rectangle : GeometricShape
{
... | magicoder | csharp |
You are tasked with creating a Python program to simulate a simple drawing application. The program should allow users to draw rectangles on a canvas using the mouse. The canvas should display the drawn rectangles in real-time, and the program should also provide the functionality to clear the canvas.
Your task is to ... | ```python
import kivy
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button
from kivy.graphics import Color, Rectangle
from kivy.uix.widget import Widget
class Canvas(Widget):
def __init__(self, **kwargs):
super(Canvas, self).__init__(**kwargs)
sel... | magicoder | python |
You are tasked with creating a program that analyzes the frequency of words in a given text. Your program should take a string of text as input and output a list of unique words along with their frequencies, sorted in descending order of frequency. For this problem, a word is defined as any sequence of non-whitespace c... | ```python
def word_frequency(text):
# Remove punctuation marks and convert text to lowercase
text = text.lower()
text = ''.join(char if char.isalnum() or char.isspace() else ' ' for char in text)
# Split the text into words
words = text.split()
# Create a dictionary to store word frequencies
... | magicoder | python |
You are tasked with creating a program to process a series of HTML list items and extract specific information from them. Each list item contains a statement related to a specific requirement or condition. Your program needs to identify and extract the following information from each list item:
1. The condition or requ... | ```python
from bs4 import BeautifulSoup
def extract_requirements(html_content):
soup = BeautifulSoup(html_content, 'html.parser')
list_items = soup.find('section').find_all('li')
extracted_info = []
for item in list_items:
statement = item.get_text()
requires_police_report = 'surat kete... | magicoder | python |
You are tasked with implementing a simplified version of a template rendering system in PHP. Your goal is to create a class that can render a view by replacing placeholders with actual values. The placeholders will be in the format `{{placeholder}}` and should be replaced with the corresponding values provided in the d... | ```php
class ViewRenderer {
public function render($viewPath, $data) {
// Check if the view file exists
if (file_exists($viewPath)) {
// Read the content of the view file
$viewContent = file_get_contents($viewPath);
// Replace the placeholders with the provided v... | magicoder | php |
You are tasked with implementing a Lookup class that can store key-value pairs and provide various operations for retrieving and manipulating the data. The Lookup class should support applying a result selector function to the stored key-value pairs and returning the result as a list. Additionally, the Lookup class sho... | ```python
class Lookup:
def __init__(self, key_value_pairs):
self.lookup_dict = {}
for key, value in key_value_pairs:
if key not in self.lookup_dict:
self.lookup_dict[key] = value
def apply_result_selector(self, selector_func):
result = [selector_func(key, va... | magicoder | python |
You are tasked with implementing a simplified version of the `exptrigsimp` function in Python. The `exptrigsimp` function takes a mathematical expression as input and simplifies it by combining exponential terms involving complex numbers. The simplified expression should have all exponential terms involving complex num... | ```python
import sympy
def exptrigsimp(expression: str) -> str:
z = sympy.symbols('z')
expr = sympy.sympify(expression)
simplified_expr = sympy.simplify(expr)
return str(simplified_expr)
```
The `exptrigsimp` function uses the `sympy` library to simplify the input expression. It first converts the inp... | magicoder | python |
You are tasked with implementing a Markdown parser that can handle the conversion of specific Markdown syntax to HTML. Your task is to write a function that replaces opening heading-tags in a Markdown string with the corresponding HTML heading-tags.
You are given a Markdown string `md` and a list of regular expression... | ```python
import re
def convert_to_html_headings(md, h_patterns):
md = md.replace("\r\n", "\n") # Normalize line endings
# Replace opening heading-tags with corresponding HTML heading-tags
for i in range(6):
md = h_patterns[i].sub(lambda match: "\n" + ("#" * (i + 1)) + " " + match.group(1) + "\n"... | magicoder | python |
You are tasked with implementing a custom endpoint span extractor for natural language processing tasks. The endpoint span extractor is used to extract spans of text from a given input based on certain criteria. In this problem, you will be working with a code snippet from a Python class that sets up the endpoint span ... | ```python
def extract_spans(input_text, endpoint_span_extractor_dim, combination, max_span_width):
if max_span_width > 1:
# Implement span extraction logic based on the combination parameter
if combination == "x,y":
# Extract spans based on individual endpoint representations 'x' and 'y'... | magicoder | python |
You are tasked with creating a Python decorator that calculates the execution time of a given function and prints the result. Your decorator should take into account the start and end times of the function execution and calculate the time difference to determine the function's speed.
Your decorator function should be ... | ```python
import time
def speed_calc_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
execution_time = (end_time - start_time) * 1000 # Convert to milliseconds
print(f"Function '{func.__name__}' to... | magicoder | python |
You are tasked with implementing a custom execution mechanism for running code in a sandboxed environment. The provided code snippet is a part of a larger system responsible for executing code with isolation and monitoring. Your goal is to design a class that extends the given base class and implements the necessary lo... | The `CustomExecutionService` class extends the `ExecutionServiceBase` class and overrides the `ExecuteWithIsolation` method to implement sandboxed execution. It creates a custom `AppDomain` with a specified setup to provide isolation for the code execution. Within the sandboxed environment, it simulates the execution o... | magicoder | assembly |
You are tasked with implementing a data logging system for environmental sensors. The system should be able to receive data from various types of sensors and store the data for later analysis. Each sensor provides specific types of data, such as temperature, humidity, pressure, etc.
Your task is to design a Python cla... | ```python
class DataLogger:
def __init__(self):
self.sensors = []
def add_sensor(self, sensor):
self.sensors.append(sensor)
def log_data(self):
for sensor in self.sensors:
# Assuming the sensors have a method to fetch data
data = sensor.fetch_data()
... | magicoder | python |
You are tasked with creating a Python program to analyze and visualize the internal metrics of a DDCW (Dynamic Density-based Clustering with Weighting) model after it has been evaluated. The evaluation object has been saved using Python's `pickle` module and needs to be loaded for visualization.
Your program should pe... | ```python
import pickle
import matplotlib.pyplot as plt
try:
# Step 1: Load the evaluation object from the file "evaluatorobject" using pickle
with open("evaluatorobject", "rb") as file:
evaluator = pickle.load(file)
# Step 2: Extract the internal metrics from the loaded evaluation object
inte... | magicoder | python |
You are tasked with designing a Python package management system that can handle dependencies between different modules. Each module has a name and may depend on other modules. Your task is to implement a function that takes a list of module dependencies and returns the order in which the modules should be loaded to sa... | ```python
def load_order(module_dependencies):
graph = {}
for dependency in module_dependencies:
parent, child = dependency
if parent not in graph:
graph[parent] = []
graph[parent].append(child)
visited = set()
load_order_list = []
def dfs(node):
if node... | magicoder | python |
You are tasked with implementing a Python function that simulates a simplified version of the `random` module. Your function should generate a random integer within a specified range using a linear congruential generator (LCG) algorithm. The LCG algorithm is defined by the recurrence relation: Xn+1 = (a*Xn + c) % m, wh... | ```python
def lcg_random(seed: int, range_start: int, range_end: int) -> int:
a = 1664525
c = 1013904223
m = 2**32
Xn = seed
Xn = (a * Xn + c) % m # Discard the first result to improve randomness
Xn = (a * Xn + c) % m # Use the second result as the initial random value
random_range = range... | magicoder | python |
You are tasked with implementing a function to create a constant buffer view in a graphics programming context using the DirectX 12 API. The provided code snippet is a part of a Rust wrapper for the DirectX 12 API, and it defines the signature of the function `create_constant_buffer_view`. This function is responsible ... | ```rust
use winapi::um::d3d12::{ID3D12Device, D3D12_CONSTANT_BUFFER_VIEW_DESC};
use std::ptr;
use std::ffi::c_void;
pub unsafe fn create_constant_buffer_view(
&self,
device: &ID3D12Device,
desc: &D3D12_CONSTANT_BUFFER_VIEW_DESC,
) -> Result<(), Error> {
// Call the underlying DirectX 12 API to create t... | magicoder | rust |
You are tasked with creating a parser for a testing framework that can extract and process specific commands and options from PHP code snippets. The parser needs to handle scenarios and features defined within the code and perform various operations based on the extracted information.
Your task is to implement a PHP p... | ```php
class TestingFrameworkParser
{
private $scenario;
public function __construct()
{
$this->scenario = new Scenario();
}
public function parseScenarioOptions($code, $options)
{
// Parse the scenario options from the code snippet
// Extract and process the scenar... | magicoder | php |
You are tasked with implementing a method to generate an output sentence based on the input data. The input data is provided as a dictionary `input_streams_dict` containing the following keys and their corresponding values:
- `'sentences_logits'`: A tensor of shape `(batch_size, max_sentence_length, vocab_size)` conta... | ```python
from typing import Dict
def compute(self, input_streams_dict: Dict[str, object]) -> Dict[str, object]:
# Extracting input data
sentences_logits = input_streams_dict['sentences_logits']
sentences_widx = input_streams_dict['sentences_widx']
sentences_one_hot = input_streams_dict['sentences_one_... | magicoder | python |
You are tasked with implementing a bounding volume calculation for a 3D shape in a Rust program. The given code snippet is a part of a larger program that defines bounding volume calculations for different 3D shapes. The `HasBoundingVolume` trait is implemented for the `Cone` and `Cylinder` shapes, providing a method `... | ```rust
#[cfg(feature = "dim3")]
impl<N: Real> HasBoundingVolume<N, AABB<N>> for CustomShape<N> {
#[inline]
fn bounding_volume(&self, m: &Isometry<N>) -> AABB<N> {
bounding_volume::support_map_aabb(m, self)
}
}
```
In the solution, we implement the `HasBoundingVolume` trait for `CustomShape<N>`. We ... | magicoder | rust |
You are tasked with implementing a post-processing system for a tree data structure. The tree is represented using a custom `Node` class, which contains a list of child nodes. Each node can have a post-processor associated with it, which is responsible for performing some operation on the node and its children.
Your t... | ```java
public PostProcessor createPostProcessor() {
if (match) {
return new PostProcessor() {
@Override
public void process(Node node) {
System.out.println("Matched node");
}
};
} else {
return new PostProcessor() {
@Overri... | magicoder | java |
You are tasked with creating a Python class that simulates a simple bank account. The class should have methods for depositing funds, withdrawing funds, and checking the current balance. Additionally, the class should incorporate a feature to set a daily withdrawal limit for each account.
Your task is to implement the... | ```python
import datetime
class BankAccount:
def __init__(self, account_holder, initial_balance):
self.account_holder = account_holder
self.balance = initial_balance
self.daily_withdrawal_total = 0
self.daily_withdrawal_limit = None
self.last_transaction_date = datetime.date... | magicoder | python |
You are tasked with creating a custom pytest plugin that dynamically generates repository paths for a simulation core (simcore) application. The plugin should also validate the schemas used in the simcore application. Your goal is to implement the necessary fixtures and plugins to achieve this functionality.
Your task... | ```python
# Implementation of the pytest plugin for repository paths
import pytest
@pytest.fixture(scope="session")
def repository_paths():
# Implement logic to dynamically generate repository paths for the simcore application
# ...
return repository_paths
# Implementation of the pytest plugin for schema ... | magicoder | python |
You are working on a project that involves implementing a custom data type for vector operations. The code snippet provided defines some operations for this custom vector type. Your task is to implement the division operation for this vector type.
The division operation for vectors is defined as follows:
Given two vec... | ```swift
static func /(lhs: Self, rhs: Self) -> Self {
var result = Self()
for i in result.indices { result[i] = lhs[i] / rhs[i] }
return result
}
```
In the solution, the division operation for the custom vector type is implemented. It takes two vectors `lhs` and `rhs` of the same length and returns a new vecto... | magicoder | swift |
You are tasked with implementing a URL routing system for a web application. The given code snippet represents a portion of the URL configuration for a Django web framework application. Each `url` function maps a URL pattern to a specific view function. The URL patterns are defined using regular expressions and capture... | ```python
import re
url_patterns = [
(r'^appleupdate/(?P<serial>[^/]+)$', 'appleupdate'),
(r'^raw/(?P<serial>[^/]+)$', 'raw'),
(r'^submit/(?P<submission_type>[^/]+)$', 'submit'),
(r'^warranty/(?P<serial>[^/]+)$', 'warranty'),
(r'^ip$', 'lookup_ip'),
(r'^(?P<submission_type>[^/]+)$', 'submit')
]... | magicoder | python |
You are tasked with creating a script to automate the setup of development environment configurations based on the presence of certain environment variables. Your script should check for the existence of specific environment variables and perform corresponding actions if they are present.
Your script should specifical... | ```bash
#!/bin/bash
# Enable GPG key to sign Git commits if environment variable is set
if [[ -n $GPG_SIGN_COMMITS ]]; then
echo "Enabling GPG key to sign Git commits."
# Add commands to enable GPG key here
fi
# Auto activate Intelephense if license key is available
if [[ -n $INTELEPHENSE_LICENSEKEY ]]; then
ms... | magicoder | shell |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.