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 filter in a TypeScript-based templating engine. The filter will be responsible for providing a default value if the original value is null or undefined. Your task is to create a class that extends the `TwingNodeExpressionFilter` and implements the necessary logic to achieve thi... | ```typescript
import { TwingNodeExpressionFilter } from "./filter";
import { TwingNode } from "../node";
import { TwingNodeExpressionConstant } from "../constant";
import { TwingCompiler } from "../../../compiler";
import { TwingNodeType } from "../../../node-type";
export const type: TwingNodeType = new TwingNodeType... | magicoder | typescript |
You are tasked with implementing a CLI-based database management system in Node.js. The system should allow users to perform basic CRUD (Create, Read, Update, Delete) operations on a SQLite database using a command-line interface. Your goal is to create a module that provides a simple and intuitive API for interacting ... | ```javascript
const sqlite3 = require('sqlite3');
class CliDatabase {
constructor(sqliteModule, dbPath, errorCallback) {
this.db = new sqliteModule.Database(dbPath, (err) => {
if (err) {
errorCallback(err);
}
});
}
insert(tableName, data) {
r... | magicoder | javascript |
You are working on a project to analyze the link probability between different points on a map. The given code snippet is part of a larger program that processes geographical data and calculates the link probability based on distances between points.
Your task is to implement a function that calculates the link probab... | ```python
import numpy as np
def LinkProbability(A, D):
"""
Calculate the link probability based on the given inputs.
Args:
A: numpy array, matrix representing the links between points (expected to be in upper triangular form)
D: numpy array, matrix of distances between points
Returns:
p:... | magicoder | python |
You are tasked with creating a Python script to automate the process of sending email notifications using Celery, a distributed task queue. Your script should utilize Django settings and Celery configurations to set up the task queue and autodiscover tasks for processing.
Your script should perform the following steps... | ```python
import os
from celery import Celery
from django.conf import settings
# Set the default Django settings module
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "storefront.settings")
# Create a Celery instance for the project
celery = Celery("storefront")
# Configure the Celery instance using Django settings... | magicoder | python |
You are tasked with creating a program to manage travel bookings for a travel agency. The program should include a class called `Booking` to represent a travel booking, and a class called `TravelAgency` to manage the bookings. The `Booking` class should have properties for the customer's name, destination, and date of ... | ```csharp
using System;
using System.Collections.Generic;
public class Booking
{
public string CustomerName { get; set; }
public string Destination { get; set; }
public DateTime DateOfTravel { get; set; }
}
public class TravelAgency
{
private List<Booking> bookings = new List<Booking>();
public v... | magicoder | csharp |
You are tasked with creating a Python script to migrate data from one system to another. The script should handle different types of data exports and provide an option for a dry run to simulate the migration without actually saving the changes. The code snippet provided is a part of the migration script and contains a ... | ```python
# Define the variables
export = ... # Replace with the actual export object
default_type = ... # Replace with the default type value
options = {
'dryrun': False # Set to True to simulate a dry run, False to perform the actual migration
}
# Complete the migration process
if not export.type:
print "... | magicoder | python |
You are tasked with implementing a function that calculates the total number of constraints added to a view in a given Swift program. Constraints are added using the `NSLayoutConstraint` class in iOS development. Each constraint is created using the `NSLayoutConstraint` initializer and then added to the view using the ... | ```swift
func totalConstraintsAdded(swiftProgram: String) -> Int {
let constraintCreationPattern = "NSLayoutConstraint\\(item:.*?\\)"
let constraintAdditionPattern = "\\.addConstraint\\(.*?\\)"
let constraintCreationRegex = try! NSRegularExpression(pattern: constraintCreationPattern, options: [])
l... | magicoder | swift |
You are tasked with implementing a neural network module for forward propagation. The provided code snippet is a part of the `forward` method of the module. The method takes a 4D tensor `inputs_bx3xhxw` as input and performs encoding and decoding operations using an encoder and decoder, respectively. The encoder and de... | ```python
# Assuming the encoder and decoder are defined elsewhere, here's an example of how they might be implemented:
class Encoder(nn.Module):
def __init__(self):
super(Encoder, self).__init__()
# Define layers for encoding
def forward(self, inputs_bx3xhxw):
# Implement encoding ope... | magicoder | python |
You are tasked with implementing a custom exception handling mechanism for a PHP web application. The application uses the Twig templating engine for rendering views. The given code snippet is a part of the exception handling logic within the application.
The `catch` block catches an instance of `Twig_Error_Loader` an... | ```php
class CustomTwigLoaderException extends Twig_Error_Loader
{
protected $templateFile;
protected $templateLine;
public function setTemplateFile($file)
{
$this->templateFile = $file;
}
public function setTemplateLine($line)
{
$this->templateLine = $line;
}
publ... | magicoder | php |
You are tasked with implementing a function that simulates a simple asynchronous task scheduler. The scheduler should execute a series of tasks in a non-blocking manner, ensuring that each task is executed after a specified delay. You need to create a function that takes an array of tasks and their corresponding delays... | ```javascript
function scheduleTasks(tasks, delays, callback) {
let completedTasks = 0;
for (let i = 0; i < tasks.length; i++) {
setTimeout(() => {
tasks[i]();
completedTasks++;
if (completedTasks === tasks.length) {
callback();
}
... | magicoder | javascript |
You are tasked with creating a SQL query to retrieve information about releases and songs by a specific artist from a music database. The database schema consists of three tables: ARTISTS, RELEASES, and SONGS. The ARTISTS table contains the ID and NAME of each artist, the RELEASES table contains the ID, NAME, and ARTIS... | The completed SQL query to retrieve the release and song information for a specific artist is as follows:
```sql
WITH ARTISTID AS (SELECT ID FROM ARTISTS WHERE NAME='<ARTIST_NAME>')
SELECT RELEASES.NAME, SONGS.TITLE
FROM RELEASES
INNER JOIN SONGS ON RELEASES.ID = SONGS.RELEASE_ID
WHERE RELEASES.ARTIST_ID IN (SELECT ID... | magicoder | sql |
You are tasked with implementing a C++ template class that provides a simple stack data structure. The stack should support the following operations:
1. `push`: Add an element to the top of the stack.
2. `pop`: Remove the element from the top of the stack.
3. `top`: Return the element at the top of the stack without re... | ```cpp
void push(const T& value) {
Node* newNode = new Node(value, topNode);
topNode = newNode;
}
void pop() {
if (topNode != nullptr) {
Node* temp = topNode;
topNode = topNode->next;
delete temp;
}
}
T top() const {
if (topNode != nullptr) {
return topNode->data;
... | magicoder | cpp |
You are tasked with implementing a function that calculates the cost of an Amazon Elastic Block Store (EBS) volume based on the volume's size and the region it is located in. The cost is calculated using the following pricing model:
- For volumes in the "us-east-1" region, the cost is $0.1 per GB for General Purpose SS... | ```javascript
function EC2_EBS_GP2_GB(size, region) {
if (typeof size !== 'number' || size <= 0 || !Number.isInteger(size)) {
throw new Error("invalid volume size");
}
if (region !== "us-east-1" && region !== "us-west-2") {
throw new Error("invalid region");
}
const costPer... | magicoder | javascript |
You are tasked with creating a Python function to validate and process JSON Web Tokens (JWT) in an Apache server environment. The function should take in a JWT payload and perform the following tasks:
1. Check if the 'userid' claim in the payload matches the result of the 'approved_user()' function.
2. Verify if the 'e... | ```python
import time
import apache
def validate_and_process_jwt(payload, req):
try:
if payload['userid'] == approved_user() and payload['exp'] > time.time():
store_to_ssm(req.headers_in['x-amzn-oidc-accesstoken'])
return apache.OK
else:
return apache.HTTP_UNAUTH... | magicoder | python |
You are working on a machine learning project and need to preprocess data for training a model. You have a dataset consisting of input features stored in a 2D array `X` and corresponding labels stored in a separate file `yFile`. The code snippet provided performs two key preprocessing steps: reshaping the input feature... | ```python
import numpy as np
from sklearn.preprocessing import OneHotEncoder
from typing import Tuple
def preprocess_data(X: np.ndarray, yFile: str) -> Tuple[np.ndarray, np.ndarray]:
# Reshape the input features
preprocessed_X = np.reshape(X, (212841, -1))
# Read the label data and perform One-Hot Encodin... | magicoder | python |
You are tasked with creating a program that analyzes a given text file to count the occurrences of specific words. Your program should read the text file, tokenize the words, and then count the occurrences of each word. However, the program should ignore any words that appear in a list of common stop words. The stop wo... | ```python
import re
from collections import Counter
def read_stop_words(file_path):
with open(file_path, 'r') as file:
stop_words = file.read().split()
return set(stop_words)
def count_non_stop_words(text_file, stop_words_file):
with open(stop_words_file, 'r') as file:
stop_words = set(fil... | magicoder | python |
You are tasked with implementing a Python function to load and preprocess image data using the torchvision library. The function should take a path to the dataset and perform the necessary data loading and preprocessing steps. You are provided with a code snippet that imports necessary libraries and initializes a funct... | ```python
from torchvision import datasets, transforms, models
from PIL import Image
def load_data(path):
print("Loading and preprocessing data from {} ...".format(path))
# Define preprocessing transformations
data_transforms = transforms.Compose([
transforms.Resize(256),
transforms.Ce... | magicoder | python |
You are tasked with implementing a class to retrieve vault proposal certificates by their unique certificate IDs. The provided code snippet is a constructor for the `RetrieveVaultProposalCertificatesByCertificateIdQuery` class, which takes a `certificateId` as a parameter and assigns it to the `CertiicateId` property a... | ```csharp
public class RetrieveVaultProposalCertificatesByCertificateIdQuery
{
private List<VaultProposalCertificate> certificates;
public RetrieveVaultProposalCertificatesByCertificateIdQuery()
{
// Initialize the certificates list with sample data
certificates = new List<VaultProposalCert... | magicoder | csharp |
You are tasked with implementing a simple event handling system in C#. Your goal is to create a class that allows registration of callback functions for specific events and the ability to trigger these callbacks when the events occur.
You are provided with a partial code snippet for an event handling class. The class ... | ```csharp
// The provided code snippet contains the partial implementation of an event handling class in C#. The class EventHandler is designed to allow registration of callback functions for specific events and the ability to trigger these callbacks when the events occur.
// The completed implementation of the EventH... | magicoder | csharp |
You are tasked with developing a simulation tool for generating payment workloads in a network. The tool uses a command-line interface (CLI) with various options to customize the simulation. The provided code snippet is a part of this tool and includes the definition of a CLI command `genWork` with several options. You... | ```python
import random
def generate_payment_workload(n_payments, min_payment, max_payment, any_node, credit_card, e_commerce):
# Define the list to store payment transactions
payment_workload = []
# Define the list of nodes in the network (example: replace with actual node list)
nodes = ['node1', 'no... | magicoder | python |
You are tasked with creating a Python program to train a convolutional neural network (CNN) for image classification using the Keras library. The program should utilize transfer learning by leveraging a pre-trained VGG16 model and fine-tuning it on a custom dataset. The dataset consists of two classes: "cats" and "dogs... | ```python
import os
import matplotlib.pyplot as plt
from keras import applications
from keras.preprocessing.image import ImageDataGenerator
from keras import optimizers
from keras.models import Sequential, Model
from keras.layers import Dropout, Flatten, Dense
from keras.applications.vgg16 import preprocess_input
from... | magicoder | python |
You are tasked with implementing a Python class that simulates a simple banking system. The class should have methods for creating a new account, depositing funds, withdrawing funds, and checking the account balance. Additionally, the class should handle cases where the user tries to withdraw more funds than are availa... | ```python
class BankAccount:
def __init__(self, account_number, initial_balance):
self.account_number = account_number
self.balance = initial_balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
print("I... | magicoder | python |
You are tasked with creating a program to manage Bluetooth devices using Swift and CoreBluetooth framework. Your program should implement a Bluetooth device scanner that can discover nearby Bluetooth devices and display their information. The program should also allow the user to connect to a specific Bluetooth device ... | ```swift
import SwiftUI
import CoreBluetooth
class BluetoothManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate {
var centralManager: CBCentralManager!
var peripheral: CBPeripheral!
override init() {
super.init()
centralManager = CBCentralManager(delegate: self, queue: nil)
... | magicoder | swift |
You are tasked with creating a web application feature that allows users to edit categories. The provided code snippet is a part of the HTML template for the category editing page. The page displays the current category name and provides a form for users to update the category name. The form uses the POST method to sub... | ```php
<?php
// Assume $categoria is an instance of the Category class with properties id and nome
function editar_categoria($categoria_id, $novo_nome) {
// Connect to the database (assuming MySQL)
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "your_database";... | 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 highest possible score by choosing a subset of the scores such that no two chosen scores are adjacent in the original list.
Write a function `maxNonAdjacentScore` that takes in a list of integers `s... | ```python
def maxNonAdjacentScore(scores: List[int]) -> int:
if not scores:
return 0
if len(scores) <= 2:
return max(scores)
dp = [0] * len(scores)
dp[0] = scores[0]
dp[1] = max(scores[0], scores[1])
for i in range(2, len(scores)):
dp[i] = max(dp[i-1], dp[i-2] +... | magicoder | python |
You are tasked with creating a Python class to manage job applicant interview sheets. The class, `JobApplicantInterviewSheet`, should have a method `validate` that calculates the average score for each section of the interview sheet. The interview sheet is divided into five sections: General, Attitude, Technical, Exper... | ```python
class JobApplicantInterviewSheet(Document):
def validate(self):
calculate_average_score(self)
def calculate_average_score(doc):
sections = ['General', 'Attitude', 'Technical', 'Experience', 'Language']
for section in sections:
table = doc.get('interview_sheet_'+section.lower())
... | magicoder | python |
You are tasked with creating a Python program that simulates a simple banking system. The program should allow users to create accounts, deposit funds, withdraw funds, and check their balance. Additionally, the program should log all transactions to a file for auditing purposes.
Your task is to implement the `BankingS... | ```python
import logging
import datetime
class BankingSystem:
def __init__(self):
# Initialize the logger
logging.basicConfig(filename="transaction.log",
format="%(message)s",
level=logging.INFO,
filemode='w')
... | magicoder | python |
You are tasked with creating a class to handle currency formatting and conversion. Your task is to implement a PHP class called `CurrencyConverter` that provides methods for formatting currency and converting between different currencies. The class should utilize the `NumberFormatter` class for currency formatting and ... | ```php
class CurrencyConverter {
private $numberFormatter;
public function __construct($locale) {
$this->numberFormatter = new NumberFormatter($locale, NumberFormatter::CURRENCY);
}
public function formatCurrency($value, $currencyCode) {
return $this->numberFormatter->formatCurrency($v... | magicoder | php |
You are tasked with creating a Python class that manages the settings of a TTY (teletypewriter) interface. The class should provide methods to set the TTY to raw mode with no echo, retrieve the window size, and determine the number of colors supported by the terminal.
Your task is to complete the implementation of the... | ```python
#!/usr/bin/env python
import sys, tty, termios, array, fcntl, curses
class TTYSettings(object):
def __init__(self):
self.tty_fd = sys.stdout.fileno()
# save
self.saved = termios.tcgetattr(self.tty_fd)
self.win_size = self.get_win_size()
self.rows, self.cols = self.... | magicoder | python |
You are tasked with creating a simple plugin system for a software application. The application uses a plugin architecture to extend its functionality. The provided code snippet is a part of the plugin system and demonstrates the initialization and release of a plugin.
Your task is to implement a plugin manager class ... | ```cpp
#include <iostream>
#include <vector>
#include <memory>
#include <dlfcn.h>
// Define the Plugin interface
class Plugin {
public:
virtual void initialize() = 0;
virtual void release() = 0;
virtual ~Plugin() {}
};
// Define the PluginManager class
class PluginManager {
private:
std::vector<std::s... | magicoder | cpp |
You are tasked with creating a Python program that calculates the age of a person based on their birth year, birth month, and birth day of the month. The program should take user input for the birth year, birth month as an integer (where January is represented as 1, February as 2, and so on), and the birth day of the m... | ```python
from datetime import datetime
def calculate_age(birth_year, birth_month, birth_day):
current_date = datetime.now()
birth_date = datetime(birth_year, birth_month, birth_day)
# Calculate age in years
age = current_date.year - birth_date.year
# Adjust age if birth month and day have not oc... | magicoder | python |
You are tasked with implementing a Swift function that constructs a URL path for a Matrix homeserver API endpoint based on the provided user ID and optional room ID. The function should be able to handle different types of account data requests and construct the URL path accordingly.
You are given the following Swift ... | ```swift
func constructAPIPath(api: MatrixAPI, request: RequestParameter) -> String {
if let roomID = request.roomID {
return "\(api.homeserver)/_matrix/client/v3/rooms/\(roomID)"
} else {
return api.accountDataPath(forUser: request.userID.fqmxid, type: request.userID.type)
}
}
```
The `con... | magicoder | swift |
You are tasked with creating a function to calculate the total value of a user's assets in Wei, using the TrustCore and BigInt libraries in Swift. The TrustCore library provides functionality for interacting with the Ethereum blockchain, while the BigInt library offers support for arbitrary-precision arithmetic.
You a... | ```swift
import TrustCore
import BigInt
func calculateTotalUserAssetsInWei(userAddress: String) -> BigInt {
let userCapRequest = KNGetUserCapInWeiEncode() // Create a request to get user's asset cap
let userCap = userCapRequest.execute() // Execute the request to get the user's asset cap
// Query the bloc... | magicoder | swift |
You are given a snippet of code that is intended to be part of a function. The function is supposed to determine if a given list of integers is sorted in non-decreasing order. However, the given code snippet is incomplete and contains a logical error. Your task is to complete the function and fix the logical error to e... | ```java
public class SortingChecker {
public static boolean isSorted(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
return false; // Return false if the current element is greater than the next element
}
}
return tru... | magicoder | java |
You are tasked with creating a TypeScript function that constructs a Warp instance with the given options. The Warp instance is a part of a web framework and is used to configure and manage the web server.
The function signature is as follows:
```typescript
function createWarp(opts: CreateWarpOpts): Warp;
```
Where `... | ```typescript
class Warp {
// Implementation of Warp class
}
function createWarp(opts: CreateWarpOpts): Warp {
const warp = new Warp();
// Configure the Warp instance using the provided options
warp.controllers = opts.controllers;
if (opts.middleware) {
warp.middleware = opts.middleware;
}
if (opts.a... | magicoder | typescript |
You are working on a data visualization application that allows users to upload and analyze spectral data. The application uses a Python backend with a class `FigureData` to manage the data and generate visualizations. The code snippet provided is a part of a method within the `FigureData` class that handles the plotti... | ```python
import logging
def generate_comparison_visualization(fig_data, bands, corrected, trans):
try:
if fig_data.last_plot == 'baseline-page':
# comparison view for the baseline page
ax1, ax2 = fig_data.figure.axes
fig_data.plot('upload', ax=ax1)
baseline ... | magicoder | python |
You are tasked with creating a Python script that generates a 2048 game board and implements the game logic. The 2048 game is played on a 4x4 grid, where the player can slide numbered tiles in four directions (up, down, left, or right). When two tiles with the same number touch, they merge into one tile with the sum of... | ```python
import random
class Game2048:
def __init__(self):
self.board = [[0] * 4 for _ in range(4)]
self.add_new_tile()
self.add_new_tile()
def add_new_tile(self):
empty_cells = [(i, j) for i in range(4) for j in range(4) if self.board[i][j] == 0]
if empty_cells:
... | magicoder | python |
You are tasked with implementing a custom data provider class in JavaScript that fetches data from an API and provides it to the application. The class should handle making HTTP requests to the API and returning the data to the caller. Your task is to create the `ApiDataProvider` class with the following requirements:
... | ```javascript
// apiDataProvider.js
export default class ApiDataProvider {
constructor(baseUrl) {
this.baseUrl = baseUrl;
}
async fetchData(path) {
try {
const response = await fetch(`${this.baseUrl}/${path}`);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status... | magicoder | javascript |
You are working on a project that involves interacting with various Python libraries. In the given code snippet, you can see that the `watcher` library is being imported from its `objects` module. Additionally, the code handles the import of the `cPickle` module, falling back to the standard `pickle` module if the form... | ```python
from watcher import objects
try:
import cPickle as pickle
except ImportError: # pragma: nocover
import pickle
from sqlalchemy import create_engine, Table, MetaData, Column, Integer, LargeBinary, select, and_
from sqlalchemy.exc import IntegrityError
def serialize_and_insert(objects, table_name):
... | magicoder | python |
You are tasked with creating a Java program to manage a library's book inventory using MongoDB as the database. Your program should handle the connection to the MongoDB database and provide methods to add, remove, and update book records. Additionally, it should have a method to retrieve all books from the database.
Y... | ```java
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.ArrayList;
import java.util.List;
public class LibraryManager {
private MongoClient client;
private MongoDatabase db;
private boolean isMon... | magicoder | java |
You are working on a text processing application that involves manipulating characters and glyphs. A glyph is a specific shape used to render a character, while a character represents a symbol, such as a letter or a number. Your task is to implement a function that determines whether a given glyph represents an upperca... | ```python
import unicodedata
def isUpper(g):
char = glyph2Char(g)
if len(char) > 1:
char = char[0]
if unicodedata.category(char) == 'Lu':
return True
return False
```
The `isUpper` function first converts the glyph `g` to a character using the `glyph2Char` method. If the resulting chara... | magicoder | python |
You are tasked with creating a Python program that simulates a simple banking system. The program should include classes for Bank, Account, and Transaction. The Bank class should have methods for creating new accounts, retrieving account information, and processing transactions. The Account class should store account d... | ```python
import uuid
class Bank:
def __init__(self):
self.accounts = {}
def create_account(self, name, initial_balance):
account_number = str(uuid.uuid4())
account = Account(account_number, name, initial_balance)
self.accounts[account_number] = account
return account_n... | magicoder | python |
You are tasked with implementing a request interceptor system for a TV show database application. The provided code snippet is a part of the codebase for this application. The `interceptors` array is used to store instances of `RequestInterceptor` protocol, which will be responsible for intercepting and modifying netwo... | ```swift
// Define the RequestInterceptor protocol
protocol RequestInterceptor {
func intercept(request: URLRequest) -> URLRequest
}
// Implement a specific interceptor for adding authentication token
struct AuthenticationInterceptor: RequestInterceptor {
let authToken: String
init(authToken: String) ... | magicoder | swift |
You are tasked with creating a program that utilizes the Dadata API to clean and standardize addresses. Dadata is a service that provides address validation, correction, and enrichment. Your program should take a raw address as input and use the Dadata API to clean and standardize it. The cleaned address should then be... | ```python
import requests
def clean_address(raw_address):
url = "https://dadata.ru/api/clean/address/"
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer YOUR_API_KEY" # Replace with your Dadata API key
}
payload = {
"query": raw_address
}
try:
... | magicoder | python |
You are tasked with creating a program that simulates a simple game of Hangman. In this game, the computer will randomly select a word from a predefined list, and the player will have to guess the letters in the word. The player has a limited number of attempts to guess the word, and for each incorrect guess, a part of... | ```python
import random
class Hangman:
def __init__(self, words):
self.word = random.choice(words)
self.hidden_word = ['_'] * len(self.word)
self.incorrect_guesses = 0
self.max_incorrect_guesses = 6
self.guessed_letters = set()
def guess(self, letter):
if letter... | magicoder | python |
You are tasked with creating a Python function that generates a formset for managing the editions of books. The function should handle the manipulation of book editions and be able to dynamically handle different authorship models associated with each edition.
Your task is to implement the `edition_formset_factory` fu... | ```python
from django.forms.models import inlineformset_factory
from django.apps import apps
def edition_formset_factory(model, model_name, **kwargs):
"""Manipulate the editions of a book."""
try:
authorship_model = apps.get_model('cv', '%sauthorship' % model_name)
return inlineformset_factory(... | magicoder | python |
You are tasked with implementing a class that manages player roles and their progress in a game. The class, named `PlayerProgress`, should have the following private member variables:
- `m_role`: a pointer to an object of type `Role`, representing the player's role in the game.
- `m_zhanshendian_pass_level`: a short in... | ```cpp
#include <iostream>
#include <ctime>
class Role {
// Class definition for Role
};
class PlayerProgress {
private:
Role *m_role;
short m_zhanshendian_pass_level;
short m_yesterday_pass_level;
unsigned int m_fetch_day_reward_timestamp;
public:
// Constructor
PlayerProgress(Role *role... | magicoder | cpp |
You are tasked with creating a Java program that simulates a simple banking system. The program should include classes for bank accounts and provide functionality for deposits, withdrawals, and balance inquiries. Additionally, the program should have a main class to demonstrate the functionality of the bank account cla... | ```java
// BankAccount class
public class BankAccount {
private int accountNumber;
private String accountHolderName;
private double balance;
public BankAccount(int accountNumber, String accountHolderName, double balance) {
this.accountNumber = accountNumber;
this.accountHolderName = acc... | magicoder | java |
You are tasked with implementing a data structure to efficiently store and retrieve contributions made by spin pairs in a quantum physics simulation. The provided code snippet is a part of a Python class method that iterates through peaks, retrieves their contributions, and then retrieves the spin pairs associated with... | ```python
class ContributionManager:
def __init__(self):
self._c_id = {} # Dictionary to store contributions based on spin pair IDs
def storeContributions(self, peaks):
for p in peaks:
for c in p.getContributions():
for sp in c.getSpinPairs():
si... | magicoder | python |
You are tasked with implementing a Python class that provides functionality for saving and loading data to and from a file. The class should have methods for saving data to a file and loading data from a file. Additionally, the class should handle exceptions that may occur during file operations.
Your task is to compl... | ```python
import pickle
class FileError(Exception):
pass
class DataHandler:
def save_data(self, data, filename):
try:
with open(filename, 'wb') as file:
file.write(pickle.dumps(data))
except IOError:
raise FileError("Unable to save data to file")
de... | magicoder | python |
You are tasked with creating a validation function for a form that captures user input for achievements. The form fields include "name," "description," "title," and "image." The validation rules are as follows:
- "name" is a required string field.
- "description" is a required string field.
- "title" is an optional str... | ```javascript
const Yup = require('yup');
function validateAchievement(input) {
const AchievementSchema = Yup.object().shape({
name: Yup.string().required('Digite o nome da conquista.'),
description: Yup.string().required('Explique como ganhar a conquista.'),
title: Yup.string(),
image: Yup.mixed(),
... | magicoder | javascript |
You are tasked with creating a Python program that interacts with a MongoDB database to perform various operations on a collection of user documents. The program should include functions to insert new user documents, retrieve user information, update user details, and delete user records. You will be provided with a co... | ```python
from pymongo import MongoClient
# Establish connection to the MongoDB database and select the "user" collection
client = MongoClient("mongodb://localhost:27017/")
coll = client.peanut.user
def insert_user(user_data):
# Insert a new user document into the "user" collection
coll.insert_one(user_data)
... | magicoder | python |
You are tasked with implementing a Python class that simulates a simple vending machine. The vending machine should be able to stock items, accept coins, process purchases, and return change if necessary. Your task is to implement the `VendingMachine` class with the following functionalities:
1. `stock_item(item_name,... | ```python
class VendingMachine:
def __init__(self):
self.stock = {} # Dictionary to store stocked items {item_name: (quantity, price)}
self.total_money_inserted = 0 # Total money inserted by the user
def stock_item(self, item_name, quantity, price):
if quantity < 0 or price < 0:
... | magicoder | python |
You are working on a project that involves interacting with a web service to perform authentication and then reading a specific file format. The code snippet provided is a part of the script you are developing. The snippet includes a password prompt, making a request to a web service for authentication, and opening a f... | ```python
import getpass
import requests
import xml.etree.ElementTree as ET
# login
username = input('Enter username: ')
pswd = getpass.getpass('Password:')
auth = {'name': username, 'pass': pswd} # Complete the 'auth' dictionary with the correct password
basis_url = 'https://example.com/' # Replace with the actual ... | magicoder | python |
You are tasked with creating a Python function that extracts specific information from an eBay product page and returns it in JSON format. The function should take a single argument, `link`, which is the URL of the eBay product page. You are required to use the `requests` library to make an HTTP GET request to the prov... | ```python
import requests
from bs4 import BeautifulSoup
import json
def ebay_to_json(link):
try:
ebay_request = requests.get(link)
if ebay_request.status_code != 200:
return json.dumps({'error': 'Failed to retrieve the eBay page'})
soup = BeautifulSoup(ebay_request.text, 'html.... | magicoder | python |
You are tasked with implementing a class that provides functionality for managing email templates. You need to create a class that implements the `IEmailTemplateMethods` interface, which defines methods for creating, checking the existence of, retrieving, and counting email templates.
The `IEmailTemplateMethods` inter... | ```csharp
using System;
using System.Collections.Generic;
public class EmailTemplateManager : IEmailTemplateMethods
{
private Dictionary<string, string> templates;
public EmailTemplateManager()
{
templates = new Dictionary<string, string>();
}
public bool CreateTemplate(string name, strin... | magicoder | csharp |
You are tasked with implementing a graph data structure and a specific method for adding nodes to the graph. The graph is represented using an adjacency list. The method for adding nodes to the graph has been partially implemented, but it contains commented-out code that needs to be completed.
You are given the follow... | ```python
class Node:
def __init__(self):
self.adjacency_list = {}
def Addnode(self, new_node, state):
if new_node in self.adjacency_list:
self.adjacency_list[new_node] = state # Update the state of the existing node
else:
self.adjacency_list[new_node] = state ... | magicoder | python |
You are tasked with writing a script to automate the installation and linking of certain files and directories. The script should handle the copying of specific files, updating symbolic links, and creating new links if necessary.
Given the code snippet provided, you need to implement a script that performs the followi... | ```bash
#!/bin/bash
TOP="/path/to/source"
DEST="/path/to/destination"
SIDECAR="/path/to/sidecar"
# Copy env-init.sh to DEST directory
cp "${TOP}/env-init.sh" "${DEST}/" || { echo "Failed to install env-init.sh"; exit 1; }
# Copy sidecar.sh to SIDECAR directory
cp "${TOP}/sidecar.sh" "${SIDECAR}/" || { echo "Failed t... | magicoder | shell |
You are tasked with implementing a custom button component in a React application. The button component, `IconButton`, is styled using the `asStyled` higher-order component and accepts various props for customization. Your goal is to create the `IconButton` component with the following features:
- The component should... | ```jsx
import React from 'react';
import { asStyled } from 'some-styling-library';
import IconButtonBox from 'IconButtonBox'; // Assuming this is the correct import
import useButtonColor from 'useButtonColor'; // Assuming this is the correct import
const IconButton = asStyled('button', IconButtonBox, (Box) => {
co... | magicoder | jsx |
You are tasked with implementing a function that checks if a given string contains any repeated characters. The function should return `True` if the string contains any repeated characters and `False` otherwise. You are not allowed to use any built-in functions or data structures to solve this problem.
Function signat... | ```python
def has_repeated_characters(input_string: str) -> bool:
# Initialize an empty list to store unique characters
matchedSingleCheck = []
# Iterate through each character in the input string
for char in input_string:
# Check if the character is already in the list
if char in match... | magicoder | python |
You are tasked with implementing a simple graph data structure using Python. Your task is to create a class `Graph` with the following methods:
1. `__init__(self)`: Initializes an empty graph with no nodes or edges.
2. `add_node(self, node)`: Adds a new node to the graph.
3. `add_edge(self, node1, node2)`: Adds an edg... | ```python
class Graph:
def __init__(self):
self.__adjacency_list = {}
def add_node(self, node):
if node not in self.__adjacency_list:
self.__adjacency_list[node] = []
def add_edge(self, node1, node2):
if node1 in self.__adjacency_list and node2 in self.__adjacency_list:... | magicoder | python |
You are tasked with implementing a projectile behavior for a game enemy in Unity. The `Projectile` class inherits from the `Enemy` class and is responsible for defining the behavior of projectiles launched by enemies. The `Projectile` class contains a member variable `direction` of type `Vector3`, which represents the ... | ```csharp
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Projectile : Enemy {
Vector3 direction;
float speed = 10f; // Define the speed of the projectile
protected override void Behaviour()
{
// Move the projectile in the specified direction
... | magicoder | csharp |
You are tasked with creating a shell script that automates the setup and configuration of a development environment. The script should execute a series of commands to set up a specific programming language, run a configuration check, and potentially create a database. Your task is to complete the shell script by fillin... | ```bash
#!/bin/sh
CURRENT_DIR=`dirname "$0"`
. $CURRENT_DIR/_common.sh
# Set up the Ruby programming language
exe $CURRENT_DIR/setup/ruby.sh
# Perform a configuration check
exe toys config check
# Optionally, create a database
# exe toys db create
```
In the provided solution, the missing parts have been complete... | magicoder | shell |
You are tasked with implementing a specialized stack data structure that supports the retrieval of the maximum element in constant time. You need to design a stack that has a `max` method, which returns the maximum element in the stack without removing it. The stack should also support the standard push, pop, and top o... | ```swift
/// The specialized stack data structure that supports retrieval of the maximum element in constant time.
struct MaxStack<T: Comparable> {
private var elements: [T] = []
private var maxElements: [T] = []
/// Inserts an element into the top of the stack.
mutating func push(_ element: T) {
... | magicoder | swift |
You are tasked with implementing a memory management system for a virtual machine. The virtual machine operates within a context and utilizes namespaces to store and retrieve values. Your goal is to create a function that will handle the deletion of a context, ensuring that memory is properly released.
You are provide... | ```cpp
void argon::vm::ContextDel(Context *context) {
if (context == nullptr) {
// Handle the case where the context pointer is already null
return;
}
// Release any resources associated with the context
// For example, release any values stored in the context's namespace
// Assumin... | magicoder | cpp |
You are tasked with creating a Python program to implement a characteristic set teacher for a deterministic finite automaton (DFA). A characteristic set teacher is a method used in machine learning to infer the behavior of a system by asking queries and observing the responses. In this case, the DFA is represented by a... | ```python
from typing import Set
from DFA.DFA import DFA
class CharacteristicSetTeacher:
def __init__(self, dfa: DFA):
self.dfa = dfa
def equivalence_query(self, hypothesis: DFA) -> bool:
return self.dfa.is_equivalent(hypothesis)
def membership_query(self, word: str) -> bool:
retu... | magicoder | python |
You are tasked with designing a database schema for a simple user management system. The system should support storing user information, including their email address and a one-to-one relationship with another entity. You are required to create a database schema using TypeScript and TypeORM to define the entities and t... | ```typescript
import { Entity, PrimaryGeneratedColumn, Column, OneToOne, JoinColumn } from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
email: string;
@OneToOne(() => OtherEntity, { primary: true })
@JoinColumn()
otherEntity: OtherEntity;
}
@Entity()
export ... | magicoder | typescript |
You are tasked with implementing an active learning algorithm to select the most informative data points for labeling in a machine learning task. Active learning is a semi-supervised learning approach where the algorithm can interactively query a user (or an oracle) to obtain the labels for selected unlabeled data poin... | ```python
import numpy as np
def activeLearning(candidates, data_model, labelPairFunction, training_data):
informativity = np.zeros(len(candidates))
for i, candidate in enumerate(candidates):
# Make a copy of the training data and add the candidate for temporary labeling
temp_training_data = t... | magicoder | python |
You are working on a machine learning pipeline management system and need to implement a function to create a mapping from pipeline names to pipeline objects. The function should ignore any additional arguments added in the future and should support MLflow experiments/runs tracking.
You are given a code snippet that o... | ```python
from typing import Dict
class Pipeline:
# Define the Pipeline class with necessary attributes and methods
pass
def create_pipeline_map(**kwargs) -> Dict[str, Pipeline]:
# Initialize an empty pipeline map
pipeline_map = {}
# Iterate through the list of subpackages with pipelines
for ... | magicoder | python |
You are tasked with implementing a custom similarity function module in PyTorch for a neural network model. The module contains a linear layer for computing the similarity score between query and key vectors. Additionally, you need to initialize the parameters of the linear layer using Xavier initialization. Finally, y... | ```python
import torch
import torch.nn as nn
from typing import Tuple
def initialize_xavier_dynet_(module: nn.Module):
for name, param in module.named_parameters():
if 'weight' in name:
nn.init.xavier_uniform_(param.data)
elif 'bias' in name:
nn.init.constant_(param.data, 0.... | magicoder | python |
You are tasked with implementing a class that manages a stack of integers and provides various operations on the stack. Your task is to implement the `StackManager` class with the following functionalities:
1. `push(int value)`: Add an integer value to the top of the stack.
2. `pop()`: Remove the integer value from the... | ```java
import java.util.Stack;
class StackManager {
private Stack<Integer> stack;
public StackManager() {
this.stack = new Stack<>();
}
public void push(int value) {
stack.push(value);
}
public int pop() {
if (stack.isEmpty()) {
return -1;
}
... | magicoder | java |
You are tasked with implementing a simple drawing program using the Pygame library in Python. The program should allow the user to draw squares on the screen and display text labels within the squares. The provided code snippet includes a function `fill_square` that draws a small square of a specified color at a given ... | ```python
import pygame
class DrawingProgram:
def __init__(self, screen_width, screen_height):
pygame.init()
self.screen = pygame.display.set_mode((screen_width, screen_height))
self.font = pygame.font.Font(None, 36)
def draw_square(self, color, column, row):
pygame.draw.rect(s... | magicoder | python |
You are given a binary tree represented by the TreeNode class as shown in the code snippet. Each node in the tree has an integer key and may have a left and/or right child. Your task is to write a function to find the maximum path sum from any leaf node to the root node.
The maximum path sum from a leaf node to the ro... | ```java
public class MaxPathSumFromLeafToRoot {
public int maxPathSumFromLeafToRoot(TreeNode root) {
if (root == null) {
return 0;
}
int[] maxSum = new int[]{Integer.MIN_VALUE};
maxPathSumFromLeafToRootHelper(root, maxSum);
return maxSum[0];
}
private int... | magicoder | java |
You are tasked with creating a script to automate the build process for a PHP extension. The build process involves running a series of commands in a specific order. Your script should execute the following commands in sequence:
1. Run `phpize` to prepare the build environment.
2. Run `./configure` to generate the conf... | ```bash
#!/bin/bash
# Function to handle command execution and error handling
execute_command() {
echo "Executing: $@"
"$@"
local status=$?
if [ $status -ne 0 ]; then
echo "Error: Command $@ failed with exit code $status"
exit $status
fi
}
# Run phpize
execute_command phpize
# Run... | magicoder | shell |
You are tasked with implementing a Python class to manage page translations for a multilingual website. The class should handle the storage and manipulation of page translations, including the title, content, revision number, and flags indicating the translation status.
You are provided with a code snippet that outlin... | ```python
class PageTranslation:
def __init__(self, title, text, currently_in_translation, version, minor_edit):
self.title = title
self.text = text
self.currently_in_translation = currently_in_translation
self.version = version
self.minor_edit = minor_edit
def update_tr... | magicoder | python |
You are tasked with implementing a custom sublist method for a linked list data structure. The sublist method should take two integer parameters, `fromIndex` and `toIndex`, and return a new linked list containing the elements from `fromIndex` (inclusive) to `toIndex` (exclusive) of the original list. If the `fromIndex`... | ```java
public LinkedList subList(int fromIndex, int toIndex) {
if (fromIndex >= toIndex || toIndex > size()) {
throw new IllegalArgumentException("Invalid indices");
}
LinkedList sublist = new LinkedList();
ListNode current = head;
int index = 0;
while (current != null && index < toIn... | magicoder | java |
You are tasked with implementing a role assignment system for a cloud-based application. The system allows assigning roles to various entities within the application, such as users, groups, or service principals. Each role assignment is associated with a specific scope, which defines the extent of its applicability wit... | ```python
def handle_role_assignment(assignee_principal_type, assignment_id, cmd, workspace_name, role, assignee, assignee_object_id, scope, item, item_type):
try:
# Attempt to create the role assignment
create_role_assignment(cmd, workspace_name, role, assignee, assignee_object_id, scope, item, ite... | magicoder | python |
You are tasked with implementing a data structure to manage symbols in a program's debug information. The debug information is represented using Program Database (PDB) format, and the symbols include functions and data elements. You need to create a class that can store and manage these symbols efficiently.
Your task ... | ```cpp
#include <vector>
#include <memory>
#include "PDBSymbolFunc.h"
#include "PDBSymbolData.h"
class SymbolManager {
private:
struct SymbolGroup {
std::vector<std::unique_ptr<PDBSymbolFunc>> Functions;
std::vector<std::unique_ptr<PDBSymbolData>> Data;
};
SymbolGroup AccessGroup;
public:... | magicoder | cpp |
You are tasked with implementing a function to perform a specific operation on arrays using the CUDA programming model. The provided code snippet is a part of a CUDA kernel that is responsible for copying elements from one array to another based on certain conditions. Your task is to complete the CUDA kernel by impleme... | ```cpp
__global__ void copyArrayElements(const T* xa, T* ya, int shiftx, int shifty, int stridex, int stridey, int incx, int incy, int n) {
ptrdiff_t tid = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;
// bound
if(tid < n)
{
const T* x = load_ptr_batch(xa, hipBlockIdx_y, shiftx, stridex);
... | magicoder | cpp |
You are tasked with implementing a Python class that simulates a voltage emulator. The class should be able to configure the driver and input, and it should have a method to set the voltage emulation per volt. Additionally, the class should handle logging using a provided Logger object or a default NullLogger if none i... | ```python
class NullLogger:
def log(self, message):
pass
class VoltageEmulator:
def __init__(self, Logger=None):
if Logger is None:
self._logger = NullLogger()
else:
self._logger = Logger
self.log = self._logger.log
self.confDriver()
self.... | magicoder | python |
You are tasked with implementing a function to generate a barcode image for a PDF document. The function should take a string content and a height as input and return the barcode image in the form of a printpdf::Image object. The barcode image should be generated based on the provided content and have the specified hei... | ```rust
use printpdf::Image;
use barcode_library::BarcodeGenerator; // Replace with the actual barcode generation library
pub fn generate_barcode_for_pdf(content: String, height: u32) -> printpdf::Image {
// Initialize the barcode generator with the content and height
let barcode_generator = BarcodeGenerator::... | magicoder | rust |
You are tasked with creating a Python module that provides a summary of a given text. The module should include a function called `generate_summary` that takes a text string and an integer `length` as input and returns a summarized version of the text with a maximum length of `length` characters. The summary should pri... | ```python
import nltk
from nltk.tokenize import sent_tokenize
from nltk.probability import FreqDist
nltk.download('punkt')
def generate_summary(text, length):
sentences = sent_tokenize(text)
words = [word for sentence in sentences for word in nltk.word_tokenize(sentence)]
freq_dist = FreqDist(words)
... | magicoder | python |
You are tasked with implementing a Python class that manages configuration settings for a web application. The class should handle the loading and retrieval of configuration settings from a dictionary, as well as provide methods for updating and accessing specific settings.
You are provided with a partial code snippet... | ```python
class ConfigManager:
def __init__(self, settings_dict):
self.settings = settings_dict
def get_setting(self, key):
return self.settings.get(key)
def update_setting(self, key, value):
self.settings[key] = value
```
The `ConfigManager` class is implemented with a constructo... | magicoder | python |
You are tasked with implementing a message queue system for a multi-threaded application. The system should handle the scheduling and execution of work items in a thread-safe manner. Your task is to design a class that manages the message queue and ensures proper execution of work items.
Your message queue class shoul... | ```cpp
#include <queue>
#include <mutex>
#include <condition_variable>
class MessageQueue {
public:
void EnqueueWorkItem(WorkItem item) {
std::unique_lock<std::mutex> lock(mutex_);
queue_.push(item);
work_scheduled_ = true;
condition_.notify_one();
}
WorkItem DequeueWorkItem() {
std::unique_... | magicoder | cpp |
You are tasked with implementing a buffer management system for a file and log manager in a C# application. The `BufferManager` class is responsible for managing a pool of buffers, each associated with a file and a log manager. The `Buffer` class represents a buffer used for reading and writing data from/to a file, and... | ```csharp
using System;
using System.Threading;
public interface IFileManager
{
// Define file manager interface
}
public interface ILogManager
{
// Define log manager interface
}
public class Buffer
{
private readonly IFileManager _file;
private readonly ILogManager _log;
public Buffer(IFileMan... | magicoder | csharp |
You are tasked with implementing a Python class that manages resources related to "extoam" in a cloud computing environment. The provided code snippet includes a list of creation attributes and the definition of two classes: `iextoam` and `iextoamManager`.
Your task is to create a new class called `iextoamManagerExten... | ```python
class iextoamManagerExtended(iextoamManager):
def get_extoam_servers_by_system_id(self, system_id):
extoam_servers = []
for extoam_server in self.list():
if extoam_server.forisystemid == system_id:
extoam_servers.append(extoam_server.extoamservers)
retur... | magicoder | python |
You are tasked with implementing a custom attribute-based mapping system in C#. The goal is to create a custom attribute that can be applied to a class, indicating that the class should be automatically mapped to another specified type. The mapping should be based on the properties of the class and the specified target... | ```csharp
using System;
using System.Linq;
using System.Reflection;
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class AutoMapToAttribute : Attribute
{
private Type _targetType;
public AutoMapToAttribute(Type targetType)
{
_targetType = targetType;
}
public void ... | magicoder | csharp |
You are working on a data processing application that involves calculating the entropy of a given dataset. Entropy is a measure of uncertainty or randomness in the data. In this problem, you are tasked with implementing a function to calculate the entropy of a given dataset.
Entropy is calculated using the formula:
\[... | ```python
import math
def calculate_entropy(dataset):
total_count = len(dataset)
value_counts = {}
# Count the occurrences of each distinct value in the dataset
for value in dataset:
if value in value_counts:
value_counts[value] += 1
else:
value_counts[value... | magicoder | python |
You are tasked with implementing a function that calculates the total number of valid paths in a grid. The grid is represented as a 2D array, where each cell contains a non-negative integer representing the cost to traverse that cell. The goal is to find the total number of valid paths from the top-left corner to the b... | ```python
from typing import List
def totalValidPaths(grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
# Initialize a 2D array to store the number of valid paths to each cell
paths = [[0] * n for _ in range(m)]
# Base case: there is only one way to reach the top-left cell
pat... | magicoder | python |
You are tasked with implementing a Python class for a custom dataset called `TieredImagenet`. This dataset is used for image classification tasks and is structured to contain a set of images along with their corresponding target labels. The dataset is intended for use in a machine learning project.
The `TieredImagenet... | ```python
import os
from PIL import Image
import torch
from torch.utils.data import Dataset
class TieredImagenet(Dataset):
def __init__(self, root, mode='train'):
self.root = os.path.expanduser(root)
self.mode = mode
# Initialize dataset based on mode
if self.mode == 'train':
... | magicoder | python |
You are tasked with implementing a custom range data structure in Rust. The range should be inclusive, meaning it includes both the start and end values. Your task is to create a struct `RangeInclusive` that stores the start and end values as pointers and provides a method to check if a given value falls within the ran... | ```rust
// Define the RangeInclusive struct
struct RangeInclusive<T> {
start: *const T,
end: *const T,
}
impl<T> RangeInclusive<T> {
// Constructor method for RangeInclusive
fn new(start: *const T, end: *const T) -> RangeInclusive<T> {
RangeInclusive { start, end }
}
// Method to check... | magicoder | rust |
You are tasked with implementing a function to process a list of DNA sequences. The function should take a list of strings representing DNA sequences as input and return the count of sequences that start with the '>' character and have been adapted using the `adapt_PEPformat` function. The `adapt_PEPformat` function is... | ```python
def adapt_PEPformat(seq):
# Implementation of the adapt_PEPformat function is not provided as it is specific to the PEPred-Suite software.
def count_adapted_sequences(sequences):
seq_num = 0
for x in sequences:
if not x:
continue
if x[0] == '>':
x = adapt_P... | magicoder | python |
You are given a snippet of code that manipulates an index variable based on the size of a source array and an offset index. Your task is to implement a function that simulates the behavior of the given code snippet.
You need to write a function `calculateNewIndex` that takes three parameters:
1. `source`: an array of ... | ```swift
func calculateNewIndex<T>(source: [T], index: Int, offsetIndex: Int) -> Int {
var newIndex = index
if source.count > 0 {
newIndex += offsetIndex
while newIndex < 0 {
newIndex += source.count
}
newIndex = newIndex % source.count
}
... | magicoder | swift |
You are tasked with implementing a data compression algorithm that can handle overlapping data types in a multi-dimensional array. Your goal is to create a class that can efficiently compress and store multi-dimensional data while handling overlapping data types. The class should have the following attributes and metho... | ```python
import numpy as np
class MultiDimensionalCompressor:
def __init__(self, n_dim):
self.compressed_data = None
self.overlap_data_types = None
self.n_dim = n_dim
def compress_data(self, data):
self.compressed_data = np.compress(data) # Implement data compression logic
... | magicoder | python |
You are tasked with creating a function to count the number of questions to which everyone in a group answered "yes". Each group's answers are represented as a list of strings, where each string contains the answers of a single person. The function should take in a list of groups and return the sum of the count of ques... | ```python
def count_every_yeses(groups):
count = 0
for group in groups:
common_answers = set(group[0])
for person_answers in group[1:]:
common_answers = common_answers.intersection(set(person_answers))
count += len(common_answers)
return count
```
The `count_every_yeses` ... | magicoder | python |
You are tasked with creating a Python function that processes a given formula and dataset using the Patsy library. Patsy is a Python library for describing statistical models and building design matrices. Your function should take a formula and a dataset as input, and then attempt to build design matrices based on the ... | ```python
from typing import Union
import pandas as pd
import patsy
from patsy import PatsyError
def process_design_matrices(formula: str, data: pd.DataFrame, new_data: pd.DataFrame) -> Union[patsy.DesignMatrix, str]:
try:
info = patsy.dmatrix(formula, data)
design_matrices = patsy.build_design_mat... | magicoder | python |
You are tasked with creating a script to automate the process of fetching gradebook databases for multiple courses from a remote server. The script should iterate through a list of courses, create directories for each course, and then securely copy the gradebook database file from the remote server to the respective co... | ```bash
#!/bin/bash
# Define the list of courses
COURSES=("course1" "course2" "course3")
# Iterate through each course and perform the necessary operations
for course in "${COURSES[@]}"; do
# Create the necessary directories for each course
mkdir -p mocks/$course/grader
# Securely copy the gradebook database f... | magicoder | shell |
You are tasked with developing a security auditing tool that analyzes a list of security-related strings and categorizes them as safe or unsafe based on predefined criteria. Each string represents a security configuration or setting and follows a specific naming convention. The naming convention consists of two parts s... | ```python
from typing import List, Dict
def categorize_security_strings(strings: List[str]) -> Dict[str, List[str]]:
categorized_strings = {}
for string in strings:
system, status = string.rsplit('_', 1)
system = system.strip() # Remove any leading/trailing whitespace
if ... | magicoder | python |
You are tasked with creating a JavaScript function that extracts the version number from a given code snippet. The code snippet is a part of a JavaScript file from a GitHub repository and contains a comment with the repository name, followed by the version number assigned to a constant and exported as the default value... | ```javascript
function extractVersion(codeSnippet) {
const versionRegex = /const version = '(\d+\.\d+\.\d+)'/;
const match = codeSnippet.match(versionRegex);
if (match) {
return match[1];
} else {
return "Version number not found";
}
}
// Test the function with the provided example
const codeSnippet ... | magicoder | javascript |
You are tasked with implementing a simple image magnification feature for a map display application. The provided code snippet contains a class with methods to handle the magnification functionality. The `setOffSet` method is used to set the offset for the magnified view, and the `paintComponent` method is responsible ... | ```java
public void paintComponent(Graphics g) {
int magnificationFactor = 2; // Define the magnification factor
int magnifiedWidth = mapGrid.getWidth() / magnificationFactor; // Calculate the width of the magnified view
int magnifiedHeight = mapGrid.getHeight() / magnificationFactor; // Calculate the heigh... | magicoder | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.