query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with creating a Python program that simulates a simple banking system. The program should allow users to create accounts, deposit money, withdraw money, and check their balance. The program should also be able to handle multiple accounts and maintain their information separately.
Your task is to impleme... | ```python
class Account:
def __init__(self, account_number, initial_balance):
self.account_number = account_number
self.balance = initial_balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount <= self.balance:
self.balanc... | magicoder | python |
You are given a function `sum(to n: Int) -> Int` that is intended to calculate the sum of all integers from 1 to `n`. However, the code snippet provided is incomplete. Your task is to complete the function `sum(to n: Int) -> Int` by adding the necessary code to calculate the sum and return the result. Additionally, you... | The solution involves completing the given function `sum(to n: Int) -> Int` to calculate the sum of all integers from 1 to `n` and return the result. The completed function is as follows:
```swift
func sum(to n: Int) -> Int {
var result = 0
for number in 1...n { // O(n)
result += number
}
retur... | magicoder | swift |
You are tasked with creating a Python function that generates an RSA key pair using the Cryptodome library and then encrypts a message using the public key. Your function should take a message as input, generate an RSA key pair, encrypt the message using the public key, and return the encrypted message along with the p... | ```python
from typing import Tuple
from Cryptodome.PublicKey import RSA
from Cryptodome.Cipher import PKCS1_OAEP
def encrypt_message(message: str) -> Tuple[str, bytes, bytes]:
try:
key = RSA.generate(2048)
public_key = key.publickey().export_key()
private_key = key.export_key()
ciph... | magicoder | python |
You are tasked with creating a function that processes and updates a list of running events. The function should take in the ID of a specific running event and the updated data for that event. The function should then update the event with the provided data and return the updated event details. You are given a TypeScri... | ```javascript
const Run = require('./models/run'); // Import the Run model from Sequelize
/**
* Updates a running event with the provided data
* @param {string} id - The ID of the running event to be updated
* @param {object} data - The updated data for the running event
* @returns {object} - The updated running e... | magicoder | javascript |
You are tasked with implementing a function that calculates the sum of all even Fibonacci numbers up to a given limit. 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. For example, the first few numbers in the Fibonacci sequence are ... | ```rust
fn even_fibonacci_sum(limit: u64) -> u64 {
let (mut a, mut b) = (1, 1);
let mut sum = 0;
while b <= limit {
if b % 2 == 0 {
sum += b;
}
let next = a + b;
a = b;
b = next;
}
sum
}
fn main() {
let limit = 10;
println!("Sum of even ... | magicoder | rust |
You are tasked with implementing a Python class method that searches for a specific device by its unique identifier in a list of devices. The method should return the device if found, or None if the device is not present in the list.
You are given a Python class `DeviceManager` with the following method:
```python
cl... | ```python
class DeviceManager:
def __init__(self, devices):
self.devices = devices
def find_by_st(self, unique_identifier):
for device in self.devices:
if device.st == unique_identifier:
return device
return None
```
In the solution, the `find_by_st` method ... | magicoder | python |
You are tasked with implementing a simple text processing function that will take a string as input and return a modified version of the string based on a set of rules. The rules are defined by the provided code snippet, which includes a context-free grammar and a function to strip tokens.
The context-free grammar is ... | ```python
import re
def process_text(input_text, context):
input_text = input_text.strip() # Remove leading and trailing whitespace
lookup = {name: name for name in context["declared"]} # Initialize lookup dictionary
# Replace declared words with their corresponding values
for name in context["decla... | magicoder | python |
You are tasked with implementing a Rust program to solve a matrix equation using pattern matching. The matrix equation is represented as a tuple of tuples, and the solution should be obtained using a specific solver implementation.
You are given a Rust code snippet that includes the creation of a matrix with patterns ... | ```rust
// Define the Matrix struct to represent the matrix equation
struct Matrix<T>(T);
// Implement the expand method for the Matrix struct
impl<T> Matrix<T> {
fn expand(self) -> ExpandedMatrix<T> {
// Perform the expansion logic here
// Example: Assuming expansion involves duplicating the matri... | magicoder | rust |
You are tasked with implementing a trait for encoding CLI calls in a blockchain application. The provided code snippet includes a trait definition and a struct with fields for payload and fee. Your goal is to create a method that encodes a CLI call based on the given trait and struct.
You are given the following trait... | ```rust
use std::convert::TryInto;
impl CliEncodeCall for YourChainType {
fn max_extrinsic_size() -> u32 {
// Implement the maximal size logic based on the requirements of your chain
// For example, if the maximal size is 100 bytes, you can return it as follows:
100
}
fn encode_cal... | magicoder | rust |
You are tasked with creating a C++ header file that provides a set of mathematical functions for working with complex numbers. Your task is to implement the header file `ComplexMath.hpp` that includes the necessary prerequisites and defines a class `Complex` with the following functionalities:
1. Constructor: Initiali... | ```cpp
#ifndef COMPLEX_MATH_HPP
#define COMPLEX_MATH_HPP
#include <string>
#include <cmath>
class Complex {
private:
double real;
double imag;
public:
// Constructor
Complex(double real, double imag) : real(real), imag(imag) {}
// Getter methods
double getReal() const { return real; }
do... | magicoder | cpp |
You are tasked with implementing a custom exception handling mechanism for a network protocol. The protocol is designed to handle various types of errors, and you need to create a custom exception class to represent protocol errors. Your task is to create a Python class that represents a custom exception called `Protoc... | ```python
class ProtocolError(Exception):
"""A protocol error occurred."""
```
The solution provides a simple implementation of the `ProtocolError` class as a subclass of the built-in `Exception` class. The class has a docstring that describes it as "A protocol error occurred." This implementation meets the specifi... | magicoder | python |
You are tasked with creating a Python function that validates the consistency of a machine learning classifier's predictions and decision scores before and after preprocessing. The function should compare the predictions and decision scores of two classifiers, one with preprocessing and one without, and ensure that the... | ```python
import numpy as np
from numpy.testing import assert_array_equal, assert_array_almost_equal
def validate_classifier_consistency(clf_pre, clf, ds_X, data_pre):
y1, score1 = clf_pre.predict(ds_X, return_decision_function=True)
y2, score2 = clf.predict(data_pre, return_decision_function=True)
predic... | magicoder | python |
You are tasked with implementing a simple entity management system for a game development project. The system should allow for the creation, retrieval, and deletion of entities, where each entity is represented by a unique identifier. The provided code snippet is a hint for the structure of the system, indicating that ... | ```java
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
public class EntitysPanel {
private Map<Integer, Entity> entities; // Map to store entities with their unique identifiers
private AtomicInteger entityIdCounter; // Atomic counter to generate unique entity ... | magicoder | java |
You are tasked with implementing a simple quiz game in Swift. The game consists of a timer, a question display, and a user input field for answering the question. The code snippet provided is a part of the Swift implementation for this quiz game. Your task is to complete the implementation by adding the necessary funct... | To complete the quiz game implementation, you can use the following code as a reference:
```swift
// Handle user input
func submitAnswer(_ answer: String) {
let correctAnswer = question.correctAnswer // Assuming the Question class has a property for the correct answer
if answer.lowercased() == correctAnswer.lo... | magicoder | swift |
You are tasked with implementing a game algorithm that simulates a sequence of numbers based on a set of rules. The game is played as follows:
1. Initialize a game with a list of starter numbers and a starting turn number.
2. At each turn, a new number is generated based on the previous number and the game's memory.
3... | ```rust
impl Game {
pub fn play_game(&mut self, num_turns: u64) -> Vec<u64> {
let mut result = self.starters.clone();
while self.turn < num_turns {
self.play_turn();
result.push(self.last_number);
}
result
}
}
``` | magicoder | rust |
You are tasked with implementing a navigation service for a questionnaire application. The provided code snippet is a part of the navigation logic for the questionnaire. The `hasNextStep$` and `hasPreviousStep$` observables are used to determine whether there are next and previous steps in the questionnaire flow, respe... | ```typescript
subscribe() {
this.navigate$.subscribe((direction: 'next' | 'previous') => {
if (direction === 'next') {
this.hasNextStep$.pipe(take(1)).subscribe((hasNext: boolean) => {
if (hasNext) {
// Navigate to the next step using the Angular Router
... | magicoder | typescript |
You are working on a machine learning project and have been given a code snippet that includes some commented-out lines. Your task is to understand the purpose of the code and the commented-out lines and then write a function to perform a specific task.
The given code snippet is related to data visualization and manip... | ```python
import matplotlib.pyplot as plt
def plot_loss(data):
x = range(len(data)) # Assuming x-axis represents the index of the data points
plt.plot(x, data, 'b')
plt.yscale('log')
plt.title('Loss')
plt.show()
```
The `plot_loss` function takes in the dataset `data`, creates a range of x-values... | magicoder | python |
You are tasked with implementing a custom view class in Swift that conforms to the `EmptyDataSetSource` and `EmptyDataSetDelegate` protocols. The class, `UEmptyView`, is intended to be used as an empty state placeholder in a user interface, such as when a table view or collection view has no data to display. The class ... | ```swift
import UIKit
import DZNEmptyDataSet // Assuming DZNEmptyDataSet is used for EmptyDataSetSource and EmptyDataSetDelegate protocols
class UEmptyView: EmptyDataSetSource, EmptyDataSetDelegate {
var image: UIImage?
var allowShow: Bool = false
var verticalOffset: CGFloat = 0
private var tapClo... | magicoder | swift |
You are tasked with implementing a function that processes and visualizes data from a sensor array. The sensor array consists of multiple sensors, each providing a stream of data points. The data points are represented as tuples of the form (sensor_id, timestamp, value), where sensor_id is a unique identifier for the s... | ```python
import matplotlib.pyplot as plt
def visualize_sensor_data(data_points):
sensor_data = {}
for sensor_id, timestamp, value in data_points:
if sensor_id not in sensor_data:
sensor_data[sensor_id] = {'timestamps': [], 'values': []}
sensor_data[sensor_id]['timestamps'].append(t... | magicoder | python |
You are tasked with implementing a feature class for a machine learning application. The feature class is responsible for encapsulating the attributes of a dataset instance. The instance contains values for different attributes and can be a regular instance or a SparseInstance. Your task is to design the Feature class ... | ```java
import weka.core.Instance;
public class Feature {
private Instance instance;
// Method to set the instance for the Feature
public void setInstance(Instance instance) {
this.instance = instance;
}
// Method to get the instance from the Feature
public Instance getInstance() {
... | magicoder | java |
You are tasked with implementing a custom publisher in Swift that combines two existing publishers. The given code snippet provides the type aliases and properties for the custom publisher.
The `Output` and `Failure` typealiases represent the output and failure types of the custom publisher, respectively. The `prefix`... | ```swift
import Combine
struct CombinedPublisher<Prefix: Publisher, Suffix: Publisher>: Publisher where Prefix.Failure == Suffix.Failure, Prefix.Output == Suffix.Output {
typealias Output = Suffix.Output
typealias Failure = Suffix.Failure
let prefix: Prefix
let suffix: Suffix
init(prefix:... | magicoder | swift |
You are tasked with implementing a simple simulation of a cellular automaton using the CompuCell3D library. The cellular automaton will model the behavior of cells in a 3D environment. The provided code snippet initializes the simulation environment using the `CompuCellSetup.run()` function. Your task is to create a Py... | ```python
# Import necessary modules from CompuCell3D library
from cc3d import CompuCellSetup
from cc3d.core.PySteppables import *
from cc3d import CompuCellSetup
from cc3d.core.XMLUtils import ElementCC3D
class MySteppable(SteppableBasePy):
def __init__(self, frequency=1):
SteppableBasePy.__init__(self, f... | magicoder | python |
You are working on a project that involves defining a graph using TensorFlow for processing triple data. The given code snippet is a part of a class method that defines placeholders for positive and negative triples. Each triple consists of three elements: head (h), relation (r), and tail (t). The placeholders are defi... | ```python
import tensorflow as tf
def define_embed_graph(pos_hs, pos_rs, pos_ts, neg_hs, neg_rs, neg_ts):
# Define embeddings for entities and relations
entity_embeddings = tf.get_variable("entity_embeddings", [num_entities, embedding_dim], initializer=tf.random_uniform_initializer(-0.01, 0.01))
relation_e... | magicoder | python |
You are tasked with creating a custom token type for a multi-token standard library in Rust. The provided code snippet declares a public type alias `MTTokenType` for the `multi_token_standard` crate's `TokenType`. Your task is to implement a custom token type that extends the functionality of the existing `multi_token_... | ```rust
// Define the custom token type
pub struct CustomTokenType;
// Define the custom token enumeration
pub enum CustomToken {
Identifier(String),
Number(i32),
Keyword(String),
}
// Implement the display_token method for CustomTokenType
impl CustomTokenType {
pub fn display_token(&self, token: &Cus... | magicoder | rust |
You are tasked with implementing a function that serializes and deserializes Pandas Series objects using a custom serialization format. The custom serialization format is implemented using the `dumps` and `loads` functions, which are not part of the standard Pandas library. The `dumps` function serializes a Pandas Seri... | ```python
import pandas as pd
import numpy as np
import json
def dumps(series, primitives=False, allow_nan=False):
if primitives:
data = series.values.tolist()
else:
data = series.to_dict()
serialized = {
"name": series.name,
"data": data,
"dtype": str(series.dtype),... | magicoder | python |
You are tasked with implementing a function that processes and boxes constant values based on their field type. The function takes in an `ehx` parameter, which is a reference to some context, and a `field_value` parameter, which represents the value of a field. The function should handle different field types and box t... | ```rust
use std::any::Any;
enum FieldType {
Char,
InternedSym,
// Add other field types as needed
}
struct boxed {
// Define the Char and Sym structs as needed
}
impl boxed {
fn downcast_ref<T: 'static>(&self) -> Option<&T> {
self.0.downcast_ref()
}
}
struct InternedSym;
fn value_to... | magicoder | rust |
You are given a list of candidate numbers `candidates` and a target number `target`. Your task is to write a function `combinationSum` that finds all unique combinations of numbers in `candidates` that sum up to the `target` number. Each number in `candidates` may be used an unlimited number of times.
The function sho... | ```python
from typing import List
def combinationSum(candidates: List[int], target: int) -> List[List[int]]:
def backtracking(start_index, candidates, remain, sub_solution, solution):
if remain == 0:
solution.append(sub_solution[:]) # Append a copy of sub_solution to the solution list
... | magicoder | python |
You are tasked with creating a program that processes LTL (Linear Temporal Logic) formulas and automata using command-line tools. Your program will take an LTL formula as input, remove weak fairness constraints, convert the formula to a non-deterministic Büchi automaton (NBA), and then minimize the NBA to a determinist... | ```python
import subprocess
def remove_weak_fairness_constraints(ltl_formula):
# Remove weak fairness constraints from the LTL formula
ltlfilt_cmd = f"$ltlfilt --remove-wm -f '{ltl_formula}' -l"
result = subprocess.check_output(ltlfilt_cmd, shell=True)
return result.decode('utf-8').strip()
def convert... | magicoder | python |
You are tasked with implementing a class that performs image processing operations on a given OpenCV matrix (`cv::Mat`). The class should provide functionality to perform padding on the input image matrix with specified padding values and then calculate the mean squared error (MSE) between the original and padded image... | ```cpp
#include <opencv2/opencv.hpp>
class ImageProcessor {
int height;
int width;
cv::Mat mat;
double maxMSE;
double maxEpoch;
int bottom_padding;
int top_padding;
int left_padding;
int right_padding;
public:
ImageProcessor(int h, int w, const cv::Mat& m, double max_mse, double... | magicoder | cpp |
You are tasked with implementing a Python function that generates test data for a machine learning experiment. The function takes several parameters and produces a dataset for training and testing a model. Your task is to create a function that fulfills the requirements specified below.
You are given a code snippet th... | ```python
import torch
def generate_test_data(problem_str, noisy, init_seed, gen_methods, kernel, comp_noise_type, device="cpu"):
# Validate input parameters
if not isinstance(problem_str, str):
raise ValueError("problem_str must be a string")
if not isinstance(noisy, bool):
raise ValueErro... | magicoder | python |
You are tasked with creating a program to parse and extract information from HTML code containing client ticker details. The HTML code snippet provided represents a client ticker information section, and you need to extract specific details from it.
Your task is to write a function or method that takes the HTML code a... | ```python
from bs4 import BeautifulSoup
def extract_client_ticker_info(html_code):
# Parse the HTML code using BeautifulSoup
soup = BeautifulSoup(html_code, 'html.parser')
# Find the div with class 'info_tiker' to extract client ticker details
info_ticker_div = soup.find('div', class_='info_tiker'... | magicoder | python |
You are tasked with simulating a simplified transaction processing system for a digital currency. The system consists of two balance pools: `receivingPool` and `fromIotaPool`. The `receivingPool` is responsible for receiving balances from external sources, while the `fromIotaPool` is used for internal transactions with... | ```java
class BalancePool {
int balance;
public BalancePool(int balance) {
this.balance = balance;
}
public BalancePool takeBalance(int amount) {
if (balance >= amount) {
balance -= amount;
return new BalancePool(amount);
} else {
return null... | magicoder | java |
You are tasked with implementing a Python function that generates unique hashes for different package versions. The function should take a package requirement in the format "package_name==version" and return a set of unique hashes for that package version. Additionally, the function should ensure that the generated has... | ```python
import hashlib
class Repository:
def __init__(self):
self.generated_hashes = set()
def get_hashes(self, package_requirement):
unique_hash = hashlib.sha256(package_requirement.encode()).hexdigest()
if unique_hash in self.generated_hashes:
# If the hash already exis... | magicoder | python |
You are tasked with creating a Python program to analyze options data from Yahoo Finance. The program should utilize the `getYahooData` module to retrieve options data and identify the best selection based on certain criteria.
The `getYahooData` module provides two main functions:
1. `getOptionsData`: This function ta... | ```python
import getYahooData as yd
# Retrieve options data
threshold = 0.9
max_price = 7500
finalFrame, bestSelection = yd.getOptionsData(threshold, max_price)
# Identify the best selection of options
# Assuming bestSelection contains the best options based on certain criteria
# Perform further analysis or filtering... | magicoder | python |
You are tasked with implementing a caching mechanism for the CAM16 color conversion process in a viewing conditions class. The CAM16 color model is used to accurately represent colors under different lighting conditions. The provided code snippet is a TypeScript class `ViewingConditions` that includes a static method `... | ```typescript
export class ViewingConditions {
private static cache: Map<string, IntermediateValues> = new Map();
static DEFAULT = ViewingConditions.make();
private constructor(private illuminance: number, private surround: string) {}
static make(illuminance: number = 500, surround: string = 'dim') {
con... | magicoder | typescript |
You are working on a grading system for a programming assignment submission platform. The code snippet provided is a part of the backend logic for grading a submission and updating the overall score for a user's submission.
The code snippet is from a method that is called when a user submits their solution to a progra... | ```python
class Grader:
def __init__(self, task_number, task_data):
self.task_number = task_number
self.task_data = task_data
self.score = Score() # Assume Score class is defined
def grade_task(self, submitted_text: str) -> int:
# Example grading logic: Counting the number of o... | magicoder | python |
You are tasked with implementing a device management system for a company that manufactures electronic devices. The system is responsible for retrieving and validating properties of target devices. The code snippet provided is a part of the device management system and contains a method that is used to retrieve the pro... | ```python
if sig != self._dev.signature:
raise DWException("Invalid signature for device '{0}'.".format(self.device_id))
```
In the provided code snippet, the missing part of the method is to raise a `DWException` if the signature of the target device does not match the expected sign... | magicoder | python |
You are tasked with implementing a function to compare and plot simulation results from three different power system simulation tools: ANDES, TSAT, and PSS/E. The function should take in various parameters and generate a plot for comparison.
You are given a code snippet that outlines the beginning of the function. You... | ```python
import matplotlib.pyplot as plt
def compare_and_plot_results(variable, system, a, a_tsat=None, a_psse=None, legend=True, title=None):
"""
Plot and compare ANDES, TSAT and PSS/E results.
Parameters:
variable (str): The variable to be plotted.
system (object): The power system object c... | magicoder | python |
You are tasked with creating a Python class for signal processing that includes methods for common signal processing operations. The class should be able to handle audio signals with a specific sample rate and provide functionality for operations such as resampling, filtering, and time-domain analysis.
Your task is to... | ```python
import numpy as np
import scipy.signal
class SignalProcessor:
def __init__(self, sample_rate):
self.sample_rate = sample_rate
# Assume signal is initialized here
def resample(self, new_sample_rate):
# Implement resampling logic using scipy.signal.resample
# resampled_... | magicoder | python |
You are tasked with implementing a C++ class that manages chunks of a game world in a Minecraft Pocket Edition (MCPE) server. The provided code snippet is a partial declaration of the `ChunkSource` class, which includes a method `getLevel` that returns a constant reference to a `Level` object. Your task is to complete ... | ```cpp
#pragma once
#include <mcpe\Level.hpp>
#include <unordered_map>
class Chunk {
// Define the Chunk class to represent a chunk of the game world
// Include necessary fields and methods to store chunk data
};
class ChunkSource {
public:
// Implement a suitable data structure to store and manage chunk... | magicoder | cpp |
You are tasked with creating a Python function that simulates the behavior of the `run` method of a custom `ComposeExecutor` class. The `run` method takes a list of command-line arguments and a dictionary of keyword arguments, and executes a command using the provided arguments.
You need to implement the `run` method ... | ```python
import subprocess
class ComposeExecutor:
def run(self, compose_cmd, compose_args, process_kwargs):
return subprocess.run([compose_cmd, *compose_args], **process_kwargs, capture_output=True, text=True).stdout
```
In the solution, we define a class `ComposeExecutor` with a method `run` that uses t... | magicoder | python |
You are tasked with creating a simple Java Spring Boot application for a banking system. The application should handle basic account management functionalities such as creating accounts, depositing funds, and withdrawing funds. Additionally, the application should utilize the Axon Framework for implementing CQRS (Comma... | ```java
import org.axonframework.commandhandling.CommandBus;
import org.axonframework.commandhandling.gateway.CommandGateway;
import org.axonframework.config.Configuration;
import org.axonframework.config.DefaultConfigurer;
import org.axonframework.eventsourcing.eventstore.inmemory.InMemoryEventStorageEngine;
import or... | magicoder | java |
You are tasked with creating a Python program that retrieves weather data using the OpenWeatherMap API and then uses the data to perform specific calculations. The program should handle the retrieval of weather data, processing the data, and performing calculations based on the weather information.
Your program should... | ```python
import requests
# OpenWeatherMap API Key
weather_api_key = "<KEY>"
def retrieve_weather_data(api_key, city):
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
response = requests.get(url)
if response.status_code == 200:
return response.json()
... | magicoder | python |
You are tasked with creating a C++ function that parses user-agent strings to extract device family and operating system information. The function will take a vector of user-agent strings and the location of a YAML file containing regular expressions for parsing user-agent strings. The function should use the `ua_parse... | ```cpp
//'@export
// [[Rcpp::export]]
DataFrame c_ua_parse(std::vector < std::string > agents, std::string yaml_file_loc) {
//Load regex file
ua_parser::Parser uap(yaml_file_loc);
//Measure input size, create output objects
int agents_size = agents.size();
std::vector < std::string > device_family(agent... | magicoder | cpp |
You are given a function `isPrime` that takes an integer `n` as input and returns a boolean value indicating whether `n` is a prime number or not. However, the implementation of the `isPrime` function is incomplete and returns `false` by default. Your task is to complete the `isPrime` function to accurately determine w... | ```java
public static boolean isPrime(int n) {
if (n <= 1) {
return false; // 1 and numbers less than 1 are not prime
}
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false; // If n is divisible by any number between 2 and sqrt(n), it's not prime
}
... | magicoder | java |
You are tasked with creating a function that processes and validates a booking request for a transportation service. The function will take in a JavaScript object representing the booking request and perform various checks to ensure the request is valid. The booking request object will contain the following properties:... | ```javascript
function validateBookingRequest(bookingRequest) {
// Check if passengers is a positive integer
if (typeof bookingRequest.passengers !== 'number' || bookingRequest.passengers <= 0 || !Number.isInteger(bookingRequest.passengers)) {
return false;
}
// Check if from and to dates are valid JavaScr... | magicoder | javascript |
You are tasked with creating a Rust library that provides functionality for converting timestamps between different time zones. The library should utilize the `time` crate for handling date and time operations and should expose a `convert_timestamp` function that takes a timestamp in one time zone and converts it to an... | ```rust
pub mod time_converter {
use crate::TimeZone;
use time::{OffsetDateTime, Duration, format_description::well_known::Rfc3339, format_description::parse};
pub fn convert_timestamp(timestamp: &str, from_timezone: TimeZone, to_timezone: TimeZone) -> Result<String, String> {
let format = Rfc3339;... | magicoder | rust |
You are working as a system administrator for a company that uses a custom deployment script to manage its web applications. The script is responsible for removing old versions of applications and their associated databases before deploying new versions. The script takes several parameters, including the directory path... | ```python
import os
import subprocess
def deployment_script(directory_path: str, database_name: str, db_username: str, db_password: str, app_version: str, file_name: str) -> None:
# Remove directory and database
try:
os.system(f"rm -rf {directory_path}/{database_name}")
print(f"Directory {direc... | magicoder | python |
You are given a Python code snippet that defines a function `hello_world`. The function takes a parameter `name` and returns a greeting message. If the `name` is not `None`, it returns "Hello " followed by the `name`. Otherwise, it returns "Hello world!". Additionally, there is a conditional check to run the `hello_wor... | ```python
def hello_world(name, language='English'):
greetings = {
'English': 'Hello',
'Spanish': 'Hola',
'French': 'Bonjour',
'German': 'Guten Tag'
}
if name is not None:
if language in greetings:
return f'{greetings[language]} {name}'
else:
... | magicoder | python |
You are tasked with implementing a username generator function for a web application. The function should take an original username and a counter as input and generate a new username by appending the counter to the original username if the original username is already taken. The function should then check if the genera... | ```python
def generate_username(original_username, counter):
while True:
if counter == 0:
username = original_username
else:
username = original_username + str(counter)
if not User.objects.filter(username=username).exists():
return username
counte... | magicoder | python |
You are tasked with creating a test suite for an event management system using Python's `unittest` framework. The system interacts with a RESTful API to perform CRUD operations on events. The code snippet provided is a part of the test suite and includes three test methods: `test_create`, `test_get_one`, and `test_get_... | ```python
import unittest
from uuid import uuid4
class EventAPITestCase(unittest.TestCase):
def setUp(self):
# Initialize the RESTful API client and event details
self.client = APIClient() # Replace with actual API client
self.record = {
"id": None, # Will be updated after cre... | magicoder | python |
You are tasked with implementing a function to process a series of instructions and states in a graph-based system. The function should take a list of instructions and a list of states as input and return a list of subgraphs, each representing a valid directed acyclic graph (DAG) formed by a subset of the instructions ... | ```python
def is_valid_dag(instructions):
# Implement a function to check if the given instructions form a valid DAG
pass
def prune_and_reference(instructions):
# Implement a function to prune the invalid instructions and return the pruned subset
pass
def process_subgraphs(instructions, states):
s... | magicoder | python |
You are tasked with implementing a training loop for a generative adversarial network (GAN). The given code snippet is a part of the training process for the generator in the GAN. The while loop condition checks if the sum of the generator loss (g_loss) and the discriminator's loss (r_loss) is greater than 0.8. If the ... | ```python
class GAN:
def __init__(self):
# Initialize GAN components and parameters
def _generate_batch(self, batch_size):
# Implement the method to generate a batch of images
# This method should return a batch of generated images
def train_generator(self, batch_size):
whi... | magicoder | python |
You are given a sequence of integers and a target sum. Your task is to write a function that finds all pairs of integers in the sequence that sum up to the target sum. Each pair should be unique and the order of the pairs does not matter.
For example, given the sequence [1, 3, 2, 2] and the target sum 4, the function ... | ```python
def find_pairs(sequence, target_sum):
pairs = set()
seen = set()
for num in sequence:
complement = target_sum - num
if complement in seen:
pair = (min(num, complement), max(num, complement))
pairs.add(pair)
seen.add(num)
return list(pai... | magicoder | python |
You are tasked with implementing a Pomodoro timer in Python. The Pomodoro Technique is a time management method developed by Francesco Cirillo in the late 1980s. It uses a timer to break work into intervals, traditionally 25 minutes in length, separated by short breaks. After a certain number of work intervals, a longe... | ```python
import time
import sys
def start_info():
print("Welcome to the Pomodoro Timer!")
def notify(duration):
time.sleep(duration * 60)
def pomodoro():
total_cycles = 0
work_intervals = 4 # Number of work intervals before a long break
while True:
start_info()
for i in range(wo... | magicoder | python |
You are tasked with implementing a Huffman coding algorithm to compress a given input string. Huffman coding is a widely used algorithm for lossless data compression. It works by assigning variable-length codes to input characters, with shorter codes assigned to more frequent characters. Your task is to write a functio... | ```rust
use std::collections::HashMap;
// Define a struct to represent a node in the Huffman tree
struct Node {
character: Option<char>,
frequency: usize,
left: Option<Box<Node>>,
right: Option<Box<Node>>,
}
// Function to build a mapping of characters to their respective Huffman codes
pub fn gen_map_... | magicoder | rust |
You are tasked with implementing a function to merge group packages in a script. The script contains two function calls to `mergeGroupPackages` with different arguments. The function `mergeGroupPackages` takes four arguments: a function (`getUniquePackages` or `getCommonPackages`), a collection group (`collgrp`), a scr... | The `mergeGroupPackages` function takes four arguments: a function, a collection group, a script, and a set of seen targets. It merges the group packages based on the provided function and updates the `script.parts` and `script.packages` accordingly.
Here's a possible implementation of the `mergeGroupPackages` functio... | magicoder | python |
You are tasked with implementing a Python function that performs a specific operation on a given graph. The function takes a binary operation as an argument and applies it to the message passed between nodes in the graph. Your task is to complete the implementation of the function by filling in the missing parts.
You ... | ```python
import torch
import dgl
def spmm_function(binary_op):
"""
Generalized SpMM function. Applies a binary operation on source nodes' features and edge features.
Then aggregates the message by the binary_op on destination nodes.
Parameters
----------
g : DGLHeteroGraph
The input g... | magicoder | python |
You are working on a computer vision project and need to implement a non-maximum suppression (NMS) algorithm for object detection. NMS is a technique used to filter out overlapping bounding boxes based on their confidence scores. Given a set of bounding boxes and their associated confidence scores, you are tasked with ... | ```python
from typing import List
def calculate_iou(box1, box2):
# Calculate the intersection over union (IoU) of two bounding boxes
x1 = max(box1[0], box2[0])
y1 = max(box1[1], box2[1])
x2 = min(box1[2], box2[2])
y2 = min(box1[3], box2[3])
intersection = max(0, x2 - x1) * max(0, y2 - y1)
... | magicoder | python |
You are tasked with implementing a Dice class in Swift that simulates the behavior of a standard six-sided die. The class should have methods to roll the die and retrieve the result of the roll. Additionally, the class should keep track of the number of times the die has been rolled and the frequency of each outcome.
... | ```swift
import XCTest
@testable import DiceApp
class DiceTests: XCTestCase {
func testRoll() {
let dice = Dice()
var rollResults = Set<Int>()
for _ in 1...1000 {
let result = dice.roll()
XCTAssertTrue((1...6).contains(result), "The result of the roll should be betwe... | magicoder | swift |
You are tasked with creating a program that analyzes a given text file to count the occurrences of specific license-related terms. The program should read the text file and identify the number of times the following terms appear: "http://www.apache.org/licenses/LICENSE-2.0.txt", "License", "WARRANTIES", "conditions", "... | ```python
def count_license_terms(file_path):
terms_to_count = [
"http://www.apache.org/licenses/LICENSE-2.0.txt",
"License",
"WARRANTIES",
"conditions",
"limitations",
"License for the specific language"
]
term_counts = {term: 0 for term in terms_to_count}
... | magicoder | python |
You are tasked with implementing a function that writes data to a CSV file using the `csv` module in Python. The function should take a list of dictionaries representing records, a file path, optional field names, and a verbosity flag. If the field names are not provided, the function should use the keys of the first d... | ```python
from typing import List, Optional
import csv
def write_records_to_csv(fp: str, records: List[dict],
fieldnames: Optional[List[str]] = None,
verbose: bool = False) -> None:
if fieldnames is None:
if records:
fieldnames = list(records[0]... | magicoder | python |
You are tasked with designing a fault-tolerant routing system for a network of US carriers. The network consists of multiple links connecting different carriers, and the goal is to ensure that a single prefix can be routed through the network even if some links fail. The network is represented by a collection of files,... | ```python
import os
def minLinksForFaultTolerance(directoryPath: str) -> int:
min_links = float('inf')
for filename in os.listdir(directoryPath):
with open(os.path.join(directoryPath, filename), 'r') as file:
fault_tolerance = int(file.read().strip())
min_links = min(min_links, ... | magicoder | python |
You are tasked with creating a program that simulates a package management system for a Linux-based operating system. The program should be able to handle the installation and removal of packages, as well as provide a list of installed packages.
Your task is to implement a class `PackageManagementSystem` with the foll... | ```python
from typing import List
class PackageManagementSystem:
def __init__(self):
self.installed_packages = []
def install(self, package_name: str) -> None:
if package_name in self.installed_packages:
print(f"Package {package_name} is already installed.")
else:
... | magicoder | python |
You are tasked with implementing a custom comparison method for a data structure representing geometric points in a 2D plane. The data structure is defined as follows:
```rust
struct Point {
x: f64,
y: f64,
}
```
You need to implement the `relative_ne` method for the `Point` struct, which compares two points ... | ```rust
impl Point {
fn relative_ne(&self, other: &Self) -> bool {
!self.relative_eq(other)
}
}
```
The `relative_ne` method simply negates the result of the `relative_eq` method, effectively returning `true` if the two points are not relatively equal, and `false` if they are relatively equal. This imp... | magicoder | rust |
You are tasked with implementing a function that calculates the average execution time of a given function over a specified number of iterations. You are provided with a code snippet that includes a test function and a performance test function. Your task is to create a function that measures the average execution time... | ```swift
import XCTest
func averageExecutionTime(_ function: () -> Void, iterations: Int) -> Double {
let startTime = CFAbsoluteTimeGetCurrent()
for _ in 0..<iterations {
function()
}
let endTime = CFAbsoluteTimeGetCurrent()
let totalTime = endTime - startTime
return totalTime / Double(... | magicoder | swift |
You are tasked with implementing a file management system for a web application. The system should allow users to upload, view, and delete files. The code snippet provided is a part of the file deletion functionality in the backend of the application. The snippet is written in PHP using the Laravel framework.
The `$tr... | ```php
public function deleteFile($fileId)
{
// Find the file by its unique identifier (e.g., file ID or name)
$transparencia = File::find($fileId);
if ($transparencia) {
// Delete the file from the system
$transparencia->delete();
// Redirect back with a success message
re... | magicoder | php |
You are tasked with simulating the behavior of a simple accelerometer-based tilt sensor using Python. The accelerometer provides three-axis readings (x, y, z) representing the orientation of the device. Your goal is to create a program that visualizes the tilt of the device by moving a pointer on a compass dial display... | ```python
# Initialize the accelerometer and screen
acc = Accelerometer() # Assuming Accelerometer class is available
ssd = Screen() # Assuming Screen class is available
# Define the filtered_xyz() method of the accelerometer
def filtered_xyz():
# Implementation of filtering algorithm to obtain filtered x, y, an... | magicoder | python |
You are tasked with implementing a simple event handling system in C#. Your goal is to create a class that allows other classes to subscribe to and trigger events. You should implement the event subscription mechanism and the event triggering functionality.
Your task is to create a class called `EventManager` with the... | ```csharp
using System;
public class EventManager
{
private event Action Event;
public void Subscribe(Action action)
{
Event += action;
}
public void Unsubscribe(Action action)
{
Event -= action;
}
public void Trigger()
{
Event?.Invoke();
}
}
public c... | magicoder | csharp |
You are tasked with creating a script to automate the setup of a Vim environment for Go programming. The script should download necessary files and place them in the appropriate directories.
Write a Bash script that accomplishes the following tasks:
1. Create a directory structure for Vim if it does not exist: `~/.vim... | ```bash
#!/usr/bin/env bash
# Create directory structure if it does not exist
mkdir -p ~/.vim/{autoload,ftplugin}
# Copy files to appropriate directories
cp autoload/gocomplete.vim ~/.vim/autoload
cp ftplugin/go.vim ~/.vim/ftplugin
```
This Bash script first creates the necessary directory structure using the `mkdir ... | magicoder | shell |
You are tasked with implementing a function that processes a list of tuples representing data entries. Each tuple contains two elements: a code and a name. Your goal is to create a dictionary where the code serves as the key and the name as the value. However, the given list may contain duplicate entries, and you shoul... | ```python
def process_data_entries(data):
code_count = {}
result = {}
for code, name in data:
if code in code_count:
code_count[code] += 1
else:
code_count[code] = 1
if code_count[code] > 1:
key = f"{code}_{code_count[code]}"
... | magicoder | python |
You are tasked with implementing a function to test the synchronization of an Electrically Excited Synchronous Permanent Magnet Motor (EEC PMSM). The motor is controlled by a control system, and the synchronization of the motor is crucial for its proper operation. The provided code snippet calls a function `test_EEC_PM... | ```python
def test_EEC_PMSM_sync_rel():
# Perform the synchronization test
# Assume that the necessary hardware interfaces and control system components are accessible
# Simulate the synchronization test result (replace this with actual synchronization test logic)
synchronization_passed = True # Place... | magicoder | python |
You are tasked with implementing a function that loads specific images from the MNIST dataset and returns them as a NumPy array. The function takes in the path to the folder containing the MNIST images and a list of image numbers to load. The images are expected to be in a 3x32x32 format.
You need to implement the `lo... | ```python
import numpy as np
import os
from PIL import Image
def load_mnist_images(path, img_nums):
images = []
for num in img_nums:
image_path = os.path.join(path, f"{num}.png")
img = Image.open(image_path)
img = img.resize((32, 32))
img_array = np.array(img)
if len(img... | magicoder | python |
You are working on a project that involves visualizing 2D data using a Python library called `visvis` (vv). The code snippet provided is a part of the visualization process. In this snippet, `a` is an object representing the axes properties, and `vv` is the visualization module. The code sets certain properties for the... | ```python
import visvis as vv
def generate_2D_visualization(data_points, properties):
a = vv.gca()
a.daspectAuto = False
a.axis.showGrid = True
vv.title(properties.get('title', ''))
vv.xlabel(properties.get('x_label', 'x'))
vv.ylabel(properties.get('y_label', 'y'))
for point in data_po... | magicoder | python |
You are tasked with implementing a Python class that interacts with a database using SQLAlchemy. The provided code snippet shows the beginning of a class named `SolutionModel` which is intended to serve as a model for interacting with a database table. Your task is to complete the implementation of the `SolutionModel` ... | ```python
try:
from db.driver import Base, Session, engine
except ModuleNotFoundError:
from puzzle.db.driver import Base, Session, engine
class SolutionModel(Base):
__tablename__ = 'solution_model'
id = Column(Integer, primary_key=True)
# Add other relevant attributes here
def __init__(self, ... | magicoder | python |
You are tasked with implementing a Java class that validates data stored in an HBase table. The HBase table contains various types of data, including strings, integers, and timestamps. Your task is to create a validator class that can check the integrity and correctness of the data stored in the HBase table.
Your vali... | ```java
package com.booking.validator.data.hbase;
import java.time.Instant;
public class HBaseDataValidator {
// Validate string data
public boolean validateStringData(String input, int maxLength) {
return input != null && !input.isEmpty() && input.length() <= maxLength;
}
// Validate integer... | magicoder | java |
You are tasked with creating a script to automate the process of cloning a GitHub repository and installing its dependencies using the yarn package manager. Your script should be able to handle potential errors and provide appropriate feedback to the user.
Write a shell script named `clone_and_install.sh` that takes a... | ```bash
#!/bin/bash
# Check if the required commands are available
if ! command -v git &> /dev/null || ! command -v yarn &> /dev/null; then
echo "Error: Git or Yarn is not installed. Please make sure both are installed and in the system's PATH." >&2
exit 1
fi
# Validate input
if [ -z "$1" ]; then
echo "Error: G... | magicoder | shell |
You are tasked with implementing a command parser for a TURRIS:DONGLE, a device used for sending commands to various gadgets. The TURRIS:DONGLE accepts commands in the format "ACTION TARGET [VALUE]", where ACTION is the operation to be performed, TARGET is the specific gadget or slot, and VALUE is an optional parameter... | ```python
import re
def execute_command(command: str) -> str:
action, target, value = re.match(r'(\w+) (\w+)(?: \[(\w+)\])?', command).groups()
if action == "GET":
return f"SENDING: {command}\nREPLY: {target} [07473725]"
elif action == "SET":
return f"SENDING: {command}"
else:
r... | magicoder | python |
You are tasked with implementing a program to read and process the header of a grid from an input stream. The grid header contains information about the dimensions and properties of the grid. The grid header is defined by the following structure:
```cpp
struct GridHeader {
int rows;
int columns;
bool hasBo... | ```cpp
#include <iostream>
struct GridHeader {
int rows;
int columns;
bool hasBorder;
};
GridHeader read_grid_header(std::istream& is)
{
GridHeader header;
is >> header.rows >> header.columns;
int border;
is >> border;
header.hasBorder = (border == 1);
return header;
}
``` | magicoder | cpp |
You are tasked with creating a plugin for a mobile application that interacts with the device's file system. The plugin contains a method `getUri` which takes a path as a parameter and retrieves the corresponding URI for the file or directory located at that path. However, the plugin's code snippet is incomplete and re... | ```java
@PluginMethod
public void getUri(PluginCall call) {
String path = call.getString("path");
String directory = getDirectoryParameter(call);
try {
File file = new File(path);
if (file.exists()) {
Uri uri = Uri.fromFile(file);
call.resolve(uri.toString());
... | magicoder | java |
You are tasked with creating a program that analyzes a given CSS file and identifies the selectors and their corresponding properties. For this problem, you need to focus on extracting the selectors and their properties from the CSS file.
Write a function `extractSelectorsAndProperties(css)` that takes a string `css` ... | ```python
import re
def extractSelectorsAndProperties(css):
selector_property_dict = {}
selector = ""
properties = []
lines = css.split("\n")
for line in lines:
line = line.strip()
if line and not line.startswith("//") and not line.startswith("/*"):
if line.endswith("{"... | magicoder | python |
You are tasked with implementing a trait for a buffer type in a graphics library. The trait, `Usage`, specifies the memory usage and flags for different buffer types. Your goal is to implement the `Usage` trait for a new buffer type called `UniformBuffer`. The `UniformBuffer` is intended to be used as a uniform buffer,... | ```rust
/// Trait specifying memory usage and flags for buffer types.
pub trait Usage {
type MemoryUsage: MemoryUsage;
fn flags(&self) -> gfx_hal::buffer::Usage;
}
/// Type that specify that buffer is intended to be used as uniform buffer.
/// Host visible memory required and device-local preferred.
#[der... | magicoder | rust |
You are tasked with creating a Python function that simulates a simple text-based adventure game. The game will involve the player navigating through a series of rooms, making decisions, and encountering various challenges. Each room will have specific descriptions and potential actions the player can take. The player'... | ```python
def adventure_game():
rooms = {
"start": {
"description": "You are in a dimly lit hallway.",
"actions": ["go left", "go right"],
"next_room": {
"go left": "kitchen",
"go right": "living_room"
}
},
"kitc... | magicoder | python |
You are tasked with implementing a method to check if a given string is a valid UTF-8 encoded string. UTF-8 is a variable-width character encoding capable of encoding all 1,112,064 valid code points in Unicode using one to four one-byte (8-bit) code units. The encoding is defined by the Unicode standard and is widely u... | ```rust
impl String {
fn is_valid_utf8(&self) -> bool {
let mut bytes = self.as_bytes().iter().peekable();
while let Some(&b) = bytes.next() {
let num_bytes = match b {
0..=127 => continue,
192..=223 => 2,
224..=239 => 3,
... | magicoder | rust |
You are tasked with implementing a generic Top-K provider for a search engine. The Top-K provider is responsible for retrieving the top K documents that satisfy a given condition for a segment. The condition for a segment is defined by the type `C`, and the Top-K provider uses a scorer for the segment to rank the docum... | ```rust
use std::cmp::Reverse;
use std::collections::BinaryHeap;
pub trait ConditionForSegment<T> {
fn satisfies_condition(&self, document: &T) -> bool;
}
pub trait ScorerForSegment<T, DocId> {
fn score_document(&self, document: &T) -> i32;
fn get_document_id(&self, document: &T) -> DocId;
}
pub struct T... | magicoder | rust |
You are given a snippet of code that manipulates a string `s` based on the first character. The snippet checks if the first character of the string is either `'-'` or `'+'`. If it is `'-'`, the variable `negative` is set to `true`. If it is `'+'`, the first character is removed from the string, and the variable `n` is ... | ```java
public void manipulateString(char[] s, int n) {
if (s[0] == '-') {
negative = true;
} else if (s[0] == '+') {
for (int i = 0; i < n - 1; i++) {
s[i] = s[i + 1];
}
n--;
}
}
``` | magicoder | java |
You are tasked with creating a Python function that manages the execution of multiple subprocesses in parallel while ensuring they do not conflict with each other. The function should generate a unique temporary directory for each subprocess and execute the subprocess within that directory. The function should take a l... | ```python
import os
import subprocess
import uuid
from tempfile import TemporaryDirectory
def execute_subprocesses(subprocess_commands, base_temp_dir):
results = []
for index, args in enumerate(subprocess_commands):
call_id = str(uuid.uuid4())
tmp_dir_name = os.path.join(base_temp_dir, f"test-{... | magicoder | python |
You are tasked with implementing a token-based authentication system for a web service. The system should generate a secure authentication token and provide a mechanism to validate and decode the token.
You are provided with a code snippet that sets up the initial parameters for the authentication process. The `audien... | ```python
import secrets
import jwt
class AuthenticationHandler:
@staticmethod
def generate_auth_token(roles, secret):
token = jwt.encode(roles, secret, algorithm='HS256')
return token
@staticmethod
def validate_and_decode_token(token, key, audience):
try:
decoded_t... | magicoder | python |
You are tasked with implementing a custom set data structure in Python. The set should support the following operations:
1. `add(element)`: Add the specified element to the set.
2. `remove(element)`: Remove the specified element from the set if it exists.
3. `contains(element)`: Check if the set contains the specified ... | ```python
from enum import Enum, auto
class set_return(Enum):
COMMON_SET = auto()
class Set:
def __init__(self):
self.elements = set()
def add(self, element):
self.elements.add(element)
def remove(self, element):
self.elements.discard(element)
def contains(self, element)... | magicoder | python |
You are working for a restaurant management system, and you have been tasked with optimizing the function `get_active_orders(table)` which retrieves active orders for a given table. The function currently performs client-side filtering, but the goal is to improve its efficiency by querying the database for the active o... | ```python
from typing import List, Tuple, Dict
import database # Assume the existence of a database connection and necessary querying functions
def get_active_orders(table: int) -> List[Dict[str, str]]:
active_orders = database.query("SELECT item_name, quantity, additional_details FROM orders WHERE table_number =... | magicoder | python |
You are tasked with implementing a specialized stack data structure that supports the following operations: push, pop, and peek. Additionally, the stack should have a method to retrieve the minimum value currently present in the stack. The stack should efficiently handle these operations in O(1) time complexity.
You a... | ```javascript
class MinStack {
constructor() {
this.stack = [];
this.minStack = [];
}
push(x) {
this.stack.push(x);
if (this.minStack.length === 0 || x <= this.minStack[this.minStack.length - 1]) {
this.minStack.push(x);
}
}
pop() {
if (t... | magicoder | javascript |
You are tasked with creating a Python function that simulates a simple authentication system using OAuth2. Your function should take in user credentials in the form of an email and password, authenticate the user, and return the corresponding user object if the authentication is successful. Additionally, the function s... | ```python
from typing import Optional
class User:
def __init__(self, email, password_hash):
self.email = email
self.password_hash = password_hash
def upgrade_password_hash(self, new_hash):
self.password_hash = new_hash
def authenticate_user(email: str, password: str) -> Optional[U... | 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 find the maximum possible profit from buying and selling a single share of that stock. If no profit is possible, return 0.
For example, given the stock prices [7, 1, 5, 3, 6, 4], the maximum profit th... | ```python
def max_profit(prices):
if not prices:
return 0
max_profit = 0
min_price = prices[0]
for price in prices:
if price < min_price:
min_price = price
else:
max_profit = max(max_profit, price - min_price)
return max_profit
``` | magicoder | python |
You are tasked with creating a Python program that processes a text file containing a list of words and their frequencies, and then generates a histogram representing the frequency distribution of the words. The program should take the input file name as a command-line argument and produce the histogram as output.
The... | ```python
import sys
def generate_histogram(input_file):
try:
with open(input_file, 'r') as file:
word_freq = [line.strip().split() for line in file.readlines()]
for word, freq in word_freq:
print(f"{word.ljust(10)} {'*' * int(freq)}")
except FileNotFoundError:
... | magicoder | python |
You are working on a project that involves creating a custom editor for a document processing application. The application uses the ProseMirror library for managing the document's structure. You need to implement a new node type for representing list items in the document. The list item node should have specific conten... | ```typescript
import { NodeSpec } from "prosemirror-model";
interface EditorNode {
name: string;
nodeSpec: NodeSpec;
}
export class ListItemNode implements EditorNode {
readonly name = 'list_item';
readonly nodeSpec: NodeSpec = {
content: "paragraph block*",
parseDOM: [{ tag: "li" }],
toDOM() {
... | magicoder | typescript |
You are tasked with creating a program that performs a linear scan algorithm to flatten a nested list of integers. The linear scan algorithm involves iterating through the nested list and flattening it into a single list by preserving the order of elements.
You are provided with the following code snippet for inspirat... | ```rust
// flatten.rs
pub fn flatten_list(input: &[Vec<i32>]) -> Vec<i32> {
let mut result = Vec::new();
for item in input {
for &val in item {
result.push(val);
}
}
result
}
```
The `flatten_list` function takes a nested list of integers as input and iterates through each ... | magicoder | rust |
You are tasked with implementing a context manager in Python that suppresses the `FileNotFoundError` exception for a specific file. The context manager should be able to handle the opening and closing of the file, and it should suppress the `FileNotFoundError` if the specified file does not exist.
Your task is to comp... | ```python
import functools
import contextlib
class suppress_file_not_found(contextlib.AbstractContextManager):
def __init__(self, filename):
self.filename = filename
def __enter__(self):
self.file = open(self.filename, 'r')
return self.file
def __exit__(self, exc_type, exc_value, ... | magicoder | python |
You are tasked with implementing a simplified version of a stack-based interpreter for a custom programming language. The interpreter will process a series of conditional statements and execute the appropriate code blocks based on the conditions. The interpreter supports the following conditional keywords: "if", "elsei... | ```python
from typing import List
def process_conditionals(code: List[str]) -> str:
stack = []
for line in code:
if line.startswith('if'):
stack.append('if')
elif line.startswith('elseif'):
stack.pop(-1)
stack.append('elseif')
elif line.startswith('el... | magicoder | python |
You are given a 2D board and a word, and you need to determine if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
Write a function `exist(b... | ```python
def exist(board, word):
def dfs(i, j, k):
if not (0 <= i < len(board) and 0 <= j < len(board[0]) and board[i][j] == word[k]):
return False
if k == len(word) - 1:
return True
temp, board[i][j] = board[i][j], '/'
res = dfs(i + 1, j, k + 1) or dfs(i - 1... | magicoder | python |
You are tasked with creating a test for a file download functionality in a Rust application. The application uses the `isahc` and `httpmock` libraries for making HTTP requests and mocking server responses, respectively. Your goal is to write a test that verifies the correct behavior of the file download feature.
The t... | ```rust
use isahc::prelude::*;
use httpmock::{MockServer, Method, Mock, MockRef};
#[test]
fn file_body_test() {
// Arrange
let server = MockServer::start();
let expected_content = "Hello, world!";
let mock_response = Mock::new()
.expect_method(Method::GET)
.return_body(expected_content)... | magicoder | rust |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.