query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with implementing a Swift data structure to represent paginated data from an API response. The structure should include properties for the size of each page, the sorting criteria, the total number of elements, the total number of pages, and should handle conversions between different data types. Your ta...
```swift // Define the Sort enum for sorting criteria enum Sort { case ascending case descending } // Define the PaginatedData struct struct PaginatedData { var size: NSNumber? var sort: Sort? var totalElements: Int64? var totalElementsNum: NSNumber? { get { return tota...
magicoder
swift
You are tasked with creating a script to automate the testing process for a .NET project. The script should perform the following tasks: 1. Restore and build the project using the `dotnet` command. 2. Run tests for two different test projects using the `Coverlet` tool, which generates code coverage reports in OpenCove...
```bash #!/bin/bash # Restore and build the project dotnet restore dotnet build # Test Client.Legacy.Test project ./Coverlet/coverlet Client.Legacy.Test/bin/Debug/"$NET_VERSION"/Client.Legacy.Test.dll --target "dotnet" --targetargs "test Client.Legacy.Test/Client.Legacy.Test.csproj --no-build --logger trx" --format ...
magicoder
shell
You are tasked with implementing a simple font management system for a graphics rendering library. The system should allow the selection and restoration of fonts for rendering text on a 2D canvas. You are given a code snippet from a C++ class that demonstrates the font management functions. The `SelectObject` function...
```cpp #include <iostream> class FontManager { private: IRenderObj* oldFont = nullptr; IRenderObj* currentFont = nullptr; public: void SelectFont(IRenderObj* font) { if (font != nullptr) { oldFont = currentFont; currentFont = font; std::cout << "Font selected fo...
magicoder
cpp
You are tasked with implementing a Python function that processes HTTP requests and responses. The function should take a list of request objects, send them to a server, and then validate the responses. Each request object contains information about the request to be made, and each response object contains information ...
```python async def process_requests(client, requests): for req in requests: resp = await client.submit(req) assert resp.status == 200 assert resp.json()['form'] == req.expected_form_data ``` In the solution, the `process_requests` function iterates through each request in the `requests` li...
magicoder
python
You are tasked with implementing a Python class that interacts with a RESTful API to perform CRUD operations on resources. The class has two methods, `_get_uri` and `_patch_request`, which are used to construct resource URIs and send PATCH requests, respectively. Your task is to complete the implementation of the `_pat...
```python def _patch_request(self, resource, uuid, patch_object): """ Update specified object with JSON-patch. :param resource: The name of the resource to be updated. :param uuid: The unique identifier of the object to be updated. :param patch_object: A JSON-patch object containing the changes...
magicoder
python
You are tasked with implementing a C++ class that simulates a simple printer. The printer should be able to receive and store print jobs, and then print them in the order they were received. The printer should also be able to report its status, including the number of pending print jobs and the details of the last erro...
```cpp #include <iostream> int main() { Printer printer; printer.addJob("Document 1"); printer.addJob("Document 2"); printer.addJob("Document 3"); try { std::cout << "Printing: " << printer.print() << std::endl; std::cout << "Printing: " << printer.print() << std::endl; st...
magicoder
cpp
You are tasked with designing a trait for a game engine in Rust. The trait, `GameEngine`, provides methods to access different components of the game engine, such as the renderer, input API, and audio API. Your goal is to implement the `GameEngine` trait for a specific game engine struct. The trait definition is as fo...
```rust // Define the MyGameEngine struct struct MyGameEngine { // Define specific types for the renderer, input API, and audio API renderer: Renderer, input_api: InputAPI, audio_api: AudioAPI, } // Implement the GameEngine trait for MyGameEngine impl GameEngine for MyGameEngine { type R = Renderer...
magicoder
rust
You are tasked with writing a program to manage different image sizes for various Android app resources. The program should take input in the form of commands and perform the necessary operations to handle the image sizes. The input commands will be in the format: `resource_type size_modifier size_value`, where `resou...
```python class ImageManager: def __init__(self): self.image_sizes = {} def add_image_size(self, resource_type, size_modifier, size_value): if resource_type not in self.image_sizes: self.image_sizes[resource_type] = {} self.image_sizes[resource_type][size_modifier] = size_va...
magicoder
python
You are tasked with creating a Python command-line interface (CLI) for a manga reading application using the `argparse` module. Your CLI should support various commands and arguments for interacting with the application's features. You need to implement the `initialize_args` function, which returns an `ArgumentParser` ...
```python from argparse import ArgumentParser from mangadex_py.meta import version from .general_args import _gen_args from .downloading_args import _download_args from .required_args import _required_args from .auth_args import _auth_args def initialize_args() -> ArgumentParser: args_parser = ArgumentParser( ...
magicoder
python
You are tasked with implementing a website routing system that determines the home page for different users based on their roles and functions. The routing system is configured using the provided code snippet, which contains commented-out configurations and generators. Your task is to create a Python function that tak...
```python def determine_home_page(role, user_function): # application home page (will override Website Settings) home_page = "login" # website user home page (by Role) role_home_page = { "Admin": "admin_dashboard", "User": "user_dashboard" } # Website user home page (by functio...
magicoder
python
You are tasked with implementing a PID controller for a system. A PID controller is a control loop feedback mechanism widely used in industrial control systems. It calculates an error value as the difference between a desired setpoint (SP) and a measured process variable (PV). The controller attempts to minimize the er...
```python class PIDController: def __init__(self, windup_guard, lowpass_D_constant): self.PTerm = 0 self.ITerm = 0 self.DTerm = 0 self.windup_guard = windup_guard self.lowpass_D_constant = lowpass_D_constant def update(self, error, dt, d_error): self.PTerm = erro...
magicoder
python
You are working on a file management script that processes a list of files and moves them to a specific directory while renaming them based on their MD5 hash. The script snippet provided below is a part of the file processing logic. ```bash #!/bin/bash files=("file1.txt" "file2.txt" "file3.txt") for file in "${files...
```bash #!/bin/bash move_files() { declare -A hash_map for file in "${files[@]}" do hash=$(md5sum "${file}" | awk '{ print $1 }') if [[ -z ${hash_map[$hash]} ]]; then hash_map[$hash]=1 mv "${file}" "./data/${hash}" else count=1 while [...
magicoder
shell
You are tasked with implementing a Java method that processes a list of advertisement DTOs and performs various validations and manipulations on the data. The advertisement DTO (`CmsAdDto`) contains information about different ads, such as title, content, and status. Your task is to write a method that takes a list of ...
```java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.Iterator; public class AdProcessor { private static final Logger logger = LoggerFactory.getLogger(AdProcessor.class); public List<CmsAdDto> processAds(List<CmsAdDto> adDtos) { Iterator<CmsAdDto> it...
magicoder
java
You are tasked with creating a custom authentication strategy for a Node.js application using the NestJS framework. The application uses JSON Web Tokens (JWT) for authentication and authorization. Your goal is to implement a custom JWT strategy that will be used to authenticate and authorize users. You are provided wi...
```typescript import { Injectable, UnauthorizedException } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; import { AuthService } from './auth.service'; import { JwtPayload } from './jwt-payload.interface'; @Injectable() export class JwtS...
magicoder
typescript
You are tasked with implementing a custom `Table` class that represents a SQL table. The class should support attribute access to retrieve the values of the table columns. The column values are stored in private attributes prefixed with an underscore. Your task is to complete the implementation of the `Table` class by...
```python class Table: """Represents a SQL Table. """ def __init__(self): self._columns = {} def __getattr__(self, name: str): return self._columns['_' + name] def __setattr__(self, name: str, value): self._columns['_' + name] = value def get_column_names(self): ...
magicoder
python
You are tasked with implementing a custom JComboBox component in Java Swing that allows users to select a specific style for the divider of a split pane. The code snippet provided demonstrates the initialization of the JComboBox and its integration with a split pane. Your task is to create a class that extends JComboB...
```java import javax.swing.*; import javax.swing.event.*; import javax.swing.plaf.SplitPaneUI; import javax.swing.plaf.basic.BasicSplitPaneUI; import java.awt.*; public class CustomDividerStyleComboBox extends JComboBox<DividerStyle> { private JSplitPane splitPane; public CustomDividerStyleComboBox(JSplitPan...
magicoder
java
You are tasked with creating a Python class that represents a geometric shape. The class should have methods to calculate the area and perimeter of the shape. You should also create specific subclasses for different geometric shapes, such as a rectangle and a circle, which inherit from the main geometric shape class. ...
```python from abc import ABC, abstractmethod import math class GeometricShape(ABC): @abstractmethod def calculate_area(self): pass @abstractmethod def calculate_perimeter(self): pass class Rectangle(GeometricShape): def __init__(self, length, width): self.length = length ...
magicoder
python
You are tasked with implementing a data structure to efficiently store and retrieve cell metadata in a blockchain application. The cell metadata consists of information related to cell outputs and dependencies. Each cell output is associated with a unique out point, and each cell dependency is linked to a cell output t...
```rust use std::collections::HashMap; // Define a struct to represent cell metadata struct CellMeta { // Define the fields for cell metadata // For example: out_point, cell_output, cell_data, cell_dep // ... // Implement any other necessary fields and methods } // Define a data structure to store ce...
magicoder
rust
You are tasked with creating a script to process a given text file and generate a vocabulary list with unique words and their corresponding indices. The script should read the input text file, tokenize the words, sort them in ascending order, remove duplicates, and then assign a unique index to each word. The final out...
```bash #!/bin/bash TEXT=$1 cat $TEXT | tr '[:space:]' '\n' | sort -u | awk 'BEGIN { n = 0;} { print n,$1; n+=1}' > vocab.for.cued.txt ``` The provided solution is a Bash script that accomplishes the task as described in the problem. It takes the input text file as a command-line argument, tokenizes the words using `...
magicoder
shell
You are tasked with creating a function that interfaces with the Vulkan API to create a new surface for rendering on a window. The function `new_xcb` takes in the Vulkan instance `vk`, a reference to the Vulkan API library `lib`, a pointer to a window context `wc`, and the width `w` of the window. The function returns ...
```rust // Rust implementation using the ash Vulkan API bindings use ash::vk; use ash::extensions::khr; use std::os::raw::c_void; fn new_xcb(vk: vk::Instance, lib: &ash::Entry, wc: *mut c_void, w: u32) -> vk::SurfaceKHR { let xcb_extension = khr::XcbSurface::new(lib, &vk); let create_info = vk::XcbSurfaceCrea...
magicoder
rust
You are tasked with implementing a custom data type that behaves like an integer but has a restricted range. Your task is to create a class `RestrictedInt` that takes an integer value and a range as input and returns a restricted integer within that range. The class should have methods to perform arithmetic operations ...
```python class RestrictedInt: def __init__(self, value: int, min_val: int, max_val: int): self.value = max(min(value, max_val), min_val) def __add__(self, other: 'RestrictedInt') -> 'RestrictedInt': return RestrictedInt(self.value + other.value, min_val, max_val) def __sub__(self, other: ...
magicoder
python
You are tasked with implementing a decision tree classifier from scratch. Decision trees are a popular machine learning algorithm used for both classification and regression tasks. In this problem, you will be focusing on the classification aspect. Your task is to implement the `DecisionTreeClassifier` class, which sh...
```python import numpy as np class DecisionTreeClassifier: def __init__(self, max_depth=None, min_samples_leaf=1): self.max_depth = max_depth self.min_samples_leaf = min_samples_leaf self.tree = None def fit(self, X, y): self.n_features = X.shape[1] self.n_classes = len...
magicoder
python
You are tasked with implementing a song generator that takes musical notes and their corresponding start times and creates a song by inserting the notes into the song at the specified start times. The code snippet provided is a part of the song generation process. The `sig_gen.sin_constant` function is used to generate...
```python from typing import List, Tuple import signal_generator as sig_gen # Assuming the signal generator module is imported def generate_song(notes: List[Tuple[float, float]]) -> str: song = "" # Initialize an empty string to represent the generated song try: for note_length, start in notes: ...
magicoder
python
You are working on a machine learning project and need to create a pipeline for feature selection and model training. You have a dataset with a large number of features, and you want to use SelectPercentile for feature selection and GridSearchCV for hyperparameter tuning. Your task is to create a pipeline using scikit-...
```python from sklearn.pipeline import Pipeline from sklearn.model_selection import GridSearchCV from sklearn.feature_selection import SelectPercentile def create_pipeline_and_tune(X_train, y_train, model, param_grid): feature_selection = SelectPercentile(percentile=50) pipeline = Pipeline([ ('feature_...
magicoder
python
You are given a chessboard of size n x n, represented by a 2D array grid[n][n]. Each cell of the grid can either be empty (denoted by 0) or occupied by a queen (denoted by 1). Your task is to write a function that checks whether it is possible to place a new queen at a given position (row, col) without attacking any ot...
```cpp bool canPlaceQueen(int grid[][n], int row, int col, int n) { // Check if there is any queen in the same column for (int i = row - 1; i >= 0; i--) { if (grid[i][col] == 1) { return false; } } // Check if there is any queen in the upper left diagonal for (int i = ro...
magicoder
cpp
You are tasked with implementing a simplified version of an audio manager system. The system is responsible for managing audio sources and providing functionality to play and stop audio. The audio manager uses the FMOD library for audio processing. Your task is to implement the necessary classes and methods to manage a...
```cpp #include <fmod.hpp> class AudioSourceBase { public: virtual void stop() = 0; // Pure virtual method for stopping audio playback virtual void play() = 0; // Pure virtual method for playing audio virtual ~AudioSourceBase() {} // Virtual destructor for proper cleanup }; class AudioManager { private...
magicoder
cpp
You are tasked with implementing a function to draw a canvas based on a given set of commands. The canvas is represented as a 2D grid of characters, and the commands include drawing lines, rectangles, and filling regions with a specified character. The canvas is initially empty, and the commands are applied sequentiall...
```python from typing import List def _draw_canvas(commands: List[str]) -> List[str]: def draw_line(canvas, x1, y1, x2, y2, c): for y in range(y1 - 1, y2): for x in range(x1 - 1, x2): canvas[y] = canvas[y][:x] + c + canvas[y][x + 1:] def draw_rectangle(canvas, x1, y1, x2, y...
magicoder
python
You are working on a project to model the reaction rates of certain particle interactions in a physics simulation. The code snippet provided is a part of a larger function that calculates the reaction rate for a specific interaction channel. The function takes in various parameters and arrays, performs calculations, an...
```python import numpy as np def calculate_reaction_rate(jfac, eta, c1, c2, WS1D, tau1, tau2, y, target, rho0, m_x, Jvals): R_S1D = jfac / 3.0 * eta * (c1[4] * c2[3] - c1[7] * c2[8]) rate = R_S1D * np.vectorize(WS1D.calcws1d)(tau1, tau2, y, target) conv = (rho0 / 2.0 / np.pi / m_x) * 1.69612985e14 # 1 Ge...
magicoder
python
You are tasked with implementing a task scheduling system using C++ that can handle concurrent execution of tasks. The system should be able to execute a specified number of tasks from multiple threads and ensure that the tasks are executed correctly. Your task is to create a class `TaskScheduler` that provides the fu...
```cpp #include <iostream> #include <thread> #include <vector> #include <functional> #include <mutex> #include <condition_variable> class TaskScheduler { public: TaskScheduler() : counter(0) {} void schedule(const std::function<void()>& task) { std::unique_lock<std::mutex> lock(mutex); tasks.p...
magicoder
cpp
You are tasked with implementing a function to perform coordinate mapping for image scaling and antialiasing. The function takes in the scale factor and a boolean flag indicating whether antialiasing should be applied. It then calculates the output-space coordinates and the corresponding input-space coordinates based o...
```python import numpy as np def coordinate_mapping(scale, antialiasing, out_length): if (scale < 1) and (antialiasing): # Use a modified kernel to simultaneously interpolate and antialias- larger kernel width kernel_width = kernel_width / scale # Output-space coordinates x = np.linspace(1...
magicoder
python
You are tasked with implementing a graph rendering algorithm that takes a list of nodes and their connections as input and produces a visual representation of the graph. Each node is represented by a unique integer, and the connections between nodes are represented as pairs of integers denoting the connected nodes. The...
```python def render_graph(nodes, connections): node_positions = {node: (0, 0) for node in nodes} rendered_graph = "" for connection in connections: node1, node2 = connection x1, y1 = node_positions[node1] x2, y2 = node_positions[node2] if x1 == x2: # Nodes are in the same...
magicoder
python
You are tasked with implementing a generic method to flatten a nested list of elements into a single list. The method should handle lists of any depth and contain elements of any type. You are required to write a Java method that accomplishes this task. Write a method with the following signature: ```java public stati...
```java import java.util.ArrayList; import java.util.List; public class NestedListFlattener { public static List<Object> flatten(List<?> nestedList) { List<Object> flattenedList = new ArrayList<>(); flattenHelper(nestedList, flattenedList); return flattenedList; } private static vo...
magicoder
java
You are tasked with designing a resource allocation system for a cloud computing platform. The system needs to efficiently allocate virtual machine instances to incoming requests based on their resource requirements and the available capacity of the platform. Each virtual machine instance has specific resource requirem...
```python def allocate_resources(total_cpu, total_memory, total_storage, requests): available_cpu = total_cpu available_memory = total_memory available_storage = total_storage allocation_status = [] for request in requests: cpu_req, memory_req, storage_req = request if cpu_req <= av...
magicoder
python
You are tasked with implementing a custom data structure in Rust to securely store and manipulate sensitive information. The data structure, `PvKy`, represents a private key and provides methods for converting the key to an array of bytes and accessing the key as a reference to an array of bytes. Your task is to comple...
```rust use rand::Rng; const SCRT_K_SZ: usize = 32; struct PvKy([u8; SCRT_K_SZ]); impl PvKy { #[inline] pub fn to_octets(&self) -> [u8; SCRT_K_SZ] { self.0 } #[inline] pub fn as_octets<'a>(&'a self) -> &'a [u8; SCRT_K_SZ] { &self.0 } pub fn generate_random() -> PvKy { ...
magicoder
rust
You are tasked with creating a Python function that simulates the behavior of the `isql_act` function used in the given code snippet. The `isql_act` function is responsible for executing a SQL script against a specified database and returning the output. Your task is to implement a function `simulate_isql_act` that ta...
```python import subprocess def simulate_isql_act(database_name, sql_script, substitutions=None): if substitutions: for key, value in substitutions.items(): sql_script = sql_script.replace(key, value) command = f'isql_act {database_name} "{sql_script}"' process = subprocess.Popen(comma...
magicoder
python
You are tasked with creating a Python class that interacts with a music streaming service's API to retrieve information about an artist and their albums. Your class should utilize asynchronous programming to efficiently fetch data from the API. Create a class `MusicService` with the following methods: - `get_artist(ar...
```python import asyncio class MusicService: async def get_artist(self, artist_uri): # Implementation to fetch artist information asynchronously pass async def get_albums(self): # Implementation to fetch albums asynchronously pass async def get_all_albums(self): # ...
magicoder
python
You are tasked with implementing a simple 2D rendering engine that utilizes a geometry object to draw a textured rectangle. The given code snippet provides a portion of the implementation for creating the geometry object. Your task is to complete the implementation by writing a function that takes the vertex and textur...
```python from typing import List from moderngl import BufferDescription, Context, Geometry, Buffer def create_geometry(vertices: List[float], texture_coords: List[float]) -> Geometry: ctx = Context() # Create a moderngl context buffer = ctx.buffer(vertices + texture_coords) # Combine vertex and texture coor...
magicoder
python
You are tasked with creating a program that manages tenants in a housing system. The program should include a class for the Tenant entity and a controller to handle tenant-related operations. The provided code snippet is a starting point for the TenantController class, which is responsible for managing tenants. Your t...
```php // Tenant.php class Tenant { public $name; public $email; public $apartmentNumber; public function __construct($name, $email, $apartmentNumber) { $this->name = $name; $this->email = $email; $this->apartmentNumber = $apartmentNumber; } } // TenantController.php namesp...
magicoder
php
You are tasked with implementing a class to manage a playlist of songs for a music player application. The `PlayerDataType.hh` header file contains the definition of a custom data type `Song` used to represent individual songs in the playlist. The `Song` data type has the following attributes: - `title` (string): The t...
```cpp #include <vector> #include <string> #include "PlayerDataType.hh" // Include the header file containing the Song data type class PlaylistManager { private: std::vector<Song> playlist; public: void addSong(const Song& song) { playlist.push_back(song); } void removeSong(const std::string&...
magicoder
cpp
You are tasked with creating a program that extracts and counts the number of HTML comments within a given HTML file. An HTML comment is defined as any text enclosed within `<!--` and `-->`. Your program should be able to handle multiple HTML comments within the file and provide the total count of comments found. Writ...
```python import re def countHTMLComments(html_content): comment_pattern = r'<!--(.*?)-->' comments = re.findall(comment_pattern, html_content, re.DOTALL) return len(comments) # Test the function with the given example html_content = ''' <reponame>LoveYouForeverS/Codeigniter-Intgration-many-API <!-- BEGIN...
magicoder
python
You are tasked with implementing a function to convert a given 32-bit signed integer into its two's complement representation. The two's complement representation is a binary representation of integers that allows both positive and negative numbers to be represented using the same binary operations. In this problem, yo...
```rust fn twos_complement_representation(num: i32) -> String { let mut result = String::new(); let mut n = num; for _ in 0..32 { result = format!("{}{}", n & 1, result); n >>= 1; } result } ``` The `twos_complement_representation` function takes the input `num` and iterates throu...
magicoder
rust
You are tasked with implementing a translation service for a robot that can translate various languages. The robot's translation functionality is based on implementing the `Translatable` interface, which allows for custom translation implementations using the `@Dictionary` annotation. The `Translatable` interface is d...
```java package com.robot.translator.core.translator; import com.robot.translator.core.annotation.Dictionary; /** * Custom translation implementation for a specific language using the @Dictionary annotation. */ public class CustomTranslator implements Translatable { @Dictionary(method = "customTranslation") ...
magicoder
java
You are tasked with implementing a simple command-line parser that can handle both short and long options. The parser should be able to recognize and extract options and their corresponding values from a given input string. Your task is to write a function `parseCommandLine` that takes a string representing the comman...
```python def parseCommandLine(input_str: str) -> dict: options = {} tokens = input_str.split() i = 0 while i < len(tokens): token = tokens[i] if token.startswith("--"): option, value = token[2:], None if "=" in option: option, value = option.split...
magicoder
python
You are tasked with implementing a memory usage monitoring system for a software application. The system provides a set of functions to track and report various metrics related to memory usage, loaded classes, and the number of threads. Your goal is to create a class that encapsulates this functionality and provides me...
```cpp #include <iostream> class MemoryMonitor { private: size_t _num_of_classes; size_t _num_of_threads; public: void startMonitoring(size_t scale, bool report_diff = false) { start(scale, report_diff); } void finishMonitoring() { done(); } void trackMemoryUsage(size_t t...
magicoder
cpp
You are tasked with implementing a class that utilizes the SentenceTransformer library to vectorize sentences using the LaBSE (Language-agnostic BERT Sentence Embedding) model. The provided code snippet initializes the SentenceTransformer model based on whether a GPU is available and sets up a logger. Your task is to c...
```python import logging from sentence_transformers import SentenceTransformer from sklearn.metrics.pairwise import cosine_similarity from translation_api import translate # Example translation API from pre_trained_classifier import predict_class # Example pre-trained classifier class Labse: def __init__(self, ...
magicoder
python
You are tasked with implementing a function that retrieves a list of recent user images from a server. The server's API is asynchronous and requires a specific request format to fetch the recent images. You are provided with a code snippet that outlines the structure of the request and the function that handles the ret...
```rust use std::rc::Rc; struct State { // Define the application state structure } struct UserRecentImageListRequest { limit: usize, // Other fields if necessary } const RECENT_COUNT: usize = 10; // Completed function implementation async fn get_recent(state: Rc<State>) { let req = UserRecentImageL...
magicoder
rust
You are tasked with creating a Python function that utilizes Celery and a web scraper utility to asynchronously scrape data from multiple URLs and log the results. The function should take a list of URLs as input, scrape the data from each URL using the provided `scraper` utility, and then log the results using Celery'...
```python from celery import Celery from celery.utils.log import get_task_logger from utils import scraper # Define the Celery app app = Celery('scrape_and_log', broker='redis://localhost:6379/0', backend='redis://localhost:6379/0') # Define the Celery task function @app.task def scrape_and_log_task(url): logger ...
magicoder
python
You are working for an environmental research organization that focuses on analyzing petroleum emissions from upstream activities. Your task is to create a Python function that generates a dataset of petroleum emissions for a given year and saves it to a CSV file. The function should take the year as input and produce ...
```python import pandas as pd def generate_petroleum_upstream(year): # Assume emissions data is obtained from a source or generated algorithmically # Here, we create a sample DataFrame for demonstration purposes data = { 'Country': ['USA', 'Canada', 'Russia'], 'Emissions_MT': [150000, 12000...
magicoder
python
You are tasked with implementing a function that will parse a given HTML snippet and extract all the attributes of the `<div>` tags present in the snippet. The function should return a list of dictionaries, where each dictionary represents the attributes of a single `<div>` tag. The function should have the following ...
```python from typing import List, Dict import re def extract_div_attributes(html_snippet: str) -> List[Dict[str, str]]: div_attributes = [] div_pattern = re.compile(r'<div\s+([^>]+)>') attribute_pattern = re.compile(r'(\w+)\s*=\s*["\']([^"\']+)["\']') div_matches = div_pattern.findall(html_snippet) ...
magicoder
python
You are tasked with implementing a custom descriptor in Python for a web automation framework. The descriptor should be used to set the value of a web element on a page. The provided code snippet shows the `__set__` method of the descriptor class. The `is_element_present_until` function is used to check if a web elemen...
```python def is_element_present_until(driver, locator, timeout): # Function to check if the element specified by the locator is present within the given timeout # Implementation of the function is not provided in this solution class CustomDescriptor: def __init__(self, add_locator): self.add_locat...
magicoder
python
You are tasked with implementing a multi-threaded OAuth provider in Rust using the `std::sync` module. The OAuth provider will manage access to various OAuth-related services through a shared state. Your goal is to create a method that allows clients to retrieve a reference to the registrar service in a thread-safe man...
```rust use std::sync::{Arc, Mutex, LockResult, MutexGuard}; // The OAuth related services trait Registrar {} trait Authorizer {} trait Issuer {} /// A struct that wraps all oauth related services and makes them available through state. #[derive(StateData, Clone)] pub struct GothamOauthProvider { registrar: Arc<M...
magicoder
rust
You are tasked with implementing a class to represent elements in a materials science library. The provided code snippet is a part of the class definition and includes the declaration of the `ElementView` class and its member function `atomic_number()`. Your goal is to complete the implementation of the `ElementView` c...
```cpp // Calculate the average atomic mass of the element double ElementView::average_atomic_mass() const { double total_mass = 0.0; double total_abundance = 0.0; // Iterate over isotopes and calculate the weighted average for (int isotope = 1; ; isotope++) { double mass = params_.atomic_mass(...
magicoder
cpp
You are tasked with implementing a Python class that combines the functionality of a counter and an ordered dictionary. Your class should be able to update its elements with those from another dictionary and sort its items based on a given key function. Your task is to create a class `OrderedCounter` that inherits fro...
```python import collections class OrderedCounter(collections.Counter, collections.OrderedDict): def update(self, other): for key, value in other.items(): if key in self: self[key] += value else: self[key] = value @staticmethod def sort(items...
magicoder
python
You are tasked with implementing a function to evaluate uncertainty performance using the Spearman rank correlation. The Spearman rank correlation is a non-parametric measure of statistical dependence between two variables. In this problem, you are required to write a Python function that calculates the Spearman rank c...
```python from typing import List def calculate_spearman_rank_correlation(rank1: List[float], rank2: List[float]) -> float: n = len(rank1) if n != len(rank2): raise ValueError("Input lists must have the same length") # Calculate the differences between the ranks rank_diff = [rank1[i] - rank2[i...
magicoder
python
You are given a data structure representing a linked list with an additional "sibling" pointer. The linked list is represented using the following Node class: ```python class Node: def __init__(self, value): self.value = value self.next = None self.sibling = None ``` The `next` pointer poi...
```python def clone_linked_list_with_sibling(head: Node) -> Node: if not head: return None # Step 1: Create a copy of each node and insert it next to the original node current = head while current: new_node = Node(current.value) new_node.next = current.next current.next ...
magicoder
python
You are tasked with implementing a function to retrain a GAN (Generative Adversarial Network) model using a given dataset. The provided code snippet gives a starting point for the retraining process. Your task is to complete the function `retrain` by implementing the training loop and handling the optimization steps. ...
```python def retrain(scratchgan, dataset, N, batch_size=1): scratchgan.train() for n in range(N): # Take a batch of data from the dataset x, y = next(dataset.take(1, batch_size)) # Perform the optimization steps for the GAN model using the batch of data for _ in range(1...
magicoder
python
You are tasked with implementing a binary tree node class and a method to serialize the binary tree into a JSON object. The binary tree node class has the following structure: ```javascript class TreeNode { constructor(value, left = null, right = null) { this.value = value; this.left = left; ...
```javascript class TreeNode { constructor(value, left = null, right = null) { this.value = value; this.left = left; this.right = right; } serializeToJSON(node) { if (node === null) { return null; } let serializedNode = { ...
magicoder
javascript
You are tasked with implementing a file open dialog class in C++ that utilizes the Windows API. The provided code snippet is a part of the implementation for the file open dialog class. The `c_file_open_dlg` class contains a constructor and a method for displaying the file open dialog window. The constructor initialize...
```cpp #include <windows.h> class c_file_open_dlg { private: OPENFILENAME _ofn; // Structure to hold the file open dialog information TCHAR _szFile[MAX_PATH]; // Buffer to store the selected file's path public: c_file_open_dlg() { ZeroMemory(&_ofn, sizeof(_ofn)); // Initialize the OPENFILENAME str...
magicoder
cpp
You are tasked with implementing a class that simulates a simple social media platform's user management system. The class should allow for the creation of user profiles and the retrieval of user IDs. Additionally, the class should provide a method to set the owner of a particular post or content. You are provided wit...
```python class UserManagement: def __init__(self): self.user_profiles = {} # Dictionary to store user profiles {username: userId} self.post_owners = {} # Dictionary to store post owners {postId: userId} self.next_user_id = 1 # Counter to generate unique user IDs def createUserProfil...
magicoder
python
You are tasked with creating a Python program to automate the generation of Abstract Syntax Tree (AST) visualizations for a given source file. The program should utilize subprocess to execute external commands and handle the generation of AST visualizations. Your program should perform the following steps: 1. Execute ...
```python import subprocess class ASTWindow: def __init__(self, data_dir, jpg_filename): self.data_dir = data_dir self.jpg_filename = jpg_filename def show(self): # Implementation of displaying the AST visualization in a window pass class ASTGenerator: def __init__(self, f...
magicoder
python
You are working on a project that involves processing and analyzing large datasets using TensorFlow, a popular open-source machine learning library. As part of this project, you need to write a Python function that reads data from a file and performs specific operations on the data using TensorFlow. Your task is to im...
```python import tensorflow as tf def process_data(filename: str): if tf.executing_eagerly(): arrays, shapes, dtypes = tf.raw_ops.IOReadFile(filename=filename) arrays = tf.unstack(arrays) return arrays, shapes, dtypes else: raise RuntimeError("TensorFlow is not executing eagerly...
magicoder
python
You are working on a project to analyze product reviews and ratings. You have a database with two tables: `Product` and `Review_Statement`. The `Product` table contains information about various products, including their `id`. The `Review_Statement` table contains the `product_id`, `review_count`, and `avg_rating` for ...
```python def retrieve_product_info(session): products_info = [] for product, review_count, avg_rating in session.query( Product, ReviewStatement.review_count, ReviewStatement.avg_rating ).outerjoin(ReviewStatement, Product.id == ReviewStatement.product_id): product_info = { 'pro...
magicoder
python
You are tasked with implementing a class for a machine learning ensemble model. The class is responsible for setting certain parameters and attributes based on the input values. The given code snippet is a part of the class initialization method. The class has attributes `n_classifiers_`, `pct_accuracy`, `pct_diversity...
```python import numpy as np import metrics # Assuming the metrics module is imported class EnsembleModel: def __init__(self, n_classifiers, pct_accuracy, pct_diversity, metric_performance): self.n_classifiers_ = n_classifiers self.pct_accuracy = pct_accuracy self.pct_diversity = pct_diver...
magicoder
python
You are tasked with implementing a Python class for embedding protein sequences using a pre-trained model. The class should load a pre-trained model, preprocess input sequences, and generate embeddings for the sequences. Your task is to complete the implementation of the `embed` method in the given class. You are prov...
```python import torch from typing import List, Tuple from pathlib import Path from esm import Alphabet, Embedder class ProteinEmbedder: def __init__(self, max_sequence_len: int, embedding_size: int): self.model, self.alphabet = Embedder.pretrained.load_model_and_alphabet("esm1_t6_43M_UR50S") self....
magicoder
python
You are tasked with creating a Python program that connects to a remote server via SSH, retrieves the network interface configuration using the `ifconfig` command, and then prints the output to the console. Your program should utilize the `paramiko` library for SSH connectivity. Write a Python program that accomplishe...
```python import paramiko def main(): # SSH connection parameters hostname = 'remote_server_ip' username = 'your_username' password = 'your_password' # Establish SSH connection ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: ssh.connect...
magicoder
python
You are tasked with implementing a function that calculates the factorial of a given non-negative integer using recursion. The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. The factorial of 0 is defined to be 1. You need to implement the following function: ```...
```python def factorial(n): if n == 0 or n == 1: return 1 else: return n * factorial(n - 1) ``` The `factorial` function uses recursion to calculate the factorial of the given non-negative integer `n`. If the input `n` is 0 or 1, the function returns 1. Otherwise, it recursively calls itself wi...
magicoder
python
You are given two strings, s1 and s2, and a third string, s3. Your task is to determine whether s3 can be formed by interleaving the characters of s1 and s2 in a way that maintains the left-to-right order of the characters from each string. For example, given s1 = "aabcc", s2 = "dbbca", and s3 = "aadbbcbcac", the func...
```python def isInterleave(s1: str, s2: str, s3: str) -> bool: if len(s1) + len(s2) != len(s3): return False dp = [[False] * (len(s2) + 1) for _ in range(len(s1) + 1)] dp[0][0] = True for i in range(len(s1) + 1): for j in range(len(s2) + 1): if i > 0: dp[i][...
magicoder
python
You are tasked with implementing a function that can parse and extract data from an HTML snippet. The HTML snippet contains a closing `</div>` tag followed by a closing `</x-app-layout>` tag. Your task is to extract the content between these two closing tags and return it as a string. Write a function `extractContent`...
```python def extractContent(htmlSnippet): div_end_index = htmlSnippet.find("</div>") app_layout_index = htmlSnippet.find("</x-app-layout>") if div_end_index != -1 and app_layout_index != -1: return htmlSnippet[div_end_index + len("</div>"):app_layout_index] else: return "" # Test ...
magicoder
python
You are working on a computer vision project that involves training a neural network for image segmentation. During the training process, you are using the Lovász-Hinge loss function to optimize the network's performance. The Lovász-Hinge loss is a differentiable surrogate for the IoU (Intersection over Union) loss, co...
```python def calculate_and_update_loss(loss_1, loss_f, loss_2, loss_3, loss_4, batch_size, loss_record, loss_4_record, loss_3_record): total_loss = loss_1 + loss_f + loss_2 + loss_3 + loss_4 loss_record.update(total_loss.data, batch_size) loss_4_record.update(loss_4.data, batch_size) loss_3_record.upda...
magicoder
python
You are working on a web scraping project to extract information about exam schedules from a university website. The given code snippet is a part of a larger program that uses the BeautifulSoup library to parse HTML and extract relevant data. The `get_excel_url` function takes a URL as input, retrieves the HTML content...
```python import requests from bs4 import BeautifulSoup ROOT = 'http://pdaotao.duytan.edu.vn' def get_url_sub(subject_name, subject_id, class_level): url = f"{ROOT}/EXAM_LIST_Detail/?ID={subject_id}&lang=VN" r = requests.get(url) if r.status_code == 200: soup = BeautifulSoup(r.text, 'lxml') ...
magicoder
python
You are tasked with implementing a function to decode a user token and extract the user ID from it. The user token is provided in the form of a JSON object. The function should handle potential errors and return the user ID if the decoding is successful. You are given the following code snippet as a reference: ```pyt...
```python from typing import Optional, Tuple import jwt def decode_user_token(user_token: str, private_key: str, check_if_admin: bool) -> Tuple[Optional[str], Optional[str]]: try: decoded_token = jwt.decode(user_token, private_key, algorithms=['HS256']) if check_if_admin and not decoded_token.get('...
magicoder
python
You are tasked with implementing a Python function that processes a given list of strings representing different algorithm categories and returns a dictionary containing the count of each category. The categories are represented by the following constants: `GENERAL`, `HEM`, `FL_AGG`, `MTL`, and `UTD`. The function shou...
```python from typing import List, Dict def count_algorithm_categories(categories: List[str]) -> Dict[str, int]: category_counts = { 'general': 0, 'hard_example_mining': 0, 'aggregation': 0, 'multi_task_learning': 0, 'unseen_task_detect': 0 } for category in categor...
magicoder
python
You are given a code snippet that seems to be part of a dynamic programming algorithm. Your task is to complete the algorithm by implementing the missing parts. The algorithm aims to fill a 2D array `dp` using the values from string `r` and integer `n`. The array `dp` has dimensions `n x 10`, where `n` is the length ...
```cpp #include <iostream> #include <vector> #include <string> using namespace std; void fillDP(vector<vector<int>>& dp, const string& r) { int n = r.length(); for (int i = n - 1; i >= 0; i--) { for (int j = 0; j < 10; j++) { dp[i][j] = 0; if (r[i] - '0' < j || (i + 1 < n && r[...
magicoder
cpp
You are tasked with implementing a transient solver for a mathematical model using the given code snippet as a reference. The model represents a physical system, and the transient solver is used to simulate the behavior of the system over time. The code snippet sets up the model and then calls the transient solver to o...
```python import numpy as np from scipy.sparse import diags from scipy.sparse.linalg import spsolve class Model: def __init__(self, mesh_pts): self.mesh_pts = mesh_pts self.forcing_function = lambda x, t, z: 0*x self.num_time_steps = 1000 self.initial_sol = np.sin(np.pi*self.mesh_pt...
magicoder
python
You are working on a robotics project that involves processing and normalizing pose data. The pose data consists of a 7-dimensional vector representing the position and orientation of a robotic arm. The first three elements of the vector represent the x, y, and z coordinates of the position, and the next four elements ...
```python import numpy as np def normalize_pose(pose): norm_pose = np.zeros((7, )) norm_pose[0:3] = pose[0:3] norm_pose[3] = np.cos(np.deg2rad(pose[3])) # Normalize the quaternion components quaternion = pose[4:] norm_quaternion = quaternion / np.linalg.norm(quaternion) norm_pose[4:] =...
magicoder
python
You are tasked with simulating the movement of particles in a 3D space. The given code snippet represents the update logic for each particle in the simulation. The variables `velocity`, `start_position`, and `start_velocity` are arrays containing the initial velocity, position, and start velocity of each particle, resp...
```cpp #include <vector> #include <glm/glm.hpp> std::vector<glm::vec3> simulateParticles(const std::vector<glm::vec4>& start_position, const std::vector<glm::vec4>& start_velocity, float time_step, ...
magicoder
cpp
You are tasked with implementing a Python decorator that collects and manages producer functions. A producer function is a function that generates data or performs some computation to produce a result. The decorator should allow registering producer functions and provide a way to retrieve all registered producers. You...
```python def producer_registry(func): producer_funcs = [] def factory(*args, **kwargs): producer_funcs.append(func) return func(*args, **kwargs) return factory def collect_producers(): return producer_funcs ``` The solution provided above completes the implementation of the `produce...
magicoder
python
You are tasked with creating a comment system for a product review platform. The platform allows users to submit comments on products, and the comments are validated and stored in a database. Your task is to implement the backend logic for creating a new comment using Laravel's validation and model creation. You are g...
```php public function createComment(Request $request, Product $product) { $validatedData = $request->validate([ 'value' => ['required', 'string', 'min:1', 'max:400'] ]); $comment = $product->comments()->create([ 'value' => $validatedData['value'], 'user_id' => Auth::id() ]); ...
magicoder
php
You are tasked with implementing a property serialization system for a software application. The system needs to support different types of properties, including enumeration, flags, and string properties. Each property type has a corresponding class (CEnumProperty, CFlagsProperty, CStringProperty) that provides a metho...
```cpp #include <iostream> #include <string> // Define the enumeration for property types enum class EPropertyType { Enum, Flags, String }; // Base class for properties class CProperty { public: virtual ~CProperty() {} }; // Class for enumeration properties class CEnumProperty : public CProperty { public: in...
magicoder
cpp
You are tasked with implementing a scheduling algorithm for a parallel processing system. The system consists of a number of processors organized into a hierarchical structure with multiple levels. Each level has a specific fan-out, which represents the number of processors at the next lower level that a single process...
```cpp Scheduler* createScheduler(int num_procs, int num_levels, const vector<int>& fan_outs, const vector<int>& sizes, const vector<int>& block_sizes, char arg) { Scheduler* sched = nullptr; if (arg == '2') { sched = new HR2Scheduler(num_procs, num_levels, fan_outs, sizes, block_sizes, 0); } else i...
magicoder
cpp
You are tasked with creating a Python program that generates an image with a specified text written on it using the ImageFont module from the PIL library. The program should take the following inputs: - Text to be written on the image - Font file path - Output image file path The program should then use the specified f...
```python from PIL import Image, ImageFont, ImageDraw def write_text_on_image(text, font_path, output_path): # Create a blank image with white background image = Image.new("RGB", (400, 200), "white") # Load the specified font font = ImageFont.truetype(font_path, 20) # Initialize ImageDraw...
magicoder
python
You are tasked with creating a Python class that simulates a simple pipeline for data processing. The pipeline will consist of multiple steps, each of which can be configured with specific properties. Your task is to implement the `Pipeline` class with the following functionalities: 1. The `Pipeline` class should allo...
```python class Pipeline: def __init__(self, code_version): self.pipeline_config = { "code_version": code_version, "steps": [], "description": "", "owner": "" } def owner(self, owner_name): self.pipeline_config["owner"] = owner_name ...
magicoder
python
You are tasked with creating a simple HTTP client library in C#. Your library should include a method to make a GET request to a given URI and deserialize the response into an object of a specified type. However, you need to ensure that the HTTP client is used in a non-blocking manner to prevent potential deadlocks and...
```csharp using System; using System.Net.Http; using System.Threading.Tasks; using Newtonsoft.Json; public class SimpleHttpClient { private readonly HttpClient _httpClient; public SimpleHttpClient() { _httpClient = new HttpClient(); } public async Task<T> GetAndDeserializeAsync<T>(string ...
magicoder
csharp
You are given a code snippet that represents a part of a program. Your task is to understand the code and implement a specific functionality based on the given snippet. The code snippet provided is a part of a program that involves variable declarations, arithmetic operations, bitwise operations, and looping construct...
```rust fn main() { let mut z: u32 = 0; // Declaration and initialization of variable z let q: u32 = (6 + 52 / length) as u32; // Assuming length is a valid variable let mut sum: u32 = q.wrapping_mul(DELTA); // Assuming DELTA is a valid constant while sum != 0 { let e = (sum >> 2) & 3; // Imple...
magicoder
rust
You are tasked with creating a program to manage user data for a web application. The program should implement basic CRUD (Create, Read, Update, Delete) operations for user entities. However, there is a requirement to discourage the direct usage of CRUD operations and instead promote the use of commands and queries for...
```csharp using System; public class UserManagement { [Obsolete("Please favor commands/queries; see https://github.com/HTBox/allReady/issues/1130", false)] public void Create(User user) { // Implementation for adding a new user } [Obsolete("Please favor commands/queries; see https://github...
magicoder
csharp
You are tasked with creating a reinforcement learning environment for a simple game. The game consists of a single agent navigating a grid-world, with the objective of reaching a goal state while avoiding obstacles. The agent can move in four directions: up, down, left, and right. The environment is represented as a gr...
```python import numpy as np class SimpleGameEnvironment: def __init__(self, grid): self.grid = grid self.num_rows = len(grid) self.num_cols = len(grid[0]) self.initial_state = self.find_initial_state() self.goal_state = self.find_goal_state() def find_initial_state(sel...
magicoder
python
You are tasked with implementing a Python function that processes a collection of documents retrieved from a web archive file. The documents are stored in a specific format within the file, and your function needs to extract and process these documents according to certain criteria. You are provided with a code snippe...
```python import json from warcio.archiveiterator import ArchiveIterator from warcio.warcwriter import WARCWriter from warcio.timeutils import iso_date_to_timestamp class MetadataFetcher: def __init__(self, tmp_path): self.tmp_path = tmp_path def map(self, cc): # Implement the logic to retriev...
magicoder
python
You are tasked with creating a program that simulates the behavior of the `phpcbf` command-line tool used in PHP development. The `phpcbf` tool is used for automatically fixing PHP coding standards issues. The command-line snippet provided is an example of using `phpcbf` with the following options: - `-p`: Indicates th...
```python import multiprocessing def simulate_phpcbf_behavior(files, coding_standard): print("Simulating phpcbf behavior:") print("Processing files in parallel...") with multiprocessing.Pool() as pool: pool.map(process_file, files) print("Colorizing output...") print("Generating full report...
magicoder
python
You are tasked with implementing a method in the `EloquentImageRepository` class that filters and returns a collection of images based on certain criteria. The `EloquentImageRepository` class is a part of a Laravel application and implements the `ImageRepository` interface. The `ImageRepository` interface defines a met...
```php use Illuminate\Database\Eloquent\Collection; class EloquentImageRepository implements ImageRepository { public function filterImages(array $criteria): Collection { $query = Image::query(); foreach ($criteria as $attribute => $value) { $query->where($attribute, $value); ...
magicoder
php
You are tasked with implementing a function to determine the order of execution for a set of tasks with dependencies. Each task is represented by a unique integer, and the dependencies are represented as pairs of tasks, where the first task must be completed before the second task can be started. Your function should r...
```python from typing import List, Tuple class CyclicDependencyError(Exception): pass def determine_execution_order(dependency_pairs: List[Tuple[int, int]]) -> List[int]: graph = {} in_degree = {} # Build the graph and calculate in-degrees for pair in dependency_pairs: task1, task2 = ...
magicoder
python
You are tasked with implementing a Python class that performs encryption and decryption using the Rot18 cipher. The Rot18 cipher is an extension of the Rot13 cipher, which is a simple letter substitution cipher that replaces a letter with the 13th letter after it in the alphabet. The Rot18 cipher extends this concept b...
```python class Rot18: """ The Rot18 Cipher """ __rot13 = Rot13() def __init__(self): alphabet = al.ENGLISH half = len(alphabet) >> 1 self.__alphabet = alphabet[:half] + al.DECIMAL[:5] + alphabet[half:] + al.DECIMAL[5:] def encrypt(self, message): encrypted_mess...
magicoder
python
You are tasked with creating a program that calculates the phase of the moon for a given date. The phase of the moon refers to the shape of the illuminated portion of the moon as seen from Earth. The program should take a date as input and determine the corresponding phase of the moon on that date. Write a function `c...
```python from ephem import Moon, next_full_moon, next_new_moon def calculate_moon_phase(date): observer = Moon() observer.compute(date) next_full = next_full_moon(date) next_new = next_new_moon(date) if observer.phase < 0.01 or observer.phase > 99.9: return "New Moon" elif abs(observe...
magicoder
python
You are tasked with creating a custom sensor for a home automation system using the Home Assistant platform. The sensor will retrieve and display cryptocurrency exchange rates in a user-friendly format. The exchange rates will be fetched from a third-party API and displayed in the Home Assistant dashboard. You are pro...
```python import requests from homeassistant.const import ATTR_ATTRIBUTION from homeassistant.components.sensor import SensorEntity CURRENCY_ICONS = { "BTC": "mdi:currency-btc", "ETH": "mdi:ethereum", "EUR": "mdi:currency-eur", # Add more cryptocurrency icons as needed } class CryptoCurrencySensor(Sen...
magicoder
python
You are given a string containing hexadecimal values. Each pair of hexadecimal values represents a byte of data. Your task is to write a function to convert this string into its corresponding ASCII representation. Write a function `hex_to_ascii(hex_string: str) -> str` that takes a string `hex_string` as input and ret...
```python def hex_to_ascii(hex_string: str) -> str: # Remove any leading or trailing whitespace and split the string into pairs of hexadecimal values hex_values = hex_string.strip().split('\\x')[1:] # Convert each pair of hexadecimal values to its corresponding ASCII character ascii_string = ''.join(ch...
magicoder
python
You are given a 2D grid representing a terrain map. Each cell in the grid contains an integer representing the elevation at that point. Your task is to implement a function that calculates the number of peaks in the terrain. A peak is defined as a cell whose elevation is greater than or equal to all of its neighboring ...
```cpp #include <vector> using namespace std; const int dx[] = {1, 0, -1, 0}; const int dy[] = {0, -1, 0, 1}; bool isPeak(int x, int y, const vector<vector<int>>& grid) { for (int i = 0; i < 4; i++) { int nx = x + dx[i]; int ny = y + dy[i]; if (nx >= 0 && nx < grid.size() && ny >= 0 && ny ...
magicoder
cpp
You are tasked with creating a Python function that simulates the behavior of a simplified version of the `pytest` command-line tool. The function should take in a list of arguments and return the final exit code that would be produced by running `pytest` with those arguments. The `pytest` command-line tool is commonl...
```python import sys def simulate_pytest_exit_code(pytest_args, cov_flag): if cov_flag: pytest_args.insert(0, '--cov=%s' % src) return pytest.main(pytest_args) ``` The `simulate_pytest_exit_code` function takes in the `pytest_args` list and the `cov_flag` boolean. If `cov_flag` is `True`, it inserts t...
magicoder
python
You are tasked with creating a Python function that processes protein structure data using the ProDy library. The function should take a list of protein structure files and return a dictionary containing the number of atoms in each structure. The code snippet provided serves as a starting point for your function. Your...
```python import numpy import prody def count_atoms(dcds): atom_counts = {} for pdb in dcds: if len(dcds) == 0: atom_counts[pdb] = numpy.array([]) else: topo = prody.parsePDB(pdb) atom_counts[pdb] = len(topo.select('protein and name CA')) return atom_coun...
magicoder
python
You are tasked with implementing a program that can efficiently determine the number of occurrences of a given word in a text file. The program should read the text file, tokenize the words, and then count the occurrences of the specified word. You are given a code snippet that reads a text file and tokenizes the word...
```java import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.StringTokenizer; public class WordCounter { public static void main(String[] args) { try { File file = new File("input.txt"); Scanner scanner = new Scanner(file); ...
magicoder
java
You are tasked with implementing a function that performs a deep copy of a given JavaScript object. A deep copy creates a new object and recursively copies all nested objects and their properties, ensuring that the original and copied objects are completely independent. You should not use any built-in functions or libr...
```javascript function deepCopy(obj) { if (obj === null || typeof obj !== 'object') { return obj; } const copy = Array.isArray(obj) ? [] : {}; for (let key in obj) { if (obj.hasOwnProperty(key)) { copy[key] = deepCopy(obj[key]); } } return copy; } const originalObject = { name: "John...
magicoder
javascript
You are tasked with implementing a prioritized replay buffer for a reinforcement learning algorithm. The prioritized replay buffer is a data structure used in training deep reinforcement learning models, such as Deep Q-Networks (DQN). The buffer stores experiences (state, action, reward, next state, and done flag) and ...
```python import numpy as np import heapq class PrioritizedReplayBuffer: def __init__(self, max_size, alpha, beta_initial, epsilon): self.max_size = max_size self.alpha = alpha self.beta = beta_initial self.epsilon = epsilon self.buffer = [] self.priorities = np.zero...
magicoder
python