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 to generate a Discrete Fourier Transform (DFT) matrix of size N. The DFT matrix is a square matrix used in signal processing and other fields to perform the DFT operation on a sequence of values. The DFT matrix is defined as follows: \[ D_{jk} = \frac{1}{\sqrt{N}} e^{-2\pi i...
```python import numpy as np def generate_dft_matrix(N: int) -> np.ndarray: D = np.zeros((N, N), dtype=np.complex128) for j in range(N): for k in range(N): D[j, k] = 1 / np.sqrt(N) * np.exp(-2j * np.pi * j * k / N) return D ``` The `generate_dft_matrix` function initializes an empty co...
magicoder
python
You are given a PHP code snippet that manipulates a string variable `$txt` based on the value of a variable `$tst` and an attribute. Your task is to understand the code and write a function that replicates its behavior. You need to implement a function `extractSubstring($txt, $attribute)` that takes in a string `$txt`...
```php function extractSubstring($txt, $attribute) { $tst = 34; $ipos = _instr(0, $txt, " " . $attribute . "=" . chr($tst), 0); if ($ipos == 0) { $tst = 39; $ipos = _instr(0, $txt, " " . $attribute . "=" . chr($tst), 0); } if ($ipos != 0) { $txt = substr($txt, $ipos + strlen(...
magicoder
php
You are tasked with implementing a method to find an available port for a server application. The method should continuously search for an available port and return the first one it finds. Additionally, you need to ensure that the server application stops properly and the port becomes available again after the server i...
```java public int findAvailablePort() { int port; do { port = getNextPort(); } while (!isPortAvailable(port)); this.port.set(port); return port; } @Override protected void after() { super.after(); Spark.stop(); await().atMost(1, TimeUnit.SECONDS).pollDelay(100, TimeUnit.MILLISE...
magicoder
java
You are given a Python class representing a graph structure. The class contains a method `timerange` that infers edge timeranges from the graph structure. The method takes in two timestamps `t1` and `t2`, a boolean parameter `inside`, and an optional parameter `sort`. The method is intended to return a list of nodes th...
```python def timerange(self, t1, t2, inside=True, sort=None): inferred_nodes = [] for edge in self.edges_iter(data=True): if t1 <= edge[2]['timestamp'] <= t2: if inside: inferred_nodes.append(edge[0]) inferred_nodes.append(edge[1]) else: ...
magicoder
python
You are tasked with implementing a Python class for managing datasets used in machine learning. The class, named `Dataset`, is designed to handle labeled collections of data for training and testing purposes. The class has an `__init__` method for initializing the dataset with training and test data, a vocabulary, and ...
```python class LabelledCollection: def __init__(self, data, classes_): self.data = data self.classes_ = classes_ def split_stratified(self, train_prop): # Implementation not required for this problem pass class Dataset: def __init__(self, training: LabelledCollection, tes...
magicoder
python
You are tasked with implementing a deck of playing cards in a C# program. The deck should support adding and removing cards, as well as shuffling the deck. Each card has a suit (Hearts, Diamonds, Clubs, Spades) and a value (Two, Three, ..., Ten, Jack, Queen, King, Ace). Your task is to implement the `Deck` class with ...
```csharp using System; using System.Collections.Generic; public class Card { public enum CardValue { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace } public enum Suit { Hearts, Diamonds, Clubs, Spades } public CardValue Value { get; set; } public Suit Suit { get; set; } ...
magicoder
csharp
You are tasked with implementing a WebSocket client class in Python. The class should include methods for handling the opening and closing of the WebSocket connection, as well as a method for handling incoming messages. Additionally, the class should allow for sending messages over the WebSocket connection. Your task ...
```python import websocket class WebSocketClient: def __init__(self, url): self.url = url self.ws = None def _on_close(self, ws): self.onClose() def _on_open(self, ws): # Grab the websocket so we can use it to send later self.ws = ws self.onOpen() def ...
magicoder
python
You are tasked with creating a Python class that manages timezones and handles timezone-related errors. Your task is to implement a `TimezoneManager` class that inherits from the `TimezoneNotFound` exception class. The `TimezoneManager` class should have methods to add timezones, retrieve timezones, and raise a `Timezo...
```python from typing import List class TimezoneNotFound(FileNotFoundError): pass class TimezoneManager: def __init__(self): self.timezones = {} def add_timezone(self, name: str, offset: int): self.timezones[name] = offset def get_timezone_offset(self, name: str) -> int: if...
magicoder
python
You are tasked with implementing a class to manage and calculate the sums of various features in a system. The class `Feature` represents a specific feature, and the class `Sums` is responsible for storing and managing the sums of these features. The method `getFeatures()` returns a collection of all features, and the ...
```java import java.util.Collection; import java.util.HashMap; import java.util.Map; class Feature { // Implementation of the Feature class is not provided for this problem } class Sums { private Map<Feature, Double> featureSums; public Sums() { featureSums = new HashMap<>(); } public Co...
magicoder
java
You are tasked with implementing a Python function that extracts a subquery from a given SQL string based on its alias. The function should take two parameters: the SQL string and the alias of the subquery to be obtained. The SQL string may contain multiple subqueries, each with a unique alias. The function should retu...
```python import re def extract_subquery(sql_string, alias): # Using regular expression to find the subquery with the given alias pattern = r'(?<=\bAS\s)' + alias + r'\b.*?(?=\b\w+\b\s*\bAS\b|\Z)' match = re.search(pattern, sql_string, re.DOTALL) if match: return match.group(0).strip() ...
magicoder
python
You are tasked with implementing a program to analyze the connectivity of a network using the NetworkX library in Python. NetworkX is a popular library for creating, manipulating, and studying the structure, dynamics, and functions of complex networks. Your task is to write a Python function that takes in a graph and ...
```python import networkx as nx def count_nodes_within_radius(graph, radius): node_counts = {} for node in graph.nodes(): count = sum(1 for path_length in nx.single_source_shortest_path_length(graph, node).values() if path_length <= radius) node_counts[node] = count return node_counts ``` ...
magicoder
python
You are tasked with creating a Django view that handles the upload of images and videos to a web application. The view should validate the uploaded files and save them to the appropriate models in the database. The `Gallery` model is used to store images, while the `Video` model is used to store videos. You need to imp...
```python from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from .models import Gallery, Video @csrf_exempt def upload_media(request): if request.method == 'POST': if 'file' in request.FILES: uploaded_file = request.FILES['file'] if uploaded_f...
magicoder
python
You are tasked with implementing a file server that can send parts of a file to a client upon request. The server code snippet provided below is responsible for handling client requests and sending the requested file parts. Your task is to complete the server implementation by writing the missing parts of the code. Th...
```python import socket import os def send_file_part(directory, filename, size, msg, s): if os.path.exists(directory + "/" + filename): if msg["action"] == "get": if "part" in msg: with open(directory + "/" + filename, "rb") as input_file: input_file.seek(siz...
magicoder
python
You are tasked with implementing a class that simulates a simple neural network layer. The layer will have the ability to store and manipulate data in the form of blobs. A blob is a multi-dimensional array used to store and process data within the neural network. Your task is to implement the `NeuralNetworkLayer` clas...
```python import numpy as np class NeuralNetworkLayer: def __init__(self): self.blobs = [] def set_params(self, blobs): self.blobs = blobs def write(self, filename, integer): # Write blobs to file in a specific format # Implementation not provided as it is not relevant to ...
magicoder
python
You are tasked with implementing a custom smart pointer class similar to `boost::shared_ptr` using C++ templates. The custom smart pointer should provide reference counting and automatic memory management features. Your task is to complete the implementation of the `CustomSharedPtr` class, which should have the follow...
```cpp // Sample usage of the CustomSharedPtr class int main() { CustomSharedPtr<int> ptr1(new int(5)); CustomSharedPtr<int> ptr2 = ptr1; // Copy constructor called, reference count incremented std::cout << *ptr1 << std::endl; // Output: 5 std::cout << *ptr2 << std::endl; // Output: 5 *ptr1 = 10...
magicoder
cpp
You are tasked with simulating a simplified version of a Markov Chain Monte Carlo (MCMC) algorithm for sampling from a probability distribution. In this problem, you will implement a function to generate an initial set of MCMC walkers by perturbing an initial parameter set and checking if the perturbed parameters satis...
```python import numpy as np def generate_initial_walkers(p, nwalkers, ep, lnprior, vinfo, snobj): ndim = p.shape[0] p0 = [] fail = 0 while len(p0) < nwalkers and fail < 1000: pp = p + ep * np.random.randn(ndim) if not np.isinf(lnprior(pp, vinfo, snobj)): p0.append(pp) ...
magicoder
python
You are working on a project that involves simulating the evolution of a population of organisms. The code snippet provided is part of a Python program that uses a library called "pk3" to perform transformations on the population. The `transform_all` method is used to apply transformations to all individuals in the pop...
```python def simulate_and_verify_compounds(population, generations, expected_compounds): pk3.transform_all(max_generations=generations) # Simulate transformations for specified generations return len(population.compounds) == expected_compounds # Verify the number of compounds and return the result ```
magicoder
python
You are tasked with implementing a system for managing wallet accounts for trading and client purposes. The system involves creating wallet accounts for trades and clients, with specific attributes and relationships. Your task is to design a Django model for the wallet accounts and implement the necessary methods to en...
```python # Django model definition for TradeWalletAccount from django.db import models class TradeWalletAccount(models.Model): money = models.DecimalField(max_digits=10, decimal_places=2) trade = models.ForeignKey('Trade', on_delete=models.CASCADE) token = models.CharField(max_length=50, blank=True, null=...
magicoder
python
You are tasked with creating a function that generates configuration parameters for a calendar view in a mobile app. The function should take in various input parameters and return an object containing these parameters. The parameters include the start and end dates for the calendar, the number of rows to be displayed,...
```swift struct ConfigurationParameters { let startDate: Date let endDate: Date let numberOfRows: Int let calendar: Calendar let generateInDates: Bool let generateOutDates: Bool let firstDayOfWeek: Int let hasStrictBoundaries: Bool } func generateCalendarConfiguration(startDate: Date, ...
magicoder
swift
You are given a simple state machine with three states: 0, 1, and 2. The state machine transitions between states based on the input. The transition rules are as follows: - If the current state is 0 and the input is "A", transition to state 1. - If the current state is 0 and the input is "B", transition to state 2. - I...
```python def state_transition(current_state, input): if current_state == 0: if input == "A": return 1 elif input == "B": return 2 elif current_state == 1: if input == "A": return 0 elif input == "B": return 1 elif current_state...
magicoder
python
You are tasked with creating a Python function that organizes files into a destination directory based on a given playlist file. The function should take three parameters: `playlistfile` (string), `destpath` (string), and `filelist` (list of strings). The `playlistfile` represents the path to a playlist file containing...
```python import shutil from pathlib import Path, PurePath def get_folder(file): return Path(file).parent def organize_files(playlistfile, destpath, filelist): playlistloc = PurePath(playlistfile).parent for file in filelist: if file in open(playlistfile).read(): shutil.copy2(file, des...
magicoder
python
You are tasked with implementing a function that takes in a list of imports and declarations from an Angular module file and returns a list of unused imports. An import is considered unused if it is not referenced in any of the declarations. You are given the following code snippet as an example of an Angular module f...
```typescript function findUnusedImports(declarations: string[], imports: string[]): string[] { const usedImports = new Set<string>(); for (const declaration of declarations) { const regex = new RegExp(`${declaration},?`, 'g'); for (const importName of imports) { if (regex.test(impo...
magicoder
typescript
You are working on a project to forecast the discharge capacity of a system using time series data and a Long Short-Term Memory (LSTM) model. The given code snippet is a part of the process to forecast the discharge values. The `series_to_supervised` function is used to frame the time series training data as a supervis...
```python import pandas as pd def series_to_supervised(data, n_in, n_out, dropnan): n_vars = 1 if type(data) is list else data.shape[1] df = pd.DataFrame(data) cols, names = list(), list() # input sequence (t-n, ... t-1) for i in range(n_in, 0, -1): cols.append(df.shift(i)) nam...
magicoder
python
You are tasked with implementing a custom class loader in a C# application. The class loader should be able to load assemblies dynamically and optionally initialize their static members. Your task is to write a method that achieves this functionality. Write a C# method `CustomClassLoader` that takes the following para...
```csharp using System; using System.Reflection; public class CustomClassLoader { public void LoadAssembly(string assemblyName, bool initializeStaticMembers) { Assembly assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.FullName == assemblyName); if (assembly == n...
magicoder
csharp
You are tasked with implementing a function to run a target in linearly-increasing round sizes and record the results for analysis. The function should take in the target to run, the default round size to start with, the increase in round size between rounds, and the total number of rounds to record. The function shoul...
```rust struct AnalysisResult { round_size: usize, result: Result<RunResult, RunError>, } fn run_linearly_increasing_rounds<T>( target: &T, start_round_size: usize, round_size_step: usize, sample_size: usize, ) -> Vec<AnalysisResult> where T: Target, { let mut results = Vec::new(); ...
magicoder
rust
You are tasked with creating a class hierarchy for a company's personnel management system. The system should be able to handle different types of employees, such as professionals, base-level employees, and clients. Each type of employee has specific attributes and behaviors that need to be captured in the class hierar...
```typescript class Base { constructor(public name: string, public id: number, public salary: number) {} // Method to get employee details getDetails(): string { return `Name: ${this.name}, ID: ${this.id}, Salary: ${this.salary}`; } } class Profissional extends Base { constructor(name: string, id: numbe...
magicoder
typescript
You are tasked with implementing a firing sequence for a weapon system in a game development project. The provided code snippet is a part of the existing codebase for the weapon system. Your goal is to complete the implementation of the `BeginFiringSequence` function, which is responsible for initiating the firing sequ...
```cpp bool UKGWeaponStateActive::BeginFiringSequence(uint8 FireModeNum, bool bClientFired) { // Check if the provided fire mode number is valid if (FireModeNum < TotalFireModes) { // Check if the firing action is initiated by the client if (bClientFired) { // Perform cli...
magicoder
cpp
You are tasked with implementing a Trie data structure in Python. A Trie, also known as a prefix tree, is a tree-like data structure used to store a dynamic set of strings. It is commonly used for efficient retrieval of a key in a dataset of strings. Your task is to implement the `Trie` class with the following methods...
```python class Node: def __init__(self): self.successors = {} self.word = False def add(self, char): self.successors[char] = Node() def next(self, char): return self.successors.get(char, None) class Trie: def __init__(self): self.root = Node() def add(se...
magicoder
python
You are tasked with creating a program that simulates a simple test-taking scenario. The program should generate a set of random questions, prompt the user for answers, and then evaluate the user's performance. Here's a sample code snippet to get you started: ```python import random class Test: def __init__(self,...
```python import random class Test: def __init__(self, num_questions): self.num_questions = num_questions self.questions = [] self.answers = [] def generate_questions(self): for _ in range(self.num_questions): operand1 = random.randint(1, 10) operand2 = ...
magicoder
python
You are tasked with implementing a class for reading and processing a custom file format called RSM (Random Scale Model). The RSM file format contains various data structures, including key frames for scaling and volume boxes for defining the volume of the model. The provided code snippet is a part of the implementati...
```cpp #include <iostream> #include <string> #include <stdexcept> #include "kaitai/kaitaistream.h" class rsm_t { public: rsm_t(kaitai::kstream* ks) : m__io(ks), m_scale_key_frames(0), m_volume_boxes(0) {} void read() { try { _read(); } catch (...) { _clean_up(); ...
magicoder
cpp
You are tasked with creating a command-line tool for importing development data into a system. The tool should be implemented as a Laravel Artisan command. The signature of the command is set to 'import:dev'. Your task is to write the code for the Artisan command that will handle the import of development data. Your c...
```php <?php namespace App\Console\Commands; use Illuminate\Console\Command; class ImportDevDataCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'import:dev'; /** * The console command description. * ...
magicoder
php
You are tasked with implementing a function to identify potential pairs of stars in a star catalogue that could be observed together in an image taken by a camera positioned within the solar system. The function should take into account the position of the camera and a flag indicating whether to allow a single catalogu...
```python from typing import List, Tuple def distance_between_points(x1: float, y1: float, x2: float, y2: float) -> float: return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5 def find_star_pairs(camera_position: float, unique_check: bool, star_catalogue: List[Tuple[str, float, float]]) -> List[Tuple[str, str]]: p...
magicoder
python
You are tasked with implementing a Python function that processes a given file to extract specific information related to imports and a variable. Your function should read the file and return the number of GitHub stars, the imported modules, and the variable names found in the file. You are given a Python file snippet...
```python from typing import List, Tuple import re def process_file(file_content: str) -> Tuple[int, List[str], List[str]]: # Extract GitHub stars stars_match = re.search(r'<gh_stars>(\d+)', file_content) gh_stars = int(stars_match.group(1)) if stars_match else 0 # Extract imported modules import_...
magicoder
python
You are tasked with creating a Python function that simulates the process of reverting a virtual machine (VM) to a named snapshot using the `pyvmomi` library. The function should take the VM name and snapshot name as input parameters and handle the connection to the server, VM retrieval, and snapshot reversion process....
```python import sys from pyVim import connect from pyVmomi import vim import atexit import time def revert_vm_to_snapshot(vm_name, snap_name): serverName = "your_server_name" login = "your_login" passwd = "your_password" try: service_instance = connect.SmartConnectNoSSL(host=serverName, user=...
magicoder
python
You are tasked with implementing a custom `ScalarDateTime` class in Python that can coerce input values into a standardized format. The `ScalarDateTime` class should have a method `coerce_input` that takes a single argument `val` and returns the coerced value according to the following rules: - If `val` is a string rep...
```python import datetime class ScalarDateTime: @staticmethod def coerce_input(val): if isinstance(val, str): if 'T' in val: return datetime.datetime.fromisoformat(val) elif '-' in val: return datetime.datetime.strptime(val, "%Y-%m-%d").date() ...
magicoder
python
You are tasked with implementing a flow control algorithm for a high-speed data processing system. The system, named "Jetstream," processes a large volume of data and requires efficient flow control to prevent overload and ensure smooth operation. The provided code snippet initiates the Jetstream server and is a part o...
```rust fn jetstream_flow_control() { let config_path = "tests/configs/jetstream.conf"; let server = util::run_server(config_path); // Implementing a sample flow control algorithm let mut data_processing_rate = DEFAULT_PROCESSING_RATE; let mut system_load = measure_system_load(); // Function to mea...
magicoder
rust
You are given a list of strings, each representing a pair of a word and a number separated by a comma. The number represents the length of the word. Your task is to sort the list based on the length of the word in ascending order. If two words have the same length, they should be sorted lexicographically. Write a fun...
```python def sort_words_by_length(words): def custom_sort(word): word, length = word.split(',') return (len(word), word) return sorted(words, key=custom_sort) ```
magicoder
python
You are tasked with designing a RESTful API for managing houses and photos. The given code snippet is a part of an Express.js router configuration for handling various HTTP requests related to houses and photos. The router is set up to handle GET, POST, and POST requests for houses and photos. Your task is to implemen...
```javascript // Define the controller functions for handling house and photo requests const HousesController = { // Controller function to retrieve all houses getHouses: (req, res) => { // Logic to retrieve all houses from the database // Send the retrieved houses as a response res.status(200).json({ m...
magicoder
javascript
You are tasked with implementing a function to validate a mnemonic string used in a cryptocurrency wallet. A mnemonic string is a human-readable representation of a cryptographic key used to access a wallet. The validation process involves converting the mnemonic string to a C string, passing it to a C function for val...
```swift func validateMnemonic(_ mnemonicString: String) throws -> Bool { let phraseStr = mnemonicString.cString(using: .utf8) if mnemonic_check(phraseStr) == 0 { throw NSError(domain: "com.swiftyeos.error", code: 1, userInfo: [NSLocalizedDescriptionKey: "Invalid Mnemonic"]) } return true } ``` ...
magicoder
swift
You are tasked with implementing a program to measure the fractal dimension of various layers in a given system. The layers are represented by sets, and the program should create an image corresponding to each layer and then measure its fractal dimension. The fractal dimension is a measure of the complexity of a fracta...
```python import numpy as np import cv2 import fractal_dimension_library # Assume the library for fractal dimension measurement is available class LayerMeasurement: def __init__(self): pass def generate_spectrum(self, layers, current_layer_singularity, singularity_step): spectrum = dict() ...
magicoder
python
You are given an array `prices` where `prices[i]` is the price of a given stock on the `i`-th day, and a non-negative integer `fee` representing a transaction fee. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum...
```python class Solution: def maxProfit(self, prices: List[int], fee: int) -> int: result = 0 lo = 0x7FFFFFFF for price in prices: if price < lo: lo = price else: profit = price - lo - fee if profit > 0: ...
magicoder
python
You are tasked with creating a Python function that simulates a simple comment parser. Your function should take a string of Python code as input and return a list of all the commented-out lines in the code. Your function should consider both single-line comments (denoted by `#`) and multi-line comments (denoted by tr...
```python from typing import List def parse_comments(code: str) -> List[str]: in_single_line_comment = False in_multi_line_comment = False result = [] lines = code.split('\n') for line in lines: line = line.strip() if in_multi_line_comment: if "'''" in line or '"""' in...
magicoder
python
You are given a string containing a series of characters. Your task is to write a function that finds the longest substring of consecutive, non-repeating characters within the given string. If there are multiple substrings with the same length, return the first one found. If there are no non-repeating substrings, retur...
```python def longestNonRepeatingSubstring(s: str) -> str: longest_substring = "" current_substring = "" seen_chars = set() start = 0 for end in range(len(s)): if s[end] in seen_chars: while s[start] != s[end]: seen_chars.remove(s[start]) start +=...
magicoder
python
You are tasked with implementing a Python function that processes file paths and performs glob pattern matching. The function should take a path as input and return a modified path object with glob pattern results. Write a function `process_glob_patterns` that takes a `path` as input and returns a modified path object...
```python from pathlib import Path class FakePathClass: def __init__(self, path): self.path = Path(path) self.glob_results = {} def process_glob_patterns(path): result = FakePathClass(path) result.glob_results = {} for pattern, paths in result.glob_results.items(): result.glob_...
magicoder
python
You are given a list of integers representing the prices of a stock on different days. Your task is to find the maximum profit that can be obtained by buying and selling the stock at most once. If it is not possible to make any profit, return 0. For example, given the list of stock prices: [7, 1, 5, 3, 6, 4], the maxi...
```python from typing import List def maxProfit(prices: List[int]) -> int: max_profit = 0 min_price = 2147483647 # Initialize min_price to int_max for price in prices: if price < min_price: min_price = price elif price - min_price > max_profit: max_profit = price - ...
magicoder
python
You are tasked with creating a form validation function for a web application. The function should validate the input fields based on the given HTML code snippet. The HTML code snippet represents a form input field for a phone number. The form input field has the following attributes: - Name: "no_telp" - Type: "text" ...
```javascript function validatePhoneNumber(phoneNumber) { // Check if the phone number is a string of digits if (!/^\d+$/.test(phoneNumber)) { return false; } // Check if the phone number is exactly 10 digits long if (phoneNumber.length !== 10) { return false; } // Check if the phone number does n...
magicoder
javascript
You are tasked with automating the installation process for a set of software packages using a package manager. The package manager in question is Homebrew, a popular package manager for macOS and Linux. Your goal is to write a script that installs the required packages and sets up the necessary environment variables. ...
```bash # Unlink and link gcc brew unlink gcc && brew link gcc # Set HOMEBREW_CC environment variable export HOMEBREW_CC=gcc # Install required packages brew install bzip2 curl expat brew install git --with-brewed-curl --with-brewed-openssl --without-tcl-tk brew tap homebrew/dupes brew install coreutils findutils gaw...
magicoder
shell
You are tasked with creating a Python function that simulates the process of cloning a Git repository and removing a directory using the `shutil` module. Your function should take in a directory path, check if a specific subdirectory exists within it, and if so, remove it. Then, it should clone a specified Git reposito...
```python import shutil import subprocess import tempfile from pathlib import Path def clone_and_remove(directory_path: str, git_repo_url: str, subdirectory_name: str) -> None: bundled_ts_dir = Path(directory_path) / subdirectory_name if bundled_ts_dir.exists(): shutil.rmtree(bundled_ts_dir) with t...
magicoder
python
You are tasked with implementing a resource management system for materials in a game engine. The provided code snippet is a part of the MaterialManager class, responsible for creating and destroying material resources. Your task is to complete the MaterialManager class by implementing the destroyResource function and...
```cpp void MaterialManager::destroyResource(Resource& resource) { Material* material = static_cast<Material*>(&resource); // Release any resources associated with the material material->releaseResources(); // Remove the material from internal data structures // Assuming m_materials is a conta...
magicoder
cpp
You are tasked with implementing a generic visitor pattern in C#. The visitor pattern is a behavioral design pattern that allows adding new behaviors to existing classes without altering their structure. In this problem, you are required to create a generic visitor interface and implement it in a class hierarchy. Your...
```csharp // Define the visitor interface public interface IVisitor<TR, TP> { TR Visit<T>(T element, TP parameter); } // Define the base element class public abstract class Element { public abstract TR Accept<TR, TP>(IVisitor<TR, TP> visitor, TP parameter); } // Define the concrete element classes public clas...
magicoder
csharp
You are tasked with implementing a function that takes a dictionary of words and returns the longest word that can be constructed by concatenating other words in the dictionary. If there are multiple longest words, the function should return the first one in lexicographical order. The function signature is: ```python ...
```python from typing import List class TrieNode: def __init__(self): self.children = {} self.is_end_of_word = False def insert_word(root, word): node = root for char in word: if char not in node.children: node.children[char] = TrieNode() node = node.children[ch...
magicoder
python
You are tasked with creating a function that parses and extracts information from a given HTML code snippet. The HTML code snippet represents a confirmation message for deleting a specific item from a library. The function should extract the name of the item to be deleted and the associated message, and then return the...
```javascript function parseDeleteConfirmation(html) { const itemNameRegex = /{{\s*\$mensaje\s*}}/; // Regex to match {{ $mensaje }} const itemNameMatch = html.match(itemNameRegex); const itemName = itemNameMatch ? itemNameMatch[0].replace(/{{\s*|\s*\$mensaje\s*}}/g, '').trim() : ''; const messageRegex...
magicoder
javascript
You are tasked with implementing a class for user authentication in a social media platform. The class, `Auth`, is designed to handle account access restoration using a code received via SMS. The class is a part of a larger system and is initialized with a `VkApiClient` instance. The `Auth` class extends a superclass t...
```java import com.vk.api.sdk.client.VkApiClient; public class Auth extends SuperClass { public Auth(VkApiClient client) { super(client); } /** * Allows to restore account access using a code received via SMS. This method is only available for apps with Direct authorization access. * ...
magicoder
java
You are tasked with implementing a simplified version of a promise-based asynchronous operation in Swift. You are given a ViewModel class that interacts with a repository to toggle the favorite state of a certificate identified by its `id`. The ViewModel uses the PromiseKit library to handle asynchronous operations. Yo...
```swift func toggleFavorite(certificateId id: String) { firstly { repository.toggleFavoriteStateForCertificateWithIdentifier(id) } .get { isFavorite in self.isFavorite = isFavorite } .done { _ in self.delegate?.viewModelDidUpdate() } .catch { [weak self] error in ...
magicoder
swift
You are tasked with creating a program to manage a library's book inventory. The program should allow librarians to add, remove, and update books in the inventory. Additionally, it should provide functionality to search for books by title, author, or category. To achieve this, you need to implement a class called `Libr...
```python class Book: def __init__(self, title, author, category, quantity): self.title = title self.author = author self.category = category self.quantity = quantity class LibraryInventory: def __init__(self): self.inventory = [] def add_book(self, title, author, c...
magicoder
python
You are tasked with implementing a test suite for a Java application using JUnit. The test suite should cover various classes and methods within the application. The code snippet provided contains a list of test classes that need to be included in the test suite. Your task is to write a JUnit test suite that includes a...
```java import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ CliTest.class, ConstantParserTest.class, EvokeTest.class, ExampleEvokeTest.class, ExampleTest.class, GetValueTest.class, JDBCQueryTest.class }) pu...
magicoder
java
You are tasked with implementing a function to extract specific information from an array of `HtmlEntities` objects. Each `HtmlEntities` object contains an array of `Content` and optional `Pageable` properties, along with other metadata. You need to create a function `extractContentByPage` that takes in an array of `H...
```typescript function extractContentByPage(entities: HtmlEntities[], pageNumber: number): Content[] { const entity = entities.find((e) => e.pageable?.pageNumber === pageNumber); return entity ? entity.content : []; } ```
magicoder
typescript
You are tasked with creating a Swift protocol for validating a specific type of data. The protocol should include a property `isValid` that returns a boolean value indicating whether the data meets certain validation criteria. Your goal is to implement a concrete type that conforms to this protocol and provides a meani...
```swift // Define the DataValidator protocol protocol DataValidator { var isValid: Bool { get } } // Implement the EmailValidator type conforming to DataValidator protocol struct EmailValidator: DataValidator { private let emailRegex = #"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"# let email: Strin...
magicoder
swift
You are tasked with implementing a date formatting utility in Java. The provided code snippet includes a regular expression pattern for matching dates in the format "YYYY-MM-DD" and a method signature for formatting a Date object. Your task is to complete the implementation of the `format` method to return a string rep...
```java import java.util.Date; import java.text.SimpleDateFormat; import java.util.regex.Pattern; public class DateFormatter { private static final Pattern PATTERN_FORMAT = Pattern.compile("[\\d]{4,4}-[\\d]{2,2}-[\\d]{2,2}"); public static String format(final Date value) { SimpleDateFormat dateFormat ...
magicoder
java
You are tasked with creating a custom property drawer for a specific type in Unity. The custom property drawer should be designed to handle a reference to a boolean variable. Your task is to implement the custom property drawer class for the `BoolReference` type, ensuring that it visually represents the boolean referen...
```csharp using UnityEditor; [CustomPropertyDrawer(typeof(BoolReference))] public class BoolReferenceDrawer : PropertyDrawer { public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { EditorGUI.BeginProperty(position, label, property); // Assuming BoolReferenc...
magicoder
csharp
You are tasked with implementing a Pet Management System using Java. The system should allow for the management of pets, including adding new pets, retrieving pets by owner ID, and searching for pets by their unique ID. You are provided with a partial implementation of the PetService class, which interacts with a PetRe...
```java import java.util.List; import java.util.NoSuchElementException; class Pet { private long id; private String name; private long ownerId; public Pet(long id, String name, long ownerId) { this.id = id; this.name = name; this.ownerId = ownerId; } // Getters and set...
magicoder
java
You are tasked with creating a command-line utility for generating text using a Markov chain model. The utility should accept various command-line arguments to customize its behavior. Your task is to implement the `parse_args` function to parse the command-line arguments using the `argparse` module in Python. The `par...
```python import argparse def parse_args(argv=None): root = argparse.ArgumentParser() root.add_argument('--config', '-c', default='config.ini') root.add_argument('--length', '-n', default=100, type=int) root.add_argument('--last', '-l', type=int, help='Markov Last param. Default: use config.') root...
magicoder
python
You are tasked with implementing a custom asynchronous context manager in Python. An asynchronous context manager is a special type of object that can be used with the `async with` statement to manage asynchronous resources. Your task is to create a class that can be used as an asynchronous context manager and handles ...
```python import asyncio class CustomAsyncContextManager: def __init__(self): # Initialize any necessary attributes pass async def __aenter__(self): # Acquire the resource asynchronously and return it # For example, acquiring a connection or opening a file resource = aw...
magicoder
python
You are tasked with implementing a method to parse a string representation of a decimal number into its corresponding decimal value. The method should handle both whole numbers and numbers with decimal points. You are provided with a partial code snippet for the method `ParseStringToDecimal` as a starting point. The `...
```csharp public static decimal ParseStringToDecimal(string numberString) { if (string.IsNullOrWhiteSpace(numberString)) { throw new ArgumentException("Input string is empty or null"); } if (decimal.TryParse(numberString, out decimal result)) { return result; } else { ...
magicoder
csharp
You are tasked with creating a Django model for a customer database. The model should include fields for customer information and preferences. One of the fields should be a boolean field to indicate whether the customer's address should be ignored. Your task is to define the Django model with the required fields and th...
```python from django.db import models class Customer(models.Model): id = models.AutoField(primary_key=True) ignore_addresses = models.BooleanField(default=False) ``` In the solution, we define a Django model named `Customer` that inherits from `models.Model`. We then define the required fields `id` and `ignor...
magicoder
python
You are working on a project to develop a trajectory filter for a particle tracking system. The filter is designed to process subcluster shapes in a particle detector and make decisions based on certain criteria. Your task is to implement a function that takes the configuration parameters for the trajectory filter and ...
```python from typing import List class SubclusterShape: def __init__(self, layer, num_strips, charge): self.layer = layer self.num_strips = num_strips self.charge = charge def apply_trajectory_filter(config_params, subcluster_shapes) -> List[SubclusterShape]: filtered_shapes = [] ...
magicoder
python
You are tasked with implementing a custom layout for a collection view in a mobile app. The collection view displays cells in a horizontal scrolling manner. The goal is to adjust the content offset of the collection view such that a specific target cell is centered after the user finishes scrolling. The given code sni...
```swift // Problem Description class CustomCollectionViewLayout: UICollectionViewLayout { // Other layout methods and properties override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { // Your implementation h...
magicoder
swift
You are tasked with implementing a custom data structure in C# that mimics the functionality of a stack, but with an added feature of tracking the minimum element in the stack at any given time. You need to create a class `MinStack` that supports the following operations: 1. `Push(int x)`: Add element x to the top of t...
```csharp public class MinStack { private Stack<int> stack; private Stack<int> minStack; public MinStack() { stack = new Stack<int>(); minStack = new Stack<int>(); } public void Push(int x) { stack.Push(x); if (minStack.Count == 0 || x <= minStack.Peek()) ...
magicoder
csharp
You are tasked with implementing a class that manages access policies for a vault in Azure Active Directory. The class should handle input validation and provide a way to store and retrieve object IDs for users, service principals, or security groups. Your task is to create a method that adds a new access policy to the...
```csharp using System; using System.Collections.Generic; public class AccessPolicy { private List<string> accessPolicies = new List<string>(); [Input("objectId", required: true)] public Input<string> ObjectId { get; set; } = null!; public bool AddAccessPolicy(string newObjectId) { // Inp...
magicoder
csharp
You are tasked with creating a Python script that simulates a simple banking system. The script should allow users to create accounts, deposit and withdraw funds, and check their balance. The script should also handle cases where users attempt to withdraw more funds than they have in their account. Your task is to imp...
```python class BankAccount: def __init__(self, account_number, account_holder, initial_balance): self.account_number = account_number self.account_holder = account_holder self.balance = initial_balance def deposit(self, amount): self.balance += amount def withdraw(self, am...
magicoder
python
You are tasked with creating a Python function that merges the messages from a source Catalog into a .po file at the specified target location. The source Catalog is a dictionary where the keys are message identifiers and the values are the corresponding message strings. The .po file format is commonly used for storing...
```python def merge(source, target_filename): with open(target_filename, 'a' if os.path.exists(target_filename) else 'w', encoding='utf-8') as target_file: for msgid, msgstr in source.items(): target_file.write(f'msgid "{msgid}"\n') target_file.write(f'msgstr "{msgstr}"\n\n') ``` In...
magicoder
python
You are tasked with implementing a Python class to represent a frequency scale for musical tones. The class should provide methods to calculate the frequency range, the number of cents per value, and to convert frequencies to cents. You are given the following code snippet as a starting point: ```python piano_min = 2...
```python class FrequencyScale: def __init__(self, f_min, f_max, v_min, v_max): self.f_min = f_min self.f_max = f_max self.v_min = v_min self.v_max = v_max def get_f_min(self): return self.f_min def get_f_max(self): return self.f_max def cent_per_value(...
magicoder
python
You are tasked with creating a 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 handle multiple accounts and ensure that each user can only access their own account. You are provided with t...
```c #include <stdio.h> #include <string.h> typedef struct { int accountNumber; float balance; char ownerName[50]; } Account; Account createAccount(int accountNumber, float initialBalance, const char* ownerName) { Account newAccount; newAccount.accountNumber = accountNumber; newAccount.balance = initialBa...
magicoder
c
You are tasked with implementing a Python class that represents a simple bank account. The class should have methods for depositing funds, withdrawing funds, and checking the current balance. Additionally, the class should keep track of the account holder's name and account number. Your task is to complete the implemen...
```python class BankAccount: account_counter = 0 def __init__(self, name, initial_balance): self.name = name self.balance = initial_balance self.account_number = self.generate_account_number() def generate_account_number(self): BankAccount.account_counter += 1 initi...
magicoder
python
You are tasked with creating a middleware function for a web framework that enforces trusted hosts for incoming requests. The middleware should only allow requests from specified hosts and reject requests from untrusted hosts. Your goal is to implement the `trusted_hosts_middleware` function and ensure that it correctl...
```python from typing import List from werkzeug.wrappers import Request, Response from werkzeug.test import create_environ from werkzeug.test import Client def trusted_hosts_middleware(request: Request, allowed_hosts: List[str]) -> Response: if request.host in allowed_hosts: return Response("Welcome", stat...
magicoder
python
You are tasked with implementing a function to draw a set of line hypotheses for a batch of images. The function `draw_hyps` takes in three parameters: `labels`, `scores`, and an optional parameter `data`. The `labels` parameter represents the line parameters and is an array of shape (NxMx2), where N is the number of ...
```python import matplotlib.pyplot as plt def draw_hyps(self, labels, scores, data=None): """ Draw a set of line hypotheses for a batch of images. labels -- line parameters, array shape (NxMx2) where N is the number of images, M is the number of lines per image, and the last dimension represents the line ...
magicoder
python
You are tasked with creating a Python class that simulates a simple platformer game character. The class should handle movement, gravity, and collision detection with platforms. Your task is to implement the missing methods and attributes of the class based on the given code snippet and requirements. The provided code...
```python import pygame as pg class Character(pg.sprite.Sprite): def __init__(self): super().__init__() # Initialize the character attributes and load images self.movement_x = 0 self.movement_y = 0 self.rect = pg.Rect(0, 0, width, height) # Replace width and height with act...
magicoder
python
You are tasked with implementing an HTTP encoding interface in Java. The interface, `Encoding`, represents an arbitrary HTTP encoding and can be used for request encoding in a client API or for handling encoded requests in a server API. An implementation of this interface should provide the ability to wrap an `OutputSt...
```java import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; interface Encoding { String getName(); OutputStream wrapOutputStream(OutputStream out) throws IOException; InputStream wrapInputStream(InputStream in) throws IOException; } // Sample implementation of the Encoding...
magicoder
java
You are tasked with implementing a simplified version of a CPU opcode handler for the ARMv6 architecture. The provided code snippet is a Python class `UbfxT1` that inherits from `Ubfx` and `Opcode`. The `Ubfx` class represents the "Unsigned Bit Field Extract" operation, and the `Opcode` class represents a generic CPU o...
```python class Ubfx: def __init__(self, lsbit, widthminus1, d, n): self.lsbit = lsbit self.widthminus1 = widthminus1 self.d = d self.n = n class Opcode: def __init__(self, instruction): self.instruction = instruction class UbfxT1(Ubfx, Opcode): def __init__(self, i...
magicoder
python
You are tasked with implementing a function to generate a SHA-1 hash of a given input string using the Boost C++ library. The SHA-1 algorithm produces a 160-bit (20-byte) hash value known as a message digest. Your task is to create a C++ function that takes a string as input and returns its SHA-1 hash as a hexadecimal ...
```cpp #include <boost/uuid/sha1.hpp> #include <boost/algorithm/hex.hpp> std::string calculateSHA1(const std::string& input) { boost::uuids::detail::sha1 sha1; sha1.process_bytes(input.data(), input.size()); unsigned int digest[5]; sha1.get_digest(digest); std::string hash; for (int i = 0; i ...
magicoder
cpp
You are tasked with creating a function that extracts the IP address and port from a given `CLUSTER_ADDR` string based on the provided code snippet. The `CLUSTER_ADDR` can be in one of two formats: IPv6 or IPv4 with a port number. The IPv6 format is enclosed in square brackets, while the IPv4 format is a standard dotte...
```python import re def extractAddressAndPort(CLUSTER_ADDR): ipv6_pattern = r'\[([0-9a-fA-F:]+)\]:(\d+)' ipv4_pattern = r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d+)' ipv6_match = re.match(ipv6_pattern, CLUSTER_ADDR) ipv4_match = re.match(ipv4_pattern, CLUSTER_ADDR) if ipv6_match: return i...
magicoder
python
You are working on a data analysis project related to quasars (QSOs) and need to write a function to analyze the restframe ranges of wavelengths for a given QSO dataset. The code snippet provided is a part of the function that performs this analysis. Your task is to complete the function by implementing the logic to ca...
```python import numpy as np class QuasarAnalyzer: def analyze_restframe_ranges(qso, rest_ranges=None): """ Analyze the restframe ranges of wavelengths for a given QSO dataset. Args: qso (object): Dataset containing information about quasars. rest_ranges (list of lists, opt...
magicoder
python
You are given a list of differences `diffs` containing tuples of integers `(o, s)`. Additionally, you are given an integer `N`. The code snippet provided initializes a list `out` with `N+1` elements, where the first element is 1 and the rest are 0. Then, it iterates through the elements of `diffs` and updates the eleme...
```python from typing import List, Tuple def final_state(N: int, diffs: List[Tuple[int, int]]) -> List[int]: out = [1] + [0]*N # Initialize the list out with N+1 elements for p in range(0, N+1): # Iterate through the elements of out x = out[p] # Store the current value of out[p] for (o, s) i...
magicoder
python
You are tasked with creating a Python package for a scientific research project. The package, named "naima," will contain various modules and data files. Your goal is to set up the package configuration using the `setuptools` library to ensure that the package is properly structured and can be easily installed by other...
```python from setuptools import setup, find_packages setup( name="naima", version="1.0", packages=find_packages("src"), package_dir={"": "src"}, package_data={"naima": ["data/*.npz"]}, install_requires=[ # Add any necessary dependencies here ] ) ``` In the provided solution, the `...
magicoder
python
You are tasked with implementing a function to remove a member from a group in a social networking application. The application uses a client-side API to manage users and groups. The code snippet provided is a part of the test suite for this functionality. The `client` object is used to interact with the API and perfor...
```typescript async function removeGroupMember(groupName: string, userId: string): Promise<boolean> { try { // Check if the group exists const group = await client.getGroup(groupName); if (!group) { console.error("Group not found"); return false; } //...
magicoder
typescript
You are tasked with creating a script to automate the deployment and testing process for a web application. The script should perform the following tasks in sequence: 1. Change the directory to `/home/wwwroot/aos`. 2. Run the command `/usr/local/bin/composer install --no-interaction` to install the necessary dependenc...
```python import subprocess # Change directory to /home/wwwroot/aos subprocess.run("cd /home/wwwroot/aos", shell=True) # Install dependencies using Composer subprocess.run("/usr/local/bin/composer install --no-interaction", shell=True) # Create schema in MySQL database for testing mysql_test_database = "test_databas...
magicoder
python
You are tasked with creating a Python function that processes a serialized data structure stored in a file and performs specific operations on the deserialized data. The function should handle potential file I/O errors and ensure the proper handling of the deserialized data. You are given the following code snippet as...
```python import os import pickle def process_serialized_data(filename): """ Deserialize the data structure from the specified file and perform operations on it. Args: filename (str): The name of the file containing the serialized data. Returns: str: A message indicating the result of the ope...
magicoder
python
You are given a code snippet that involves the usage of a custom data type `Fp` and its extension `Fp2`. The code snippet also includes assertions to test the behavior of the `sgn0` method of the `Fp2` type. Your task is to understand the behavior of the `sgn0` method and implement it in the `Fp2` type. The `Fp` type ...
```rust // Define the finite field element type Fp struct Fp { value: i32, // Assuming the value is stored as an integer for simplicity } impl Fp { fn zero() -> Fp { Fp { value: 0 } } fn one() -> Fp { Fp { value: 1 } } } // Define the quadratic extension field element type Fp2 st...
magicoder
rust
You are given a 2D boolean array `table` of size `xSize` by `ySize`. The array represents a table with cells that can be either true (1) or false (0). Your task is to implement a function that creates a new 2D boolean array `toReturn` of the same size, where each cell is the logical OR of the corresponding cells from t...
```c bool** mirrorTable(bool** table, size_t xSize, size_t ySize) { bool** toReturn = (bool**)malloc(xSize * sizeof(bool*)); // Allocate memory for the new array for (size_t i = 0; i < xSize; ++i) { toReturn[i] = (bool*)malloc(ySize * sizeof(bool)); // Allocate memory for each row of the new array ...
magicoder
c
You are tasked with implementing a frame source management system for a video processing application. The system should support two types of frame sources: video files and camera input. The provided code snippet includes a partial implementation of the frame source management system using OpenCV's super resolution modu...
```cpp Ptr<FrameSource> cv::superres::createFrameSource_Camera(int deviceId) { VideoCapture capture(deviceId); if (!capture.isOpened()) { CV_Error(cv::Error::StsError, "Failed to open camera with the specified device ID"); return Ptr<FrameSource>(); } return makePtr<CameraFrameSource>(c...
magicoder
cpp
You are working for a data analysis company that specializes in visualizing crime data. Your task is to create a program that generates a line plot to visualize the monthly counts of crime victims based on victim types. The data is provided in a CSV file named "crime_data.csv", which contains the following columns: "da...
```python import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # Step 1: Read the data from CSV into a pandas DataFrame crime_data = pd.read_csv("crime_data.csv") # Step 2: Convert the "datetime" column to datetime format crime_data['datetime'] = pd.to_datetime(crime_data['datetime']) # Step 3: ...
magicoder
python
You are tasked with creating a Python program that utilizes the `multiprocessing` module to spawn multiple processes to perform a specific task. Your program should create a number of processes, each of which will execute a function called `work`. The `work` function takes an identifier as an argument and prints a mess...
```python import os from multiprocessing import Process def work(identifier): print(f'Hey, I am the process {identifier}, pid: {os.getpid()}') def main(): processes = [Process(target=work, args=(number,)) for number in range(5)] for process in processes: process.start() if __name__ == "__main__":...
magicoder
python
You are working on a file management system and need to automate certain tasks using shell scripting. Your task is to write a shell script that performs the following operations: 1. Delete all empty files in the current directory and its subdirectories. 2. Delete all empty directories in the current directory and its ...
```bash #!/bin/bash # Delete all empty files in the current directory and its subdirectories find . -type f -empty -delete # Delete all empty directories in the current directory and its subdirectories find . -type d -empty | xargs rm -rf # Create old_file_list.txt containing a sorted list of all files find . -type ...
magicoder
shell
You are tasked with creating a Rust function that processes and sends internal metrics. The function receives a `ticker` that generates events, a `recorder` that captures metrics, and an `output` channel to send the captured metrics. The function should continuously process the incoming events, capture metrics, and sen...
```rust async fn process_metrics(ticker: &mut dyn Stream<Item = ()>, recorder: &dyn Recorder, output: mpsc::Sender<Event>) { while let Some(_) = ticker.next().await { let timestamp = Some(chrono::Utc::now()); let metrics = recorder.capture_metrics(); let events = metrics.map(|mut m| { ...
magicoder
rust
You are tasked with implementing a Python class for the Makwa cryptographic hash function. Makwa is a cryptographic hash function designed for password hashing and key derivation. It is based on the RSA trapdoor permutation and is resistant to quantum attacks. Your task is to implement the `_digest` method of the `Makw...
```python from Crypto.Util.number import bytes_to_long, long_to_bytes from Crypto.PublicKey import RSA from Crypto.Hash import SHA256 class Makwa: def __init__(self, work_factor, pre_hashing): self.work_factor = work_factor self.pre_hashing = pre_hashing def _digest(self, pi, n, salt=b''): ...
magicoder
python
You are tasked with implementing a method to parse a JSON string representing multiple seasons of a TV show and create a collection of Season objects. Each Season object should contain information about the season number, episode count, and average rating of the season. The JSON string is in the following format: ```js...
```java import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; public class Season { private int seasonNumber; private int episodeCount; private double averageRating; public Season(int seasonNumber, int episodeCount, double averageRating) { ...
magicoder
java
You are tasked with implementing a function that extracts the package name from a given code snippet written in Japanese. The package name is enclosed within double quotes and is followed by the comment "のテストコード群パッケージです。" (which translates to "test code package for View(WebAPI)"). Your task is to write a function that ...
```python import re def extract_package_name(code: str) -> str: pattern = r'"(.*?)"のテストコード群パッケージです。' match = re.search(pattern, code) if match: return match.group(1) else: return "" ```
magicoder
python
You are tasked with implementing a command-line argument parser for a home automation web server. The provided code snippet includes a partial routing configuration for the web server and a function for parsing command-line arguments using the `argparse` module. Your task is to extend the command-line argument parser ...
```python import argparse # Existing routing configuration and parse_args function routing_config = { '/healthz': view.healthz_view, '/static.*': view.static_view, '/status': view.status_view, '/statusz': view.statusz_view, '/touchz': view.touchz_view, '/trigger.*': view.trigger_view...
magicoder
python
You are given a C++ code snippet that performs some operations on an array `div` and prints the result to the standard error output. Your task is to understand the code and implement a function that replicates the same operations on an input array and returns the modified array. The given code snippet performs the fol...
```cpp #include <iostream> #include <vector> #include <cmath> using namespace std; vector<double> performOperations(vector<double> div, int offset, double n, int VERB) { vector<double> result = div; // Create a copy of the input array for (int ix = 0; ix < div.size() - offset; ix++) { if (result[off...
magicoder
cpp
You are tasked with creating a function that processes a file upload and updates the details of a ministry. The function should handle different scenarios and provide appropriate messages based on the outcome of the file upload and ministry details update. You are given a code snippet from a PHP class method that hand...
```php function processMinistryDetails($ministry_update, $file_uploaded, $file_type) { if ($ministry_update) { return 'Ministry details updated successfully!|alert-success'; } elseif (!$file_uploaded) { return 'Select an image. Only JPG, JPEG, PNG files are allowed!|alert-danger'; } elseif (...
magicoder
php