query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a reinforcement learning (RL) environment for a simple pendulum system. The pendulum is controlled by applying a torque to the joint, and the goal is to swing the pendulum up so it stays upright. The code snippet provided initializes a random policy, creates an RL task with the environm... | ```python
import gym
import numpy as np
class PendulumEnv(gym.Env):
def __init__(self):
self.gravity = 9.8
self.mass = 1.0
self.length = 1.0
self.dt = 0.02
self.max_torque = 2.0
self.max_speed = 8.0
self.viewer = None
high = np.array([1., 1., self.ma... | magicoder | python |
You are tasked with creating a function that validates and processes a configuration object for a GPU task. The configuration object contains the following properties:
- `gpuMemorySize` (optional): A number representing the GPU memory size in megabytes.
- `runtime`: A string representing the runtime environment for th... | ```javascript
function validateAndProcessConfig(config) {
if (config.gpuMemorySize !== undefined && (typeof config.gpuMemorySize !== 'number' || config.gpuMemorySize <= 0)) {
throw new Error('Invalid gpuMemorySize: must be a positive number');
}
if (typeof config.runtime !== 'string' || config.runtime.trim()... | magicoder | javascript |
You are tasked with creating a Python function to calculate the minimum and maximum distances between two sets of 3D coordinates representing molecular structures. The function should take in two NumPy arrays, `mol1` and `mol2`, each containing a set of 3D coordinates for a molecular structure. Additionally, the functi... | ```python
import numpy as np
def compute_min_max_dist(mol1, mol2, CLASH_DIST, BOX_SIZE):
def pack_transformation(mol1, mol2, CLASH_DIST, BOX_SIZE):
# Implementation of pack_transformation function is not provided
pass
# Assuming the pack_transformation function is implemented correctly
tra... | magicoder | python |
You are tasked with implementing a simple data processing pipeline using Rust. The pipeline will involve creating and manipulating data blocks and columns. Your task is to implement a function that takes a table schema and a set of data rows, and returns a data block containing the data in the specified format.
You ar... | ```rust
fn create_data_block(table_info: Arc<TableInfo>, data_rows: Vec<Vec<Box<dyn Any>>>) -> Result<DataBlock> {
// Validate the number of columns
if table_info.fields().len() != data_rows.get(0).map_or(0, |row| row.len()) {
return Err("Number of columns in table_info does not match the number of elem... | magicoder | rust |
You are given a collection of integers that might contain duplicates, nums. Write a function to return all possible subsets (the power set).
The solution set must not contain duplicate subsets. Return the solution in any order.
**Example 1:**
Input: nums = [1,2,2]
Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]
**Example 2... | ```python
class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
nums.sort()
res = []
self.dfs(nums, 0, [], res)
return res
def dfs(self, nums, index, path, res):
res.append(path)
for i in range(index, len(nums)):
if i > ind... | magicoder | python |
You are tasked with implementing a JavaScript function that takes a callback as an argument and calls the callback function when a message is received. The function should be able to handle asynchronous message reception and execute the callback function with the received message as its argument.
Your task is to compl... | ```javascript
function receiveMessage(callback) {
// Simulate asynchronous message reception using setTimeout
setTimeout(() => {
const message = "Hello, this is the received message!";
callback(message); // Call the provided callback function with the received message
}, 1000); // Simulate a delay of 1 se... | magicoder | javascript |
You are tasked with creating a program that evaluates mathematical expressions using lambda expressions in C#. Your program should take a mathematical expression as input and then use lambda expressions to evaluate and return the result.
Your program should include the following components:
1. A method named `Evaluate... | ```csharp
using System;
using System.Linq.Expressions;
class Program
{
static void Main()
{
string inputExpression = "2 * (3 + 5)";
double result = EvaluateExpression(inputExpression);
Console.WriteLine($"Result: {result}");
}
static double EvaluateExpression(string expression)... | magicoder | csharp |
You are tasked with implementing a custom SnackBar component in Swift for a mobile application. The SnackBar is a UI element that displays a brief message at the bottom of the screen and then disappears after a short period of time. Your task is to create a SnackBar class that can be easily integrated into the applicat... | ```swift
import UIKit
class SnackBar: UIView {
private let messageLabel: UILabel = UILabel()
private let actionButton: UIButton = UIButton()
private var displayTimer: Timer?
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder: NSCoder) {
... | magicoder | swift |
You are tasked with implementing a function to parse and process a custom data format used in a genealogy application. The data format consists of records representing individuals and families, with each record having a specific type. The function `has_record_type` is used to check if a given record type is supported b... | ```python
class UnsupportedRecordType(Exception):
pass
def has_record_type(record_type):
supported_record_types = ['individual', 'family', 'event']
if record_type in supported_record_types:
return True
else:
raise UnsupportedRecordType(f"Unsupported record type: {record_type}")
# Examp... | magicoder | python |
You are tasked with creating a script to monitor the availability of web servers running on different application servers. The script should enumerate the application servers, retrieve the port numbers of the web servers, and then send a simple HTTP request to each web server to check if it is responsive.
Write a Pyth... | ```python
import subprocess
import re
import requests
# Step 1: Enumerate application servers
netstat_output = subprocess.check_output(["netstat", "-tulpn"]).decode("utf-8")
# Step 2: Extract port numbers of web servers
port_numbers = re.findall(r".*:([0-9]+).*LISTEN", netstat_output)
# Step 3: Send HTTP request to ... | magicoder | python |
You are tasked with creating a utility class for generating Core Animation keyframe animations in Swift. The class should provide methods for creating scale and rotate animations with customizable duration, key times, timing functions, and values.
Your task is to implement the `KeyframeAnimationUtility` class with the... | ```swift
import UIKit
class KeyframeAnimationUtility {
let duration: TimeInterval
let timingFunction: CAMediaTimingFunction
let keyTimes: [NSNumber]
init(duration: TimeInterval, timingFunction: CAMediaTimingFunction, keyTimes: [NSNumber]) {
self.duration = duration
self.timingFunction ... | magicoder | swift |
You are tasked with implementing a Metropolis-Hastings MCMC (Markov Chain Monte Carlo) algorithm to sample from a given posterior density function. The goal is to generate samples from the posterior distribution using the Metropolis-Hastings algorithm and analyze the convergence and mixing properties of the samples.
Y... | To implement the Metropolis-Hastings MCMC algorithm, you can use the following Python code as a starting point:
```python
import numpy as np
# Define the posterior density function
def posterior_density(x, y):
# Define the posterior density function here
# Example:
return np.exp(-((x - 2)**2 + (y - 3)**2)... | magicoder | python |
You are tasked with creating a password validation function for a web application. The function should check if the provided password meets certain criteria and return a message indicating whether the password is valid or not.
Write a function `validatePassword` that takes a single parameter `password` (a string) and ... | ```javascript
function validatePassword(password) {
if (password.length < 8) {
return "Password must be at least 8 characters long.";
}
if (!/[A-Z]/.test(password)) {
return "Password must contain at least one uppercase letter.";
}
if (!/[a-z]/.test(password)) {
return "Password must contain at le... | magicoder | javascript |
You are tasked with creating a program to visualize features of a directed graph (DG). The program should take as input the adjacency matrix of the graph and produce a visualization of the graph's features. The features to be visualized include the presence of cycles, the presence of strongly connected components, and ... | ```python
import networkx as nx
import matplotlib.pyplot as plt
def visualize_dg_features(adj_matrix):
G = nx.DiGraph(adj_matrix)
# Detection of Cycles
if nx.is_directed_acyclic_graph(G):
cycles = nx.simple_cycles(G)
for cycle in cycles:
cycle_edges = [(cycle[i], cycle[i+1]... | magicoder | python |
You are tasked with implementing a function that takes a string as input and returns a modified version of the string. The modification involves reversing the order of characters in each word while keeping the words themselves in the same order. Additionally, the function should ignore any leading or trailing whitespac... | ```java
public String reverseWords(String s) {
String[] words = s.trim().split("\\s+"); // Split the input string by whitespace and remove leading/trailing whitespace
StringBuilder result = new StringBuilder();
for (String word : words) {
result.append(new StringBuilder(word).reverse()).append(... | magicoder | java |
You are tasked with implementing a custom web resource class in TypeScript that extends the `WebResource` class. The `TestWebResource` class should have a constructor that accepts an optional `AbortSignalLike` parameter and calls the constructor of the base `WebResource` class with certain parameters.
Your task is to ... | ```typescript
import { WebResource, HttpResponse, AbortSignalLike, HttpMethods } from 'ms-rest-js';
export class TestWebResource extends WebResource {
constructor(
url: string = '',
method: HttpMethods = 'GET',
body: any = undefined,
query: { [key: string]: any } = {},
headers: { [key: string]: a... | magicoder | typescript |
You are tasked with implementing a custom Seq2VecEncoder for a natural language processing (NLP) model using the AllenNLP library. The Seq2VecEncoder is a crucial component in NLP models for converting sequences of word embeddings into a single vector representation. Your task is to create a custom Seq2VecEncoder class... | ```python
import torch
import torch.nn as nn
from allennlp.modules.seq2vec_encoders import Seq2VecEncoder
class CustomSeq2VecEncoder(Seq2VecEncoder):
def __init__(self, input_dim: int, encoding_dim: int):
super().__init__()
self.linear_layer = nn.Linear(input_dim, encoding_dim)
def forward(sel... | magicoder | python |
You are tasked with implementing a simplified version of a coroutine scheduler in Python. A coroutine is a specialized version of a generator that can pause and resume its execution, allowing for cooperative multitasking. Your goal is to create a class that can manage the execution of coroutines and handle their suspen... | ```python
import threading
class CoroutineScheduler:
def __init__(self):
self.step_thread = None
def step(self, coro_deliver, contval):
# Run a step of the coroutine, i.e. execute it until a suspension or
# completion, whichever happens first.
here = self.step_thread = threadin... | magicoder | python |
You are given a list of integers representing the daily stock prices of a company. Your task is to write a function to calculate the maximum profit that can be obtained by buying and selling the stock at most once. If it is not possible to make any profit, return 0.
Write a function `max_profit(prices: List[int]) -> i... | ```python
from typing import List
def max_profit(prices: List[int]) -> int:
if not prices:
return 0
min_price = prices[0]
max_profit = 0
for price in prices:
if price < min_price:
min_price = price
else:
max_profit = max(max_profit, price - min_... | magicoder | python |
You are tasked with creating a system to evaluate candidates based on various criteria. The code snippet provided is a part of a larger system that defines specifications and tests whether a candidate meets those specifications. The specifications are defined as classes, and the tests are combined using logical operato... | ```python
class HasNameSpec:
def passes(self, candidate: PersonDTO) -> bool:
return bool(candidate.name)
# Modify the passes method to include the HasNameSpec in the composite test
def passes(self, candidate: PersonDTO) -> bool:
has_age_spec = HasAgeSpec()
has_name_spec = HasNameSpec() # New speci... | magicoder | python |
You are tasked with implementing a function that generates a blurhash for an image. Blurhash is a compact representation of a placeholder for an image, allowing for a smooth loading experience. The blurhash algorithm encodes the average color and the distribution of high-frequency components in an image into a short st... | ```javascript
function generateBlurhash(imageData, width, height) {
// Implementation of the blurhash generation algorithm
// This function should return the generated blurhash as a string
// ...
}
// Integration with the provided code snippet
const blurhash = generateBlurhash(imageData, width, height);
const AS... | magicoder | javascript |
You are tasked with implementing a neural network architecture for a specific task. The architecture consists of multiple discriminators and pooling layers. Each discriminator is an instance of the `Discriminator` class, and the pooling layers consist of an `Identity` layer followed by multiple instances of `nn.AvgPool... | ```python
import torch.nn as nn
class CustomNetwork(nn.Module):
def __init__(self):
super(CustomNetwork, self).__init__()
self.discriminators = nn.ModuleList(
[Discriminator() for _ in range(3)]
)
self.pooling = nn.ModuleList(
[Identity()] +
... | magicoder | python |
You are tasked with creating a program that analyzes a given text file to count the occurrences of each unique word. For the purpose of this problem, a word is defined as a sequence of alphanumeric characters, excluding any punctuation or whitespace. The program should be case-insensitive, meaning that "Hello" and "hel... | ```python
import re
from collections import Counter
from typing import Dict
def count_word_occurrences(file_path: str) -> Dict[str, int]:
# Read the file and convert its content to lowercase
with open(file_path, 'r') as file:
content = file.read().lower()
# Use regular expression to find all alpha... | magicoder | python |
You are tasked with implementing a multi-armed bandit algorithm for a recommendation system. The algorithm involves selecting an arm (option) based on a probability distribution that changes with time. The code snippet provided is a part of the `select_arm` method in the bandit algorithm class. The method is responsibl... | ```python
def select_arm(self, z):
if self.annealing:
self.update_temperature()
probs = self.arms['Reward'].map(lambda x: exp(x/self.temperature))
probs /= float(probs.sum())
cum_prob = probs.cumsum()
# Select the arm based on the random value z and cumulative probabilities
selected_a... | magicoder | python |
You are tasked with creating a responsive web layout using CSS and styled-components library in React. The goal is to implement a responsive grid system with specific styling properties.
Given the following code snippet:
```javascript
const Container = styled.div`
display: flex;
align-items: center;
justify-con... | ```javascript
const Container = styled.div`
display: flex;
align-items: center;
justify-content: center;
margin: 12px;
max-width: 1200px;
width: 100%;
margin: 0 auto;
`;
const ImageWrapper = styled.div`
margin: 12px;
max-width: 300px;
width: 100%;
`;
// Media query for responsive layout
@media (ma... | magicoder | javascript |
You are working on a software system that processes medical data using Python. The given code snippet is a function `get_astm` that takes a list of directions, an analyzer object, a boolean flag `full`, and an output file object `out` as input. The function returns a string representing the encoded medical data.
The `... | ```python
import json
import itertools
class api:
class Analyzer:
def __init__(self):
# Initialize any necessary attributes
pass
def analyze(self, direction, full):
# Implement the logic to analyze the given direction
pass
def get_iss_direction(dire... | magicoder | python |
You are tasked with implementing a version comparison function for a software library. The function should compare the installed version of the library with the required version and provide a message indicating whether the installed version is compatible or not.
You are given the following information:
- The name of t... | ```python
def version_check(self, installed_version, version_range):
min_version, max_version = version_range
if min_version <= installed_version < max_version:
return "Library version for '{}' is compatible.".format(self.name)
else:
return "Library version for '{}' is incompatible. Installe... | magicoder | python |
You are tasked with creating a program that processes a list of vehicles and performs various operations on them. The program should utilize the provided code snippet and additional context to implement the required functionality.
Context:
The code snippet includes necessary imports for the FleetClients and GACore lib... | ```csharp
using System;
using System.Collections.Generic;
using System.Linq;
namespace VehicleProcessing
{
// Define the Vehicle class with properties
public class Vehicle
{
public string Make { get; set; }
public string Model { get; set; }
public int Year { get; set; }
publ... | magicoder | csharp |
You are working on a computer vision project and need to implement a pooling kernel function for a Convolutional Neural Network (CNN). The function `PoolKernel` takes in an array of input feature maps `Pout` and outputs the pooled feature maps `Cout`. The parameters `fout`, `foutr`, and `foutc` represent the number of ... | ```cpp
void SW_CBIR::PoolKernel(float* Cout, float* Pout, int fout, int foutr, int foutc, int ksize, int kstride) {
for (int f = 0; f < fout; ++f) {
for (int r = 0; r < foutr; r += kstride) {
for (int c = 0; c < foutc; c += kstride) {
float max_val = std::numeric_limits<float>::l... | magicoder | cpp |
You are tasked with creating a Python script that fetches JSON data from a 4chan board and saves it to a file. The script should use the current date and time to create a unique filename and organize the data into monthly folders. The board name and URL are provided, and the script should handle the file path and filen... | ```python
import datetime as dt
import os
import requests
# Setup
#===============================================================================
board = 'pol'
url = "https://a.4cdn.org/" + board + "/catalog.json"
datetime = dt.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
dateMonth = dt.datetime.now().strftime("%Y-%... | magicoder | python |
You are tasked with implementing a simplified version of a virtual DOM rendering system in JavaScript. The virtual DOM system is responsible for efficiently updating the actual DOM based on changes to the application state.
You are provided with a code snippet that includes a `render` function and its usage. The `rend... | ```javascript
const registry = {
renderRoot: (root, state, events) => {
// Implement the logic to render the root element based on the state and events
// Return the newly rendered root element
}
};
const applyDiff = (parent, oldNode, newNode) => {
// Implement the logic to apply the differences between ... | magicoder | javascript |
You are tasked with creating a command-line tool for loading flashcard data into a study application. The flashcard data is stored in JSON files and is organized into categories, contexts, and terms. Your task is to implement the logic for loading the flashcard data from these JSON files and performing validation check... | ```python
import json
class FlashcardLoader:
def __init__(self):
self.categories = []
self.contexts = []
self.terms = []
def load_flashcards(self, file_path):
with open(file_path, 'r') as file:
data = json.load(file)
if 'categories' in data:
... | magicoder | python |
You are tasked with implementing a function that calculates the sum of all prime numbers within a given range. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The function should take two integers, `start` and `end`, as input and return the sum of all prime numbe... | ```rust
fn is_prime(n: u32) -> bool {
if n <= 1 {
return false;
}
for i in 2..=(n as f64).sqrt() as u32 {
if n % i == 0 {
return false;
}
}
true
}
fn sum_of_primes(start: u32, end: u32) -> u32 {
let mut sum = 0;
for num in start..=end {
if is_prim... | magicoder | rust |
You are tasked with creating a script to automate the process of downloading and extracting a file from a given URL. Your script should be able to handle various file types and provide feedback on the success or failure of the download and extraction process.
Write a Python function called `download_and_extract` that ... | ```python
import requests
import os
import shutil
import tarfile
import zipfile
def download_and_extract(url, destination):
try:
response = requests.get(url, stream=True)
if response.status_code == 200:
file_name = url.split('/')[-1]
file_path = os.path.join(destination, fil... | magicoder | python |
You are tasked with creating a Python function that reads and processes the content of multiple files. Your function should read the content of the files and concatenate them into a single string, excluding any empty lines. Additionally, the function should execute a Python script to retrieve specific information from ... | ```python
from typing import List
import os
def process_files(file_paths: List[str]) -> str:
concatenated_content = ''
for file_path in file_paths:
with open(file_path, 'r') as file:
content = file.read()
concatenated_content += content.strip() + '\n'
about_script_path = 'd... | magicoder | python |
You are tasked with creating a function that retrieves the content of a given URL using PHP. Your task is to implement the `getUrlContent` function, which takes a URL as input and returns the content of the URL. You should handle any potential errors or exceptions that may occur during the retrieval process.
Your func... | ```php
function getUrlContent($url) {
$ch = curl_init(); // Initialize cURL session
curl_setopt($ch, CURLOPT_URL, $url); // Set the URL to fetch
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the transfer as a string
$content = curl_exec($ch); // Execute the cURL session
if ($content === ... | magicoder | php |
You are tasked with implementing a simplified version of a function pointer comparison mechanism in C++. Given a class `updateThread` with a member function `sendInfo` and a function pointer `func`, you need to compare the function pointer with the address of the `sendInfo` member function and update the value pointed ... | ```cpp
void compareFunctionPointer(void* func, int* result) {
typedef void (updateThread::*_t)(std::string);
if (*reinterpret_cast<_t*>(func) == static_cast<_t>(&updateThread::sendInfo)) {
*result = 2;
}
}
```
The `compareFunctionPointer` function uses a typedef to define a function pointer type `_... | magicoder | cpp |
You are tasked with implementing a custom equality comparator for comparing two buffers of characters in a case-insensitive manner. The comparator should ignore the case of the characters when determining equality between the buffers. You are required to write a method that takes two buffers of characters as input and ... | ```java
public class CaseInsensitiveBufferEqualityComparator {
private CaseInsensitiveBufferEqualityComparator() {
}
public static boolean areBuffersEqual(char[] buffer1, char[] buffer2) {
if (buffer1.length != buffer2.length) {
return false;
}
for (int i = 0; i < buffer... | magicoder | java |
You are working on a project that involves a geographic information system (GIS) and need to implement a search functionality for NUTS3 regions based on their names and area sizes. The code snippet provided is a part of a method in a Django application that handles the search functionality. The method `get_search_resul... | ```python
from django.db.models import Q
class ArealFieldAdmin:
# Other methods and attributes
def get_search_results(self, request, queryset, search_term):
"""Add NUTS3 (by name) search and area size search (using `<>` operator)
"""
# Call the superclass method to get the initial sea... | magicoder | python |
You are tasked with creating a Python function that validates a username based on certain criteria and displays an appropriate message using a Windows message box if the username is invalid.
Write a Python function called `validate_username` that takes a single argument `username` (a string). The function should perfo... | ```python
import ctypes
def validate_username(username):
if len(username) < 5:
ctypes.windll.user32.MessageBoxW(0, 'Invalid username: Too short', 'Invalid username', 16)
elif len(username) > 15:
ctypes.windll.user32.MessageBoxW(0, 'Invalid username: Too long', 'Invalid username', 16)
else:
... | magicoder | python |
You are tasked with implementing a custom memory allocator for a specific data structure library. The library contains various allocator classes, and your goal is to compare the performance of these allocators with the standard `std::allocator`. The code snippet provided is a part of the testing framework for the memor... | ```cpp
#include <iostream>
#include <chrono>
#include <vector>
#include <memory>
// Define the GenericTestObject type for memory allocation
struct GenericTestObject {
// Define the properties of the test object
// ...
};
namespace DS {
// Define the custom memory allocator class AllocatorSimple
templa... | magicoder | cpp |
You are tasked with creating a Python function that increments the version number of a software project. The version number is represented as a string in the format "x.y.z", where x, y, and z are non-negative integers. The function should increment the version number based on the following rules:
- If the input version... | ```python
def increment_version(version):
x, y, z = map(int, version.split('.'))
if z < 9:
z += 1
elif z == 9:
z = 0
if y < 9:
y += 1
elif y == 9:
y = 0
x += 1
return f"{x}.{y}.{z}"
# Test cases
print(increment_version("1.2.3... | magicoder | python |
You are tasked with implementing a custom dataset class for measuring objects in images. The dataset class should be able to load and process images and their corresponding annotations for object measurements. The measurements could include dimensions, areas, or any other relevant metrics.
Your task is to create a Pyt... | ```python
import torch
from torch.utils.data import Dataset
from PIL import Image
import os
import json
class MeasureDataset(Dataset):
def __init__(self, data_dir, transform=None):
self.data_dir = data_dir
self.transform = transform
self.image_paths = [os.path.join(data_dir, img) for img in... | magicoder | python |
You are tasked with creating a Python function that generates a SQL script to add a new column to an existing PostgreSQL database table using SQLAlchemy and Alembic.
Your function should take the following parameters:
- `table_name`: A string representing the name of the existing table to which the new column will be ... | ```python
def generate_add_column_script(table_name, column_name, column_type):
import datetime
current_date_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
script = f"-- Generated SQL script\n"
script += f"-- Add column '{column_name}' to table '{table_name}'\n"
script += f"-- Generat... | magicoder | python |
You are tasked with implementing a function to parse and process configuration data for a monitoring system. The configuration data is provided in a JSON format and contains information about various monitoring targets and their associated checks.
The configuration data is structured as follows:
- The top-level object... | ```rust
use std::collections::HashMap;
use serde_json::{Value, Map};
fn process_configuration(config_data: &str) -> HashMap<String, (String, Vec<String>)> {
let mut result_map: HashMap<String, (String, Vec<String>)> = HashMap::new();
if let Ok(parsed_data) = serde_json::from_str::<Value>(config_data) {
... | magicoder | rust |
You are tasked with implementing a message caching system for a messaging application. The provided code snippet is a part of the message caching logic. The system is designed to cache message threads and their associated metadata. The `tLastActivityEM` model is used to represent the last activity in a message thread. ... | ```swift
class MessageCacheManager {
var cachedThreads: [String: ThreadMetadata] = [:] // Dictionary to store cached thread metadata
var enableCache: Bool = true // Flag to control caching behavior
weak var delegate: ThreadEventsDelegate? // Delegate to handle thread events
// Method to c... | magicoder | swift |
You are tasked with implementing a cache management system for a dictionary application. The application has a service class with methods for inserting dictionary details and removing dictionary details by their IDs. The methods are annotated with `@CacheEvict` and `@Transactional` to handle cache eviction and transact... | To implement the cache management system, you can use a caching framework such as Spring Cache, which provides support for declarative cache management. Below is a sample solution using Spring Cache annotations and configuration.
```java
import org.springframework.cache.annotation.CacheEvict;
import org.springframewor... | magicoder | java |
You are tasked with creating a program to optimize SQL queries by rewriting them to improve performance. Your program should take an input SQL query and output the optimized version of the query.
Your program should focus on optimizing the query by rearranging the conditions and clauses to minimize the number of opera... | To solve this problem, you can use a query optimization algorithm that rearranges the clauses and conditions to minimize the number of rows scanned and operations performed. One approach is to reorder the clauses and conditions based on their selectivity and index usage.
Here's a sample solution using a simple optimiz... | magicoder | sql |
You are tasked with creating a Python function that processes a list of kernel module names and returns a dictionary containing the frequency of each unique name. The kernel module names are provided in the form of a list, and the function should return a dictionary where the keys are the unique module names and the va... | ```python
from typing import List, Dict
def count_kernel_modules(module_names: List[str]) -> Dict[str, int]:
module_frequency = {}
for module in module_names:
if module in module_frequency:
module_frequency[module] += 1
else:
module_frequency[module] = 1
return modul... | magicoder | python |
You are tasked with implementing a function to calculate the total size of a grid-based layout for displaying images. The given code snippet provides the initial box size calculation and sets up an image canvas. Your task is to complete the function `csize(boxes, gridbuf, boxsize)` that takes in three parameters:
- `bo... | ```python
def csize(boxes, gridbuf, boxsize):
grid_width = (boxes * boxsize) + ((boxes - 1) * gridbuf) # Calculate the total width of the grid
rows = (boxes // grid) + (1 if boxes % grid != 0 else 0) # Calculate the number of rows in the grid
grid_height = (rows * boxsize) + ((rows - 1) * gridbuf) # Calc... | magicoder | python |
You are working on a data processing pipeline that involves handling a large dataset of resources. Each resource has a format associated with it, but some entries have missing format values (NaN). To address this issue, you need to implement a function that retrieves the missing format for resources from a URL. The cod... | ```python
import requests
from typing import List, Dict
def get_missing_format_from_url(url_list: List[str]) -> Dict[str, str]:
formats = {}
for url in url_list:
try:
response = requests.get(url)
if response.status_code == 200:
# Extract format from the response ... | magicoder | python |
You are tasked with implementing a Python class that manages tasks within a session. The class should have the ability to add, remove, and list tasks, as well as mark tasks as completed. Additionally, the class should be able to provide statistics about the tasks, such as the total number of tasks and the percentage of... | ```python
class TaskManager:
def __init__(self, session):
self.session = session
self.tasks = []
def add_task(self, task_name):
self.tasks.append(task_name)
def remove_task(self, task_name):
if task_name in self.tasks:
self.tasks.remove(task_name)
def list_... | magicoder | python |
You are tasked with creating a Python class that represents a geometric shape. The class should have methods to calculate the area and perimeter of the shape. Use the given code snippet as a starting point and create a class called `GeometricShape` that inherits from `AbstractIkologikObject`. The `GeometricShape` class... | ```python
from ikologikapi.domain.AbstractIkologikObject import AbstractIkologikObject
from abc import ABC, abstractmethod
class GeometricShape(AbstractIkologikObject, ABC):
@abstractmethod
def calculate_area(self):
pass
@abstractmethod
def calculate_perimeter(self):
pass
class Rectan... | magicoder | python |
You are tasked with implementing a data structure to efficiently compute polynomial evaluations at specified points. The data structure should support building a pre-computation table over the given points and then efficiently evaluating the polynomial at any new point using the pre-computed table.
You are given a cod... | ```rust
use std::ops::{Add, Mul};
/// A data structure to represent a polynomial with coefficients of type F.
#[derive(Debug, Clone)]
pub struct Polynomial<F>(pub Vec<F>);
impl<F: Clone + Default + Add<Output = F> + Mul<Output = F>> Polynomial<F> {
/// Construct the pre-computation table over the points.
pub ... | magicoder | rust |
You are tasked with creating a Python function that downloads a file from a given URL and saves it to a specified file path. Your function should utilize the `requests` library to download the file in chunks and display a progress bar using the `tqdm` library. The function should take three parameters: `url` (the URL o... | ```python
import requests
import tqdm
def download_file_with_progress(url: str, filepath: str, chunksize: int) -> None:
response = requests.get(url, stream=True)
total_size = int(response.headers.get('content-length', 0))
with open(filepath, "wb") as f:
for chunk in tqdm.tqdm(response.iter_content... | magicoder | python |
You are tasked with implementing a custom object dumper utility in Java. The utility should be able to generate a string representation of an object's state, including its fields and their values. You are provided with a partial code snippet for the `ObjectDumper` class, which includes a method `dumpObject` that takes ... | ```java
import java.lang.reflect.Array;
import java.util.*;
public class ObjectDumper {
private StringBuilder builder;
public ObjectDumper(StringBuilder builder) {
this.builder = builder;
}
public void appendObject(Object object, DumpMode dumpMode) {
if (dumpMode == DumpMode.DEEP) {
... | magicoder | java |
You are tasked with implementing a custom React hook that manages the state of farm balances in a decentralized finance (DeFi) application. The hook should provide functions to fetch and update balances, as well as access to the current balances and loading state.
You are given the following TypeScript interface and a... | ```typescript
import { useState, useEffect } from 'react';
function useBalances(): FarmAllProps {
const [balances, setBalances] = useState<BalanceState>({ /* initial state */ });
const [loading, setLoading] = useState(true);
const [farms, setFarms] = useState<FarmConfig[]>([]);
const balanceDispatch =... | magicoder | typescript |
You are tasked with creating a Django web application that includes both a frontend and an API for managing leads. The code snippet provided is a part of the Django application's URL configuration. The `urlpatterns` list contains two path configurations using the `include` function to include URLs from other apps. The ... | ```python
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls), # Admin panel
path('', include('frontend.urls')), # Home page react
path('api/', include('leads.urls')), # Leads page API
path('accounts/', include('accounts.urls')), # ... | magicoder | python |
You are working on a data analysis project and need to manipulate and analyze a dataset containing information about connectors. The dataset is stored in a CSV file named "connectors.csv" and is located in the "maggot_models/data/processed/2020-05-08" directory. You need to load this dataset into a pandas DataFrame and... | ```python
import pandas as pd
def analyze_connectors(connector_path: str) -> dict:
# Load the "connectors.csv" file into a pandas DataFrame
connectors = pd.read_csv(connector_path)
# Calculate the total number of connectors in the dataset
total_connectors = len(connectors)
# Identify the unique t... | magicoder | python |
You are tasked with creating a Python script that processes a list of integers and performs a specific operation on them. However, the script requires the bitarray module to be installed. If the module is not installed, the script should display an error message and exit with a status code of -1. Your task is to write ... | ```python
import sys
try:
import bitarray
except ImportError:
print("Please install the bitarray module from pypi")
print("e.g. sudo pip install bitarray")
sys.exit(-1)
# If the bitarray module is successfully imported, continue with the script
# Process the list of integers using the bitarray module
... | magicoder | python |
You are tasked with implementing a function that processes a batch of data, which may contain elements of different types. The function should detach any PyTorch tensors in the batch and convert them to NumPy arrays, while leaving other elements unchanged. If the input batch contains elements of an unsupported type, th... | ```python
import torch
import numpy as np
def process_batch(batch):
processed_batch = []
for item in batch:
if isinstance(item, torch.Tensor):
processed_batch.append(item.detach().cpu().numpy())
else:
processed_batch.append(item)
return processed_batch
```
The provid... | magicoder | python |
You are tasked with implementing a Python class for visualizing the outputs of a model. The class should provide a method for generating a quick plot of a subset of key outputs of the model, allowing for easy assessment. Additionally, the class should support setting axis limits for the plot and resetting them to defau... | ```python
import matplotlib.pyplot as plt
class ModelVisualizer:
def __init__(self):
self.axis = {}
def plot_outputs(self, outputs):
for variable, values in outputs.items():
plt.plot(values, label=variable)
plt.legend()
plt.show()
def set_axis(self, variable_na... | magicoder | python |
You are tasked with creating a Python function that processes a list of files and attempts to delete each file. If a file is successfully deleted, the function should print "File deleted". If the file does not exist, it should print "Could not delete file: [filename]. File does not exist". If an error occurs during the... | ```python
from typing import List
import os
def delete_files(file_list: List[str]) -> None:
for file in file_list:
try:
os.remove(file)
print("File deleted")
except FileNotFoundError:
print(f"Could not delete file: {file}. File does not exist")
except Per... | magicoder | python |
You are working on a data processing system that involves querying a remote database and saving the results to a local file. The code snippet provided is a part of a Python class method that handles the retrieval and storage of query results. The method uses the pandas library to read HTML tables from the query respons... | ```python
import pandas as pd
import os
import logging
def process_query_response(query_info, out_dir):
dfs = pd.read_html(query_info)
status = dfs[1]
position_in_queue = status['Position in Queue']
if any(position_in_queue != 'Query complete'):
logging.info("{}Query incomplete.".format(' ... | magicoder | python |
You are tasked with implementing a custom Swift protocol for managing the area affect directions and view for side buttons in a user interface. The provided code snippet includes an extension for the UIView class, which defines two computed properties. The `sideButtonsAreaAffectDirections` property returns an instance ... | ```swift
// Define the MWMAvailableAreaAffectDirections protocol
protocol MWMAvailableAreaAffectDirections {
var availableDirections: [String] { get }
func isDirectionAvailable(_ direction: String) -> Bool
}
// Implement the protocol for a hypothetical map view
class MapView: UIView, MWMAvailableAreaAffectDire... | magicoder | swift |
You are tasked with creating a validation function for a social media authentication service. The function will receive a request and query parameters, and it should validate the parameters based on specific conditions. Your task is to implement the validation function according to the given requirements.
The validati... | ```csharp
public class SocialMediaValidator
{
public HttpResponseMessage ValidateRequest(HttpRequestMessage request, Dictionary<string, string> queryParameters)
{
HttpResponseMessage response = new HttpResponseMessage();
if (request.RequestUri.AbsoluteUri.StartsWith("https://www.facebook.com/di... | magicoder | csharp |
You are tasked with implementing a custom learning rate schedule function for a machine learning model. The function should take in several parameters and return a learning rate schedule based on these parameters. The learning rate schedule should follow a specific formula to adjust the learning rate over time during t... | ```python
import math
def custom_learning_rate_schedule(
global_step,
initial_lr=0.1,
decay_rate=0.1,
decay_steps=1000,
warmup_steps=200,
power=1.0,
min_lr=1e-5):
"""Creates a custom learning rate schedule.
Args:
global_step (int): The current tr... | magicoder | python |
You are given a list of integers representing a sequence of numbers. Your task is to write a function to find the longest increasing subsequence (LIS) within the sequence. The LIS is the longest subsequence of the given sequence such that all elements of the subsequence are sorted in increasing order.
For example, giv... | ```python
def longest_increasing_subsequence(sequence):
if not sequence:
return 0
n = len(sequence)
lis = [1] * n
for i in range(1, n):
for j in range(0, i):
if sequence[i] > sequence[j] and lis[i] < lis[j] + 1:
lis[i] = lis[j] + 1
return max(lis)
``` | magicoder | python |
You are tasked with creating a program that analyzes a given CSS file and identifies the number of unique CSS properties used within it. A CSS property is considered unique if it appears with a different value or in a different context within the file. Your program should ignore any comments and only consider propertie... | ```python
import re
def countUniqueCSSProperties(css):
properties = set()
css_rules = re.findall(r'(?<=\{)(.*?)(?=\})', css, re.DOTALL)
for rule in css_rules:
property_value_pairs = re.findall(r'(\w+-?\w*):[^;]+;', rule)
for pair in property_value_pairs:
properties.add(pair.stri... | magicoder | python |
You are tasked with creating a web application that allows users to schedule tasks for future execution. The application uses the Mediator pattern to handle commands and queries. The code snippet provided is a part of the ASP.NET MVC application that handles scheduling tasks for future execution.
Your task is to imple... | ```csharp
// ScheduleController.cs
using MediatR;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
public class ScheduleController : Controller
{
private readonly IMediator _mediator;
public ScheduleController(IMediator mediator)
{
_mediator = mediator;
}
// GE... | magicoder | csharp |
You are tasked with implementing a function that processes a dataset to identify and count the occurrences of a specific pattern within it.
You are given a dataset in the form of a 2D array, where each element is a signed byte. The dataset is represented as a numpy array. Your task is to implement a function `count_pa... | ```python
import numpy as np
def count_pattern_occurrences(dataset: np.array, pattern: np.array) -> int:
dataset_height, dataset_width = dataset.shape
pattern_height, pattern_width = pattern.shape
count = 0
for i in range(dataset_height - pattern_height + 1):
for j in range(dataset_width - pat... | magicoder | python |
You are tasked with implementing a simplified blockchain data structure in Rust. A blockchain is a decentralized, distributed ledger that records transactions across many computers in such a way that the recorded transactions cannot be altered retroactively. Each block in the blockchain contains a cryptographic hash of... | ```rust
struct Transaction {
sender: String,
receiver: String,
}
impl Transaction {
fn new(sender: &str, receiver: &str) -> Transaction {
Transaction {
sender: sender.to_string(),
receiver: receiver.to_string(),
}
}
}
struct Block {
// Define the fields of t... | magicoder | rust |
You are tasked with creating a script to analyze the output of a log file from a Ceph installation workflow and perform specific actions based on the results. The log file contains information about the success or failure of various tasks related to the installation process. The script needs to identify any hosts that ... | ```bash
#!/bin/bash
# Read the log file and extract the relevant information
failed_hosts=$(sudo tail /var/log/mistral/ceph-install-workflow.log | grep "PLAY RECAP" -A 100 | grep -v "PLAY RECAP" | grep -v failed=0 | awk {'print $6'} | uniq)
# Check if there were failures in the last Ceph-ansible run
if [ -n "$failed_... | magicoder | shell |
You are tasked with implementing a Python package for simple lazy regular expressions and string expressions manipulation. The package, named "slrp," provides modules for handling combinations, lazy evaluation, regular expressions, and string expressions. The code snippet provided initializes the package and imports ne... | ```python
# slrp/expressions.py
from slrp.combos import Lazy
# Abbreviations
L = Lazy
RE = RegExpr
S = StringExpr
class ExpressionBuilder:
def __init__(self):
self.expression = None
def add_reg_expr(self, pattern):
if self.expression is None:
self.expression = RE(pattern)
... | magicoder | python |
You are tasked with implementing a simplified version of a completion handler for an asynchronous operation using C++ and Boost.Asio library. The completion handler is responsible for managing the completion of an asynchronous operation and invoking the appropriate callback function.
Your task is to complete the imple... | ```cpp
template <typename... Args>
void complete(Args&&... args)
{
if (state_ == starting)
{
state_ = completed;
std::apply(callback_, std::forward_as_tuple(std::forward<Args>(args)...));
state_ = starting;
}
}
```
In the `complete` method, we first check if the state is `starting`. If it is, we tran... | magicoder | cpp |
You are tasked with writing a script to parse and manipulate file paths based on the given code snippet. The script should handle the extraction of specific directory paths and the manipulation of file paths using the provided variables and commands.
Given the code snippet:
```
echo "main_workdir: ${main_w... | ```bash
#!/bin/bash
# Extract the value of the variable main_workdir
main_workdir=$(echo "${main_workdir}" | sed 's/.*: //')
# Parse the file paths provided in the comment and extract the directory paths
comment_path="./ansible/inventories/0z-cloud/products/types/\\!_bare/vortex/beta/"
relative_path="../vortex/123"
... | magicoder | shell |
You are given a snippet of code that represents a simplified version of a function in a programming language. The function takes a string as input and returns an optional value. If the input string is not empty, the function returns a `Some` containing the input string; otherwise, it returns `None`.
Your task is to im... | ```rust
fn process_strings(input: Vec<&str>) -> Vec<Option<&str>> {
input.iter().map(|&s| if s.is_empty() { None } else { Some(s) }).collect()
}
fn main() {
let input = vec!["hello", "", "world", ""];
let output = process_strings(input);
println!("{:?}", output); // Output: [Some("hello"), None, Some("... | magicoder | rust |
You are tasked with creating a Python function that interacts with a web application testing framework. The function is responsible for testing the deletion of the first group in the application. The function should log in as an admin user, delete the first group, and then log out. The `<PASSWORD>` placeholder in the c... | ```python
def delete_first_group(self):
# Assuming app.group.get_groups() returns a list of groups
groups = self.get_groups()
if groups:
group_id = groups[0].id # Assuming each group has an 'id' attribute
self.delete_group_by_id(group_id)
else:
raise Exception("No groups found t... | magicoder | python |
You are tasked with creating a program that simulates a simple game of "resolved nonflashed." In this game, players take turns marking numbers from 1 to N, where N is a given positive integer. The game starts with an empty list of marked numbers. On each turn, a player can mark a number that has not been marked before,... | ```python
def resolved_nonflashed_winner(N, moves):
marked_numbers = set()
player_moves = {"A": [], "B": []}
for move in moves:
player, number = move.split()
number = int(number)
if number in marked_numbers:
player_moves[player].remove(number)
marked... | magicoder | python |
You are tasked with creating a script to automate the deployment and execution of a DICOM (Digital Imaging and Communications in Medicine) DIMSE (DICOM Message Service Element) proxy server. The DICOM DIMSE proxy server is a critical component in medical imaging systems, facilitating the communication between different... | ```bash
#!/bin/bash
# Set the shell option to export all defined variables
set -o allexport
# Source the environment variables from the file dicom-dimse-proxy.env
source ./dicom-dimse-proxy.env
# Disable the allexport option to prevent unintended variable exports
set +o allexport
# Print a message indicating the st... | magicoder | shell |
You are tasked with implementing a custom kernel function for Gaussian process regression. In Gaussian process regression, the choice of kernel function significantly impacts the model's performance. Your task is to create a custom kernel function that combines the properties of the Matern32 and Matern52 kernels. The M... | ```python
import numpy as np
def custom_kernel(x, x_prime, l=1.0, sigma=1.0):
# Calculate the Euclidean distance
r = np.linalg.norm(x - x_prime)
# Define the Matern32 and Matern52 kernel functions
matern32 = (1 + np.sqrt(3)*r)*np.exp(-np.sqrt(3)*r)
matern52 = (1 + np.sqrt(5)*r + 5/3*r**2)*np.exp(-... | magicoder | python |
You are tasked with creating a Python function that utilizes the `bifacial_radiance` library to perform a solar panel analysis. The `bifacial_radiance` library is used for simulating and analyzing the performance of bifacial solar panels. Your function should take in the necessary parameters and return the total annual... | ```python
def calculate_annual_energy_yield(scene_file: str, module_file: str, tracking_type: str, tilt: float, azimuth: float) -> float:
from bifacial_radiance.main import AnalysisObj, GroundObj, MetObj, RadianceObj, SceneObj
from bifacial_radiance.module import ModuleObj
from bifacial_radiance import mode... | magicoder | python |
You are given a list of solutions, each containing a sequence of items with associated weights. Your task is to find the solution with the smallest total weight and return the sequence of items in that solution.
Write a function `find_smallest_path(result: List[List[Item]]) -> List[Item]` that takes in a list of solut... | ```python
class Item:
def __init__(self, name, weight):
self.name = name
self.weight = weight
def find_smallest_path(result):
smallest_val = float('inf')
path = []
for solution in result:
total_cost = sum(map(lambda x: x.weight, solution))
if smallest_val > total_cost:
... | magicoder | python |
You are tasked with creating a Python class that processes data from a form using the `Form7Parsing` module. The `Form7Parsing` module provides a class with a method for parsing form data. Your task is to create a new class that inherits from the `Form7Parsing` class and adds additional functionality to process the par... | ```python
from .parse_form7 import Form7Parsing
class ExtendedFormParser(Form7Parsing):
def validate_data(self):
# Add validation logic here
pass
def process_data(self):
# Add data processing logic here
pass
```
In the solution, we create a new class `ExtendedFormParser` that i... | magicoder | python |
You are tasked with creating a program that extracts the license information from a given code snippet. The license information is embedded within comment blocks and may vary in format. Your program should be able to identify and extract the license text from the code snippet.
Create a function `extract_license` that ... | ```python
import re
def extract_license(code):
# Define regular expression patterns to match comment blocks
comment_patterns = [
r'#.*', # Matches single-line comments starting with '#'
r'"""(.*?)"""', # Matches multi-line comments enclosed in triple double quotes
r"'''(.*?)'''" # Ma... | magicoder | python |
You are working on a deep learning project and are tasked with implementing a residual block for a convolutional neural network (CNN). The residual block consists of two main components: a main path and a shortcut path. The main path contains a series of operations, including a convolutional layer followed by batch nor... | ```python
from keras.layers import Input, Conv2D, BatchNormalization
from keras.regularizers import l2
from keras.models import Model
# Define input tensors for main and shortcut paths
input_main = Input(shape=(height, width, channels))
input_skip = Input(shape=(height, width, channels))
# Main Path
x = BatchNormaliz... | magicoder | python |
You are tasked with creating a Python class for a weapon in a role-playing game. The class should have the following attributes and methods:
Attributes:
- `weight`: an integer representing the weight of the weapon in pounds.
- `damage_die`: a string representing the damage die of the weapon (e.g., "1d8", "2d6", etc.).... | ```python
class Weapon:
def __init__(self, weight, damage_die, reach):
self.weight = weight
self.damage_die = damage_die
self.reach = reach
def get_info(self):
return f"Weight: {self.weight} lbs, Damage Die: {self.damage_die}, Reach: {self.reach} ft"
# Example usage
sword = Wea... | magicoder | python |
You are tasked with implementing a class that manages HTTP response headers in a graphical user interface. The provided code snippet is a part of the implementation for displaying response headers in a table format using Qt framework. Your task is to complete the implementation of the `TabResponseHeaders` class by addi... | ```cpp
void TabResponseHeaders::populateHeaders(const QMap<QString, QString>& responseHeaders)
{
// Clear any existing data in the table
headersTable->clearContents();
headersTable->setRowCount(responseHeaders.size());
int row = 0;
for (auto it = responseHeaders.constBegin(); it != responseHeaders.... | magicoder | cpp |
You are tasked with implementing a Python function that takes a dictionary and returns a new dictionary with the same keys but with the values replaced by their corresponding types. You should also handle nested dictionaries and lists within the input dictionary and return the types of their elements as well.
The func... | ```python
def type_mapper(input_dict: dict) -> dict:
result = {}
for key, value in input_dict.items():
if isinstance(value, dict):
result[key] = type_mapper(value)
elif isinstance(value, list):
result[key] = [type(item) for item in value]
else:
result[... | magicoder | python |
You are tasked with creating a Python function that simulates a file synchronization process and verifies the successful transfer of a file to a server. The function should wait for a specified duration, check for the existence of a specific file in a designated folder, and compare its content with expected data. Addit... | ```python
import os
import time
def verify_file_synchronization(user_id, expected_content):
time.sleep(5) # wait till synchronization finished
expected_path = os.path.join(server_paths.get_users_root_folder(user_id), "folder1/dummy.txt")
if not os.path.exists(expected_path):
raise AssertionError(... | magicoder | python |
You are tasked with creating a student exam access control system for an online education platform. The system should allow students to access exams only if they are enrolled in the corresponding course and have a valid student exam record. The following code snippet is a part of the implementation for this system:
``... | ```java
public class StudentExamAccessService {
// Other methods and dependencies
public Optional<ResponseEntity<Void>> checkStudentExamAccess(Long courseId, Long examId, Long studentExamId) {
// Check if the student is enrolled in the course
if (!isEnrolled(courseId, studentExamId)) {
... | magicoder | java |
You are tasked with implementing a class for handling video data processing. The class, named `VideoProcessor`, is responsible for managing various attributes and methods related to video processing. Your task is to implement the `VideoProcessor` class with the following specifications:
Attributes:
- `is_static`: A bo... | ```python
import pandas as pd
class VideoProcessor:
def __init__(self, quality_df):
self.is_static = None
self.duration = self.get_duration()
self.num_frames = quality_df.shape[0]
def get_duration(self):
# Placeholder for duration calculation logic
# Replace this with a... | magicoder | python |
You are tasked with implementing a dynamic programming solution to calculate the nth Fibonacci number. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. The function `fib_dp(n)` should take an integer `n` as input and return the nth F... | ```python
def fib_dp(n):
if n <= 1:
return n
fib = [0] * (n + 1)
fib[1] = 1
for i in range(2, n + 1):
fib[i] = fib[i - 1] + fib[i - 2]
return fib[n]
```
The `fib_dp` function first handles the base cases where `n` is 0 or 1. Then, it initializes a list `fib` to store the Fibonacci nu... | magicoder | python |
You are tasked with implementing a custom `ndpointer` class in Python that mimics the behavior of the `numpy.ctypeslib.ndpointer` class. The `ndpointer` class is used to define the data type and shape of arrays when passing data between Python and C/C++ code.
Your task is to create a custom `ndpointer` class with the ... | ```python
import numpy
class ndpointer:
def __init__(self, *args, **kwargs):
self.base = numpy.ctypeslib.ndpointer(*args, **kwargs)
@classmethod
def from_param(cls, obj):
if obj is None:
# Create a new instance of the class with default arguments
return cls()
... | magicoder | python |
You are tasked with creating a custom user model in a Django application. The code snippet provided is a part of the custom user model implementation. The `_create_user` method is responsible for creating a new user with the given username, email, and password. Additionally, it allows for extra fields to be passed as k... | ```python
from django.contrib.auth.models import BaseUserManager
class CustomUserManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, username, email, password, **extra_fields):
if not username:
raise ValueError('The username must be set')
email = self.normaliz... | magicoder | python |
You are tasked with implementing a function that takes a list of strings as input and returns a new list containing only the strings that have a length greater than 5 and start with the letter "O". If no strings meet these criteria, the function should return an empty list.
Write a function `filter_strings` that takes... | ```python
from typing import List
def filter_strings(input_list: List[str]) -> List[str]:
return [s for s in input_list if len(s) > 5 and s.startswith("O")]
``` | magicoder | python |
You are tasked with creating a program that analyzes the code comments in a given source file and extracts specific information from them. The comments are formatted in a specific way, and the program needs to parse these comments to extract the creation date, author, and copyright information.
The comments are format... | ```python
import re
def extractCodeInfo(file_path):
with open(file_path, 'r') as file:
content = file.read()
match = re.search(r'//\s*Created by\s+(.*?)\s+on\s+(\d{2}/\d{2}/\d{4}).*All code \(c\) (\d{4}) - present day, (.+?)\.', content)
if match:
author = match.group(1)
... | magicoder | python |
You are tasked with creating a class to manage player-portal mappings in a game. The class should allow for adding, removing, and retrieving player-portal mappings. Additionally, it should provide a method to retrieve all portals associated with a specific player.
You need to implement the `PlayerPortalManager` class ... | ```typescript
class PlayerPortalManager {
private playerPortalMap: Map<string, Set<string>>;
constructor() {
this.playerPortalMap = new Map();
}
addMapping(playerId: string, portalId: string): void {
if (!this.playerPortalMap.has(playerId)) {
this.playerPortalMap.set(playerId, new Set());
}
... | magicoder | typescript |
You are tasked with implementing a function to process a dictionary and extract an integer value associated with a specific key. The function should handle the case where the key is not present in the dictionary by returning a default value.
You are given a code snippet that demonstrates the usage of a hypothetical `D... | ```cpp
#include <iostream>
#include <string>
#include <optional>
class Dictionary {
public:
std::optional<int> FindInt(const std::string& key) const {
// Implementation of FindInt method
// Assume it returns the optional integer value associated with the key
// or an empty optional if the k... | magicoder | cpp |
You are tasked with creating a RESTful resource for managing a security master in a financial application. The security master is responsible for storing and managing information about various securities, such as stocks, bonds, and derivatives. Your goal is to implement a method that processes a specific type of RESTfu... | ```java
@Path("securityMaster")
public class DataSecurityMasterResource extends AbstractDataResource {
private final SecurityMaster _secMaster;
// Constructor to initialize the SecurityMaster instance
public DataSecurityMasterResource(SecurityMaster secMaster) {
this._secMaster = secMaster;
}
/**
* ... | magicoder | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.