query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a custom access control mechanism for a web application using Django. The provided code snippet is a part of a Django application and demonstrates a custom user detail view that restricts access based on certain conditions. Your task is to extend this functionality by implementing a cus... | Custom permission class implementation:
```python
from django.core.exceptions import PermissionDenied
from django.contrib.auth.models import User
from django.http import Http404
class CustomUserPermission:
def has_permission(self, request, view):
if request.user.is_superuser:
return True
... | magicoder | python |
You are tasked with implementing 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 keep track of the total number of transactions (deposits and withdrawals) made on the account.
Yo... | ```python
class BankAccount:
def __init__(self, initial_balance):
self.balance = initial_balance
self.transactions = 0
def deposit(self, amount):
self.balance += amount
self.transactions += 1
def withdraw(self, amount):
if self.balance >= amount:
self.ba... | magicoder | python |
You are tasked with implementing a simple C++ program that models a basic lighting system for a 3D scene using the provided code snippet as a starting point. The program should define a base class for lights and two derived classes for point lights and directional lights. Additionally, the program should calculate the ... | ```cpp
#include "Components/Lights/LightInterface.hpp"
#include <vector>
#include <algorithm>
namespace Components::Lights {
class PointLight : public LightInterface {
public:
PointLight(const glm::vec3& position, const glm::vec3& color)
: position_(position), color_(color) {}
virt... | magicoder | cpp |
You are tasked with creating a Python function that processes files in a directory and uploads them to an AWS S3 bucket. The function should take the directory path, the S3 bucket name, and the AWS credentials as input parameters. The function should upload each file in the directory to the specified S3 bucket with a t... | ```python
import os
import boto3
from datetime import datetime
from typing import List
def upload_files_to_s3(directory_path: str, bucket_name: str, aws_access_key: str, aws_secret_key: str) -> List[str]:
s3 = boto3.client('s3', aws_access_key_id=aws_access_key, aws_secret_access_key=aws_secret_key)
uploaded_f... | magicoder | python |
You are tasked with designing a system for a web application that involves configuring security, authentication, setting up a database, registering routes, and serving the frontend. Your goal is to organize these tasks in a way that ensures proper execution and efficiency.
Given the code snippet provided, you need to ... | ```python
class WebApplication:
def __init__(self, app, router):
self.app = app
self.router = router
def configureSecurity(self):
# Implement security configuration logic here
pass
def configureAuthentication(self):
# Implement authentication configuration logic her... | magicoder | python |
You are working on a project for a data analysis company called Incognita. Your task is to analyze census data for various districts and generate a report based on specific criteria. The census data is loaded from the `scout_census` module, and district boundaries are obtained from the `geographies` module. The project... | ```python
def generate_report(criteria, attributes):
census_data = load_census_data() # Load census data
filtered_data = filter.apply_criteria(census_data, criteria) # Apply filtering criteria
report = {}
for attribute in attributes:
attribute_data = [row[attribute] for row in filtered_data if... | magicoder | python |
You are tasked with implementing a location search form for a travel website. The form should allow users to search for locations based on various criteria such as city, country, and type of location (e.g., beach, mountain, city). The form should also provide the option to filter results based on the availability of sp... | ```java
import java.util.ArrayList;
import java.util.List;
class Location {
private String name;
private String city;
private String country;
private String type;
private List<String> amenities;
public Location(String name, String city, String country, String type, List<String> amenities) {
... | magicoder | java |
You are tasked with implementing a class that manages context buffers for a GPU computing environment. The provided code snippet is a partial implementation of the `ContextBuffers` class, which is responsible for managing the memory buffers and associated resources for a specific GPU device. Your task is to complete th... | ```cpp
class ContextBuffers {
private:
bool _allocated;
int _deviceId;
void* _execStream;
void* _specialStream;
public:
// Constructor to initialize the ContextBuffers object with the device ID and allocate necessary resources
ContextBuffers(int deviceId) : _deviceId(deviceId), _allocated(true)... | magicoder | cpp |
You are working on a project that involves implementing a neural network model for processing sequential data. As part of this project, you need to create a custom implementation of a Long Short-Term Memory (LSTM) network in PyTorch. The provided code snippet is a part of the implementation and involves initializing th... | ```python
import torch
import torch.nn as nn
class CustomLSTM(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, output_size):
super(CustomLSTM, self).__init__()
self.num_layers = num_layers
self.time_hidden = hidden_size # Assuming hidden size for time LSTM is the same as... | magicoder | python |
You are tasked with creating a script to automate the build process for the Real-Time Executive for Multiprocessor Systems (RTEMS) operating system. RTEMS is a real-time operating system designed for embedded systems and is known for its high reliability and performance. Your script should perform the following tasks:
... | ```bash
#!/bin/bash
# Clone the RTEMS source code repository
git clone https://github.com/RTEMS/rtems.git
cd rtems
# Configure the build for a specific target architecture
./bootstrap -c
./bootstrap -p
./configure --target=arm-rtems5 --enable-rtemsbsp=realview_pbx_a9_qemu --enable-tests=samples
# Build the RTEMS ope... | magicoder | shell |
You are tasked with implementing a custom resource loader for a natural language processing (NLP) model. The provided code snippet initializes three resources for a machine translation model using Marian, a popular NLP framework. Your task is to create a resource loader that can fetch these resources from a remote serv... | ```rust
use anyhow::{Result, Context};
use std::io::Read;
use reqwest;
enum MarianModelResources {
ENGLISH2CHINESE,
// Add other model resources here
}
enum MarianConfigResources {
ENGLISH2CHINESE,
// Add other config resources here
}
enum MarianVocabResources {
ENGLISH2CHINESE,
// Add other ... | magicoder | rust |
You are tasked with implementing a reducer function for a shopping cart application using TypeScript and Redux. The provided code snippet includes imports for the initial state of the cart, the reducer state interface, and action types.
Your task is to create a TypeScript reducer function that handles various action t... | ```typescript
// cart-reducer.ts
import { initialState } from '../cart-initial-state';
import { DaffCartReducerState } from '../cart-state.interface';
import { ActionTypes } from '../action-types.type';
const cartReducer = (state: DaffCartReducerState = initialState, action: { type: ActionTypes, payload: any }): DaffC... | magicoder | typescript |
You are tasked with implementing a custom optimizer for a convolutional neural network (CNN) model. The optimizer should be designed to minimize a specific loss function while incorporating custom update rules for the model's parameters. Your task is to create a custom optimizer class that inherits from the base optimi... | ```python
class CustomOptimizer(Optimizer):
def __init__(self, learning_rate=0.001, momentum=0.9):
super(CustomOptimizer, self).__init__()
self.learning_rate = learning_rate
self.momentum = momentum
self.velocity = {}
def update(self, model, gradients):
if not self.veloc... | magicoder | python |
You are tasked with implementing a Python function that calculates the Hybrid EState-VSA descriptors for a given molecule. The EState-VSA descriptors are a set of molecular descriptors used in chemoinformatics to characterize the distribution of atomic properties within a molecule. The function should take a molecule r... | ```python
import numpy
from rdkit import Chem
from rdkit.Chem.EState import EStateIndices
from rdkit.Chem.MolSurf import _LabuteHelper
def calculate_hybrid_estate_vsa_descriptors(smiles: str) -> dict:
try:
mol = Chem.MolFromSmiles(smiles)
if mol is None:
raise ValueError("Invalid SMILES... | magicoder | python |
You are working on a file processing system that needs to count the occurrences of a specific word in multiple files. The function `count "touched" $file` is used to count the occurrences of the word "touched" in a given file. Additionally, there are multiple files named `depth0.txt`, `depth1.txt`, `depth2.txt`, `depth... | ```bash
#!/bin/bash
total_count=0
# Loop through each depth file and calculate the total count
for depth_file in base_${grammar}/depth*.txt; do
count=$(count "touched" $depth_file) # Assuming count "touched" $file returns the count
total_count=$((total_count + count))
done
echo "Total count of the word 'tou... | magicoder | shell |
You are tasked with creating a script to automate the deployment process of a web application. The deployment process involves navigating to the "web" directory, setting the NODE_ENV environment variable to "production", running the "build" script using yarn with the --color flag, and then returning to the original dir... | ```bash
#!/bin/bash
# Store the current directory
original_dir=$(pwd)
# Change directory to "web"
cd web || { echo "Error: Unable to change directory to web"; exit 1; }
# Set NODE_ENV environment variable to "production"
export NODE_ENV=production
# Run the "build" script using yarn with the --color flag
yarn -s ru... | magicoder | shell |
You are tasked with implementing a data generator class in Python that can be used to preprocess and augment image data for machine learning tasks. The class should be capable of fitting to the training data and generating batches of augmented data for training and testing.
Your task is to complete the implementation ... | ```python
import numpy as np
import imgaug.augmenters as iaa
class DataGenerator:
def __init__(self):
self.augmentor = iaa.Sequential([
iaa.Fliplr(0.5), # horizontally flip 50% of the images
iaa.Affine(rotate=(-30, 30)) # rotate images by -30 to 30 degrees
])
def fit(... | magicoder | python |
You are tasked with creating a Python function that takes a string as input and converts it into Morse code using Raspberry Pi GPIO pins. The function should utilize the provided `morse` dictionary to map characters to their Morse code equivalents and the `print_dot` function to output the Morse code using GPIO pins.
... | ```python
import RPi.GPIO as GPIO
import time
morse = {"a": ".-", "b": "-...", "c": "-.-.", "d": "-..", "e": ".", "f": "..-.", "g": "--.", "h": "....", "i": "..", "j": ".---", "k": "-.-", "l": ".-..", "m": "--", "n": "-.", "o": "---", "p": ".--.", "q": "--.-", "r": ".-.", "s": "...", "t": "-", "u": "..-", "v": "...-",... | magicoder | python |
You are tasked with creating a Python function that simulates a simple banking system. The function should take in three parameters: the account balance, the amount to deposit, and the amount to withdraw. The function should perform the deposit and withdrawal operations and return the updated account balance.
Your tas... | ```python
from rpc4django import rpcmethod
from .othermodule import intro, getrequest
from .secretmodule import *
@rpcmethod(name='rpc4django.mytestmethod', signature=['int', 'int', 'int', 'int'])
def mytestmethod(a, b, c):
'''
This method performs a test operation with three integer parameters.
'''
pa... | magicoder | python |
You are tasked with implementing a dueling deep Q-network (DQN) for reinforcement learning. The dueling DQN architecture separates the value and advantage streams to improve learning efficiency. Your goal is to complete the implementation of the `dueling_Q_net` class by defining the `forward` method, which builds a net... | ```python
class dueling_Q_net(nn.Module):
def __init__(self, input_dim, output_dim):
super(dueling_Q_net, self).__init__()
self.input_dim = input_dim
self.output_dim = output_dim
# Define the shared layers for both streams
self.shared_layers = nn.Sequential(
nn.L... | magicoder | python |
You are tasked with implementing a package management system that involves handling different types of content packages. The system is designed to work with a `PackageManager` and supports strict validation. Additionally, it utilizes a map of sub-content packages, where each package is associated with a unique `Package... | ```java
import java.util.Map;
public class PackageHandler extends BasePackageHandler {
private Converter converter;
private EntryHandler[] handlers;
public PackageHandler(PackageManager packageManager, boolean strictValidation, Map<PackageId, String> subContentPackages, Converter converter) {
supe... | magicoder | java |
You are given a 2D grid representing a map where each cell contains a non-negative integer representing the cost to move through that cell. You need to find the minimum sum of a path from the top-left cell to the bottom-right cell, moving only right or down.
For example, given the following grid:
```
[
[1,3,1],
[1... | ```swift
func minPathSum(_ grid: [[Int]]) -> Int {
let m = grid.count
let n = grid[0].count
var dp = Array(repeating: Array(repeating: 0, count: n), count: m)
dp[m-1][n-1] = grid[m-1][n-1]
for i in (0..<m-1).reversed() {
dp[i][n-1] = grid[i][n-1] + dp[i+1][n-1]
}
for j... | magicoder | swift |
You are tasked with implementing a behavior for a PHP class that manages access control for a web application. The behavior should enforce access control rules based on the roles of the users. The behavior should be implemented within the `behaviors` method of the class, which returns an array of behaviors. The behavio... | ```php
/**
* {@inheritdoc}
*/
public function behaviors()
{
return [
'access' => [
'class' => \yii\filters\AccessControl::class,
'rules' => [
[
'allow' => true,
'actions' => ['view', 'index'],
'roles' => ['... | magicoder | php |
You are working on a project to evaluate the performance of a machine learning model. The code snippet provided is a part of a Python script that calculates and stores performance metrics for different cycles of model training and validation. The script uses the NumPy library for mathematical operations.
Your task is ... | ```python
import numpy as np
def generate_performance_summary(tr_avg_performances, vl_avg_performances, vl_std_performances):
tr_mean_dice = np.mean(tr_avg_performances[:-1])
tr_std_dice = np.std(tr_avg_performances[:-1])
vl_mean_dice = np.mean(vl_avg_performances[:-1])
vl_std_dice = np.std(vl_std... | magicoder | python |
You are tasked with implementing a media tagging system for a digital media library. The media library contains various types of media such as images, videos, and audio files. Each piece of media can be associated with multiple tags, and each tag can have a corresponding value. The media tagging system should allow for... | ```python
class MediaTaggingSystem:
def __init__(self):
self._media_tags = {}
def add_tag(self, media, tag, value):
if media in self._media_tags:
self._media_tags[media][tag] = value
else:
self._media_tags[media] = {tag: value}
def get_tag_value(self, media,... | magicoder | python |
You are tasked with creating a program that generates unique usernames for a given number of users. Each username will be either a standalone username or an email address, depending on a specified flag. The program should also support the option to use custom email providers for the email addresses.
The program should... | ```python
import random
def generate_username():
# Implement the logic to generate a unique username
pass # Placeholder for the actual username generation logic
def generate_usernames(args, email_providers):
usernames = []
for i in range(args.number):
username = generate_username()
if... | magicoder | python |
You are working on a robotics project that involves interacting with a simulated environment. The code snippet provided is a part of the policy function used for controlling the robot's actions. The policy function takes a timestep as input and performs various operations based on the observation received. The observat... | ```python
import cv2
def process_observation(timestep):
obs = timestep.observation
# Display the images from the observation
for k in ['basket_back_left/pixels', 'basket_front_left/pixels', 'basket_front_right/pixels']:
cv2.imshow('{}'.format(k), obs[k])
cv2.waitKey(1)
# Print the workspa... | magicoder | python |
You are tasked with implementing a function that converts a one-dimensional array of coordinates into a multi-dimensional grid. The function takes in the following parameters:
- `args`: A list of lists, where each inner list contains the coordinates for a specific dimension.
- `npcube`: A list containing the number of ... | ```python
def convert_to_grid(args, npcube, npo):
na = len(npcube)
g = [[[0 for _ in range(na)] for _ in range(npcube[0])] for _ in range(npcube[1])]
ai = [0]*na
for i in range(npo):
itemp = i
for j in range(na-1, 0, -1):
ai[j] = itemp // npcube[j-1]
itemp -= ai[j... | magicoder | python |
You are tasked with implementing a macro in Rust that emulates the behavior of the `add!` macro. The `add!` macro should take a variable number of arguments and return their sum. The macro should be able to handle both integers and floating-point numbers.
Your task is to complete the implementation of the `add!` macro... | ```rust
#[macro_export]
macro_rules! add {
() => { 0 };
($val:expr) => { $val };
($val:expr, $($vals:expr),+) => { $val + add!($($vals),+) };
}
```
The provided solution implements the `add!` macro using Rust's macro_rules. It handles the base case of an empty input list, a single input value, and multiple ... | magicoder | rust |
You are tasked with implementing a Java class that translates error information into a data transfer object (DTO). The provided code snippet is a partial implementation of a class named `ErrorCodeTranslator`, which is a Spring component responsible for converting `ErrorInfo` objects into `ErrorCodeDto` objects. The `Er... | ```java
import org.jbb.lib.restful.domain.ErrorInfo;
import org.springframework.stereotype.Component;
@Component
public class ErrorCodeTranslator {
public ErrorCodeDto toDto(ErrorInfo errorInfo) {
return ErrorCodeDto.builder()
.errorName(errorInfo.name())
.build();
}
}
... | magicoder | java |
You are tasked with creating a program to manage a version-controlled repository using a custom tool called "yadm." The program needs to handle various operations such as error handling, file manipulation, and merging branches. Your task is to implement a function that performs these operations based on the given code ... | ```bash
manage_repository() {
if [ ! -d "$master" ]; then
echo ":: %F{red}ERROR%f: master worktree does not exist"
return 1
fi
files=( $(git -C $master ls-files -ci -X $repo/info/sparse-checkout) $(yadm diff --name-only --cached) )
yadm stash push -- ':/:'${^files} || return 1
yadm merge --no-edit ma... | magicoder | shell |
You are tasked with creating a Python function that processes data from an Excel file and generates an HTML table based on the data. The function should take the file path as input and return the HTML string representing the table.
Your task is to implement the `excel_to_html_table` function, which takes a file path t... | ```python
import pandas as pd
def excel_to_html_table(file_path):
try:
data = pd.read_excel(file_path).to_dict(orient='records')
html = "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n </head>\n <body>\n <table>\n"
# Add table headers
... | magicoder | python |
You are tasked with creating a Python class that manages cargo information for a shipping company. The class should utilize PyQt and provide a method to retrieve all cargo information in a specific format.
Create a class `CargoManager` that inherits from `QObject` and includes the following methods:
1. `__init__`: The... | ```python
from PyQt5.QtCore import QObject, pyqtSlot, QVariant
class Cargo:
@staticmethod
def select():
# Simulated method to retrieve cargo data
return [Cargo("Item1", 100), Cargo("Item2", 200)]
def __init__(self, name, weight):
self.name = name
self.weight = weight
d... | magicoder | python |
You are tasked with creating a Python program that processes files in a specified directory and its subdirectories. Your program should search for files that match a specific pattern and perform a designated action on those files.
You are given the following code snippet as a starting point:
```python
import os
impo... | ```python
import os
import re
def process_files_matching_pattern(directory, pattern):
for root, dirs, files in os.walk(directory):
for file in files:
if re.match(pattern, file):
# Perform the desired action, for example, printing the file name
print(os.path.join(... | magicoder | python |
You are tasked with creating a Python function that calculates the time elapsed in minutes and seconds and then prints a message indicating the time taken for a process to complete. Your function should take a start time (`since`) as a parameter and return the model used for the process.
The function should perform th... | ```python
import time
def calculate_time_and_print_message(since, model):
time_elapsed = time.time() - since
minutes = int(time_elapsed // 60)
seconds = int(time_elapsed % 60)
print('Training complete in {}m {}s'.format(minutes, seconds))
return model
```
The `calculate_time_and_print_message` func... | magicoder | python |
You are tasked with implementing a class that simulates a relay for handling OSC (Open Sound Control) messages. OSC is a protocol for communication among computers, sound synthesizers, and other multimedia devices that is optimized for modern networking technology. The relay should be able to receive OSC messages and p... | ```python
# Example implementation in Python using the python-osc library for handling OSC messages
from pythonosc import dispatcher, osc_server, udp_client, osc_message_builder
from pythonosc.osc_server import AsyncIOOSCUDPServer
import asyncio
class OSCRelay:
def __init__(self):
self.devices = {} # Dic... | magicoder | python |
You are tasked with implementing a NodeStyleManager class that manages different NodeStyle objects for various device types and orientations. Each NodeStyle object represents the visual style for a specific device type and orientation.
The NodeStyle class has the following properties:
- supportsTablet: A boolean indic... | ```swift
class NodeStyleManager {
var tabletPortraitNodeStyle: NodeStyle?
var phoneLandscapeNodeStyle: NodeStyle?
var phonePortraitNodeStyle: NodeStyle?
func setNodeStyle(deviceType: DeviceType, orientation: Orientation, style: NodeStyle) {
switch (deviceType, orientation) {
case (.tabl... | magicoder | swift |
You are tasked with implementing a Python class that simulates a match client for a multiplayer game. The match client will be responsible for managing player interactions and game state during a match. The class should include methods for adding players to the match, starting the match, and handling player actions dur... | ```python
from abc import ABC, abstractmethod
from gloop.entities.match import Match
from gloop.entities.player import Player
class MatchClient(ABC):
def __init__(self):
self.players = []
def add_player(self, player: Player):
self.players.append(player)
@abstractmethod
def start_match... | magicoder | python |
You are tasked with implementing a custom annotation processor for a Java application framework. The framework uses the `@Getter` and `@Setter` annotations to automatically generate getter and setter methods for class fields. Your goal is to create a processor that identifies classes implementing the `HelixObject` inte... | ```java
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
impor... | magicoder | java |
You are tasked with creating a program that simulates a simplified version of a task runner. The task runner will execute a series of tasks, each represented by a command, and report the execution status of each task. Your program should be able to handle both successful and failed task executions.
You are given a cod... | ```python
import subprocess
def execute_tasks(commands):
for i, command in enumerate(commands, start=1):
process = subprocess.Popen(command, shell=True)
process.communicate()
if process.returncode == 0:
print(f"Task {i}: Success")
else:
print(f"Task {i}: Fail... | magicoder | python |
You are tasked with creating a function that takes in an array of movie objects and generates a dynamic HTML layout to display these movies. Each movie object contains the following properties: `title`, `posterUrl`, and `description`. The function should generate HTML markup for each movie, including the movie title, p... | ```javascript
function generateMovieHTML(movies) {
let html = '<div class="movie-container">';
movies.forEach(movie => {
html += `
<div class="movie">
<img src="${movie.posterUrl}"/>
<div class="description">
<h3>${movie.title}</h3>
... | magicoder | javascript |
You are tasked with implementing a machine learning model for sentiment analysis using the scikit-learn library in Python. Your goal is to train a classifier using grid search to achieve the best performance on a given dataset. The dataset contains features (X) and corresponding labels (Y) for sentiment analysis. After... | ```python
# Import necessary libraries
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.svm import SVC
# Split the dataset into training and testing sets
X_train, X_test, Y_train, Y_test = train_test_split(X, Y... | magicoder | python |
You are tasked with implementing a pagination system for fetching data from an API. The API uses a continuation token to retrieve subsequent pages of data. The provided code snippet is a part of a Swift class that is responsible for managing the pagination process. The `initialContinueId` property is used to provide th... | ```swift
class PaginationManager {
var continuationToken: String?
var initialContinueId: String? {
return nil
}
func fetchNextPage(completion: @escaping ([Data]) -> Void) {
guard let token = continuationToken ?? initialContinueId else {
completion([])
... | magicoder | swift |
You are tasked with creating a registration form for a web application using Flask and its associated libraries. The provided code snippet includes a part of the form validation logic for checking the existence of a username and email in the database. The `name_exists` and `email_exists` functions are used as custom va... | ```python
class RegisterForm(FlaskForm):
username = StringField(
'Username',
validators=[
DataRequired(),
Regexp(r'^[a-zA-Z0-9_]+$',
message="Username must contain only letters, numbers, or underscores.")
]
)
email = StringField(
'Em... | magicoder | python |
You are tasked with implementing a Python class method that manipulates a NumPy array based on given input parameters. The method should take two integer values, `num_lower` and `num_upper`, and two float values, `dist_high` and `dist_low`, as input. The method should then perform the following steps:
1. Convert `num_l... | ```python
import numpy as np
class ArrayManipulator:
def __init__(self, dim_fc_out):
self.dim_fc_out = dim_fc_out
def manipulate_array(self, num_lower, num_upper, dist_high, dist_low):
lower_ind = int(num_lower)
upper_ind = int(num_upper)
array = np.zeros(self.dim_fc_out)
... | magicoder | python |
You are tasked with implementing a Python class that represents a fully connected network (FCN) head for a computer vision model. The FCN head is responsible for processing the features extracted from the backbone stage of the model. The provided code snippet outlines the initial configuration for the FCN head, specify... | ```python
class FCNHead:
def __init__(self, type='FCNHead', in_index=-1):
self.type = type
self.in_index = in_index
self.processed_output = None
def process_features(self, input_features):
# Perform processing specific to the FCN head using the input features
# Here, we ... | magicoder | python |
You are tasked with implementing a lexer for a simple programming language. The lexer is responsible for tokenizing the input source code into meaningful units, such as keywords, identifiers, and symbols. The given code snippet is a part of the lexer's implementation, specifically the `next_token` method.
The `next_to... | ```rust
fn next_token(&mut self) -> Option<Result<(usize, Token, usize), LexicalError>> {
while let Some((i, c)) = self.cursor.current() {
match c {
// Add logic to handle different token types
// For example, to handle identifiers
'a'..='z' | 'A'..='Z' => {
... | magicoder | rust |
You are tasked with implementing a function that processes data from a table view in an iOS application. The table view displays a list of contacts, and the user can select a contact to view its details in a separate view controller. Your task is to write a function that retrieves the selected contact's details and pre... | ```swift
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ShowContactSegue" {
if let destination = segue.destinationViewController as? ContactDetailViewController {
if let indx = tableview.indexPathForSelectedRow?.row {
let contactDetai... | magicoder | swift |
You are tasked with implementing a simple temperature monitoring system using Swift. The provided code snippet includes a `TemperatureViewController` class that inherits from `NSViewController`. This class has two properties: `temperature` and `isOn`, both marked as `@objc dynamic`. The `temperature` property is initia... | ```swift
import Cocoa
class TemperatureViewController: NSViewController {
@objc dynamic var temperature = 50
@objc dynamic var isOn = true
override func viewDidLoad() {
super.viewDidLoad()
}
// Method to update the temperature property
func updateTemperature(newTemperatur... | magicoder | swift |
You are tasked with implementing a cryptocurrency address generator using Python. The given code snippet outlines a method `generate_address` within a class, which takes no arguments and returns a tuple of two strings. The method is responsible for generating a cryptocurrency address from a private key.
The method sta... | ```python
from typing import Tuple
import hashlib
class CryptocurrencyAddressGenerator:
def __init__(self, private_key: bytes):
self.private_key = private_key
def generate_address(self) -> Tuple[str, str]:
q = point_mul(int.from_bytes(self.private_key, byteorder="big"))
public_key = b"... | magicoder | python |
You are tasked with implementing a data stream sink for a TLS socket in Swift. The provided code snippet is a part of a TLS socket library and shows the extension method `sink` for the `TLSSocket` class. Your goal is to create a `TLSSocketSink` class that will handle writing data to the TLS socket on a specific event l... | ```swift
import NIO
public class TLSSocketSink<Socket: TLSSocket> {
private let socket: Socket
private let eventLoop: Worker
init(socket: Socket, on eventLoop: Worker) {
self.socket = socket
self.eventLoop = eventLoop
}
public func write(_ data: ByteBuffer) {
eventLoop.exe... | magicoder | swift |
You are tasked with implementing a function that checks whether a given string is a valid parentheses sequence. A valid parentheses sequence is defined as a string consisting of only '(' and ')' characters, where each open parenthesis must have a corresponding closing parenthesis and the pairs must be properly nested.
... | ```python
def valid_parentheses(s: str) -> bool:
stack = []
for char in s:
if char == '(':
stack.append(char)
elif char == ')':
if not stack:
return False # Unmatched closing parenthesis
stack.pop()
return len(stack) == 0 # True if all pa... | magicoder | python |
You are tasked with implementing a custom validation for the "nome" (name) field in the "Funcionario" class. The validation rule requires that the length of the name should be between 3 and 50 characters. You need to create a custom validation annotation and apply it to the "nome" field in the "Funcionario" class.
You... | ```java
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.FIELD, ElementType.M... | magicoder | java |
You are tasked with creating a Java program that utilizes external libraries and packages. Your goal is to package the program and its dependencies into a single JAR file using the `jar` command. The `jar` command is a utility provided by the Java Development Kit (JDK) for creating Java Archive (JAR) files.
Your prog... | To solve this problem, you can follow these steps:
1. Write a Java program that includes external libraries or packages. For example:
```java
package kata.app;
import external.library.ExampleClass;
public class HelloModUsingLibs1 {
public static void main(String[] args) {
ExampleC... | magicoder | java |
You are tasked with implementing a function to calculate the perspective projection matrix for a 3D camera. The provided code snippet contains a part of the implementation for the perspective camera's projection matrix. Your task is to complete the implementation of the `sm::mat4::Perspective` function, which takes in ... | ```cpp
sm::mat4 sm::mat4::Perspective(float fov, float aspect, float znear, float zfar) {
float tanHalfFov = tan(fov / 2);
sm::mat4 mat;
mat.x[0] = 1 / (aspect * tanHalfFov);
mat.x[5] = 1 / tanHalfFov;
mat.x[10] = -(zfar + znear) / (zfar - znear);
mat.x[11] = -2 * zfar * znear / (zfar - znear);... | magicoder | cpp |
You are tasked with implementing a module resolution algorithm for a JavaScript module system. The module system uses the `export * from` syntax to re-export all named exports from other modules. Your goal is to write a function that resolves the exports from a given module and returns a list of all the named exports, ... | ```javascript
function resolveModuleExports(moduleCode) {
const exportStatements = moduleCode.match(/export \* from "([^"]+)";/g) || [];
const namedExports = new Set();
const resolveExports = (modulePath) => {
const moduleCode = getModuleCode(modulePath);
const namedExports = moduleCode.match(/export\s*{... | magicoder | javascript |
You are tasked with implementing a class for managing rule activations in a rule-based system. The class `Activation` represents an activation of a rule and has the following attributes and methods:
- `name`: a string representing the name of the rule
- `salience`: an integer representing the salience of the activation... | ```python
class Activation:
def __init__(self, name, salience):
self.name = name
self.salience = salience
def __str__(self):
return f"{self.salience} {self.name}: f-1"
def __repr__(self):
return f"Activation: {self.salience} {self.name}: f-1"
def delete(self):
... | magicoder | python |
You are tasked with implementing a simplified version of a social media app's networking module. The provided code snippet is part of a function that makes a network request to fetch a tweet and then processes the response.
The function takes in a `tweetDict` dictionary containing the details of the tweet to be fetche... | ```swift
class Tweet {
let tweetDict: [String: Any]
init(tweetDict: [String: Any]) {
self.tweetDict = tweetDict
}
}
class User {
var timeline: [Tweet] = []
}
class App {
static var delegate: AppDelegate?
}
protocol AppDelegate {
var currentUser: User? { get }
}
// Sample usage
l... | magicoder | swift |
You are tasked with implementing a function that performs a specific operation on a given 3D array. The operation involves summing the elements along the third axis of the array, then reshaping the resulting 2D array to match the shape of another given 2D array.
You are given the following information:
- A 3D NumPy ar... | ```python
import numpy as np
def perform_operation(res: np.ndarray, Y: np.ndarray) -> np.ndarray:
# Step 1: Sum the elements along the third axis of the res array
summed_res = np.sum(res, axis=2)
# Step 2: Reshape the resulting 2D array to match the shape of the Y array
reshaped_summed_res = summe... | magicoder | python |
You are tasked with creating a Swift package manager manifest file for a new project. The manifest file should include dependencies on various Swift packages with specific version requirements. Your task is to write the Swift package manager manifest file based on the given dependencies.
The Swift package manager mani... | ```swift
// Package.swift
// swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "YourPackageName",
platforms: [
.macOS(.v10_15)
],
products: [
.library(name: "YourPackageName", targets: ["YourPackageName"])
],
dependencies: [
.package(url: "h... | magicoder | swift |
You are tasked with creating a Python program to solve a 1D steady-state heat conduction problem using the finite element method. The problem involves defining the necessary boundary conditions, material properties, and solving for the temperature distribution within the domain.
You are given the following code snippe... | ```python
from fenics import *
# Define the domain and mesh
mesh = IntervalMesh(100, 0, 1)
P = FiniteElement('P', interval, 1)
V = FunctionSpace(mesh, P)
# Define material properties and boundary conditions
k = Constant(1.0)
Q = Constant(1.0)
bc_left = DirichletBC(V, Constant(1.0), "on_boundary && near(x[0], 0)")
bc_... | magicoder | python |
You are tasked with implementing a Python class that simulates a simple banking system. The class should support basic operations such as account creation, deposit, withdrawal, and balance inquiry. Additionally, the class should handle exceptions for invalid operations and insufficient funds.
Your task is to complete ... | ```python
# Sample usage of the BankAccount class
try:
# Create a new bank account with an initial balance of 1000
account1 = BankAccount(1000)
# Deposit 500 into the account
account1.deposit(500)
# Withdraw 200 from the account
account1.withdraw(200)
# Check the current balance
print... | magicoder | python |
You are tasked with creating a script to automate the setup and teardown of a PostgreSQL database for testing purposes. The script should handle the creation of a database, installation of a specific extension (TimescaleDB), and cleanup after the tests are completed. The script should also ensure that certain clusterwi... | ```bash
#!/bin/bash
# Function to handle cleanup
cleanup() {
${PSQL} $@ -U $TEST_ROLE_SUPERUSER -d postgres -v ECHO=none -c "DROP DATABASE \"${TEST_DBNAME}\";" >/dev/null
}
trap cleanup EXIT
# Setup clusterwide settings on first run
if [[ ! -f ${TEST_OUTPUT_DIR}/.pg_init ]]; then
touch ${TEST_OUTPUT_DIR}/.pg_ini... | magicoder | shell |
You are tasked with writing a Bash script to perform a series of calculations for a computational fluid dynamics simulation. The script takes in a single command-line argument, `ROOT`, which represents the root directory for the simulation. The script also initializes several arrays: `ps`, `etas`, `angles`, `angles_str... | ```bash
#!/bin/bash
ROOT=$1
ps=(1 2)
etas=(5 10 20 41 82)
angles=("0" "PI/32" "PI/16" "PI/8" "PI/4")
angles_str=("00000" "PIo32" "PIo16" "PIo08" "PIo04")
cfls=(99 90 80 70 60)
for p in "${ps[@]}"; do
for eta in "${etas[@]}"; do
for ((i=0; i<${#angles[@]}; i++)); do
angle=${angles[i]}
... | magicoder | shell |
You are tasked with implementing a custom navigation controller class in Swift. The class should support interactive transitioning between view controllers using the `UIViewControllerInteractiveTransitioning` protocol. Additionally, the class should handle the `navigationController(_:didShow:animated:)` method to reset... | ```swift
class CustomNavigationController: UINavigationController {
private var currentAnimationTransition: UIViewControllerInteractiveTransitioning?
// Method to set the current animation transition
func setCurrentAnimationTransition(_ transition: UIViewControllerInteractiveTransitioning?) {
s... | magicoder | swift |
You are tasked with implementing a Python class for a simple 2D game. The game involves two types of characters: "Gobo" and "Player". The "Gobo" class represents non-player characters, while the "Player" class represents the user-controlled character. Your task is to implement the "Gobo" and "Player" classes with speci... | ```python
class Gobo:
def __init__(self, x, y, health):
self.x = x
self.y = y
self.health = health
def move(self, new_x, new_y):
self.x = new_x
self.y = new_y
def take_damage(self, damage):
self.health -= damage
def is_alive(self):
return self.h... | magicoder | python |
You are tasked with creating a Django model for a food ordering system. The model should represent a customer's order, including the items ordered, the quantity of each item, and the total cost of the order. Additionally, the model should store the customer's name and the date and time the order was placed.
Create a D... | ```python
# models.py
from django.db import models
class Order(models.Model):
customer_name = models.CharField(max_length=100)
order_date = models.DateTimeField()
items = models.TextField()
total_cost = models.DecimalField(max_digits=10, decimal_places=2)
```
In the solution, we define a Django model ... | magicoder | python |
You are tasked with implementing a method `get_aligned_body` within a class. The method takes a string `formula` as input and should return a modified version of the formula with aligned body elements.
The input `formula` represents a chemical formula, where the body elements are enclosed in parentheses. The goal is t... | ```python
class ChemicalFormula:
def get_aligned_body(self, formula: str) -> str:
stack = []
result = ""
for char in formula:
if char == '(':
if stack:
result += ' ' * (len(stack) - 1)
stack.append('(')
result +=... | magicoder | python |
You are working on a project that involves processing OCT (Optical Coherence Tomography) data. You have a class `OCTProcessor` that contains a method `_struct_to_dict` for converting a structured object `S` into a dictionary. The method uses the `construct` library to handle structured data. However, the code snippet p... | The `_struct_to_dict` method is completed to handle the conversion of structured data to a dictionary. It iterates through the items of the structured object `S`, checks the `pickleable` flag, and recursively converts nested structures and lists into dictionaries. The `construct` library is used to handle structured da... | magicoder | python |
You are tasked with implementing a Python class for processing real-time data feeds from LimeBike scooters. LimeBike is a bike and scooter sharing company that provides real-time data feeds for their vehicles. Your task is to create a LimeBikeSocketFeedProcessor class that processes the real-time data received from Lim... | ```python
# lime_bike_socket_feed_processor.py
class LimeBikeSocketFeedProcessor:
def process_data(self, real_time_data):
# Perform processing operations on the real-time data
# Example: Calculate average speed of LimeBike scooters
average_speed = self.calculate_average_speed(real_time_data... | magicoder | python |
You are tasked with implementing a class for tracking and storing prediction drift metrics in a machine learning system. The class should have a method for updating the prediction drift metrics and a method for retrieving the results in a specific format.
You are provided with a partial code snippet that includes a me... | ```python
from datetime import datetime
from typing import Optional
class PredictionDriftTracker:
def __init__(self, name: str):
self._name = name
self._result = None
def update_drift_metrics(self, drift: float):
result_json = {'metrics': {'prediction_drift': drift}}
self._resu... | magicoder | python |
You are tasked with creating a Python script that extracts metadata information from a given code snippet. The metadata includes the copyright, version, author, email, and URL. Your script should be able to parse the code snippet and extract the metadata information, then display it in a structured format.
Write a Pyt... | ```python
import re
def extract_metadata_info(code_snippet):
metadata = {}
pattern = r'__(\w+)__\s*=\s*"([^"]+)"'
matches = re.findall(pattern, code_snippet)
for match in matches:
metadata[match[0]] = match[1]
return metadata
```
The `extract_metadata_info` function uses regular expression... | magicoder | python |
You are working as a DevOps engineer for a software company. Your team is responsible for managing the deployment of various applications using Docker containers. You have been tasked with creating a script to automate the deployment of a Tomcat web server using Docker. The script should run a Tomcat container with spe... | ```bash
#!/bin/bash
docker run --name tomcat -d -p 9003:8080 -v /c/docker/volumes/tomcat:/usr/local/tomcat/webapps tomcat:latest
```
The provided Bash script accomplishes the required tasks for deploying a Tomcat web server using Docker. It runs a Docker container named "tomcat" in detached mode with the specified por... | magicoder | shell |
You are tasked with debugging and fixing a concurrency issue in a C++ program that uses mutexes for thread synchronization. The given code snippet is part of a larger program that manages a mutex object. The `ArMutex` class contains a method `lock()` for acquiring the mutex, and the snippet shows part of the destructor... | The issue in the given code snippet is that the `CloseHandle` function is called unconditionally, regardless of whether the mutex initialization (`myFailedInit`) was successful or not. This can lead to attempting to close an uninitialized or invalid handle, resulting in undefined behavior or resource leaks.
To fix thi... | magicoder | cpp |
You are tasked with optimizing the execution of a scientific simulation code called P-Gadget3, which is used for cosmological simulations. The code snippet provided sets environment variables and then runs the P-Gadget3 program with specific parameters. Your goal is to understand the significance of the environment var... | The environment variables and program parameters play a crucial role in optimizing the execution of P-Gadget3. Here's a breakdown of their significance and a strategy to optimize the execution:
1. Environment Variables:
- `MP_EUILIB=us`: This sets the MPI (Message Passing Interface) library to be used for communica... | magicoder | python |
You are tasked with creating a Python class that performs edge detection on an image using the Sobel operator. The Sobel operator is a popular method for edge detection in image processing. It works by convolving the image with a pair of 3x3 kernels to calculate the gradient of the image intensity at each pixel. The ma... | ```python
import numpy as np
from scipy.signal import convolve2d
class EdgeDetector:
def __init__(self):
self.sobel_x = np.array([[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1]])
self.sobel_y = np.array([[-1, -2, -1],
... | magicoder | python |
You are tasked with creating a Python class that generates configuration commands for a network device. Your task is to implement the `build_config` method of the class, which takes in several parameters and constructs configuration commands based on the provided attributes.
The method signature is as follows:
```pyth... | ```python
class NetworkConfigurator:
def build_config(self, apply=True, attributes=None, unconfig=False, **kwargs):
'''Interface build config'''
if apply:
assert attributes is not None, "Attributes must be provided for configuration"
# Extracting attribute values
... | magicoder | python |
You are tasked with implementing a module resolution system for a simple JavaScript project. The project has a file structure with the following components:
1. A directory named `components` containing various component files.
2. A file named `Editor.ts` inside the `components` directory.
3. A file named `Editor.types... | ```typescript
function resolveModule(moduleName: string): string | null {
const componentsDir = './components/';
const possibleExtensions = ['.ts', '.js', ''];
for (const ext of possibleExtensions) {
const filePath = `${componentsDir}${moduleName}${ext}`;
// Check if the file exists
// If the file ex... | magicoder | typescript |
You are tasked with creating a Python function that checks whether a given string is a valid Git branch name. Git branch names have certain rules and restrictions that must be adhered to. Your function should return `True` if the input string is a valid Git branch name and `False` otherwise.
A valid Git branch name mu... | ```python
import re
def is_valid_git_branch(branch_name: str) -> bool:
if any(char in branch_name for char in ['~', '^', ':', '?', '*', '[', '\\']) or \
' ' in branch_name or \
branch_name.startswith('-') or \
branch_name.endswith('/') or \
'..' in branch_name or \
'./' in branch... | magicoder | python |
You are tasked with implementing a function to calculate the hash value of a given message using the SHA-256 algorithm. The SHA-256 algorithm is a widely used cryptographic hash function that produces a 256-bit (32-byte) hash value. Your task is to create a function that takes a message as input and returns its SHA-256... | ```rust
use sha2::{Digest, Sha256};
fn calculate_sha256_hash(message: &str) -> String {
let mut hasher = Sha256::new();
hasher.update(message);
let result = hasher.finalize();
// Convert the hash result to a hexadecimal string
let hex_string: String = result.iter().map(|byte| format!("{:02x}", byt... | magicoder | rust |
You are tasked with creating a unit test for an Angular component that handles user registration. The component relies on various services and modules, and your goal is to test its behavior under different scenarios.
The component's template contains a form for user registration, and it interacts with the `UserRegiste... | ```typescript
import { TestBed, ComponentFixture, waitForAsync } from '@angular/core/testing';
import { ReactiveFormsModule } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing';
import { I18nTestingModule } from 'path-to-i18n-module';
import { FormErrorsModule } from 'path-to-form-erro... | magicoder | typescript |
You are tasked with creating a Python function that validates the structure of an abstract syntax tree (AST) representing a specific code pattern. The AST is represented as a nested structure of nodes, each node corresponding to a specific element in the code. Your task is to implement a function `validate_ast` that ta... | ```python
import ast
def validate_ast(node):
if not isinstance(node, ast.If):
return False
if not isinstance(node.test, ast.Compare):
return False
if len(node.body) != 1 or not isinstance(node.body[0], ast.Expr):
return False
return True
```
The `validate_ast` function first che... | magicoder | python |
You are tasked with implementing a method to calculate the nth Fibonacci number using a recursive approach. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. The method should throw an IllegalArgumentException if a negative number is ... | ```java
public class FibonacciCalculator {
public long calculateFibonacci(int n) {
if (n < 0) {
throw new IllegalArgumentException("n can not be a negative number");
}
return fibInner(n);
}
private long fibInner(int n) {
if (n == 0) {
return 0;
... | magicoder | java |
You are tasked with implementing a function to find the minimum and maximum positions of a light source in a 2D space. The light source moves based on its velocity and position, and your task is to write a method that calculates the minimum and maximum x and y coordinates that the light source reaches during its moveme... | ```rust
impl Light {
fn find_pos_min_max(&self) -> Option<((isize, isize), (isize, isize))> {
if self.velocity.0 == 0 && self.velocity.1 == 0 {
return Some((self.pos, self.pos));
}
let min_x = if self.velocity.0 < 0 {
Some(self.pos.0 + self.velocity.0)
} else... | magicoder | rust |
You are tasked with writing a Python function that generates the first n prime numbers. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Your function should take an integer n as input and return a list of the first n prime numbers.
Your task is to complete the f... | ```python
def generate_primes(n):
primes = []
num = 2
while len(primes) < n:
is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
primes.append(num)
num += 1
re... | magicoder | python |
You are tasked with implementing a generic class for managing environment constants in a Spring application. The class `SpringEnvConstant` is designed to store and retrieve environment-specific constants with default values. Your goal is to complete the implementation of the `SpringEnvConstant` class by adding the nece... | ```java
public class SpringEnvConstant<T> {
private String name;
private T value;
private T defaultValue;
public SpringEnvConstant(String name) {
this(name, null);
}
public SpringEnvConstant(String name, T defaultValue) {
this.name = name;
this.defaultValue = defaultVal... | magicoder | java |
You are given a Bash script snippet that processes files and extracts specific information from their names and contents. Your task is to write a Bash function that replicates the functionality of the given code snippet.
The given code snippet performs the following tasks:
1. It defines two regular expressions: `OPT_R... | ```bash
process_file() {
local f="$1"
OPT_REGEX='(adlb|O[0-3])'
PROC_REGEX='p[0-9]+'
params=$(basename "$f" | grep -o -E "${OPT_REGEX}\.${PROC_REGEX}")
opt=$(echo "$params" | grep -o -E "${OPT_REGEX}")
procs=$(echo "$params" | grep -o -E "${PROC_REGEX}")
echo -n "$opt $procs "
ELAPSED_STR="ADLB Total E... | magicoder | shell |
You are tasked with implementing a URL signing mechanism for a web service. The goal is to ensure that only authorized clients can access the service by signing the URLs they request. The signing process involves adding a signature to the URL query string based on certain parameters and a client key. Your task is to im... | ```python
import hashlib
from urllib.parse import urlencode
class ClientError:
@staticmethod
def get_code():
return "CLIENT_ERROR"
class URLSigner:
def __init__(self, key):
self.KEY = key
def sign(self, client_key, params):
sorted_params = sorted(params.items(), key=lambda x: ... | magicoder | python |
You are given a string of comma-separated numbers representing ASCII values. Your task is to decode the string and convert it into the corresponding characters. Each number represents the ASCII value of a character. The string may contain non-printable characters as well.
Write a function or program that takes the inp... | ```python
def decode_ascii_string(input_str):
ascii_values = input_str.split(',')
decoded_message = ''.join(chr(int(val)) for val in ascii_values)
return decoded_message
input_str = "60,63,120,109,108,32,118,101,114,115,105,111,110,61,34,49,46,48,34,32,101,110,99,111,100,105,110,103,61,34"
print(decode_asc... | magicoder | python |
You are tasked with creating a Django web application for managing special pages within a site. The provided code snippet is a part of the URL configuration for this application. The `urlpatterns` list contains URL patterns and their corresponding views for adding, updating, and deleting special pages.
Your task is to... | ```python
# views.py
from django.shortcuts import get_object_or_404, redirect, render
from .models import SpecialPage
from .forms import SpecialPageForm
def special_page_add(request, site_settings_pk):
if request.method == 'POST':
form = SpecialPageForm(request.POST)
if form.is_valid():
... | magicoder | python |
You are tasked with implementing a function to calculate the area of a triangle on a polar coordinate system. The function should take in the polar coordinates of two points on the triangle and return the area of the triangle formed by these points and the origin.
The polar coordinate system represents points in the f... | ```csharp
using System;
public class Program
{
public static void Main()
{
double area = PolarTriangleArea(1.5, 0.8, 2.0, 1.2);
Console.WriteLine("Area of the triangle: " + area);
}
static double PolarTriangleArea(double tan1, double lng1, double tan2, double lng2)
{
double... | magicoder | csharp |
You are tasked with creating a program that simulates a simple game of rock-paper-scissors. The program should prompt the user to input their choice (rock, paper, or scissors), generate a random choice for the computer, compare the choices, and declare the winner. The program should then ask the user if they want to pl... | ```python
import random
def get_user_choice():
while True:
user_choice = input("Enter your choice (rock, paper, or scissors): ").lower()
if user_choice in ["rock", "paper", "scissors"]:
return user_choice
else:
print("Invalid choice. Please enter rock, paper, or scis... | magicoder | python |
You are tasked with implementing a rate-limiting algorithm for a web service. The rate limiter should restrict the number of requests a client can make within a specific time interval. Your task is to design and implement a rate limiter class that enforces the following rules:
- The rate limiter should allow a maximum ... | ```python
from collections import deque
import time
class RateLimiter:
def __init__(self, max_requests, interval_minutes):
self.max_requests = max_requests
self.interval_minutes = interval_minutes
self.request_times = deque()
def allow_request(self):
current_time = time.time() ... | magicoder | python |
You are tasked with implementing a function to perform smooth false discovery rate (FDR) estimation on a given dataset. The smooth FDR method is used to control the rate of false discoveries in statistical hypothesis testing. Your task is to create a Python function that takes in various parameters and returns the esti... | ```python
from smoothfdr.utils import calc_fdr
import numpy as np
def smooth_fdr(data, fdr_level, edges=None, initial_values=None, verbose=0, null_dist=None, signal_dist=None, num_sweeps=10, missing_val=None):
flat_data = data.flatten()
nonmissing_flat_data = flat_data
if edges is None:
# Assuming... | magicoder | python |
You are tasked with implementing a function that preprocesses and augments image data for a convolutional neural network (CNN) model. The function should take in the image data and perform the following preprocessing and augmentation steps:
1. Resize the images to a specified input shape.
2. Apply data augmentation te... | ```python
from tensorflow.keras.preprocessing.image import ImageDataGenerator
def preprocess_augment_images(image_data, input_shape):
# Resize images to the specified input shape
image_data_resized = []
for img in image_data:
resized_img = cv2.resize(img, input_shape)
image_data_resized.app... | magicoder | python |
You are given a list of strings representing software licenses. Each license is represented by a string containing the license name and version, separated by a space. The version is a positive integer. Your task is to write a function that returns the highest version of each unique license name.
Write a function `high... | ```python
from typing import List
def highestVersion(licenses: List[str]) -> List[str]:
license_versions = {}
for license in licenses:
name, version = license.rsplit(' ', 1)
version = float(version)
if name not in license_versions or version > license_versions[name]:
license... | magicoder | python |
You are tasked with implementing a simple flagging system for debugging purposes in a C++ program. The provided code snippet is a part of a header file generated by SCons build system and defines a debug flag for a SimpleCPU class.
Your task is to create a C++ class called `SimpleFlag` that represents a debug flag and... | ```cpp
// SimpleFlag.h
#ifndef __DEBUG_SIMPLEFLAG_H__
#define __DEBUG_SIMPLEFLAG_H__
class SimpleFlag {
private:
bool flagStatus;
public:
void setFlag(bool status) {
flagStatus = status;
}
bool checkFlag() {
return flagStatus;
}
};
#endif // __DEBUG_SIMPLEFLAG_H__
// Debug.h
#if... | magicoder | cpp |
You are tasked with creating a program to manage and process DNS (Domain Name System) records. The DNS system is crucial for translating domain names into IP addresses and vice versa. Your program needs to handle various aspects of DNS record management and manipulation.
Your task is to implement a DNS record manageme... | To solve this problem, you would need to create a DNS record management system that incorporates the provided components and functionalities. This would involve implementing classes or modules for parsing DNS responses, visiting and manipulating resource records, handling negative caching time-to-live values, and proce... | magicoder | python |
You are tasked with creating a Python function that processes statistics related to a natural language processing (NLP) model's performance. The function takes in three parameters: `batch` (a list of input data), `pred_tgt_words` (a list of predicted target words), and `gold_regexes` (a list of gold standard regular ex... | ```python
import logging
def process_stats(batch, pred_tgt_words, gold_regexes):
if len(pred_tgt_words) > 0:
logging.info('pred tgt_word: %s', pred_tgt_words[0])
else:
logging.info('pred tgt_word: None')
rewards = [] # Assuming rewards is defined somewhere in the code
pred_regexes = [... | magicoder | python |
You are tasked with implementing a simple Lisp interpreter in Rust. Your goal is to create a function that evaluates a given Lisp expression and returns the result. The Lisp expressions will consist of atoms (symbols or values) and lists. The interpreter should support basic operations such as arithmetic, conditional e... | ```rust
use std::collections::HashMap;
#[derive(Debug, Clone)]
enum LispExpr {
Atom(String),
List(Vec<LispExpr>),
}
type Environment = HashMap<String, LispExpr>;
fn eval(expr: &LispExpr, env: &Environment) -> Result<(LispExpr, Environment), String> {
match expr {
LispExpr::Atom(val) => {
... | magicoder | rust |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.