query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a function that takes a string as input and modifies it based on a specific set of rules. The function should modify the input string by replacing all occurrences of certain characters with their corresponding replacements, and then return the modified string. The replacement rules are ... | ```rust
fn modify_string(input: &str, separators: &[char], alphabet: &[char]) -> String {
let mut modified_string = String::new();
for c in input.chars() {
if separators.contains(&c) {
modified_string.push(c);
} else if let Some(index) = alphabet.iter().position(|&x| x == c) {
... | magicoder | rust |
You are tasked with creating a Python class that manages API session accesses for a web application. The class should handle the creation, retrieval, and deletion of API sessions, and it should maintain a record of these accesses. Your task is to implement the `APISessionManager` class with the following requirements:
... | ```python
import time
class SessionExistsError(Exception):
pass
class SessionNotFoundError(Exception):
pass
class APISessionManager:
def __init__(self):
self.sessions = []
def create_session(self, session_id, user_id):
for session in self.sessions:
if session['session_id'... | magicoder | python |
You are tasked with creating a Python function that generates and executes a SQL query based on given input parameters. The function should construct a SELECT query with optional WHERE clause and return the result set from the database.
You are provided with a code snippet that partially implements the functionality. ... | ```python
def execute_select_query(s_from, where, vals):
"""
Construct and execute a SELECT query based on input parameters.
Args:
s_from (list): A list of table names to select from.
where (dict): A dictionary representing the WHERE clause conditions.
vals (list): A list of values to be used i... | magicoder | python |
You are tasked with implementing a function that performs genesis initialization for a module in a blockchain application. The function should take in the context of the blockchain, a JSON marshaler, and raw message data, and return a list of validator updates. The provided code snippet contains a commented-out impleme... | ```go
// InitGenesis performs genesis initialization for the genutil module. It returns
// no validator updates.
func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data json.RawMessage) []abci.ValidatorUpdate {
var genesisState types.GenesisState
cdc.MustUnmarshalJSON(data, &genesisState)... | magicoder | go |
You are given a list of operations to be performed on a stack. The operations are represented as strings in the following format:
- "PUSH X": Push the integer X onto the stack.
- "POP": Pop the top element from the stack.
- "INC Y Z": Increment the bottom Y elements of the stack by Z.
Your task is to simulate these op... | ```python
def final_stack_state(operations):
stack = []
for op in operations:
if op.startswith("PUSH"):
_, num = op.split()
stack.append(int(num))
elif op == "POP":
stack.pop()
elif op.startswith("INC"):
_, y, z = op.split()
y, ... | magicoder | python |
You are given an array of integers `nums` of length `n`. Your task is to write a function that finds the two numbers in the array that have the maximum absolute difference. The function should return the absolute difference and the two numbers themselves.
Write a function `maxAbsoluteDifference` that takes in an array... | ```javascript
function maxAbsoluteDifference(nums) {
let maxDiff = 0;
let result = { difference: 0, numbers: [] };
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
let diff = Math.abs(nums[i] - nums[j]);
if (diff > maxDiff) {
maxDiff = diff;
resu... | magicoder | javascript |
You are tasked with creating a program that processes text content to identify and extract specific patterns using regular expressions. Your program should be able to identify and extract various types of text patterns, such as block quotes, code spans, and mathematical expressions, based on the provided regular expres... | ```python
import re
def extract_text_patterns(text):
reTextileQuot = re.compile(r'^bq\.\s.+')
reMkdCodeSpans = re.compile('`[^`]*`')
reMkdMathSpans = re.compile(r'\\[\(\[].*?\\[\)\]]')
block_quotes = reTextileQuot.findall(text)
code_spans = reMkdCodeSpans.findall(text)
math_expressions = ... | magicoder | python |
You are tasked with creating a Python class for normalizing audio and video files using FFmpeg. Your class should provide a simple interface for users to normalize media files to a specified audio level.
Create a class called `FFmpegNormalizer` with the following specifications:
- The class should have a constructor t... | ```python
import subprocess
class FFmpegNormalizer:
def __init__(self, input_file, output_file, target_level):
self.input_file = input_file
self.output_file = output_file
self.target_level = target_level
def normalize(self):
command = f'ffmpeg -i {self.input_file} -af "volume=v... | magicoder | python |
You are tasked with creating a program that extracts URLs from an HTML file and returns them as a list of strings. The HTML file contains a list of anchor tags (`<a>`) with `href` attributes representing the URLs. Your program should parse the HTML file and extract all the URLs present in the anchor tags.
For example,... | ```python
from bs4 import BeautifulSoup
from typing import List
def extract_urls(html_file: str) -> List[str]:
urls = []
soup = BeautifulSoup(html_file, 'html.parser')
for a_tag in soup.find_all('a'):
href = a_tag.get('href')
if href:
urls.append(href)
return urls
```
The s... | magicoder | python |
You are tasked with implementing a custom data structure called `DayOf` in Swift. The `DayOf` data structure represents a day of the week and contains two values of type `A`. Your task is to define the `DayOf` type and implement two functions: `extract` and `coflatMap`.
The `DayOf` type has the following definition:
`... | ```swift
struct DayOf<F, G, A> {
let value: A
func extract() -> (A, A) {
return (value, value)
}
func coflatMap<B>(_ transform: (DayOf<F, G, A>) -> B) -> B {
return transform(self)
}
}
```
In the solution, the `DayOf` type is defined as a struct with a single property `val... | magicoder | swift |
You are tasked with creating a Python function that performs a specific file operation based on certain conditions. The function should take in three parameters: `version` (string), `task` (object), and `langs_path` (string). The `task` object has an attribute `app` which contains a property `jam_version`. The function... | ```python
import os
from shutil import copyfile
def update_langs_file(version, task, langs_path):
if version != task.app.jam_version or not os.path.exists(langs_path):
# Copy the file langs.sqlite from the directory of the jam module to langs_path
copyfile(os.path.join(os.path.dirname(jam.__file__)... | magicoder | python |
You are tasked with creating a Python function that compares two files and asserts whether a specific portion of one file matches the content of another file. Your task is to implement the function that performs this comparison and raises an assertion error if the content does not match.
You are given the following co... | ```python
def file_comparison(file1_path: str, file2_path: str) -> bool:
with open(file1_path, 'rb') as file1:
content1 = file1.read().replace(b'\r\n', b'\n')
with open(file2_path, 'rb') as file2:
content2 = file2.read(6351)[28:]
assert content2 == content1, "File content does not match"
... | magicoder | python |
You are tasked with implementing a simplified version of a performance monitoring system. The system should track the duration of various operations and provide summary statistics for different categories of operations.
You are given a code snippet from a Java method that is part of the performance monitoring system. ... | ```java
import java.util.HashMap;
import java.util.Map;
public class PerformanceMonitor {
private Map<String, SummaryStatistics> categoryStatistics;
public PerformanceMonitor() {
categoryStatistics = new HashMap<>();
}
public void observe(long duration) {
updateOverallStatistics(durat... | magicoder | java |
You are tasked with implementing a media file metadata parser that extracts and populates metadata information from audio and video files. The provided code snippet is a part of a larger media file parsing library. The `Fill` function is used to populate metadata fields such as audio codec, codec settings, encoded libr... | ```cpp
#include <iostream>
#include <string>
#include <cstdint>
// Define the supported audio codecs and their corresponding settings
enum AudioCodec {
AAC,
MP3,
Musepack
};
// Define the supported encoded libraries
enum EncodedLibrary {
LAME,
FFMPEG,
MusepackEncoder
};
// Define the sample f... | magicoder | cpp |
You are tasked with implementing a function that mimics the behavior of the `export default` statement in JavaScript. The `export default` statement is used to export a single default export from a module. When another module imports the default export from the original module, it can choose to import it under any name... | ```javascript
function createDefaultExport(input) {
return {
default: input,
import: function (name) {
const importedObject = {};
importedObject[name] = this.default;
return importedObject;
}
};
}
// Test the solution
const defaultExport = createDefaultExport(42);
const importedValue ... | magicoder | javascript |
You are tasked with creating a Minecraft mod that utilizes the Forge modding framework. Your mod needs to listen for a specific event and perform a custom action when that event occurs. The event you are interested in is the opening of a GUI (Graphical User Interface) within the game. You want to register a listener fo... | ```java
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import net.minecraftforge.client... | magicoder | java |
You are given a text file containing a series of comments in the form of Python multi-line comments. Each comment starts with a '#' symbol and may span multiple lines. Your task is to write a program that counts the total number of comments in the file and the average number of lines per comment.
Write a function `cou... | ```python
from typing import Tuple
def count_comments_and_average_lines(filename: str) -> Tuple[int, float]:
with open(filename, 'r') as file:
lines = file.readlines()
comment_count = 0
total_lines = 0
comment_lines = 0
in_comment = False
for line in lines:
line = line.str... | magicoder | python |
You are tasked with implementing a task management system for a web application. The system should allow users to create, view, and manage tasks within different folders. Each task can be marked as complete or incomplete, and users should be able to remove tasks from the system.
You are given a code snippet from the f... | ```javascript
// Sample data structure for tasks and folders
const folders = [
{ id: 1, name: 'Work' },
{ id: 2, name: 'Personal' }
];
const tasks = [
{ id: 1, folderId: 1, description: 'Complete project report', isComplete: false },
{ id: 2, folderId: 1, description: 'Prepare presentation slides', isComplete:... | magicoder | javascript |
You are tasked with creating a program that simulates the behavior of the `rsync` command for synchronizing files and directories between two locations. The `rsync` command is a widely used utility for efficiently transferring and synchronizing files across systems. Your program should handle the synchronization of fil... | ```python
import os
import shutil
import fnmatch
def rsync(source_dir, destination_dir, exclude_patterns=None):
if not os.path.exists(destination_dir):
os.makedirs(destination_dir)
for root, dirs, files in os.walk(source_dir):
relative_path = os.path.relpath(root, source_dir)
destinati... | magicoder | python |
You are tasked with creating a user authentication system using PHP. Your goal is to implement a function that verifies a user's credentials and sets a session if the user is active and the password is correct.
You are given the following code snippet as a starting point:
```php
if ($user['active'] == 1) {
// CEK... | ```php
function authenticateUser($username, $password) {
// Assume $db is the database connection object
// Retrieve user data from the database
$query = "SELECT * FROM users WHERE username = :username";
$stmt = $db->prepare($query);
$stmt->execute(['username' => $username]);
$user = $stmt->fet... | magicoder | php |
You are tasked with creating a form validation function for a web application. The function should validate the input fields based on the provided rules and return an array of error messages for any invalid fields.
You are given a code snippet representing an input field in the form. The input field has the following ... | ```php
function validateFormInput($input, $rules) {
$errors = [];
foreach ($rules as $field => $rule) {
$rulesArray = explode('|', $rule);
foreach ($rulesArray as $singleRule) {
if ($singleRule === 'required' && empty($input[$field])) {
$errors[$field][] = "The $fiel... | magicoder | php |
You are tasked with implementing a customer management system for a retail company. One of the requirements is to generate a unique customer ID for each new customer. The customer ID should be a combination of the customer's initials and a sequential number. The initials are derived from the customer's first and last n... | ```java
public class CustomerManager {
private Map<String, Integer> customerCountMap = new HashMap<>();
public String getCustomerId(String firstName, String lastName) {
String initials = (firstName.substring(0, 1) + lastName.substring(0, 1)).toUpperCase();
int count = customerCountMap.getOrDefa... | magicoder | java |
You are tasked with implementing a class that manages file operations for a Visual Studio solution. The class should provide functionality for working with solution files, project file references, and stringly-typed paths. Your task is to complete the implementation of the class by adding the necessary methods to perfo... | ```csharp
public class SolutionFileOperator : IHasSolutionContext
{
public IStringlyTypedPathOperator StringlyTypedPathOperator { get; set; }
public IVisualStudioProjectFileReferencesProvider VisualStudioProjectFileReferencesProvider { get; set; }
public IVisualStudioSolutionFileOperator VisualStudioSolutio... | magicoder | csharp |
You are given a string representing a sequence of instructions. Each instruction is either "(" or ")". The instructions are meant to represent movements in a building. Each "(" instruction means going up one floor, and each ")" instruction means going down one floor. The building has an infinite number of floors, and t... | ```python
def find_basement_position(puzzle_input: str) -> int:
FLOOR = 0
for (index, character) in enumerate(puzzle_input, start=1):
if character == "(":
FLOOR += 1
elif character == ")":
FLOOR -= 1
if FLOOR == -1:
return index
return -1
`... | magicoder | python |
You are working on a graphics application that involves handling color values and layout parameters. Your task is to create a function that calculates the total size of a header section based on the given constants and rules.
Given constants:
- `RGB_EVENT_MARKER`: A constant representing a color marker in RGB format.
... | ```rust
pub const RGB_EVENT_MARKER: RGBInt = rgb(0x5A494F);
pub const SWATCH_SIZE: i32 = 32;
pub const BG_SAMPLE_HEIGHT: u32 = 32;
pub const SCROLL_SPLIT_POINT: i32 = VARIABLE_BOTTOM;
pub const HEADER_BLEND_START: i32 = 8;
pub const HEADER_BLEND_END: i32 = 16;
fn calculate_header_size() -> i32 {
let mut header_siz... | magicoder | rust |
You are given a code snippet that represents a configuration for a game or simulation system. The snippet contains declarations of various data structures and their associated properties. Your task is to write a program that parses this configuration and extracts specific information based on the given structure.
Your... | To solve this problem, you can use a programming language with strong string manipulation capabilities, such as Python. Here's a sample solution using Python:
```python
import re
# Given code snippet
code_snippet = """
[FloatArray, "areas", "*", "tiles", "*", "mappos"],
[FloatArray, "areas", "... | magicoder | python |
You are tasked with creating a script to automate the generation of gRPC code from Protocol Buffer (.proto) files using the `protoc` compiler. The provided code snippet is a part of such a script and contains some variables and a command to execute `protoc` with specific options and flags.
Your task is to write a Bash... | ```bash
#!/bin/bash
# Check if the correct number of arguments are provided
if [ "$#" -ne 3 ]; then
echo "Usage: $0 <source_directory> <destination_directory> <gogo_protobuf_path>"
exit 1
fi
SRC_DIR=$1
DST_DIR=$2
GOGOPROTO_PATH=$3
# Check if source directory exists
if [ ! -d "$SRC_DIR" ]; then
echo "Sour... | magicoder | shell |
You are tasked with implementing a simple checkpoint system for a 3D game using Unity and C#. The provided code snippet is a part of the checkpoint system. The `OnTriggerEnter` method is called when another collider enters the trigger collider attached to the game object. The goal is to complete the implementation of t... | ```csharp
// LevelManager.cs
public class LevelManager : MonoBehaviour
{
public static LevelManager Instance { get; private set; }
public int currentTrial = 0;
private Vector3 checkpointPosition;
private Quaternion checkpointRotation;
private void Awake()
{
if (Instance == null)
... | magicoder | csharp |
You are tasked with implementing a simple parser for a custom programming language. The parser is responsible for processing tokens generated by a lexer and constructing an abstract syntax tree (AST) for further processing. Your goal is to implement the `Parser` struct and its associated methods to achieve this functio... | ```rust
// Define the Token and Lexer types for reference
enum Token {
// Define token variants
N_A,
// Other token variants
}
struct Lexer {
// Define lexer fields and methods
}
impl Parser {
// Define the Parser struct and associated methods
pub fn new(lexer: Lexer) -> Parser {
Parse... | magicoder | rust |
You are tasked with implementing a higher-order function called `reject` in TypeScript. The `reject` function should take an array or object as input and return a new array or object containing only the elements that do not satisfy a given predicate function.
The `reject` function should be implemented using the provi... | ```typescript
import curryN from './utils/curry_n.ts'
import type { PH, Obj, Predicate1 } from './utils/types.ts'
import { complement } from './complement.ts'
import { filter } from './filter.ts'
type Reject<T> = (<F extends T[] | Obj<T>>(filterable: F, predicate: Predicate1<T>) => F) &
((filterable?: PH, predicate?... | magicoder | typescript |
You are given a list of strings representing various categories. Your task is to implement a function that takes this list as input and returns a dictionary where the keys are the first letters of the categories and the values are lists of categories starting with the corresponding letter. If a category starts with a l... | ```python
def categorize_by_first_letter(categories):
categorized_dict = {}
for category in categories:
first_letter = category[0].upper()
if first_letter not in categorized_dict:
categorized_dict[first_letter] = [category]
else:
categorized_dict[first_letter].app... | magicoder | python |
You are working on a recommendation system for a book-sharing platform. The system aims to suggest books to users based on their wishlists and the wishlists of other users. You have been given a snippet of code that processes the wishlists of users and calculates suggestion scores for books. Your task is to complete th... | ```python
import pandas as pd
def get_suggested_books(user_ids, wishlist_data, books):
suggested_books = {}
for user_id in user_ids:
user_wishlist = wishlist_data.get(user_id)
if user_wishlist is None or user_wishlist.empty:
suggested_books[user_id] = [] # No wishlist for the ... | magicoder | python |
You are tasked with implementing a concrete subclass of the abstract class `CmsPageAdapter` to adapt a specific type of source data to a `CmsStructureModel`. The `CmsStructureModel` represents the structure of a content management system (CMS) page, while the `CmsPageAdapter` serves as a generic adapter for different t... | ```typescript
import { CmsPageAdapter, CmsStructureModel } from './path-to-cms-adapter';
// Define the specific type of source data
interface MySourceData {
title: string;
content: string;
metadata: Record<string, any>;
}
// Create a concrete subclass of CmsPageAdapter
export class MyCmsPageAdapter extends CmsP... | magicoder | typescript |
You are tasked with creating a Python function that retrieves replay data from a database based on a specified timestamp. The function should interact with a database session, send a GET request to a specified URL, and handle the response data appropriately. Your task is to implement the function `get_replays_with_date... | ```python
from requests import Request
def get_replays_with_date_after(initialize_database_tags, test_client, timestamp):
session = initialize_database_tags.get_session()
url = LOCAL_URL + '/api/replay'
params = {'limit': 200, 'page': 0, 'date_after': timestamp}
r = Request('GET', url, params=params)
... | magicoder | python |
You are tasked with creating a Python class that manages the placement of text labels in a document. The class, `TextLabelManager`, should provide methods for adding text labels and generating a PDF document with the added labels. The text labels can be placed in different positions such as 'left', 'right', 'top', or '... | ```python
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
class TextLabelManager:
def __init__(self):
self.labels = {'left': [], 'right': [], 'top': [], 'bottom': []}
def add_text_label(self, text, placement):
label = {'text': text, 'placement': placement}
... | magicoder | python |
You are tasked with implementing a Python function that processes the output of a command-line program and extracts specific information from it. The output of the program is captured in the variable `result.stdout_`, which contains a multi-line string. Each line in the string represents a separate piece of information... | ```python
def extract_information(output: str) -> dict:
lines = output.strip().split('\n')
name = lines[0].split(': ')[1]
version = lines[1].split(': ')[1]
last_update = lines[2].split(': ')[1]
return {
"name": name,
"version": version,
"last_update": last_update
}
```
Th... | magicoder | python |
You are tasked with creating a Python program that utilizes the `openface` library to perform facial recognition and then organizes the recognized faces into separate directories based on their identities. The program should take a source directory containing images of individuals' faces as input and create a destinati... | ```python
import openface
import os
import shutil
import cv2
# Load the pre-trained facial recognition model from openface
modelDir = "<path_to_openface_model_directory>"
align = openface.AlignDlib("<path_to_dlib_model>")
# Function to extract and save face images
def extract_faces(source_img, destination_dir, identi... | magicoder | python |
You are tasked with implementing a custom view in Swift that separates and displays two lists of items. The view should be able to receive two arrays of items and visually separate them within the view. Each list should be displayed with its own distinct style, and the view should be able to handle different types of i... | ```swift
import UIKit
final class ListsSeparatorView: UIView {
var firstList: [Any] = [] {
didSet {
updateFirstList()
}
}
var secondList: [Any] = [] {
didSet {
updateSecondList()
}
}
private let firstListContainerView = UIView()
... | magicoder | swift |
You are tasked with creating a Python class that simulates a simple banking system. The class should have methods for depositing funds, withdrawing funds, and checking the account balance. Additionally, the class should keep track of the account holder's name and account balance.
Create a Python class named `BankAccou... | ```python
class BankAccount:
def __init__(self, account_holder):
self._account_holder = account_holder
self._account_balance = 0
def deposit(self, amount):
self._account_balance += amount
def withdraw(self, amount):
if amount <= self._account_balance:
self._acco... | magicoder | python |
You are tasked with creating a program that simulates a simple inventory management system for a small retail store. The store sells three types of products: electronics, clothing, and groceries. Each product has a unique identifier, a name, a price, and a quantity in stock. Your program should allow the user to perfor... | ```swift
import UIKit
// Define the Product class to represent individual products
class Product {
let id: Int
let name: String
let price: Double
var quantity: Int
init(id: Int, name: String, price: Double, quantity: Int) {
self.id = id
self.name = name
self.price = price
... | magicoder | swift |
You are tasked with creating a script that automates the process of running ESLint, a popular tool for identifying and reporting on patterns found in ECMAScript/JavaScript code. The provided code snippet sets the `-e` flag, which causes the script to exit immediately if any command exits with a non-zero status, and ass... | ```bash
#!/bin/bash
# Check if the ESLint executable exists
if [ ! -x "$ESLINT" ]; then
echo "ESLint executable not found at the specified path: $ESLINT"
exit 1
fi
# Validate input parameters
if [ "$#" -ne 2 ]; then
echo "Usage: $0 <directory_path> <output_file_path>"
exit 1
fi
DIRECTORY_PATH=$1
OUTPUT_FILE_... | magicoder | shell |
You are tasked with implementing a simple TCP socket server for a keylogger application. The provided code snippet shows the function `start_socket_server()` that sets up and starts the server. The server listens on all network interfaces (`0.0.0.0`) and a specific port denoted by `SOCKET_PORT`. Upon starting, it logs ... | ```python
import socketserver
import threading
import logging
SOCKET_PORT = 9999 # Example port number
logger = logging.getLogger(__name__)
class KeyLoggerTCPServer(socketserver.TCPServer):
allow_reuse_address = True # Allow reuse of the server address
daemon_threads = True # Allow the server threads to ex... | magicoder | python |
You are tasked with implementing a hierarchical clustering algorithm using the Poincaré ball model. The Poincaré ball model is a hyperbolic space that is commonly used for clustering data with hierarchical structures. In this problem, you will create a Python class that performs hierarchical clustering using the Poinca... | ```python
import torch.nn as nn
from util.ml_and_math.poincare import project
class PoincareHierarchicalClustering:
def __init__(self, num_clusters, max_iterations):
self.num_clusters = num_clusters
self.max_iterations = max_iterations
self.clusters = None
def fit(self, data):
... | magicoder | python |
You are tasked with implementing a Python class that manages a process and its associated PID file. The given code snippet is part of a class method that handles the reloading of the process. Your task is to complete the implementation of the `ProcessManager` class by adding the necessary methods to manage the PID file... | ```python
import os
class ProcessManager:
def __init__(self, pidfile, proc_name):
self.pidfile = pidfile
self.proc_name = proc_name
self.pid = os.getpid()
def on_reload(self):
# Perform any necessary actions on reload
pass
def unlink_pidfile(self):
# Unlink... | magicoder | python |
You are tasked with implementing a function that processes an array of tags and returns a subset of the most popular tags. Each tag is represented as a string, and the popularity of a tag is determined by the number of occurrences in the input array. The function should return a subset of the most popular tags, limited... | ```python
from collections import Counter
from typing import List
def popular_tags(tags: List[str]) -> List[str]:
tag_counts = Counter(tags)
sorted_tags = sorted(tag_counts, key=lambda x: (-tag_counts[x], x))
return sorted_tags[:5]
``` | magicoder | python |
You are tasked with implementing a class that manages email verification for a mobile application. The class, `EmailVerificationManager`, should handle the process of sending a verification email to the user and then navigating to the login screen upon successful completion. The class should utilize the Android framewo... | ```java
public class EmailVerificationManager {
private Context context;
public EmailVerificationManager(Context context) {
this.context = context;
}
public void sendVerificationEmail(String email) {
// Implement the logic to send a verification email to the specified email address
... | magicoder | java |
You are tasked with creating a web application using Python and Panel library to display a modal dialog box with customizable content. The modal should be triggered by a button and should contain a form with input fields for the user to enter their name and email address. Upon submission of the form, the modal should d... | ```python
import panel as pn
import param
# Define a Panel class for the modal application
class ModalApp(param.Parameterized):
name = param.String()
email = param.String()
modal = pn.widgets.Modal(button_type='primary', header='User Details', body=pn.Column(
pn.widgets.TextInput(name='name', place... | magicoder | python |
You are tasked with implementing a function that checks whether a given string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward, disregarding spaces, punctuation, and capitalization.
You need to write a function `isPalindrome` that takes ... | ```python
def isPalindrome(s: str) -> bool:
# Remove spaces and punctuation and convert to lowercase
clean_str = ''.join(char.lower() for char in s if char.isalnum())
# Check if the clean string is equal to its reverse
return clean_str == clean_str[::-1]
```
The `isPalindrome` function first removes sp... | magicoder | python |
You are tasked with creating a React Native component that fetches a list of sentiments from an API and allows the user to select multiple sentiments using a checkbox group. Upon confirming the selected sentiments, an alert should be displayed to confirm the user's selection. You are provided with a code snippet that i... | ```javascript
import React, { useState, useEffect } from 'react';
import Alert from '../../../../components/AlertConfirm';
import CheckBoxGroup from './CheckBoxGroup';
import Input from '../../../../components/Input';
import { sentimentos } from './mock';
import { useNavigation } from '@react-navigation/native';
import... | magicoder | javascript |
You are tasked with creating a script to automate the synchronization of articles from a local directory to a remote server using Ruby. The script should handle the transfer of files from the local directory to the remote server, ensuring that only new or modified files are synchronized.
Your task is to implement a Ru... | ```ruby
require 'net/sftp'
require 'logger'
# Remote server details
hostname = ENV['REMOTE_HOSTNAME']
username = ENV['REMOTE_USERNAME']
password = ENV['REMOTE_PASSWORD']
remote_directory = '/path/to/remote/directory'
# Local directory to synchronize
local_directory = '/path/to/local/directory'
# Initialize logger
lo... | magicoder | ruby |
You are tasked with implementing a class that represents a rational number and provides methods for arithmetic operations. The class should be able to simplify the rational number to its simplest form and provide a string representation of the rational number.
You are given a code snippet that represents a method in t... | ```php
class RationalNumber {
private $numerator;
private $denominator;
public function __construct($numerator, $denominator) {
$gcd = $this->gcd($numerator, $denominator);
$this->numerator = $numerator / $gcd;
$this->denominator = $denominator / $gcd;
}
public function add... | magicoder | php |
You are given a Python dictionary representing a nested structure. Your task is to write a function that flattens this nested dictionary into a single-level dictionary, where the keys are concatenated with a dot (.) to represent the nesting.
For example, given the following nested dictionary:
```python
nested_dict = {... | ```python
def flatten_dict(nested_dict, parent_key='', sep='.'):
items = {}
for key, value in nested_dict.items():
new_key = f"{parent_key}{sep}{key}" if parent_key else key
if isinstance(value, dict):
items.update(flatten_dict(value, new_key, sep=sep))
else:
item... | magicoder | python |
You are tasked with implementing a simple command-line interface for a state machine. The state machine can be in one of several states, and the user can input commands to interact with the state machine. Your task is to implement the logic for processing user commands and updating the state machine accordingly.
You a... | ```cpp
// Assume the state machine class has methods: start(), stop(), reset(), isTerminated()
cout << "> ";
cout.flush();
getline(input, cmd);
if (!stateMachine.isTerminated()) {
if (!cmd.empty()) {
if (cmd == "start") {
stateMachine.start();
} else if (cmd == "stop") {
st... | magicoder | cpp |
You are tasked with creating a multithreaded Python program that simulates a simple ticket booking system for a movie theater. The program should use threading to handle multiple ticket booking requests concurrently. The movie theater has a limited number of seats, and each booking request should be processed in a thre... | ```python
import threading
class MovieTheater:
def __init__(self, num_seats):
self.num_seats = num_seats
self.lock = threading.Lock()
def book_ticket(self, customer_name, num_tickets):
with self.lock:
if self.num_seats >= num_tickets:
self.num_seats -= num_t... | magicoder | python |
You are tasked with creating a custom UITableViewCell subclass for a location-based app. The cell should display information about a specific location, including its name, street, city, date, and an image. Your task is to implement the `LocationTableViewCell` class with the necessary properties and methods to populate ... | ```swift
import UIKit
class LocationTableViewCell: UITableViewCell {
// MARK: @IBOutlets
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var streetLabel: UILabel!
@IBOutlet weak var cityLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var cellImageView: UIImageVi... | magicoder | swift |
You are given a list of courses labeled from 0 to numCourses - 1, and an array of prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi before you can take course ai. Write a function to return the ordering of courses you should take to finish all courses. If it is impossible to finish ... | ```python
from collections import defaultdict, deque
def findOrder(numCourses, prerequisites):
graph = defaultdict(list)
indegree = [0] * numCourses
for course, pre in prerequisites:
graph[pre].append(course)
indegree[course] += 1
queue = deque([i for i in range(numCourses) if indegree... | magicoder | python |
You are tasked with implementing a custom data processing pipeline using the MiddleMan library in C#. The MiddleMan library provides a flexible and efficient way to create data processing pipelines by allowing the chaining of multiple processing steps.
Your task is to create a pipeline that performs the following oper... | ```csharp
using MiddleMan.Pipeline;
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// Sample data
List<int> data = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Create the pipeline
var pipeline = new Pipeline<int>(d... | magicoder | csharp |
You are tasked with implementing a JSON serializer in C#. Your goal is to write a method that serializes a given object into a JSON string. The JSON serializer should support serializing primitive types (such as integers, strings, booleans), arrays, and objects. The serializer should handle nested objects and arrays, a... | ```csharp
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
public class JsonSerializer
{
public string SerializeToJson(object obj)
{
StringBuilder jsonUtf8 = new StringBuilder();
SerializeValue(obj, jsonUtf8);
return jsonUtf8.ToString();
}... | magicoder | csharp |
You are working on a computer vision project that involves processing images and extracting information from them. Your task is to write a Python function that takes in an image file path, performs certain operations on the image using the OpenCV library, and then processes the results to generate a specific output for... | ```python
import cv2
import json
def process_image_and_generate_json(image_path):
img = cv2.imread(image_path)
original_height, original_width, _ = img.shape
resized_img = cv2.resize(img, (768, 576))
info_dict = {
"image_info": {
"height": original_height,
"width": orig... | magicoder | python |
You are tasked with implementing a custom data structure in Swift that mimics the behavior of a loadable integer wrapper. The loadable integer wrapper is a type that represents an integer value and provides the ability to load and store the value from memory. The wrapper has the following properties and methods:
Prope... | ```swift
// Define the LoadableIntWrapper structure
struct LoadableIntWrapper {
private var value: Int
// Initialize the wrapper with an initial value
init(initialValue: Int) {
self.value = initialValue
}
// Method to load the value from memory
func load() -> Int {
return value... | magicoder | swift |
You are tasked with implementing a function to initialize parameter parallel groups for distributed training in a parallel computing environment. The function `_initialize_parameter_parallel_groups` takes an optional parameter `parameter_parallel_size`, which represents the number of processes to be used for parameter ... | ```python
import torch
import torch.distributed as dist
def _initialize_parameter_parallel_groups(parameter_parallel_size=None):
data_parallel_size = int(dist.get_world_size())
if parameter_parallel_size is None:
parameter_parallel_size = int(data_parallel_size)
print(data_parallel_size, parameter_... | magicoder | python |
You are tasked with implementing a function to calculate the time derivative of the spatial metric in a numerical relativity simulation. The given code snippet is part of a larger computational physics simulation and represents a portion of the time evolution equation for the spatial metric in a spacetime with a specif... | ```cpp
// Function to calculate the time derivative of the spatial metric
void calculateTimeDerivative(const Scalar& lapse,
const Tensor& extrinsic_curvature,
Tensor& dt_spatial_metric,
const Vector& shift,
... | magicoder | cpp |
You are given a code snippet that processes input from the standard input. The input consists of rows, where each row contains tab-separated fields. The fields are delimited by the characters '~^~'. Your task is to write a program that reads the input and processes it according to the following rules:
1. For each row,... | ```python
import sys
ARR_DELIM = '~^~'
for row_number, row in enumerate(sys.stdin, 1):
fields = row.strip().split('\t')
processed_fields = []
for field in fields:
values = field.split(ARR_DELIM)
processed_fields.append(', '.join(values))
print(f"Row {row_number}: {', '.join(processed_f... | magicoder | python |
You are tasked with implementing a point adjustment system for a loyalty program. The system should allow for adjusting the points of a specific payer by deducting points from the oldest transactions associated with that payer.
You are given a Python function `adjust(data)` that takes a dictionary `data` as input. Th... | ```python
def adjust(data):
try:
points = data['points']
payer = data['payer']
# Get transactions by payer ordered by timestamp
transaction_adjust = transactions.objects.filter(payer=payer).order_by('timestamp')
total_points_to_adjust = points
adjust... | magicoder | python |
You are tasked with implementing a particle simulation program. The program should allow users to set various parameters for the simulation, such as maximum velocity, random factor, and other relevant attributes. The provided code snippet is a part of the user interface setup for the program, where controls for setting... | ```python
class ParticleSimulation:
def __init__(self, max_velocity, random_factor):
self.max_velocity = max_velocity
self.random_factor = random_factor
self.particles = [] # List to store particle objects
def set_max_velocity(self, max_velocity):
self.max_velocity = max_veloci... | magicoder | python |
You are tasked with implementing a custom neural network layer in Python using PyTorch. Your task is to create a class called `CustomLayer` that inherits from `nn.Module` and contains two operations: a softmax operation and a hyperbolic tangent (tanh) operation. The `forward` method of the class should take an input te... | ```python
import torch
import torch.nn as nn
class CustomLayer(nn.Module):
def __init__(self):
super(CustomLayer, self).__init__()
self.soft = nn.Softmax(dim=1)
self.tanh = nn.Tanh()
def forward(self, x):
x = self.soft(x)
x = self.tanh(x)
return x
```
The provid... | magicoder | python |
You are tasked with creating a Python function that automates the process of logging into a website using Selenium and Chrome WebDriver. Your function should take in the website URL, username, and password as input parameters, and return a boolean value indicating whether the login was successful or not.
Your function... | ```python
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
import time
def automate_login(url: str, username: str, password: str) -> bool:
options = Options()
options.add... | magicoder | python |
You are tasked with creating a PHP class that manages a simple inventory system for a fictional online store. The class should allow for adding and removing items from the inventory, as well as checking the availability of a specific item.
Your task is to implement the `Inventory` class with the following specificatio... | ```php
class Inventory {
private $items = [];
public function addItem($itemName, $quantity) {
if (array_key_exists($itemName, $this->items)) {
$this->items[$itemName] += $quantity;
} else {
$this->items[$itemName] = $quantity;
}
}
public function removeI... | magicoder | php |
You are tasked with creating a program that processes a list of software licenses and determines whether each license is valid according to the Apache License, Version 2.0. The Apache License, Version 2.0 is a permissive free software license written by the Apache Software Foundation. It allows users to use the softwar... | ```python
def is_valid_license(license_text):
if "Licensed under the Apache License, Version 2.0" in license_text and "http://www.apache.org/licenses/LICENSE-2.0" in license_text:
return "Valid"
else:
return "Invalid"
# Read input file
with open('input.txt', 'r') as file:
licenses = file.re... | magicoder | python |
You are tasked with implementing a file tracking system that keeps track of files being added and removed. The system should maintain two sets of files: `todo` for files to be processed and `done` for files that have been processed. The system should also calculate a unique hash for each file based on its original path... | ```javascript
// Solution for getOriginalPathHash function
const getOriginalPathHash = (file) => {
// Assuming file.path is the original path of the file
// Using a simple hash function to generate a unique hash based on the file's original path
return hashString(file.path);
};
// Solution for reportComplete fun... | magicoder | javascript |
You are tasked with creating a Python class to represent and manipulate microscope settings. The class should have methods to set and get the values of various microscope parameters, such as acquisition mode, beam current, beam energy, convergence angle, magnification indicated, and microscope name. Each parameter can ... | ```python
class MicroscopeSettings:
def __init__(self):
self.settings = {
'acquisition_mode': {'value': 'STEM'},
'beam_current': {'value': 0.0, 'units': 'NanoA'},
'beam_energy': {'value': 300.0, 'units': 'KiloEV'},
'convergence_angle': {'value': 13.0, 'units':... | magicoder | python |
You are tasked with creating a C# method that validates the configuration settings for an authentication provider. The method should ensure that the required environment variables are set and that the configuration object is properly initialized.
You are given the following C# code snippet as a starting point:
```cs... | ```csharp
using System;
public class Auth0FactoryOptions
{
public string Domain { get; set; }
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public bool ReuseAccessToken { get; set; }
}
public class AuthValidator
{
public bool ValidateAuth0Configuration(Auth0FactoryO... | magicoder | csharp |
You are tasked with creating a program that categorizes companies based on their industry. The program should take a company's industry code as input and output the corresponding industry name. The industry codes and their corresponding names are as follows:
1: "Other"
2: "Mining"
3: "Processing"
4: "Energy"
5: "Utili... | ```python
def categorize_company(industry_code):
industry_map = {
1: "Other",
2: "Mining",
3: "Processing",
4: "Energy",
5: "Utilities",
6: "Construction",
7: "Retail_and_wholesale",
}
return industry_map.get(industry_code, "Unknown Industry")
# Test ... | magicoder | python |
You are tasked with implementing a class that renders data into a string format. The class should adhere to a specific interface and handle various data types. Your task is to create a PHP class that fulfills the requirements of the given interface and can render different types of data into a string.
You are provided... | ```php
class DataRenderer implements DataInterface {
public function render(DataInterface $data): string {
if (is_int($data)) {
return (string)$data;
} elseif (is_string($data)) {
return $data;
} elseif (is_array($data)) {
return json_encode($data);
... | magicoder | php |
You are working on a user role management system for a project management application. The code snippet provided is part of a Python class that handles the creation and management of user roles on a project. The `_create_user_role_on_project` method is responsible for creating user roles on a project, and the `_list_an... | ```python
@classmethod
def _list_and_clear_user_roles_on_project(cls, role_ids):
# List all the user roles associated with the project
all_user_roles = cls.admin_roles_client.list_user_roles_on_project(cls._project_id, cls._user_id)
# Clear the user roles specified by the role_ids parameter from the projec... | magicoder | python |
You are tasked with simulating the behavior of a network device controller in response to a series of commands and messages. The controller is responsible for configuring a device and sending a renew message to the device. The given code snippet is a part of the controller's functionality, where it resets the device to... | ```python
class NetworkDeviceController:
def __init__(self, controller_mac):
self.controller_mac = controller_mac
self.ieee1905 = {
'eMessageType': {
'AP_AUTOCONFIGURATION_RENEW_MESSAGE': 0x0A
},
'eTlvType': {
'TLV_AL_MAC_ADDRESS': ... | magicoder | python |
You are tasked with implementing a function that performs element-wise multiplication on two matrices using the Eigen C++ library. The function should handle different scenarios, including when one of the matrices is a row vector and the other is a matrix. Your task is to write a function that correctly performs the el... | ```cpp
#include <Eigen/Dense>
Eigen::MatrixXd elementWiseMultiplication(const Eigen::MatrixXd& a, const Eigen::MatrixXd& b) {
if (a.rows() == b.rows() && a.cols() == b.cols()) {
// Case 1: Both matrices have the same dimensions
return a.array() * b.array();
} else if ((a.rows() == 1) && (a.cols... | magicoder | cpp |
You are tasked with implementing a Python function to calculate the gravitational acceleration at a specific geodetic latitude on the Earth's surface. The gravitational acceleration is influenced by the Earth's rotation and its ellipsoidal shape. The formula for calculating the gravitational acceleration (g) at a given... | ```python
import math
def calculate_gravitational_acceleration(latitude_degrees: float) -> float:
R0 = 6378137.0
f = 1/298.257223563
omega_E = 7.2921151467e-5
phi = math.radians(latitude_degrees)
e2 = f * (2 - f)
g0 = 9.780327
cos_phi = math.cos(phi)
sin_phi = math.sin(phi)
term1... | magicoder | python |
You are tasked with implementing a utility function to determine whether a given string is a valid Base64 encoded string. Base64 encoding is a method of encoding binary data into an ASCII string format, which is commonly used for encoding data in email attachments, image uploads, and other data transmission processes.
... | ```php
namespace Ezpizee\Utils;
final class EncodingUtil
{
private static $MD5_REGEX = '/^[a-f0-9]{32}$/';
private static $UUID_V4_REGEX1 = '/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i';
private static $UUID_V4_REGEX1_2 = '/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}... | magicoder | php |
You are tasked with creating a Python function that generates a directed graph using the `networkx` library, saves it to a temporary file in the DOT format, and then returns the path to the temporary file. Your function should take in the number of nodes in the graph and the probability of an edge between any two nodes... | ```python
import networkx as nx
import tempfile
def generate_and_save_graph(num_nodes, edge_probability):
# Generate a directed graph using the Erdős-Rényi model
graph = nx.erdos_renyi_graph(num_nodes, edge_probability, directed=True)
# Create a temporary file with a .dot extension
with tempfile.Named... | magicoder | python |
You are tasked with creating a function that processes a CSV file containing information about tasks and stores them in a database using functional programming techniques. The CSV file contains the following columns: `id`, `name`, `description`, and `completed`. Each row represents a task to be stored in the database. ... | ```typescript
import { PrismaClient } from '@prisma/client'
import * as Task from 'fp-ts/lib/Task'
import cuid from 'cuid'
import * as A from 'fp-ts/lib/Array'
import { pipe } from 'fp-ts/lib/pipeable'
import parse from 'csv-parse'
import { createReadStream, ReadStream } from 'fs'
import { join } from 'path'
import { a... | magicoder | typescript |
You are tasked with implementing a feature flag system for a web service that provides different response types based on enabled features. The code snippet provided is a part of the feature flag system and demonstrates the use of conditional compilation in Rust.
Your task is to create a function `generate_response` th... | ```rust
// Feature flag configuration
#[cfg(feature = "erased-json")]
mod erased_json {
pub struct ErasedJsonResponse;
}
// Define the Response trait
trait Response {
fn generate_response(&self);
}
// Implement the Response trait for ErasedJsonResponse
#[cfg(feature = "erased-json")]
impl Response for erased_... | magicoder | rust |
You are tasked with implementing a function that generates a statistical table for a given set of test titles, variable names, and statistics. The function should utilize the `limix._display.Table` class to create the table and populate it with the provided data.
The function `draw_lrt_table(test_titles, pv_names, sta... | ```python
def draw_lrt_table(test_titles, pv_names, stats):
from limix._display import Table
# Create a Table instance with test_titles as column headers and pv_names as index
table = Table(test_titles, index=pv_names)
# Iterate through each variable name
for name in pv_names:
# Get the st... | magicoder | python |
You are working in a factory that produces items on a conveyor belt. The belt has N slots, and each slot contains a number representing the item's durability. Additionally, there are K robots placed on the belt to assist in the production process. The robots can move along the belt and pick up items to perform various ... | ```python
from collections import deque
def min_steps_to_complete_task(N, K, durability):
belt = deque(durability)
robot = deque([0] * 2 * N)
step = 1
while True:
belt.rotate(1)
robot.rotate(1)
robot[N - 1] = 0
for i in range(N - 2, -1, -1):
if robot[i] != 0... | magicoder | python |
You are tasked with creating a script to automate the process of compiling a C++ project. The project has the following directory structure:
```
project/
src/
main.cpp
file1.cpp
file2.cpp
include/
header1.h
header2.h
obj/
lib/
```
Your script should perform the ... | ```bash
#!/bin/bash
# Create obj directory if it doesn't exist
mkdir -p project/obj
# Create lib directory if it doesn't exist
mkdir -p project/lib
# Compile the project using make with parallel compilation
make -C project -j4
```
The script first creates the `obj` and `lib` directories if they do not exist using t... | magicoder | shell |
You are given a non-negative index `rowIndex`. Your task is to generate the `rowIndex`-th row of Pascal's triangle.
Pascal's triangle is a triangular array of binomial coefficients. The `n`-th row of the Pascal's triangle represents the coefficients of the expanded polynomial `(a + b)^n`.
For example, when `rowIndex ... | ```python
from typing import List
def getPascalRow(rowIndex: int) -> List[int]:
if rowIndex == 0:
return [1]
row = [1]
for i in range(1, rowIndex + 1):
next_val = row[i - 1] * (rowIndex - i + 1) // i
row.append(next_val)
return row
```
The `getPascalRow` function first handles t... | magicoder | python |
You are given a Python function `merged_arrays(heap1, heap2)` which takes in two heaps `heap1` and `heap2`. Each heap is represented as a list of integers and contains elements in ascending order. Your task is to implement the `merged_arrays` function to return a single combined array with all the elements from both he... | ```python
def merged_arrays(heap1, heap2):
"""Return combined array with sorted values."""
merged_heap = []
i, j = 0, 0
while i < len(heap1) and j < len(heap2):
if heap1[i] < heap2[j]:
merged_heap.append(heap1[i])
i += 1
else:
merged_heap.append(heap2... | magicoder | python |
You are tasked with implementing a network update algorithm for a social media platform. The platform has a network of users, and the algorithm aims to update the connections between users based on certain criteria. The code snippet provided is a part of the network update process, where the function `update_network` i... | ```python
from typing import List
def update_network(f_ij: List[List[float]]) -> List[List[float]]:
n = len(f_ij)
updated_network = [[0.0 for _ in range(n)] for _ in range(n)]
for i in range(n):
for j in range(n):
# Perform the network update logic based on specific criteria
... | magicoder | python |
You are tasked with implementing a custom pipeline for feature data processing using the AutoNet framework. The AutoNetFeatureData class inherits from the AutoNet class and is responsible for defining the default pipeline for feature data processing.
Your task is to complete the implementation of the get_default_pipel... | ```python
class AutoNetFeatureData(AutoNet):
@classmethod
def get_default_pipeline(cls):
from autoPyTorch.pipeline.base.pipeline import Pipeline
# Define and configure the default pipeline for feature data processing
default_pipeline = Pipeline([
# Add feature data processin... | magicoder | python |
You are tasked with implementing a class for creating cylinder primitives in a 3D graphics library. The class should support two constructors, one with default parameters and another with explicit parameters. Your task is to implement the constructors and ensure that the cylinder is aligned with the height in the z-dir... | ```cpp
#include <iostream>
class Cylinder {
public:
// Default constructor with default parameters
Cylinder(int levels = 16) : radius_(1.0f), height_(1.0f), levels_(levels) {}
// Constructor with explicit parameters
Cylinder(float radius, float height, int levels = 16) : radius_(radius), height_(heigh... | magicoder | cpp |
You are tasked with creating a program to efficiently crawl and retrieve submissions for problems from an online judge platform. The code snippet provided is a simplified representation of the asynchronous crawling process using Python's `asyncio` library.
Your task is to implement a function that takes a list of prob... | ```python
import asyncio
async def crawl(problem_id):
# Simulated submission retrieval
return f"Submission for problem {problem_id}"
async def retrieve_submissions(problem_ids):
submissions = {}
tasks = []
async def crawl_and_store(problem_id):
submission = await crawl(problem_id)
... | magicoder | python |
You are tasked with implementing a function to retrieve the latest day for the weekly ranking. The function should take an optional format parameter and return the latest day in the specified format.
You are given the following code snippet as a starting point:
```php
/**
* Retrieve the latest day for the weekly rank... | ```php
/**
* Retrieve the latest day for the weekly ranking
*
* @param string $format (optional) The format for the returned date
*
* @return string The latest day in the specified format
*/
function get_latest_ranking_day($format = ''){
// Get the current date and time
$currentDate = new DateTime();
... | magicoder | php |
You are tasked with implementing a function to calculate the factorial of a given non-negative 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 5 * 4 * 3 * 2 * 1 = 120.
Your task is to implement the `f... | ```python
import sys
def factorial(n: int) -> int:
sys.setrecursionlimit(5000) # Set a higher recursion limit to handle large inputs
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
```
The `factorial` function calculates the factorial of a given non-negative integer `n`. I... | magicoder | python |
You are tasked with implementing a wallet system for a financial application. The system involves transferring funds from one user's wallet to another. You are given a Python code snippet that partially implements this functionality using SQLAlchemy, a popular Python SQL toolkit and Object-Relational Mapping (ORM) libr... | ```python
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import IntegrityError
class ReceiverDoesNotExist(Exception):
pass
class InsufficientFunds(Exception):
pass
class WalletSystem:
def __init__(self, db_url):
self.engine = create_engine(db_url)... | magicoder | python |
You are given a Python class with a method `merge_k_sorted_lists` that takes in a list of sorted lists and merges them into a single sorted list. The method uses a helper function `merge_two_sorted_lists` to merge two sorted lists. Your task is to complete the implementation of the `merge_k_sorted_lists` method to merg... | ```python
class Solution:
def merge_two_sorted_lists(self, l1, l2):
# Helper method to merge two sorted lists
# Implementation is not shown
def merge_k_sorted_lists(self, lists):
if len(lists) == 0:
return None
if len(lists) == 1:
return lists[0]
... | magicoder | python |
You are tasked with implementing a simple messaging system using Python's Twisted framework. The provided code snippet includes the beginning of a class definition for a client avatar in a networking application. Your task is to complete the implementation of the `ClientAvatar` class by adding methods to handle message... | ```python
from twisted.internet.protocol import Protocol
from twisted.protocols.basic import LineReceiver
from twisted.cred import checkers, portal
from twisted.conch import avatar, recvline
from zope.interface import implementer
from twisted.internet import reactor
@implementer(avatar.IAvatar)
class ClientAvatar(obj... | magicoder | python |
You are tasked with implementing a simple calculator program that can perform addition and subtraction operations on numerical inputs. The calculator accepts a series of tokens representing either numbers or operators and must evaluate the expression to produce a final result.
The calculator supports the following ope... | ```cpp
#include <iostream>
#include <vector>
#include <memory>
// Token class representing numerical values or operators
class Token {
public:
using Ptr = std::shared_ptr<Token>;
virtual ~Token() = default;
};
// Numerical token class derived from Token
class NumToken : public Token {
public:
double value... | magicoder | cpp |
You are tasked with creating a SwiftUI view for an insulin pump application. The view, `InsertCannulaView`, is responsible for guiding the user through the process of inserting a cannula for insulin delivery. The view is initialized with an `InsertCannulaViewModel` object, which manages the data and behavior of the vie... | ```swift
import SwiftUI
import LoopKitUI
struct InsertCannulaView: View {
@ObservedObject var viewModel: InsertCannulaViewModel
@Environment(\.verticalSizeClass) var verticalSizeClass
@State private var cancelModalIsPresented: Bool = false
var body: some View {
VStack {
... | magicoder | swift |
You are tasked with implementing a session visit counter for a web application. The session visit counter should keep track of the number of times each page is visited by a user. The code snippet provided is a series of assertions that test the functionality of the session visit counter. The `client` object simulates a... | ```python
class SessionVisitCounter:
def __init__(self):
self.visit_count = {}
def update_visit_count(self, path):
if path in self.visit_count:
self.visit_count[path] += 1
else:
self.visit_count[path] = 1
def get_visit_count(self, path):
return self.... | magicoder | python |
You are tasked with creating a script to automate the process of moving plot directories based on certain conditions. The script should iterate through a list of directories and move each directory to a specified destination if certain conditions are met. Your task is to implement the logic for moving the plot director... | ```bash
#!/bin/bash
# Assuming $directories is an array containing the list of directories to be processed
for k in "${directories[@]}"; do
if $VERBOSE; then
echo "----- moving plot dir: $(basename $k)"
fi
$ECHO $OP $k $SINK_PLOTDIR || exit $?
done
if ! $BACK; then
# Additional actions to be performed if... | magicoder | shell |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.