query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with creating a Python function that can convert a given dictionary into a nested dictionary, where the keys are the individual characters of the original keys, and the values are the original values. For example, given the input dictionary `{"key1": "value1", "key2": "value2"}`, the output should be `{"... | ```python
def convert_to_nested_dict(input_dict: dict) -> dict:
nested_dict = {}
for key, value in input_dict.items():
current_dict = nested_dict
for char in key:
if char not in current_dict:
current_dict[char] = {}
current_dict = current_dict[char]
... | magicoder | python |
You are working on a natural language processing (NLP) project and need to implement a function to extract rolesets from a given text. A roleset is a set of semantic roles associated with a predicate in a sentence. Your task is to write a function that takes a list of DEPNode objects representing words in a sentence an... | ```java
{
String roleset;
DEPNode node;
while ((node = state.shift()) != null)
{
if (node.getFeat(DEPLib.FEAT_PB) != null)
{
if ((roleset = m_rolesets.get(node.lemma)) == null)
{
// Extract roleset for the lemma of the current word
... | magicoder | java |
You are tasked with creating a custom model field in a Django application that automatically generates a unique code for each instance of the model. The unique code should be a combination of a prefix and a sequential number, where the number is incremented for each new instance of the model. The prefix and the initial... | ```python
from django.db import models
class UniqueCodeField(models.CharField):
def __init__(self, prefix, initial_number, *args, **kwargs):
self.prefix = prefix
self.initial_number = initial_number
super().__init__(*args, max_length=len(prefix) + 10, unique=True, **kwargs)
def pre_sav... | magicoder | python |
You are tasked with implementing a class that manages user authentication and email change functionality. The class `ChangeEmailFrame` is responsible for handling the process of changing a user's email address. Your task is to create a method within the class that allows the user to change their email address, while en... | ```csharp
public class UserAuthentication
{
protected ChangeEmailFrame ChangeEmailParent { get; set; }
public void ChangeEmail(string newEmailAddress)
{
if (IsValidEmailFormat(newEmailAddress) && IsUniqueEmail(newEmailAddress))
{
// Update the user's email address to the new val... | magicoder | csharp |
You are working on a web application that interacts with an Oracle database using PHP and the OCI8 extension. Your task is to create a function that retrieves data from the database and processes it. The function should take a SQL query as input and return an array of associative arrays, where each inner array represen... | ```php
function fetchData($query) {
$connection = oci_connect('username', 'password', 'localhost/XE');
if (!$connection) {
$error = oci_error();
trigger_error(htmlentities($error['message'], ENT_QUOTES), E_USER_ERROR);
return false;
}
$statement = oci_parse($connection, $query);... | magicoder | php |
You are tasked with implementing a learning rate scheduler for a deep learning model training process. The provided code snippet includes configuration parameters for the learning rate scheduler, checkpoint saving, and logging during the training process. Your goal is to create a Python function that takes these config... | ```python
def generate_learning_rate_schedule(by_epoch, periods, restart_weights, min_lr):
learning_rate_schedule = []
current_lr = 1.0
restart_counter = 0
for period, weight in zip(periods, restart_weights):
if by_epoch:
restart_point = period
else:
restart_poin... | magicoder | python |
You are tasked with creating a program that reads a text file and counts the occurrences of each word in the file. Your program should ignore punctuation and be case-insensitive when counting words. Additionally, the program should output the top N most frequently occurring words and their respective counts.
For examp... | ```python
import re
from collections import Counter
def count_words_in_file(file_path, top_n):
with open(file_path, 'r') as file:
text = file.read().lower()
words = re.findall(r'\b\w+\b', text)
word_counts = Counter(words)
top_words = word_counts.most_common(top_n)
for word,... | magicoder | python |
You are given a code snippet that contains functions for calculating the Fx value and performing some matrix and vector operations. Your task is to understand the given code and write a function to calculate the Fx value based on the provided inputs.
You need to implement a function `calculate_Fx` that takes the follo... | ```rust
use nalgebra::{Complex, DMatrix, DVector};
type MatrixXcf = DMatrix<Complex<f64>>;
type VectorXf = DVector<f64>;
type Float = f64;
fn calculate_Fx(BhB: &MatrixXcf, x: &VectorXf, n: usize, m: usize) -> Float {
let t = x.iter().map(|&x| Complex::new(0., x).exp()).collect::<Vec<Complex<f64>>>();
let t = ... | magicoder | rust |
You are tasked with implementing a script to monitor the addition of a marathon application. The script should repeatedly check the status of the application addition process and exit with an error message if the process fails to complete within a specified time frame. You are given a code snippet that includes a loop ... | ```bash
# Define the exit_with_msg function to display an error message and terminate the script
exit_with_msg() {
echo "$1" >&2
exit 1
}
# Implement the script logic to monitor the application addition process and handle the timeout scenario
count=10 # Maximum number of attempts
while [ $count -gt 0 ]; do
# Ch... | magicoder | shell |
You are tasked with implementing a custom view layout for a login screen in an iOS app. The code snippet provided is part of a view controller class that sets up a stack view for organizing UI elements. The `stackView` is a UIStackView object, and the `logoImage` is an UIImageView object representing the logo of the ap... | ```swift
import UIKit
class LoginViewController: UIViewController {
private let stackView = UIStackView()
private let logoImage = UIImageView()
private let usernameTextField = UITextField()
private let passwordTextField = UITextField()
private let loginButton = UIButton()
override fun... | magicoder | swift |
You are tasked with implementing a Python package for controlling a PID (Proportional-Integral-Derivative) system. The package should include a module called `pidPS` that contains the necessary classes and functions for PID control. Your task is to create the `pidPS` module with the required components.
The `pidPS` mo... | ```python
# pidPS.py
class PIDController:
def __init__(self, Kp, Ki, Kd):
self.Kp = Kp
self.Ki = Ki
self.Kd = Kd
self.prev_error = 0
self.integral = 0
def set_gains(self, Kp, Ki, Kd):
self.Kp = Kp
self.Ki = Ki
self.Kd = Kd
def compute_output... | magicoder | python |
You are working on a web application that displays user information and their email status. The code snippet provided is a part of a Blade template in a Laravel application. The snippet is responsible for rendering a visual indicator of whether a user is eligible to receive emails or not. The `isEmailable()` method is ... | ```php
class User extends Model
{
// Other model attributes and methods...
public function isEmailable()
{
return $this->is_email_verified && !$this->opted_out_of_emails;
}
}
```
In the `User` model, the `isEmailable()` function checks if the user's email is verified (`$this->is_email_verified... | magicoder | php |
You are tasked with implementing a function that interacts with an API client to delete a search query connection. The function `delete_query_connection` takes two parameters: `self` (referring to the current instance of the class) and `search_id` (the unique identifier of the search query connection to be deleted). Th... | ```python
class QueryConnectionManager:
def __init__(self, api_client):
self.api_client = api_client
def delete_query_connection(self, search_id):
try:
response = self.api_client.delete_search(search_id)
return response
except Exception as err:
print(... | magicoder | python |
You are tasked with implementing a custom layout constraint in a Swift iOS application. The `applyConstraint` method is used to define a constraint between two views, `viewOne` and `viewTwo`, within a container view. The constraint specifies that the right edge of `viewOne` should be greater than or equal to the safe r... | ```swift
// Define the applyConstraint method
func applyConstraint(closure: (UIView) -> Void) {
// Create the layout constraint
let constraint = viewOne.rightAnchor.constraint(greaterThanOrEqualTo: viewTwo.safeAreaLayoutGuide.rightAnchor, constant: 10)
constraint.isActive = true
// Verify the installed... | magicoder | swift |
You are tasked with implementing a data transfer management system in Rust. The system is responsible for tracking the progress and timing of data transfers. You are provided with a partial code snippet for a `TransferManager` struct, which includes a method to retrieve transfer timings and a method to add a part of th... | ```rust
use std::collections::HashMap;
#[derive(Default)]
struct UpdatedAt {
// Define the structure to track timing information
// (e.g., start time, end time, duration, etc.)
// This can be a placeholder for the actual timing information.
}
struct TransferId {
// Define the structure to represent a ... | magicoder | rust |
You are tasked with implementing a Python function that processes a dictionary of parameters and performs certain operations based on the given input. The function should extract specific values from the input dictionary, perform tensor operations using TensorFlow, and return the result. Your task is to complete the im... | ```python
import tensorflow as tf
from tensorflow.python.framework import tensor_util
def process_distribution_params(distribution, validity_mask, safe_sample_fn, name=None):
"""
Process the distribution parameters and perform tensor operations.
Args:
- distribution: A TensorFlow distribution object.
... | magicoder | python |
You are tasked with implementing a simplified version of a checkpointer system in C++. The checkpointer system is responsible for managing the state of a service and providing the ability to save and restore the service's state.
You are provided with a partial implementation of the `Checkpointer` class, which includes... | ```cpp
#include <iostream>
#include <memory>
class ServiceContext {
// Implementation details not provided
};
class OperationContext {
public:
ServiceContext* getServiceContext() {
// Implementation details not provided
}
};
class Checkpointer {
public:
// Get the checkpointer for a given ser... | magicoder | cpp |
You are tasked with creating a Python function that generates a Django settings file based on a given set of parameters. The settings file should include configurations for static and media files, and the function should ensure that the file is properly formatted and ready for use in a Django project.
You are provided... | ```python
def generate_django_settings(static_url, static_root, media_url, media_root):
settings_template = f"""from .base import *
STATIC_URL = '{static_url}'
STATIC_ROOT = '{static_root}'
MEDIA_URL = '{media_url}'
MEDIA_ROOT = '{media_root}'
"""
return settings_template
```
The `generate_django_settings` f... | magicoder | python |
You are tasked with implementing a chatter detection system for a machining process. The system consists of several components, including a Kalman filter, bandpass filters, a NEO (presumably an acronym for a specific component), a mean filter, and the chatter detection algorithm itself. The provided code snippet shows ... | ```cpp
#include <iostream>
#include <vector>
// Define the ChatterDetection class
class ChatterDetection {
public:
void detectChatter(double measurement, double spindleSpeed) {
// Implement chatter detection logic
// Example: Print a message based on the measurement and spindle speed
if (me... | magicoder | cpp |
You are working on a data processing system that involves handling complex data arrays and performing operations on them. One of the requirements is to implement a function that adds complex data arrays and then reads the objects from the resulting array. Your task is to implement the function to add complex data array... | To solve this problem, you can implement the function to add complex data arrays and retrieve the objects using the following steps:
Step 1: Implement the function to add complex data arrays:
```python
def add_complex_data_arrays(array1, array2):
return array1 + array2
```
Step 2: Implement the function to retrie... | magicoder | python |
You are tasked with implementing a class that represents a simple 2D grid with cells that can be navigated in four cardinal directions (up, down, left, right). The grid is represented by a matrix of cells, and each cell can hold a non-negative integer value. The class should provide methods to move within the grid, upd... | ```cpp
#include <string>
#include "Direction.hpp"
#include <map>
#define MAX_VALUE 4294967295
class Grid {
private:
std::vector<std::vector<int>> grid;
int rows, cols;
public:
Grid(int numRows, int numCols) : rows(numRows), cols(numCols) {
grid = std::vector<std::vector<int>>(rows, std::vector<int... | magicoder | cpp |
You are tasked with implementing a custom comparison function for floating-point numbers with a specified tolerance. The function should compare the results of two mathematical operations and determine if they are within a certain number of units in the last place (ULPs) of each other. The comparison function will be u... | ```python
import math
def _compare_ufunc(ufunc, *args, ulps=1):
result1 = ufunc(*args)
result2 = ufunc(*args[::-1]) # Perform the operation with arguments reversed for comparison
# Calculate the absolute difference in ULPs
diff_ulps = abs(math.isclose(result1, result2, rel_tol=0, abs_tol=0) - 1)
... | magicoder | python |
You are tasked with implementing a function that compares two arrays and performs specific operations on them. The function should take two input arrays, `x1` and `x2`, and a fill value `fill_value`. The function should perform the following tasks:
1. Convert `x2` to strings and store the results in variables `junk` an... | ```python
import numpy
def compare_arrays(x1, x2, fill_value):
# Convert x2 to strings
junk, garbage = str(x2), repr(x2)
# Sort x2 using fill_value and compare with sorted x1
sort_comparison = numpy.array_equal(numpy.sort(x1), numpy.sort(x2, fill_value=fill_value))
# Perform tests of indexing
... | magicoder | python |
You are tasked with implementing a function to encrypt and decrypt messages using the Advanced Encryption Standard (AES) algorithm. The AES algorithm is a symmetric block cipher that encrypts and decrypts data in blocks of 128 bits using cipher keys of 128, 192, or 256 bits.
You need to implement a Swift function `aes... | ```swift
import Foundation
import CommonCrypto
extension Data {
func aesEncrypt(key: Data) -> Data? {
var encryptedData = Data(count: self.count + kCCBlockSizeAES128)
var encryptedLength: Int = 0
let status = key.withUnsafeBytes { keyBytes in
self.withUnsafeBytes { dataBytes in... | magicoder | swift |
You are tasked with implementing a function to extract and sort hit scores from a hit collector object in a search engine application. The hit collector object contains a collection of hits, each with a score representing its relevance to a search query. The goal is to retrieve the top N hits based on their scores and ... | ```cpp
#include <vector>
#include <algorithm>
class HitCollector {
public:
// ... other member functions
std::vector<std::pair<int, int>> getSortedHitSequence(int N) {
// Implementation to retrieve and sort hits
}
};
std::vector<int> extractAndSortHits(const HitCollector& hc, int N) {
std::ve... | magicoder | cpp |
You are tasked with implementing a Python function to calculate the factorial of a given positive integer. The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. For example, the factorial of 5 (denoted as 5!) is calculated as 5 x 4 x 3 x 2 x 1 = 120. The function sho... | ```python
def factorial(n=5):
"""
Calculate the factorial of a given positive integer.
Args:
n: An optional integer for which the factorial needs to be calculated (default is 5).
Returns:
The factorial of the input integer n.
"""
f = 1
for i in range(1, n + 1):
f *= i
r... | magicoder | python |
You are tasked with implementing a custom React hook that manages the state of a component and handles side effects. The hook should be designed to mimic the behavior of the `useState` and `useEffect` hooks provided by React. Your goal is to create a custom hook called `useCustomEffect` that can be used within a functi... | ```javascript
import React, { useState, useEffect } from 'react';
function useCustomEffect(initialState, effectFunction) {
const [state, setState] = useState(initialState);
useEffect(() => {
const effectCleanup = effectFunction();
return () => {
if (typeof effectCleanup === 'function') {
eff... | magicoder | javascript |
You are tasked with creating a Python class that manages database sessions using SQLAlchemy. Your task is to complete the implementation of the `DbSession` class by adding methods for establishing a database connection, creating a session, and closing the session.
Your `DbSession` class should have the following metho... | ```python
import socket
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm import sessionmaker
from sqlalchemy_utils import database_exists, create_database
from settings import settings
class DbSession():
def __init__(self):
self.engine = None
self... | magicoder | python |
You are tasked with implementing a program to parse and process a log file containing information about server tasks. The log file contains entries in the following format:
```
Task started: <timestamp>
Task ID: <task_id>
```
Your task is to write a function or method that takes the log file as input and returns a co... | ```csharp
using System;
using System.Collections.Generic;
using System.IO;
class Program
{
static void Main()
{
string logFilePath = "path_to_log_file.log";
List<Header> headers = ParseLog(logFilePath);
foreach (var header in headers)
{
Console.WriteLine($"Task ID: {... | magicoder | csharp |
You are tasked with implementing a program to analyze web traffic data. The program should read a stream of URLs from a file, calculate the hash of the host part of each URL, and identify unique hosts based on their hash values.
You are given a code snippet that demonstrates part of the process. The `decompress_stream... | ```cpp
#include <iostream>
#include <fstream>
#include <unordered_set>
#include <string>
#include <functional>
// Define the URL class with a host_hash() method
class URL {
public:
URL(const std::string& url) : url_(url) {}
uint64_t host_hash() const {
// Implement the hash calculation for the host pa... | magicoder | cpp |
You are tasked with implementing a class that utilizes the `IContentProvider` interface to open and read content from various sources. The `IContentProvider` interface contains a method `Open` that returns a `Stream` for a given content name. Your task is to create a class `ContentReader` that provides a method `ReadCo... | ```csharp
using System;
using System.IO;
using System.Threading.Tasks;
public interface IContentProvider
{
Task<Stream> Open(string name);
}
public class ContentReader
{
public async Task<string> ReadContent(IContentProvider provider, string contentName)
{
try
{
using (Stream s... | magicoder | csharp |
You are tasked with implementing a generic serializer registry in TypeScript. The registry should allow registering and retrieving serializers for different types. A serializer is a function that converts an object of a specific type to a string representation and vice versa.
You are provided with a partial implementa... | ```typescript
type Constructor<T> = new (...args: any[]) => T;
type Serializer<T> = {
serialize: (obj: T) => string;
deserialize: (str: string) => T;
};
class SerializerRegistry {
private serializersMap: Map<Constructor<any>, Serializer<any>>;
constructor() {
this.serializersMap = new Map();
}
getSer... | magicoder | typescript |
You are tasked with creating a program that simulates a simple banking system. The program should be able to handle basic banking operations such as account creation, deposit, withdrawal, and balance inquiry. The program should also be able to handle multiple accounts and perform operations on each account independentl... | ```python
class BankAccount:
def __init__(self, account_number, account_holder, initial_balance):
self.account_number = account_number
self.account_holder = account_holder
self.balance = initial_balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, am... | magicoder | python |
You are tasked with implementing a custom slider component in a web application. The slider component should have the following properties and methods:
Properties:
- `thumpPadding`: A private property representing the padding around the slider thumb.
- `thumbColor`: A private property representing the color of the sli... | ```typescript
class DataPoint {
// Define the DataPoint class properties and methods
}
class Rect {
// Define the Rect class properties and methods
}
class Slider {
private thumpPadding: number;
private thumbColor: string;
points: DataPoint[];
leftRect: Rect;
rightRect: Rect;
midRect: Rect;
private ... | magicoder | typescript |
You are tasked with creating a program to simulate the spread of an epidemic over a period of time. The epidemic starts on a specific date and spreads over a certain period length. Your program should calculate the dates when the epidemic will reach different stages of its spread.
You are given the following code snip... | ```typescript
export const EPIDEMIC_START: string = "2020/01/07";
export const PERIOD_LENGTH: number = 5;
function calculateEpidemicDates(startDate: string, periodLength: number): string[] {
const epidemicDates: string[] = [];
let currentDate = new Date(startDate);
for (let i = 1; i <= 5; i++) { // Assuming 5 s... | magicoder | typescript |
You are working on a web application using the Flask framework. Your task is to create a route that handles a POST request and processes the data sent from an HTML form. The form will contain fields for username and password. You need to write a Flask route that receives the form data, validates the username and passwo... | ```python
from flask import Flask, render_template, request
app = Flask(__name__)
# Route to render the login form
@app.route("/")
def show_login_form():
return render_template("login.html")
# Route to handle the form submission
@app.route("/login", methods=["POST"])
def login():
# Get the username and passw... | magicoder | python |
You are tasked with implementing a redemption system for a loyalty program. The system involves redeeming items from a goodie pack using a handler and updating the account repository with the redeemed items.
You are provided with the following code snippet as a starting point:
```csharp
private readonly GoodiePackHan... | ```csharp
public void RedeemItem(string itemId, string accountId)
{
try
{
// Use the GoodiePackHandler to redeem the item
Item redeemedItem = _goodiePackHandler.RedeemItem(itemId);
// Update the account in the IAccountRepository with the redeemed item
_accountRepository.UpdateAc... | magicoder | csharp |
You are tasked with implementing a function to process a list of coordinates and perform specific operations based on the type of each coordinate. The function should take in a list of coordinates `xy`, where each coordinate can be either a tuple of two integers representing Cartesian coordinates (x, y) or a complex nu... | ```python
import numpy
def process_coordinates(xy):
distances = []
magnitudes = []
last_cartesian_coord = None
for i in range(len(xy)):
if isinstance(xy[i], tuple) and len(xy[i]) == 2 and all(isinstance(val, int) for val in xy[i]):
if last_cartesian_coord is not None:
... | magicoder | python |
You are tasked with creating a function that parses HTML code to extract information about the list items and their attributes. Specifically, you need to extract the attributes of the `<li>` tag and determine if the `class` attribute is present and set to "active". The function should return a list of dictionaries, whe... | ```python
from typing import List, Dict, Union
import re
def parse_html(html: str) -> List[Dict[str, Union[str, bool]]]:
li_tags = re.findall(r'<li\s(.*?)>(.*?)</li>', html, re.DOTALL)
result = []
for tag in li_tags:
attributes = {}
active = False
if 'class="active"' in tag[0]:
... | magicoder | python |
You are tasked with creating a custom storage module for a blockchain runtime using the Rust programming language. The module should be designed to work within the context of a blockchain runtime that adheres to the specified trait. Your goal is to implement the storage module according to the given trait and define th... | ```rust
decl_storage! {
trait Store for Module<T: Trait> as Akt {
// Define the storage items here
// Example:
SomeStorageItem: map T::AccountId => u64;
AnotherStorageItem: u32;
// Define other storage items as per the requirements of the trait
}
}
```
In the solution, t... | magicoder | rust |
You are tasked with implementing a class for performing grid search to find the optimal hyperparameters for a machine learning model. The grid search algorithm involves testing different combinations of hyperparameters and selecting the combination that yields the best performance. Your task is to implement the `GridSe... | ```python
from itertools import product
class GridSearch:
def __init__(self, parameters, model, performance_validator):
self.parameters = parameters
self.model = model
self.performance_validator = performance_validator
self.best_params = None
self.best_performance = float('-... | magicoder | python |
You are tasked with implementing a TypeScript action creator and action interface for a user profile feature in a rental application. The action creator should create an action to indicate that spot rentals have been sent for a user's profile. The action interface should define the structure of the action object.
You ... | ```typescript
export const USER_PROFILE_SPOT_RENTALS_SENT = "USER_PROFILE_SPOT_RENTALS_SENT";
export interface UserProfileSpotRentalsSentAction {
type: typeof USER_PROFILE_SPOT_RENTALS_SENT;
// Add any necessary payload properties here
}
function createSpotRentalsSentAction(): UserProfileSpotRentalsSentAction {
... | magicoder | typescript |
You are tasked with implementing a merge function that aligns the ordering of ordered features that are not containment references in a software system. The merge function takes two lists of strings as input and merges them into a single list while aligning the ordering of the elements based on certain rules.
The rule... | ```java
import java.util.ArrayList;
import java.util.List;
public class MergeOrderedFeatures {
public List<String> merge(List<String> list1, List<String> list2) {
List<String> mergedList = new ArrayList<>();
int index1 = 0, index2 = 0;
while (index1 < list1.size() && index2 < list2.size(... | magicoder | java |
You are given a code snippet that involves the use of the PyTorch library. Your task is to create a function that takes a 2D tensor as input and performs a specific operation on it. The operation involves creating a sequence of integers and using it to compute the loss using the Cross Entropy Loss function from PyTorch... | The `compute_loss` function takes the input tensor, extracts the number of columns N, creates a sequence of integers from 0 to N-2, and then computes the loss using the Cross Entropy Loss function from PyTorch. The loss is then returned as a scalar value using the `item()` method. | magicoder | python |
You are tasked with implementing a custom view in an iOS application using Swift. The view should contain a label for displaying a name, and the label's position should be defined using SnapKit constraints.
Your task is to create a custom view class that includes a `nameLabel` and sets up its constraints using SnapKit... | ```swift
import UIKit
import SnapKit
class CustomNameView: UIView {
let nameLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
setupNameLabel()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupNameLabel()
}
pr... | magicoder | swift |
You are tasked with creating a function that simulates a simple wallet system for managing digital credentials. The wallet system will allow users to store, retrieve, and delete credentials. You are provided with a code snippet that includes a macro, module imports, and a test function for the wallet system.
Your task... | ```rust
#[macro_use]
mod utils;
use indy::wallet::Wallet;
use utils::constants::DEFAULT_CREDENTIALS;
pub struct WalletManager {
name: String,
credentials: String,
}
impl WalletManager {
pub fn new(wallet_name: &str, wallet_credentials: &str) -> Result<WalletManager, String> {
// Create a new wall... | magicoder | rust |
You are tasked with creating a Python function that retrieves information about Star Wars characters from the Star Wars API (SWAPI). The function should take a character's name as input and return their details, including their name, birth year, gender, and list of films they appeared in. You will need to use the reque... | ```python
import requests
def get_character_details(character_name: str) -> dict:
endpoint = 'https://swapi.py4e.com/api/people/'
response = requests.get(endpoint, params={'search': character_name})
data = response.json()
if data['count'] == 0:
return {"error": "Character not found"}
... | magicoder | python |
You are tasked with creating a Python class that simulates a simple online store inventory system. The inventory system should be able to add products, remove products, update product quantities, and display the current inventory. The class should also have a method to calculate the total value of the inventory based o... | ```python
class OnlineStoreInventory:
def __init__(self):
self.inventory = {}
def add_product(self, product_name, price, quantity):
if product_name in self.inventory:
self.inventory[product_name]['quantity'] += quantity
else:
self.inventory[product_name] = {'pric... | magicoder | python |
You are tasked with implementing a command-line utility that reads a list of commands from a file and executes them in the order they appear. The commands are stored in a file specified by the `_commands_file` variable. The commands are to be stored in a vector of strings named `_commands`. Additionally, the program sh... | ```cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <list>
#include <cstdlib>
std::vector<std::string> executeCommands() {
std::vector<std::string> output;
// Read commands from the file
std::ifstream file(_commands_file);
if (file.is_open()) {
std::... | magicoder | cpp |
You are tasked with creating a function that parses a given HTML snippet and extracts the text content within specific HTML elements. The function should take the HTML snippet and the tag names as input and return a list of the text content within the specified tags.
For example, given the following HTML snippet:
```h... | ```python
from bs4 import BeautifulSoup
def extract_text_from_tags(html, *tags):
soup = BeautifulSoup(html, 'html.parser')
text_contents = []
for tag in tags:
elements = soup.find_all(tag)
for element in elements:
text_contents.append(element.get_text().strip())
return text_... | magicoder | python |
You are tasked with implementing a web scraping algorithm to search for a specific word on a website. The provided code snippet is a part of a Python class that handles the search functionality. The `do_search` method is responsible for executing the search and retrieving the results. The `word` attribute contains the ... | ```python
import requests
class WebSearch:
def __init__(self, word, limit):
self.word = word.replace(' ', '%20')
self.results = ""
self.totalresults = ""
self.server = "www.google.com"
self.hostname = "www.google.com"
self.userAgent = "(Mozilla/5.0 (Windows; U; Windo... | magicoder | python |
You are tasked with comparing the performance of two different implementations for generating prime numbers. The first implementation uses the Numba library to accelerate the computation, while the second implementation uses a traditional approach without any optimization. Your goal is to analyze the time taken by each... | ```python
from time import time
import numba
import numpy as np
@numba.jit
def numba_primes(limit):
primes = []
for num in range(2, limit + 1):
is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if ... | magicoder | python |
You are tasked with creating a Discord bot command that retrieves and displays the Bedwars statistics of a given player. The bot interacts with an external API to fetch the player's UUID and then uses the UUID to retrieve the player's statistics. Your task is to implement the `get_uuid` and `get_player` methods to comp... | ```python
import requests
class BedwarsStatsBot:
def __init__(self, api_url):
self.api_url = api_url
async def get_uuid(self, username):
response = requests.get(f"{self.api_url}/get_uuid?username={username}")
if response.status_code == 200:
data = response.json()
... | magicoder | python |
You are tasked with implementing a custom view controller transition animation in a Swift iOS app. The given code snippet demonstrates the animation setup and execution using UIKit's `UIViewControllerContextTransitioning` and `UIView` animation methods.
Your task is to complete the implementation of the custom view co... | ```swift
UIView.addKeyframe(withRelativeStartTime: 0.667, relativeDuration: 0.166, animations: {
toView.transform = CGAffineTransform(scaleX: 1.1, y: 1.1) // 110% scale
})
UIView.addKeyframe(withRelativeStartTime: 0.833, relativeDuration: 0.167, animations: {
toView.transform = .identity // Restore original siz... | magicoder | swift |
You are tasked with implementing a class that represents an immutable list of all complete bids in a negotiation space. The negotiation space is defined by a domain, which specifies the possible values for each issue. A bid is a combination of values for all the issues in the domain. Your task is to create the `AllBids... | ```python
from typing import TypeVar, Generic, List
from geniusweb.issuevalue.Bid import Bid
from geniusweb.issuevalue.Domain import Domain
from tudelft.utilities.immutablelist.AbstractImmutableList import AbstractImmutableList
T = TypeVar('T')
class AllBidsList(AbstractImmutableList[Bid]):
'''
A list contai... | magicoder | python |
You are tasked with implementing a class to validate usernames based on certain criteria. The `Username` class should raise a `ConanException` if the username does not meet the specified requirements. The requirements for a valid username are as follows:
1. The username must not be empty.
2. The username must not excee... | ```python
class ConanException(Exception):
pass
class Username:
def __init__(self, username):
if not username:
raise ConanException("Username cannot be empty")
if len(username) > 30:
raise ConanException("Username cannot exceed 30 characters")
if not username.isa... | magicoder | python |
You are working on a computer vision project that involves stereo matching using block matching algorithms. In this project, you are tasked with implementing a block matching algorithm with the following parameters:
- `bm_SAD_window_size`: The size of the Sum of Absolute Differences (SAD) window used for block matchin... | ```cpp
#include <opencv2/opencv.hpp>
std::vector<int> blockMatching(const std::vector<cv::Mat>& leftImage, const std::vector<cv::Mat>& rightImage, int bm_SAD_window_size, int bm_12_max_diff, int bm_min_disparity, int bm_num_disparities, int bm_speckle_window_size) {
std::vector<int> disparityMap;
// Perform b... | magicoder | cpp |
You are tasked with implementing a function that parses a given HTML snippet and extracts all the URLs present in the anchor tags (`<a>`). The function should return a list of all the URLs found in the HTML snippet.
Function Signature: `def extract_urls(html: str) -> List[str]:`
Input:
- `html` (1 <= len(html) <= 10^... | ```python
from typing import List
import re
def extract_urls(html: str) -> List[str]:
pattern = r'href="([^"]*)"'
urls = re.findall(pattern, html)
return urls
```
The `extract_urls` function uses the `re.findall` method to extract all the URLs from the HTML snippet using a regular expression pattern. The ... | magicoder | python |
You are tasked with implementing a function to parse a given C++ source code file and extract all the function names present in the file. The function names should be returned as a list of strings. A function name is defined as any valid C++ identifier followed by an opening parenthesis '('.
You are given a code snip... | ```python
from typing import List
import re
def extractFunctionNames(sourceCode: str) -> List[str]:
function_names = re.findall(r'\b\w+\s*\([^)]*\)\s*{', sourceCode)
function_names = [name.split('(')[0].strip() for name in function_names]
return function_names
```
The `extractFunctionNames` function uses ... | magicoder | python |
You are tasked with implementing a Python unit test for a class called `ExperimentMock`, which is a subclass of `WorkloadExperiment`. The `ExperimentMock` class represents the logic for a specific experiment and is expected to perform various actions during its execution. Your goal is to write a unit test that verifies... | ```python
import unittest
from unittest.mock import Mock
class TestExperimentMock(unittest.TestCase):
def test_experiment_actions(self):
exp = ExperimentMock()
# Mocking the methods and attributes of ExperimentMock
exp.run_experiment = Mock()
exp.write_summary_file = Mock()
... | magicoder | python |
You are tasked with implementing a value iteration algorithm to solve a dynamic programming problem. The problem involves finding the optimal value function and policy for a given set of states and actions in a Markov decision process (MDP).
The value iteration algorithm is used to iteratively update the value functio... | ```python
import numpy as np
import math
def value_iteration(m, W, rewards, beta, u, N):
tol = 1.
psi_ind = np.zeros(m, dtype=int) # Initialize policy indices
values = np.zeros(m) # Initialize value function
while tol >= 1e-9:
for i in range(m):
values[i] = u(W[i] - W[psi_ind[i]]... | magicoder | python |
You are tasked with implementing a URL routing system for a web application using Python's Flask framework. The given code snippet is a part of the routing setup for a Flask blueprint. The `is_login_require` variable is a boolean flag indicating whether the view function requires login authentication. If it does, the `... | ```python
from flask import Blueprint
from functools import wraps
def generate_url_rules(blueprint, view_func, is_login_require, pk_type, pk):
if is_login_require:
view_func = login_required(view_func)
def login_required(view_func):
@wraps(view_func)
def decorated_view(*args, **kwargs)... | magicoder | python |
You are tasked with implementing a reinforcement learning algorithm using a deep Q-network (DQN) to train an agent to navigate a grid-based environment. The provided code snippet contains various hyperparameters and settings that will be used in the implementation. Your goal is to create a function that initializes the... | ```python
import torch
import torch.nn as nn
import torch.optim as optim
class DQN(nn.Module):
def __init__(self, input_size, output_size, hidden_size):
super(DQN, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size)
self.fc2 = nn.Linear(hidden_size, hidden_size)
self.fc3 ... | magicoder | python |
You are given a list of integers and a target sum. Your task is to write a function that finds all unique combinations in the list that sum up to the target. Each number in the list may only be used once in the combination. The same number may be chosen from the list multiple times.
For example, given the list [2, 3, ... | ```java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CombinationSum {
public List<List<Integer>> findCombinations(int[] nums, int target) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
backtrack(result, new ArrayList<>(), num... | magicoder | java |
You are given a Python function that calculates the factorial of a positive integer using a stack data structure. The function uses a stack `S` to store the numbers from `n` down to 1, and then calculates the factorial by popping the numbers from the stack and multiplying them together. Your task is to implement the st... | ```python
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
else:
raise IndexError("Pop from an empty stack")
def length(self):
r... | magicoder | python |
You are given a code snippet that contains a comment block. Your task is to write a program that counts the occurrences of each word within the comment block, ignoring any non-alphabetic characters and considering words in a case-insensitive manner. A word is defined as a sequence of alphabetic characters separated by ... | ```python
import re
def count_word_occurrences(comment_block):
words = re.findall(r'\b\w+\b', comment_block.lower())
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
return word_count
```
The `count_word_... | magicoder | python |
You are tasked with creating a Python function that generates a bar graph based on a given dataset. The function should take in the dataset, title, and x-axis label as input and produce a bar graph with the specified title and x-axis label.
The function signature should be:
```python
def generate_bar_graph(dataset: di... | ```python
import matplotlib.pyplot as plt
def generate_bar_graph(dataset: dict, title: str, x_axis_label: str) -> None:
categories = list(dataset.keys())
values = list(dataset.values())
plt.bar(categories, values)
plt.title(title)
plt.xlabel(x_axis_label)
plt.ylabel('Values')
plt.show()
``... | magicoder | python |
You are tasked with implementing a Python class that generates Dogecoin TestNet addresses based on the BIP32 hierarchical deterministic wallet specification. The BIP32 path for the addresses will be derived from a given index.
Your task is to complete the implementation of the `generate_address` method in the `Dogecoi... | ```python
import hashlib
import hmac
import base58
class DogecoinTestNet:
EXT_PUBLIC_KEY = 0x02facafd
EXT_SECRET_KEY = 0x02fac398
BIP32_PATH = "m/44'/3'/0'/"
@classmethod
def generate_address(cls, index):
path = cls.BIP32_PATH + str(index)
extended_key = cls.EXT_PUBLIC_KEY.to_bytes... | magicoder | python |
You are tasked with implementing a logging system in Python. Your goal is to create a custom logger that logs messages at different levels and then write a unit test to verify the functionality of the logger.
Your custom logger should have the following features:
- It should be able to log messages at different levels... | ```python
import unittest
import logging
class CustomLogger:
def __init__(self):
self.logger = logging.getLogger('custom_logger')
self.logger.setLevel(logging.DEBUG)
self.captured = logging.handlers.MemoryHandler(1000)
self.logger.addHandler(self.captured)
def log_debug(self, m... | magicoder | python |
You are tasked with creating a program that simulates a simple quiz game. The program should present a series of questions to the user, accept their answers, and then provide feedback on their performance. The questions should cover a variety of topics and be presented in a random order. The user's score should be calc... | ```python
import random
def get_answers():
questions = {
"What is the capital of France?": {
"A": "London",
"B": "Paris",
"C": "Berlin",
"D": "Madrid",
"correct": "B"
},
"Which planet is known as the Red Planet?": {
"A"... | magicoder | python |
You are tasked with creating a Python program that reads a text file, encodes its content using a specified encoding, and then writes the encoded content to a new file. Your program should also be able to decode the encoded content back to its original form.
Your program should have the following functionalities:
1. ... | ```python
import argparse
import codecs
def encode_file(input_file, output_file, encoding):
try:
with open(input_file, 'r', encoding='utf-8') as file:
content = file.read()
encoded_content = codecs.encode(content, encoding)
with open(output_file, 'wb') as output:
... | magicoder | python |
You are tasked with implementing a class that performs various mathematical calculations and string manipulations. Your task is to complete the implementation of the `Calculate` class by adding methods to perform specific operations.
You are provided with a code snippet that creates an instance of the `Calculate` clas... | ```java
public class Calculate {
public String echo(String str) {
return "echo: " + str;
}
public static void main(String[] args) {
System.out.println("Hello World!");
Calculate calc = new Calculate();
String echo = calc.echo("ahh");
System.out.println(echo);
}
}... | magicoder | java |
You are tasked with implementing a function to calculate the Euclidean distance between two vectors in a machine learning framework. The provided code snippet is a part of this function, but it lacks the complete implementation. Your task is to complete the function and ensure that it correctly calculates the Euclidean... | ```python
def _euclidean_distance(vects):
x, y = vects
sum_square = K.sum(K.square(x - y), axis=1, keepdims=True)
# Calculate the Euclidean distance between the input vectors
distance = K.sqrt(K.maximum(sum_square, K.epsilon()))
return distance
# The shape of the output vector representing the dist... | magicoder | python |
You are tasked with implementing a Python class that processes and analyzes data from a given source. The class should have methods to perform various data operations and provide insights into the dataset.
You are provided with a basic `Data` class that has the following structure:
```python
class Data:
def __in... | ```python
import pandas as pd
import matplotlib.pyplot as plt
class Data:
def __init__(self, source):
self.source = source
self.data = self.load_data()
def load_data(self):
# Method to load data from the provided source
# Assuming source is a CSV file
return pd.read_csv... | magicoder | python |
You are tasked with implementing a simple web server using Python's `socket` module. Your server should be able to handle multiple client connections and serve basic HTTP requests. The server should be capable of receiving and responding to HTTP GET requests for static files, such as HTML, CSS, and image files.
Your t... | ```python
import socket
import os
import mimetypes
from threading import Thread
class MipiWSServer:
def __init__(self, mipi):
self.host, self.port = mipi
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEAD... | magicoder | python |
You are tasked with implementing a class for a slimming neural network framework. The class `SlimmableLinear` is a subclass of a neural network layer and is used to create a linear layer that supports dynamic slimming. The constructor of `SlimmableLinear` takes in the following parameters:
- `in_features`: An integer r... | ```python
import torch.nn as nn
class SlimmableLinear(nn.Linear):
def __init__(self, in_features, out_features, bias=True,
non_slimmable_out=False, non_slimmable_in=False):
super(SlimmableLinear, self).__init__(in_features, out_features, bias=bias)
self.max_in_features = in_featur... | magicoder | python |
You are tasked with creating a function that retrieves and processes order data from a database using Laravel's Eloquent ORM. Your goal is to complete the `manager_order` function within a Laravel controller. The function should perform the following tasks:
1. Ensure that the user is authenticated before accessing the ... | ```php
public function manager_order(){
// Ensure user authentication
$this->authLogin();
// Retrieve and process order data
$all_order = DB::table('tbl_order')
->join('tbl_customers','tbl_order.customer_id','=','tbl_customers.customer_id')
->select('tbl_order.*', 'tbl_customers.custome... | magicoder | php |
You are tasked with implementing a system for parallel processing of tasks. The system is designed to handle multiple parallel tasks, each identified by a unique system ID. The code snippet provided defines several system IDs for parallel processing.
Your task is to design a data structure and implement the necessary ... | ```python
class ParallelProcessingSystem:
def __init__(self):
self.systemIDs = set()
def registerSystemID(self, systemID):
self.systemIDs.add(systemID)
def removeSystemID(self, systemID):
if systemID in self.systemIDs:
self.systemIDs.remove(systemID)
else:
... | magicoder | python |
You are tasked with creating a script to manage Docker Compose configuration files based on the environment. The script should handle the creation of symbolic links to the appropriate Docker Compose configuration file based on the environment specified as an argument. If no argument is provided, the default environment... | ```bash
#!/bin/bash
ENV=${1:-'dev'} # Set the environment variable to the provided argument or 'dev' if no argument is given
DOCKERFILE="docker/docker-compose.${ENV}.yml" # Construct the file path for the Docker Compose configuration file
if [ -f "$DOCKERFILE" ]; then # Check if the Docker Compose file exists
r... | magicoder | shell |
You are tasked with implementing a Java interface for managing seal entities in a virtual world simulation. The interface, `ISealEntity`, defines methods for interacting with seal entities and retrieving relevant information. Your goal is to create a concrete class that implements this interface and provides the necess... | ```java
public class SealEntity implements ISealEntity {
private ISeal seal;
private SealPos sealPos;
private byte priority;
public SealEntity(ISeal seal, SealPos sealPos, byte priority) {
this.seal = seal;
this.sealPos = sealPos;
this.priority = priority;
}
@Override
... | magicoder | java |
You are given an array of integers, where every element appears twice except for one. Write a function to find the unique element.
Write a function `findUniqueElement` that takes in an array of integers and returns the unique element.
Example:
Input:
[4, 3, 2, 4, 3]
Output:
2
Input:
[7, 5, 6, 5, 6]
Output:
7
Note:
... | ```python
def findUniqueElement(nums):
unique_element = 0
for num in nums:
unique_element ^= num
return unique_element
```
The `findUniqueElement` function iterates through the array of integers and uses the XOR operation to find the unique element. Since XOR of a number with itself is 0, and XOR o... | magicoder | python |
You are tasked with creating a command-line tool for text summarization using Python. Your program should utilize the `argparse` library to handle command-line arguments and the `Summarizer` class to perform the text summarization. The `Summarizer` class has a method `add_model_specific_args` for adding model-specific ... | ```python
import argparse
import os
class Summarizer:
@staticmethod
def add_model_specific_args(parser, current_dir):
parser.add_argument('--model', type=str, default='default_model', help='Specify the summarization model')
parser.add_argument('--length', type=int, default=100, help='Specify th... | magicoder | python |
You are tasked with developing a multilingual validation system for a web application. The system should support the validation of various user inputs, such as passwords and email addresses, and provide appropriate error messages in different languages. To achieve this, you need to implement a function that takes in a ... | ```python
import re
def parseValidationMessages(code_snippet: str) -> dict:
validation_messages = {}
pattern = r'"(.*?)".*?=>.*?__\(\'(.*?)\'\)'
matches = re.findall(pattern, code_snippet)
for match in matches:
validation_messages[match[0]] = match[1]
return validation_messages
# Test the ... | magicoder | python |
You are given a dictionary containing color filter thresholds for a computer vision application. The dictionary contains keys for different color channels and their corresponding lower and upper thresholds. Your task is to write a function that takes this dictionary and a color image as input, and applies the color fil... | ```python
import cv2
import numpy as np
def apply_color_filters(image, color_filters):
# Convert the image from BGR to HSV color space
hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# Define the lower and upper bounds for each color channel
lower_bound = np.array([color_filters['H_low'], color_fil... | magicoder | python |
You are given a series of rounds in a game where each round has a specific score. However, some rounds may have invalid data, and the scores need to be adjusted accordingly. Your task is to write a program to calculate the final score after adjusting for the invalid rounds.
You are given a list of strings, where each ... | ```python
def calculateFinalScore(rounds: List[str]) -> int:
total_score = 0
for round_data in rounds:
data_parts = round_data.split()
if len(data_parts) >= 6 and data_parts[5].isdigit():
total_score += int(data_parts[5].strip('.'))
return total_score
```
The `calculateFinalScore... | magicoder | python |
You are tasked with automating the installation of the ionCube loader for different PHP versions and operating systems. The code snippet provided is a part of a shell script that handles the installation process. The script checks the PHP version and the operating system, then downloads and installs the ionCube loader ... | ```bash
function installIonCubeLoader() {
local PHP_VERSION=$1
local OS=$2
local EXTENSION_DIR=$(php -r 'echo ini_get("extension_dir");')
local LOADER_INI
if [ $OS = "centos7" ]; then
LOADER_INI=/usr/local/php${PHP_VERSION}/etc/php.d/01-ioncube_loader.ini
else
LOADER_INI=/path/to/centos6/php${PHP_V... | magicoder | shell |
You are given a sequence of integers `a[0], a[1], ..., a[n-1]`. Your task is to implement a function `transform_sequence(a)` that performs a specific transformation on the input sequence and returns the resulting sequence.
The transformation is defined as follows:
- For each element `a[i]` in the sequence, perform the... | ```python
from typing import List
def transform_sequence(a: List[int]) -> List[int]:
result = []
for num in a:
binary_num = bin(num)[2:] # Convert to binary representation
transformed_num = num ^ (num << 1) ^ (num & (num << 1)) ^ (num & (num << 1) & (num << 2)) # Perform transformation
... | magicoder | python |
You are tasked with creating a Swift program that interacts with a SQLite database. Your goal is to implement a class that manages the database connection and provides methods for executing SQL queries. The provided code snippet defines a `GlobalSQLite` struct with two properties: `secret` and `newsecret`. Your task is... | ```swift
import Foundation
import SQLite3
class SQLiteManager {
private var database: OpaquePointer? = nil
private let databaseFilePath: String
init(databaseFilePath: String) {
self.databaseFilePath = databaseFilePath
}
func openConnection() -> Bool {
if sqlite3_open(databaseFileP... | magicoder | swift |
You are tasked with implementing a custom error handling system in Rust. The provided code snippet is importing error-related modules from a parent module using the `super` keyword. Your goal is to create a custom error type and an error collector to handle and report errors in a Rust application.
Your task is to impl... | ```rust
use std::fmt;
// Define the custom error type
#[derive(Debug)]
struct CustomError {
message: String,
}
// Implement the Display trait for CustomError
impl fmt::Display for CustomError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.message)
}
}
// Implement t... | magicoder | rust |
You are given a function `binary_search` that performs a binary search to find the value of `k` such that `f(k)` is true. The function `binary_search` takes a closure `f` as an argument, which represents the function to be evaluated. The closure `f` takes an unsigned 32-bit integer as input and returns a boolean value.... | ```rust
fn find_k<F: Fn(u32) -> bool>(f: F) -> u32 {
binary_search(f)
}
```
The solution is simply to call the `binary_search` function with the provided closure `f` as an argument, as the `binary_search` function already handles the binary search logic to find the value of `k` for which `f(k)` is true. | magicoder | rust |
You are tasked with implementing a simple package manager for a programming language. The package manager should be able to handle the creation, management, and distribution of software packages. Each package can have a name, version, and list of dependencies. The package manager should be able to resolve dependencies ... | ```swift
func installOrder(_ packages: [Package]) -> [String] {
var graph: [String: Set<String>] = [:]
var indegree: [String: Int] = [:]
// Build the dependency graph and calculate indegrees
for package in packages {
graph[package.name] = Set(package.dependencies)
indegree[package.name]... | magicoder | swift |
You are tasked with implementing a resource key generation system for a software application. The system should be able to generate unique keys based on the type and ID of a resource, with the option to include a locale if the resource is associated with a localized system.
You are provided with a code snippet that de... | ```php
function generateResourceKey($sys) {
if ($sys instanceof LocalizedResourceSystemProperties) {
$options = ['locale' => $sys->getLocale()];
} else {
$options = [];
}
$key = $this->resourcePool->generateKey($sys->getType(), $sys->getId(), $options);
return $key;
}
```
In the solu... | magicoder | php |
You are tasked with implementing a program to process and analyze data from a particle physics experiment. The experiment involves isolating and summing the transverse momentum of particles using a specific algorithm called CITKPFIsolationSumProducerForPUPPI. Your task is to write a function that takes in the relevant ... | ```python
from typing import List
class Particle:
def __init__(self, pt: float, eta: float, phi: float, properties: dict):
self.pt = pt
self.eta = eta
self.phi = phi
self.properties = properties
def calculate_isolation_sum(particles: List[Particle]) -> List[float]:
isolation_su... | magicoder | python |
You are tasked with implementing a feature in a Laravel application that allows users to upload and import data from an Excel file. The provided code snippet is a part of the `UploadController` in the Laravel application. The `importExportView` method is responsible for rendering the view for importing data from an Exc... | ```php
use App\Imports\PostImport;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;
use App\Models\Post; // Assuming the model for storing imported data is Post
class UploadController extends Controller
{
public function importExportView()
{
return view('import');
}
pub... | magicoder | php |
You are tasked with implementing a Java class to manage events for a charting application. The class, `ChartEvent`, should handle various types of events that occur within the charting application. Your task is to complete the implementation of the `ChartEvent` class by adding methods to handle different types of event... | ```java
public class ChartEvent {
public void mouseClicked(int x, int y) {
// Add code to handle the event when the mouse is clicked at coordinates (x, y) on the chart
System.out.println("Mouse clicked at coordinates: (" + x + ", " + y + ")");
}
public void mouseMoved(int x, int y) {
... | magicoder | java |
You are tasked with implementing a C++ class that represents a histogram for a given range of values. The class should provide methods to add data points to the histogram and to retrieve the frequency of data points falling within specific bins.
Your task is to complete the implementation of the `Histogram` class, whi... | ```cpp
#include <iostream>
#include <vector>
class Histogram {
private:
const double &xlo;
const double &xhi;
const int &nbins;
double binWidth;
std::vector<int> bins;
int getBinIndex(const double &x) {
return static_cast<int>((x - xlo) / binWidth);
}
public:
Histogram(const d... | magicoder | cpp |
You are tasked with implementing a custom data structure in Swift that represents a byte buffer. The data structure should be initialized with a collection of bytes, and it should enforce the constraint that the collection's elements are of type `UInt8` and its indices are of type `Int`.
Your task is to create a Swift... | ```swift
class ByteBuffer {
private let bytes: [UInt8]
init<T: Collection>(bytes: T) where T.Element == UInt8, T.Index == Int {
self.bytes = Array(bytes)
}
func byte(atIndex index: Int) -> UInt8? {
guard index >= 0, index < bytes.count else {
return nil
}
re... | magicoder | swift |
You are tasked with creating a Python function that simulates a simplified version of a Discord bot's channel management functionality. The function should take in a list of channel names and create these channels in a guild, while also deleting any existing channels in the guild. The function should follow these speci... | ```python
import discord
async def manage_channels(guild_channels, guild):
# Assuming 'client' is the Discord bot client
client = discord.Client()
# Assuming 'token' is the bot's token
await client.login('token')
# Assuming 'ctx' is the context for the guild
ctx = await client.get_guild(guild)
... | magicoder | python |
You are tasked with implementing a function that processes a given `TestRunnerConfiguration` and returns the count of negative compile test targets. The `TestRunnerConfiguration` is an array of `ConfiguredNegativeCompileTestTarget` instances, where each instance represents a test target with a boolean flag indicating w... | ```swift
func countNegativeCompileTestTargets(_ configuration: TestRunnerConfiguration) -> Int {
return configuration.reduce(0) { $0 + ($1.isConfiguredForNegativeCompileTest ? 1 : 0) }
}
```
The `countNegativeCompileTestTargets` function uses the `reduce` method to iterate through the `TestRunnerConfiguration` arra... | magicoder | swift |
You are tasked with creating a program to convert a given amount in Euros (EUR) to Polish Zloty (PLN) using the current exchange rate. The exchange rate is provided as a constant value and should be used to perform the conversion. Your program should include a function `convertEURtoPLN` that takes the amount in Euros a... | ```c
#include <stdio.h>
const double EXCHANGE_RATE_EUR_TO_PLN = 4.55;
double convertEURtoPLN(double amountInEUR) {
return amountInEUR * EXCHANGE_RATE_EUR_TO_PLN;
}
int main() {
double amountInEUR = 100.0;
double amountInPLN = convertEURtoPLN(amountInEUR);
printf("%.2f EUR is equal to %.2f PLN\n", amo... | magicoder | c |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.