query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with creating a function that extracts the route prefix from a given HTML code snippet. The route prefix is defined as the value assigned to the `route_prefix` variable within a `<script>` tag in the HTML code. The function should take the HTML code as input and return the route prefix value. Function S...
```javascript function extractRoutePrefix(htmlCode) { const scriptTagStart = htmlCode.indexOf('<script>'); const scriptTagEnd = htmlCode.indexOf('</script>', scriptTagStart); if (scriptTagStart !== -1 && scriptTagEnd !== -1) { const scriptContent = htmlCode.substring(scriptTagStart, scriptTagEnd); ...
magicoder
javascript
You are tasked with implementing a priority queue using a max-heap data structure. A priority queue is an abstract data type that operates similar to a regular queue or stack, but where each element has a priority associated with it. In this problem, you will implement the `MaxHeapPriorityQueue` class, which supports t...
```java public void insert(int value, int priority) { Element newElement = new Element(value, priority); heap.add(newElement); int currentIndex = heap.size() - 1; while (currentIndex > 0) { int parentIndex = (currentIndex - 1) / 2; if (heap.get(currentIndex).priority > heap.get(parentInd...
magicoder
java
You are tasked with implementing a simple UI update function for a mobile application. The function should update the title and subtitle labels based on the provided view data and adjust the box constraints accordingly. You are given the following code snippet as a starting point: ```swift private func updateUI() { ...
```swift private func updateUI() { if let title = viewData?.getTitle?() { titleLabel.text = title } else { titleLabel.text = "Default Title" } if let subtitle = viewData?.getSubtitle?() { subtitleLabel.text = subtitle } else { subtitleLabel.text = "Default Subtit...
magicoder
swift
You are tasked with implementing a higher-order component (HOC) in a React application. The HOC should provide the ability to specify a custom component to be used for rendering a header or footer within a details view. The provided code snippet defines some types and interfaces that are relevant to this task. Your ta...
```javascript import React, { ComponentType } from 'react'; type CustomComponentProps = { headerComponent?: ComponentType<any>; footerComponent?: ComponentType<any>; }; function withCustomComponent<T extends CustomComponentProps>( BaseComponent: ComponentType<T> ): ComponentType<T> { return function WithCusto...
magicoder
javascript
You are tasked with creating a program that parses and extracts metadata information from a given PHP script's comment block. The metadata includes the author's name, email, copyright years, license, version, link, and any additional notes. The comment block is formatted as follows: ```php /** * @author <NAME> <<...
```python import re def extract_metadata(php_script): metadata = {} comment_block = re.search(r'/\*\*(.*?)\*/', php_script, re.DOTALL) if comment_block: metadata_lines = comment_block.group(1).strip().split('\n') for line in metadata_lines: match = re.match(r'\s*\*\s*@(\w+)\s+(....
magicoder
python
You are given a matrix representing the cost of traveling from one city to another. The matrix has dimensions `n x 3`, where `n` is the number of cities. Each row represents a city, and the three columns represent the cost of traveling to the next city in three different modes of transportation. You need to find the mi...
```python from typing import List def minCostTravel(matrix: List[List[int]]) -> int: n = len(matrix) if n == 1: return min(matrix[0]) dp = [[0, 0, 0] for _ in range(n)] dp[0] = matrix[0] for i in range(1, n): dp[i][0] = matrix[i][0] + min(dp[i-1][1], dp[i-1][2]) dp[i][1] =...
magicoder
python
You are tasked with implementing a function that processes and formats data from a 3D array into a specific text format. The function takes in three parameters: `header` (a string representing the header of the data), `data` (a 3D array containing the data to be processed), and `shape` (a tuple representing the shape o...
```python from typing import List, Tuple def process_data(header: str, data: List[List[List[int]]], shape: Tuple[int, int, int]) -> int: with open('processed_data.txt', 'w') as f: f.write(header + '\n') elements_processed = 0 for n in range(shape[1]): d = data[n] d_s...
magicoder
python
You are tasked with creating a Python function to securely store and retrieve sensitive information, such as API keys, using environment variables. Environment variables are a secure way to store sensitive information outside of your codebase, preventing accidental exposure of credentials. Your function should retrieve...
```python import os import requests def fetch_api_data(): try: consumer_key = os.environ['consumer_key'] consumer_secret = os.environ['consumer_secret'] access_token = os.environ['access_token'] access_secret = os.environ['access_secret'] headers = { 'Authorizat...
magicoder
python
You are tasked with creating a script to generate SSL/TLS certificates for a server. The script takes command-line arguments and environment variables to customize the certificate generation process. Your task is to complete the script by implementing the missing parts. The script starts by setting a default value for...
```bash #!/bin/bash TLS_FILE_PREFIX=${TLS_FILE_PREFIX:-server} # The certificate's common name. [ "${#}" -ge "1" ] || { echo "COMMON_NAME is required"; exit 1; } TLS_COMMON_NAME="${1}" # The signing CA. [ -e "${TLS_CA_CRT-}" ] || { echo "the public key of the CA must be specified with -1"; exit 1; } [ -e "${TLS_CA_K...
magicoder
shell
You are tasked with implementing a Python function that checks for the presence of specific modules and their submodules within a given code snippet. The code snippet provided contains import statements for various modules and submodules. Your task is to create a function that identifies the presence of the "torch" mod...
```python import ast def check_module_imports(code: str) -> bool: tree = ast.parse(code) for node in ast.walk(tree): if isinstance(node, ast.Import): for alias in node.names: if alias.name.split('.')[0] == 'torch': return True elif isinstance(node...
magicoder
python
You are tasked with creating a script to automate the testing of multiple frontend packages in a project. The script should iterate through each package in the `frontend` directory, run the tests using npm, and handle any errors that occur during testing. Your task is to write a bash script that accomplishes the follo...
```bash #!/bin/bash echo "Testing..." for pkg in $(ls frontend); do cd "$pwd_cache/frontend/$pkg" # Assuming $pwd_cache is a valid variable containing the project's root directory set -e npm run test if [ $? -ne 0 ]; then echo "Error while testing frontend/$pkg" exit $? fi done ``` In the solutio...
magicoder
shell
You are given a list of application names `APP_STR` and a function `filter_apps` that takes a list of strings and returns a new list containing only the strings that are present in `APP_STR`. However, the function has a bug that causes it to return an empty list. Your task is to fix the bug in the `filter_apps` functio...
```python def filter_apps(app_names): return [app for app in app_names if app in APP_STR] APP_STR = ['INS', 'VG', 'VG_AHRS', 'Compass', 'Leveler', 'IMU', 'OpenIMU'] ``` The bug in the original `filter_apps` function was that it was not correctly checking if each app name in the input list was present in the `APP_S...
magicoder
python
You are tasked with creating a Django management command that generates a given number of random documents for a specific category. The code snippet provided is a part of the handle method of the management command. The handle method takes two arguments: the number of documents to create and the ID of the category for ...
```python import random from django.core.management.base import BaseCommand from yourapp.models import Document, Category class Command(BaseCommand): help = 'Creates a given number of random documents' def add_arguments(self, parser): parser.add_argument('nb_of_docs', type=int, help='Number of documen...
magicoder
python
You are working on a bioinformatics pipeline that involves processing DNA sequencing data in the BAM file format. The code snippet provided is a part of a Python script that utilizes the `subprocess` module to execute a command-line tool called `samtools`. This tool is used for manipulating BAM files, specifically for ...
```python import pysam import os def sort_and_index_bam(input_bam, output_bam, threads): # Sort the input BAM file with pysam.AlignmentFile(input_bam, "rb") as bam_in: with pysam.AlignmentFile(output_bam, "wb", template=bam_in) as bam_out: for read in bam_in.fetch(): bam_out...
magicoder
python
You are tasked with implementing a custom form type in a PHP application using the Symfony framework. The form type should be named `ProductType` and should extend the `AbstractType` class provided by Symfony. Your task is to define the necessary methods and configurations within the `ProductType` class to create a for...
```php use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class ProductType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('name') ...
magicoder
php
You are tasked with creating a program that manages user roles in a web application. The program should allow users to be assigned different roles, such as "Admin", "User", "Manager", etc. Each role should have specific permissions associated with it, and users should be able to have multiple roles assigned to them. Y...
```csharp using System; using System.Collections.Generic; public class UserRole { public string Name { get; set; } public List<string> Permissions { get; set; } public UserRole(string name) { Name = name; Permissions = new List<string>(); } public void AddPermission(string per...
magicoder
csharp
You are tasked with creating a custom neural network model for a graph-based classification problem. The model will take graph data as input and perform a series of operations to produce a classification output. The graph data consists of nodes and edges, where each node represents a data point and edges represent rela...
```python import torch import torch.nn as nn from torch_geometric.nn import MessagePassing from torch_geometric.utils import add_self_loops, degree class CustomGraphNetwork(nn.Module): def __init__(self, input_dim, hidden_dim, num_classes): super(CustomGraphNetwork, self).__init__() self.conv1 = Cu...
magicoder
python
You are tasked with implementing a Python class that extends the functionality of the `UuidAuditedModel` class from the `api.models` module. Additionally, you need to utilize the `fingerprint` function from the `api.utils` module to generate a unique fingerprint for each instance of the class. The `UuidAuditedModel` cl...
```python from api.models import UuidAuditedModel from api.utils import fingerprint class FingerprintedUuidAuditedModel(UuidAuditedModel): fingerprint = models.CharField(max_length=255, blank=True) def save(self, *args, **kwargs): if not self.fingerprint: self.fingerprint = fingerprint(sel...
magicoder
python
You are tasked with implementing a stochastic gradient descent algorithm for logistic regression. Logistic regression is a popular classification algorithm that models the probability of a binary outcome. The given code snippet provides the necessary functions for logistic regression, including the sigmoid function, th...
```python import numpy as np # sigmoid function def my_sigmoid(w, x): return 1 / (1 + np.exp(-w.T.dot(x.T))) # 损失函数 def obj_fun(w, x, y): tmp = y.reshape(1, -1) * np.log(my_sigmoid(w, x)) + (1 - y.reshape(1, -1)) * np.log(1 - my_sigmoid(w, x)) return np.sum(-tmp) # 计算随机梯度的函数 def my_Stgrad(w, x, y): r...
magicoder
python
You are tasked with implementing a Python class that validates the scale for a 3D scatter plot using the Plotly library. The provided code snippet is a part of the class definition and shows the initialization of the `ScaleValidator` class, which is a subclass of a parent class. Your task is to complete the implementat...
```python class ScaleValidator(ParentClass): def __init__(self, plotly_name='scale', parent_name='scatter3d.projection.x', **kwargs): super(ScaleValidator, self).__init__(plotly_name, parent_name, **kwargs) def validate_scale(self, scale_value): # Add validation logic for scale value here ...
magicoder
python
You are tasked with implementing a multi-threaded encryption and decryption system using Rust. The system should utilize the `Arc` and `Mutex` types to ensure safe concurrent access to a shared `Cipher` instance. The `Cipher` struct contains the necessary methods for encryption and decryption. You are provided with th...
```rust use std::sync::{Arc, Mutex}; use std::thread; struct Cipher { // Define the necessary fields and methods for encryption and decryption key: u8, } impl Cipher { fn new() -> Self { Cipher { key: 3 } } fn encrypt(&self, data: &str) -> String { let encrypted: String = data.cha...
magicoder
rust
You are tasked with completing a C++ program that establishes a connection to a server using a specified IP address and port number. The program should then send a word to the server and receive a response. Your task is to implement the missing parts of the program to achieve this functionality. The provided code snip...
```cpp #include <iostream> #include <cstring> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #define PORTNUM 3425 #define BUFSIZE 256 int main(int argc, char** argv) { if (argc < 3) { std::cout << "need IP address as 1 argument and WORD as 2 argument\n"; return 1; } ...
magicoder
cpp
You are tasked with creating a program that checks the validity of software licenses based on the Apache License, Version 2.0. The Apache License, Version 2.0 is a widely used open-source software license that allows users to use, modify, and distribute the licensed software. Your program should verify whether a given ...
```python import re def validateApacheLicense(licenseText: str) -> bool: apache_license_pattern = r"Licensed under the Apache License, Version 2.0" disclaimer_pattern = r"You may not use this file except in compliance with the License." copyright_pattern = r"Copyright .*" permission_pattern = r"You may...
magicoder
python
You are tasked with implementing a function that performs a specific image processing operation. The function takes in an input image `observation`, and it needs to zoom in on the central portion of the image while maintaining the original image dimensions. The provided code snippet can be used as a reference for the i...
```python import cv2 as cv def zoom_in(observation): old_len = observation.shape[0] # Assuming observation is a square image new_len = old_len // 2 # Assuming zooming in to half the original size off_len = (old_len - new_len) // 2 boundary = off_len + new_len zoomed_in = observation[off_len:boun...
magicoder
python
You are tasked with implementing a JWT (JSON Web Token) decoder in Java. A JWT is a compact, URL-safe means of representing claims to be transferred between two parties. The JWT consists of three parts separated by dots: the header, the payload, and the signature. Each part is base64 encoded, and the resulting strings ...
```java import java.util.Base64; import org.json.JSONObject; public class JWTDecoder { public static JSONObject decode(String jwt) { String[] parts = jwt.split("\\."); if (parts.length != 3) { return new JSONObject(); } String payload = parts[1]; try { ...
magicoder
java
You are tasked with implementing a scoring system for a game involving enemies. The game has a feature where a specific action needs to be performed when an enemy's remaining life falls below a certain threshold. Your task is to create a function that updates the score and performs a specific action when an enemy's lif...
```csharp public void UpdateScoreAndProcess(Enemy enemy) { IDisposable subscription = enemy.Life .Where(life => (float)life / (float)enemy.MaxLife < lastSwitchData.HPRatio) .First() .Subscribe(life => { if (life > 0) { UIManager.Score.AddScore(...
magicoder
csharp
You are tasked with implementing a class that converts alien numerals to Roman numerals. The class should have the following methods: 1. `set_mineral_price(mineral: str, price: int)`: This method sets the price of a mineral in the alien civilization. 2. `get_numeral(numeral: str) -> str`: This method takes an alien n...
```python class AlienToRomanConverter: def __init__(self): self.mineral_prices = {} def set_mineral_price(self, mineral: str, price: int): self.mineral_prices[mineral] = price def get_numeral(self, numeral: str) -> str: roman_numerals = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, ...
magicoder
python
You are tasked with implementing a generic interface for a simple CRUD (Create, Read, Update, Delete) operations in a programming language of your choice. The interface, named `ICrud`, defines four methods: `create()`, `read()`, `update()`, and `delete()`. Your goal is to create a class that implements this interface a...
```java // Define the ICrud interface interface ICrud { void create(Object obj); Object read(String identifier); void update(String identifier, Object obj); void delete(String identifier); } // Implement the MyCrud class class MyCrud implements ICrud { private Map<String, Object> dataStore; pu...
magicoder
java
You are tasked with implementing a custom text drawing function in Swift. The function should take a string and draw it within a given rectangle, applying specified insets to the text. You are provided with a code snippet that calls the `drawText` function from a superclass within a custom view's `draw` method. Your ta...
```swift func drawText(_ text: String, in rect: CGRect) { let textInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5) // Example insets, you can adjust these values as needed let textRect = rect.inset(by: textInsets) let textAttributes: [NSAttributedString.Key: Any] = [ .font: UIFont.sy...
magicoder
swift
You are given a list of integers representing the daily stock prices of a company. Your task is to write a function to calculate the maximum profit that can be obtained by buying and selling the stock at most once. If it is not possible to make any profit, the function should return 0. Write a function `max_profit(pri...
```python from typing import List def max_profit(prices: List[int]) -> int: if not prices: return 0 min_price = prices[0] max_profit = 0 for price in prices: if price < min_price: min_price = price else: max_profit = max(max_profit, price - min_...
magicoder
python
You are tasked with implementing a function to add a new entry to a dictionary database. The given code snippet is a part of a function that attempts to add a new entry to the dictionary. The function first checks if an entry with the same label and parent ID already exists in the database. If it does, the function ret...
```python from datetime import datetime from django.http import JsonResponse from .models import Dict # Assuming the model for dictionary entries is named Dict from .services import DictService # Assuming the service for dictionary operations is named DictService def add_dictionary_entry(label, value, sort, dictType...
magicoder
python
You are tasked with implementing a custom window trigger for a streaming data processing application using Apache Flink. The trigger is responsible for determining when a window should be evaluated to emit the results. Your task is to create a subclass of the abstract class `WindowTrigger<W extends Window>` and impleme...
```java import org.apache.flink.api.common.state.ValueState; import org.apache.flink.api.common.state.ValueStateDescriptor; import org.apache.flink.api.common.typeutils.base.LongSerializer; import org.apache.flink.streaming.api.windowing.triggers.Trigger; import org.apache.flink.streaming.api.windowing.windows.Window; ...
magicoder
java
You are tasked with creating a routing module for a web application using Angular. Your goal is to implement a feature that allows users to navigate to a page displaying information about different occupations. To achieve this, you need to define the routing configuration and set up the necessary components. Given the...
```typescript import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { OccupationListComponent } from './occupation-list/occupation-list.component'; import { OccupationDetailsComponent } from './occupation-details/occupation-details.component'; const routes: Routes = [...
magicoder
typescript
You are tasked with implementing a distributed training framework for a deep learning model. The framework supports different distributed training strategies, including Data Parallelism and SlowMo. Your task is to implement the logic for initializing the distributed training process based on the provided arguments and ...
```python if args.distributed_wrapper == "DataParallel": initialize_data_parallel_training( world_size=args.distributed_world_size, buffer_size=2**28, process_group=process_group, ) elif args.distributed_wrapper == "SlowMo": if _GOSSIP_DISABLED: raise ImportError("Gossip-base...
magicoder
python
You are tasked with implementing a decorator pattern in Python to manage the access control and response formatting for a set of API endpoints. The provided code snippet lists the different types of decorators that need to be implemented. Each decorator serves a specific purpose, such as controlling access, formatting ...
```python # Define the decorators def expose_api(func): def wrapper(*args, **kwargs): # Access control logic # Response formatting logic return func(*args, **kwargs) return wrapper def expose_api_anonymous(func): def wrapper(*args, **kwargs): # Access control logic for anony...
magicoder
python
You are tasked with creating a Python function that processes a given HTML snippet to extract and organize the social media links and tag cloud links present in the snippet. The HTML snippet contains anchor tags for social media links and tag cloud links, and it uses Jinja2 templating syntax for iterating through the l...
```python from bs4 import BeautifulSoup def extract_links(html_snippet): soup = BeautifulSoup(html_snippet, 'html.parser') social_media_links = {} tag_cloud_links = [] # Extract social media links social_media_tags = soup.find_all('a', class_='btn btn-circle page-scroll') for tag in s...
magicoder
python
You are tasked with creating a Python function that automates the process of web scraping using Selenium. Your function should take in a URL and a CSS selector as input and return a list of text content from the web page that matches the given CSS selector. Your function should utilize the Selenium library to set up a...
```python from selenium.webdriver.chrome.options import Options from selenium import webdriver from selenium.webdriver.common.by import By from typing import List def scrape_web_content(url: str, css_selector: str) -> List[str]: chrome_options = Options() chrome_options.add_argument('--headless') webdrive...
magicoder
python
You are tasked with implementing a loading indicator for a dashboard application. The `DashboardLoadingIndicator` class is responsible for managing the loading state and displaying the indicator when necessary. The class has a property `isActive` that indicates whether the loading indicator is currently active. Your ta...
```typescript export class DashboardLoadingIndicator { private loading: boolean private timeoutId: number public get isActive(): boolean { return this.loading } public startLoading(): void { this.loading = true; this.timeoutId = setTimeout(() => { // Display the loading indicator logic her...
magicoder
typescript
You are tasked with implementing a class that generates a data reporter for console output. The class `ConsoleMetricsReporterFactory` has a constructor that takes an integer parameter `ignoreValuesBelow`, and a method `CreateReporter` that returns an `Action<DataPoint>`. The `ConsoleReporter` class is assumed to exist ...
```csharp using System; public class DataPoint { public double Value { get; set; } public DateTime Timestamp { get; set; } } public class ConsoleReporter { private int _ignoreValuesBelow; public ConsoleReporter(int ignoreValuesBelow) { _ignoreValuesBelow = ignoreValuesBelow; } pu...
magicoder
csharp
You are tasked with implementing a Python function that calculates the last number in the Fibonacci sequence up to a given index. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. The function should handle invalid input gracefully an...
```python def last_fibonacci(x: int) -> int: if x < 0: print("Invalid input") return if x == 0: return 0 elif x == 1: return 1 a, b = 0, 1 for _ in range(2, x + 1): a, b = b, a + b return b ```
magicoder
python
You are tasked with implementing a class method for a video dataset processing module. The method is responsible for decoding various tensors and constructing a dictionary containing the decoded data. The method has conditional logic based on the dataset type and a flag indicating the use of two frames. Your task is to...
```python class VideoDatasetProcessor: def __init__(self, is_video_dataset, use_two_frames): self._is_video_dataset = is_video_dataset self._use_two_frames = use_two_frames def process_tensors(self, parsed_tensors): return_dict = {} return_dict['label'] = self._decode_label(pars...
magicoder
python
You are tasked with implementing a symbol tracking system for a code analysis tool. The system should track the usage and visibility of symbols within a given codebase. Symbols can be of various kinds, such as variables, functions, or classes, and can be scoped within different contexts, such as namespaces or classes. ...
```cpp #include <iostream> #include <unordered_map> #include <vector> #include <string> enum class SymbolKind { Variable, Function, Class }; enum class ContextType { Namespace, Class }; struct SymbolInfo { std::string name; SymbolKind kind; std::string header; std::vector<std::pair<ContextType, std...
magicoder
cpp
You are given a code snippet in a fictional programming language. Your task is to identify and fix the syntax errors in the code to make it valid. The code snippet is as follows: ```plaintext import a struct B struct d{enum e<T where B:a{struct c} class a ``` Your task is to correct the code to make it syntactically ...
The corrected code snippet is as follows: ```plaintext import Foundation struct B { struct d { enum e<T> where T: B { struct c {} } } } class a {} ``` In the corrected code: - The missing import statement for the Foundation framework has been added. - The struct and enum declarat...
magicoder
plaintext
You are tasked with implementing a custom random number generator (RNG) using a linear congruential generator (LCG) algorithm. The LCG algorithm generates a sequence of pseudo-random numbers using the recurrence relation: Xn+1 = (a * Xn + c) mod m, where Xn is the current value, a is a multiplier, c is an increment, an...
```csharp public class CustomRNG { private uint[] _State = new uint[1]; // Internal state array /// <param name="seed"> /// RNG seed. /// </param> public void SetSeed(uint seed) { this._State[0] = (seed & 0x1fffffffu) + 1156979152u; // Accepts 29 seed-bits. } /// <summary...
magicoder
csharp
You are tasked with creating a simulation to analyze the performance of various investment portfolios. The code snippet provided contains calculations for the volatility of a portfolio, using the dot product and covariance of log returns for two assets, 'PG' and '^GSPC'. Additionally, it mentions the intention to creat...
```python import numpy as np import pandas as pd import matplotlib.pyplot as plt def simulate_min_variance_portfolios(assets, log_returns): num_portfolios = 1000 expected_returns = log_returns.mean() * 250 # Annualized expected returns covariance_matrix = log_returns.cov() # Covariance matrix of log retu...
magicoder
python
You are tasked with implementing a function to compile an SQL "IN" expression for a given query. The function should handle various scenarios, including the presence of null values in the input array. Your task is to complete the implementation of the `compileInExpression` method, ensuring that it correctly compiles th...
```php protected function compileInExpression(CompilableClause $query, $values, string $column, string $operator = 'IN', bool $converted = false) { if (!is_array($values)) { throw new InvalidArgumentException('$values must be an array'); } // Handle null values and store the information $hasNul...
magicoder
php
You are working on a project that involves processing geotiff files containing elevation data. You need to write a Python function that takes in the filename of a geotiff file, the NaN (Not a Number) value used in the file, and the resolution of the geotiff. The function should read the geotiff file, calculate the mean...
```python import numpy as np from PIL import Image import scipy.stats import matplotlib.pyplot as plt def process_geotiff(filename, nan, resolution): try: # Read the geotiff file dh = np.array(Image.open(filename)) # Calculate the mean elevation values for tiles of the specified resolution...
magicoder
python
You are tasked with creating a Python function that parses a JSON configuration file and extracts specific information from it. The configuration file contains settings for a simulation software, and you need to retrieve the value of a particular parameter nested within the JSON structure. The JSON configuration file ...
```python import json def get_gidpost_mode(config_file_path): with open(config_file_path, 'r') as file: config_data = json.load(file) gidpost_mode = config_data.get("simulation_settings", {}).get("result_file_configuration", {}).get("gidpost_flags", {}).get("GiDPostMode") return gidpost_mod...
magicoder
python
You are tasked with creating a version comparison function that compares two version strings and determines which one is greater. The version strings follow the semantic versioning format, which consists of three non-negative integers separated by periods (e.g., "1.0.0-alpha20"). The version comparison should consider ...
```python def compare_versions(version1: str, version2: str) -> int: v1_parts = version1.split('-')[0].split('.') v2_parts = version2.split('-')[0].split('.') for i in range(3): if int(v1_parts[i]) > int(v2_parts[i]): return 1 elif int(v1_parts[i]) < int(v2_parts[i]): ...
magicoder
python
You are tasked with implementing a Python class to represent a file path. The class should support various operations related to file paths, such as joining paths, retrieving components, and determining whether a path is absolute or relative. Your task is to implement the `Path` class with the following specifications...
```python class Path: def __init__(self, components, with_drive=False): self.components = components self.with_drive = with_drive def join(self, new_components): if self.with_drive: joined_components = [self.components[0]] + new_components else: joined_co...
magicoder
python
You are working on a robotics project and need to implement a trajectory optimization problem using OpenSim Moco library. The code snippet provided sets up the time bounds, state and control bounds, and a marker tracking cost for the optimization problem. Your task is to write a function that takes the provided informa...
The `setupTrajectoryOptimization` function takes the final time and marker reference data as input and sets up the complete trajectory optimization problem using the Moco library. It configures the time bounds, state and control bounds, and adds the marker tracking cost to the problem. The function then returns the con...
magicoder
python
You are given a snippet of code that manipulates a `RectF` object and performs some calculations based on its dimensions. Your task is to implement a function that takes in a `RectF` object and an `ImageView` and calculates the vertical position for the `RectF` within the `ImageView` based on certain conditions. You a...
```java public class Solution { public static float calculateVerticalPosition(RectF rectF, ImageView imageView, YPosition yPosition) { float f1 = rectF.getHeight(); float f3 = rectF.getWidth(); int i1 = imageView.getHeight(); if (f1 <= i1) { switch (yPosition) { ...
magicoder
java
You are tasked with creating a program to parse and extract data from an HTML table. The HTML snippet provided below represents a table with statistical data for a sports team. Your goal is to extract the statistical categories and their corresponding values from the table. HTML Snippet: ```html ###<span id="showKey">...
```python from bs4 import BeautifulSoup def extractStatistics(html): soup = BeautifulSoup(html, 'html.parser') stat_table = soup.find('table', class_='keyTable') categories = [td.get_text() for td in stat_table.find_all('td')] statistics = {category: "" for category in categories} return statistics...
magicoder
python
You are tasked with implementing a file retrieval method for a custom file system library in C#. The library is designed for a resource-constrained embedded system using the nanoFramework. Your goal is to create a method that mimics the behavior of the `GetFileFromPathAsync` method in the Universal Windows Platform (UW...
```csharp using System; using System.IO; public class CustomFileSystem { /// <summary> /// Gets a StorageFile object to represent the file at the specified path. /// </summary> /// <param name="path">The path of the file to get a StorageFile to represent.</param> /// <returns>Returns the file as a ...
magicoder
csharp
You are tasked with implementing a safe and efficient method for converting between two custom data types, `A` and `B`, which are represented as raw byte buffers. The conversion process is highly unsafe and requires the exact `PointLayout` of both `A` and `B` to be valid. The `PointLayout` is a struct that defines the ...
```rust use std::collections::HashMap; use lazy_static::lazy_static; // Define the custom data types A and B struct A { // Define the fields of type A } struct B { // Define the fields of type B } // Define the PointLayout struct struct PointLayout { // Define the layout information } impl PointLayout {...
magicoder
rust
You are tasked with implementing a Singleton pattern in Python. The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. Your task is to create a Singleton metaclass and a class that uses this metaclass to enforce the Singleton behavior. Implement a Pytho...
```python class Singleton(type): _registry = {} def __call__(cls, *args, **kwargs): if cls not in Singleton._registry: Singleton._registry[cls] = super(Singleton, cls).__call__(*args, **kwargs) return Singleton._registry[cls] class Me(metaclass=Singleton): def __init__(self, d...
magicoder
python
You are tasked with implementing a file path auto-completion validator for a command-line interface. The validator should determine whether a given input is a valid file path for auto-completion purposes. The file path must adhere to certain rules and patterns to be considered valid. Your task is to complete the `File...
```typescript import { lstatSync, existsSync } from "fs"; interface AutoCompletionValidator { isValidForAutoCompletion(executionArgument: string): boolean; } class FilePathAutoCompletionValidator implements AutoCompletionValidator { public isValidForAutoCompletion(executionArgument: string): boolean { ...
magicoder
typescript
You are tasked with implementing a memory management system for a simple dynamic array. The system should allocate memory for the array, manage its size, and ensure proper deallocation when the array is no longer needed. Your task is to create a class that encapsulates this memory management functionality. You are pro...
```cpp #include <iostream> #include <memory> #include <vector> class DynamicArray { private: std::unique_ptr<int[]> data; int size; public: // Constructor to allocate memory for the array DynamicArray(int initialSize) : size(initialSize), data(new int[initialSize]) {} // Method to access and modi...
magicoder
cpp
You are working on a natural language processing (NLP) project and need to implement a data preprocessing module for tokenizing and padding input sentences. Your task is to create a Python class that tokenizes input sentences, handles special tokens, and pads the tokenized sequences to a specified maximum length. You ...
```python class Tokenizer: def __init__(self, special_tokens=[]): self.special_tokens = special_tokens self.vocab = Vocabulary() def tokenize(self, src_sents, max_len=-1): """ Tokenizes the input sentences and pads the sequences to a specified maximum length. Args: ...
magicoder
python
You are given a Python code snippet that defines a class `Q` and demonstrates the division operation between two instances of this class. Your task is to implement the class `Q` and its division operation to perform rational number arithmetic. The class `Q` represents a rational number with a numerator `a` and a non-z...
```python class Q: def __init__(self, a, b): if b == 0: raise ValueError("Denominator cannot be zero") self.a = a self.b = b def __truediv__(self, q): if q.b == 0: raise ValueError("Denominator of divisor cannot be zero") a = self.a * q.b ...
magicoder
python
You are tasked with implementing a generic delegate system in C#. The provided code snippet defines a set of generic delegate types for both actions and functions. Your task is to create a class that utilizes these delegate types to perform various operations. Create a class called `DelegateManager` with the following...
```csharp public class DelegateManager { public void ExecuteAction(ActionCall action) { action(); } public void ExecuteAction<T1>(ActionCall<T1> action, T1 arg1) { action(arg1); } public void ExecuteAction<T1, T2>(ActionCall<T1, T2> action, T1 arg1, T2 arg2) { a...
magicoder
csharp
You are working on a system that manages various components for a web crawling and indexing service. The system consists of Index Servers, a Crawler, an Index Builder, and a Watchdog. Your task is to write a program that calculates the total number of resources needed for the system based on the given parameters. The ...
```python def calculate_total_resources(number_of_rows, number_of_links, number_of_chunks, number_of_comps): resources_per_index_server = 100 resources_per_link = 50 resources_per_chunk = 200 resources_per_comp = 20 total_resources_index_servers = number_of_rows * resources_per_index_server tot...
magicoder
python
You are tasked with implementing a function that determines whether a given number is a prime number or not. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Your task is to create a function `isPrime` that takes an integer as input and returns `true` if the numbe...
```java public class PrimeChecker { public static void main(String[] args) { assertSuccess(2, 3); assertSuccess(5, 3); assertSuccess(8, 7); assertSuccess(97, 101); assertSuccess(99.0, 97); assertSuccess(127_782, 127_781); } public static void assertSuccess(in...
magicoder
java
You are tasked with implementing a function that determines the quadrant of a given point within a grid, based on the size of the grid and the direction of travel within the grid. The grid is represented as a 2D array, and the point is represented as a tuple of coordinates (x, y). The direction of travel is represented...
```python def determine_quadrant(grid, point, direction): rows, cols = len(grid), len(grid[0]) x, y = point dx, dy = direction if (rows, cols) == (1, 1): return "T" if dy == 1 else "B" elif (rows, cols) == (2, 1): return "T" if dx == 1 else "B" elif (rows, cols) == (2, 2): ...
magicoder
python
You are tasked with implementing a generic data structure in Rust to represent a type-level list and a type-level operation to check if a given type is a member of the list. Define a Rust trait `MemberMatch` with two type parameters `TargetL` and `Bool` and an associated type `Output`. The trait should have two implem...
```rust // Implementation of the MemberMatch trait for the Cons type impl<TargetL, L, T> MemberMatch<TargetL, True> for Cons<L, T> where L: PartialEq<TargetL>, T: MemberMatch<TargetL, False>, { type Output = True; } impl<TargetL, L, T> MemberMatch<TargetL, False> for Cons<L, T> where L: PartialEq<Targe...
magicoder
rust
You are tasked with implementing a custom exception handling mechanism for a web service. The web service is designed to return a response object with a status code and a message. Your goal is to create a function that handles exceptions and returns a response object with a 500 status code and the exception message as ...
```python class Response: def __init__(self, status_code, message): self.status_code = status_code self.message = message @staticmethod def of(status_code, message): return Response(status_code, message) def respond(self): return f"Status Code: {self.status_code}, Messa...
magicoder
python
You are working on a codebase that involves processing type names and cleaning them up. The code snippet provided initializes three variables: `process_type_name_ns_to_clean`, `synopsis_maxlen_function`, and `synopsis_class_list`. Your task is to implement a function that takes a type name as input and cleans it up bas...
```python def clean_type_name(type_name: str) -> str: global process_type_name_ns_to_clean, synopsis_maxlen_function, synopsis_class_list # Rule 1: Truncate if length exceeds synopsis_maxlen_function if len(type_name) > synopsis_maxlen_function: type_name = type_name[:synopsis_maxlen_function] ...
magicoder
python
You are tasked with creating a Python class to manage and plot CPMG (Carr-Purcell-Meiboom-Gill) data for chemical exchange processes. The CPMG experiment is a widely used NMR (nuclear magnetic resonance) technique for studying chemical exchange phenomena in solution-state NMR spectroscopy. Your class should be able to ...
```python import numpy as np import matplotlib.pyplot as plt class CpmgAnalyzer: def __init__(self, cpmg_data): self.cpmg_data = cpmg_data self.time = np.array([point[0] for point in cpmg_data]) self.intensity = np.array([point[1] for point in cpmg_data]) def process_data(self): ...
magicoder
python
You are tasked with creating a Java program that processes files in a directory and encodes specific content within those files using Base64 encoding. The program should traverse through all the files in a given directory and its subdirectories, identify certain patterns within the files, and encode the matched content...
```java import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileTime; import java.util.Base64; impor...
magicoder
java
You are tasked with implementing a naming strategy class in C#. The naming strategy class is responsible for transforming property names, extension data names, and dictionary keys. The class contains several methods for these transformations, as well as some overridden and abstract methods. Your task is to create a con...
```csharp public abstract class NamingStrategy { public virtual string GetPropertyName(string name, bool hasSpecifiedName) { // Implementation for GetPropertyName method } public virtual string GetExtensionDataName(string name) { // Implementation for GetExtensionDataName method ...
magicoder
csharp
You are tasked with creating a Python function that simulates a job management system using the `ctypes` library to interact with Windows API functions. The goal is to implement a function that sets information for a job object and terminates a job object in a Windows environment. Your task is to complete the `set_and...
```python import ctypes kernel32 = ctypes.windll.kernel32 DWORD = ctypes.c_ulong LPVOID = ctypes.c_void_p HANDLE = ctypes.c_void_p JOBOBJECTCLASS = ctypes.c_int BOOL = ctypes.c_int kernel32.SetInformationJobObject.errcheck = _errcheck() kernel32.SetInformationJobObject.restype = BOOL kernel32.SetInformationJobObject...
magicoder
python
You are tasked with creating a program to analyze cryptocurrency price changes and identify fast-moving markets. Your program will receive two sets of data: `prev_data` and `latest_data`. Each set of data is a dictionary where keys are cryptocurrency names and values are dictionaries containing price and volume informa...
```python def identify_fast_markets(prev_data, latest_data, config): fast_markets = [] for name in latest_data: prev_changes = [] for i in range(len(prev_data)-1): old_price = float(prev_data[i].get(name, {}).get('Summary', {}).get('Last', 0.0)) new_price = float(prev_dat...
magicoder
python
You are tasked with creating a Django view that handles a form submission and saves the data to the database. Your task is to complete the implementation of the `submit_contact` function in the `views.py` file of a Django application. The function should handle POST requests, validate the form data, and save the valid ...
```python # views.py from django.shortcuts import render, redirect from .forms import ContactForm from .models import Contact def submit_contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): form.save() # Save the form data to the database...
magicoder
python
You are tasked with creating a Python function that processes a configuration file and adjusts the volume mixer settings based on the configuration. The configuration file is in the form of a dictionary, where the keys represent different settings and the values represent the corresponding values for those settings. Th...
```python import alsaaudio def adjust_mixer_volume(config: dict) -> None: try: mixer = alsaaudio.Mixer(config['global']['mixer']) mixer.setvolume(config['volume']) except ImportError: raise ImportError("alsaaudio library is not available") ``` In the solution, we first attempt to creat...
magicoder
python
You are tasked with creating a Swift function that interacts with a local Core Data database to delete specific counters. The function should take an array of counter IDs as input and delete the corresponding counters from the Core Data storage. You need to implement the `deleteLocalCounters` function, ensuring that it...
```swift func deleteLocalCounters(countersIds: [String], _ completion: (Result<Void, Error>) -> Void) { guard let managedContext = CounterWorker.getManagedContext() else { completion(.failure(AppError(id: .coreData))) return } let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityNam...
magicoder
swift
You are tasked with creating a Python script that processes audio files to generate embeddings and then uses these embeddings to perform speaker verification. The script will take command-line arguments using the `argparse` module to specify the necessary input files and parameters. Your task is to implement the `spea...
```python import argparse import numpy as np def load_embeddings(file_path): # Load embeddings from the specified numpy file try: embeddings = np.load(file_path) return embeddings except FileNotFoundError: print("Error: Embeddings file not found.") return None def load_mani...
magicoder
python
You are tasked with implementing a simple remote control system for various electronic devices. The system should allow users to easily switch different devices on and off using a remote control. You are provided with a `SimpleRemoteControl` class that serves as the main controller for the remote. This class has a met...
```java // Command interface interface Command { void execute(); } // Concrete command for turning on the light class LightOnCommand implements Command { private Light light; public LightOnCommand(Light light) { this.light = light; } @Override public void execute() { light.tur...
magicoder
java
You are tasked with creating a vote counting program for a local election. The program should read a CSV file containing the voter ID, county, and candidate name. The program needs to calculate the total number of votes cast, the total number of votes for each candidate, the percentage of votes for each candidate, and ...
```python import csv # Initialize variables to store vote counts for each candidate total_votes = 0 candidate_votes = {} # Read the input CSV file with open('input.csv', 'r') as file: reader = csv.reader(file) next(reader) # Skip header row for row in reader: total_votes += 1 candidate_na...
magicoder
python
You are tasked with implementing a function to generate 2D rotation matrices. A rotation matrix is a 2x2 matrix that can be used to rotate a 2D vector in the Cartesian coordinate system. The rotation matrix is defined as: ``` | cos(θ) -sin(θ) | | sin(θ) cos(θ) | ``` Your task is to implement a Python function `gen...
```python import numpy as np def generate_rotation_matrices(angles): num_angles = len(angles) rotation_matrices = np.zeros((num_angles, 2, 2)) cos_theta = np.cos(angles) sin_theta = np.sin(angles) rotation_matrices[:, 0, 0] = cos_theta rotation_matrices[:, 1, 1] = cos_theta rotation_ma...
magicoder
python
You are tasked with creating a program that processes course data from Yale University to identify the most popular classes based on enrollment numbers. The course data is available in a CSV file format and contains information about the course code, title, enrollment count, and other relevant details. Your program sho...
```python import csv import argparse from multiprocessing import Pool def process_course_data(course): course_code, course_title, enrollment_count = course return course_code, course_title, int(enrollment_count) def identify_top_classes(course_data, top_n): processed_data = [process_course_data(course) fo...
magicoder
python
You are tasked with implementing a Swift protocol and class for a location-based app. The protocol, `HomePresenterProtocol`, extends another protocol, `BasePresenterProtocol`, and defines two methods: `loadStoredLocations()` and `deleteLocation(location: LocationModel)`. The `HomePresenter` class conforms to `HomePrese...
```swift import UIKit import Foundation public protocol HomePresenterProtocol: BasePresenterProtocol { func loadStoredLocations() func deleteLocation(location: LocationModel) } class HomePresenter: HomePresenterProtocol { func loadStoredLocations() { // Implement logic to retrieve and handle store...
magicoder
swift
You are given a code snippet that defines a class `Query` with an unspecified number of methods and properties. Your task is to design and implement a method `execute` for the `Query` class that takes in a SQL query string and executes it against a database. The `execute` method should return the result of the query as...
```python class Query: def __init__(self, db_connection): self.db_connection = db_connection def execute(self, sql_query): try: cursor = self.db_connection.cursor() cursor.execute(sql_query) columns = [col[0] for col in cursor.description] result_...
magicoder
python
You are tasked with creating a custom ROS (Robot Operating System) state in Python for a robot control system. The state should be responsible for calling a service to perform an IMU (Inertial Measurement Unit) tare operation, which resets the IMU's reference orientation to the current orientation of the robot. This is...
```python #-*- coding: utf-8 -*- import rospy from flexbe_core import EventState, Logger from sonia_common.srv import ImuTareSrv class imu_tare(EventState): def __init__(self): super(imu_tare, self).__init__(outcomes=['success', 'failure']) # Initialize a ROS node with the appropriate name ...
magicoder
python
You are tasked with creating a program that can enumerate the members of a given type in C#. Your task is to implement a function that takes a type as input and returns a list of all the members (fields, properties, and methods) of that type. You should also handle any potential exceptions that may occur during the enu...
```csharp using System; using System.Collections.Generic; using System.Reflection; public class TypeMemberEnumerator { public List<string> EnumerateTypeMembers(Type type) { List<string> memberNames = new List<string>(); try { // Get all public fields, properties, and method...
magicoder
csharp
You are tasked with implementing a Redux store configuration for a web application. The application uses Redux for state management and follows the standard practice of combining reducers and epics using the `redux-observable` middleware. You are provided with the following code snippet: ```javascript import { rootEp...
```javascript import { createStore, combineReducers, applyMiddleware } from 'redux'; import { createEpicMiddleware } from 'redux-observable'; import { rootEpic, rootReducer } from './reducers'; const configureStore = () => { // Step 1: Create a Redux store const store = createStore( // Step 2: Combine reducers...
magicoder
javascript
You are tasked with implementing a custom delta structure for a set variable in a constraint satisfaction problem solver. The delta structure is responsible for efficiently storing and managing the changes to the set variable's domain during search, allowing for effective backtracking and propagation. Your task is to ...
```java import org.chocosolver.memory.IEnvironment; import org.chocosolver.solver.ICause; import org.chocosolver.solver.search.loop.TimeStampedObject; import java.util.HashSet; import java.util.Set; public class SetDelta extends TimeStampedObject implements ISetDelta { private Set<Integer> addedElements; priva...
magicoder
java
You are tasked with implementing a function that navigates through a JSON object using a given array of paths. The function should return the value at the final path if it exists, or indicate if the path is invalid or if the JSON object is not properly formatted. You are given the following code snippet as a starting ...
```swift func navigateJSON(_ jsonObject: [String: Any], _ paths: [String]) -> String { var next = jsonObject var result: Any? var abort = false paths.forEach({ (seg) in if seg.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) == "" || abort { return } i...
magicoder
swift
You are tasked with implementing a Java method that processes an array of integers and returns the median value of the array. The median is the middle value in a sorted list of numbers. If the list has an odd number of elements, the median is the middle number. If the list has an even number of elements, the median is ...
```java public static double calculateMedian(int[] arr) { Arrays.sort(arr); int n = arr.length; if (n % 2 != 0) { return arr[n / 2]; } else { return (arr[n / 2 - 1] + arr[n / 2]) / 2.0; } } ```
magicoder
java
You are given a 2D grid representing a maze with '.' representing empty spaces and '#' representing walls. Additionally, there are portals in the maze that can transport you to another location within the maze. Each portal is represented by a pair of matching letters (e.g., 'ab', 'cd', etc.). When you step on one lette...
```python from collections import deque def minSteps(maze): directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] portals = {} start = end = None for y in range(len(maze)): for x in range(len(maze[0])): if maze[y][x] == 'S': start = (x, y) elif maze[y][x] == '...
magicoder
python
You are tasked with implementing a decompression algorithm for a specific type of network protocol frame. The decompression function takes in a compressed frame, the decompressor object, and the length of the packet. The function returns a boost::indeterminate result, indicating that the decompression process is ongoin...
```cpp #include <iostream> #include <boost/asio.hpp> // Define the decompressor function boost::indeterminate decompressor(const char* compressedFrame, size_t length, int decompressionLevel) { // Implement the decompression logic here // Example: using zlib for decompression // Assume zlib is properly conf...
magicoder
cpp
You are tasked with implementing a TypeScript type that extracts the value types from a settings configuration and maps them to a setting priority list. The setting priority list is a list of setting values and conditions ordered by the conditions' priorities. You are given the following TypeScript code snippet as a s...
```typescript type SettingsConfigSetPriorityList<S> = { [K in keyof S]: { value: S[K]["value"]; priority: S[K]["priority"]; }; }; ``` The `SettingsConfigSetPriorityList` type is defined as a mapped type that iterates over the keys of the input settings type `S`. For each key `K`, it creates an object with ...
magicoder
typescript
You are tasked with implementing a custom task scheduler in Python. The scheduler should support adding tasks with associated execution times and running them in the correct order. Each task will have a unique identifier and an associated execution time. The scheduler should be able to run the tasks based on their exec...
```python import time class TaskScheduler: def __init__(self, time_attr='epoch'): self.tasks = [] self.time_attr = time_attr def add_task(self, task_id, execution_time): # Add a new task to the scheduler # task_id: unique identifier for the task # execution_time: time i...
magicoder
python
You are working on a game development project and need to implement a loot distribution system. The system should handle various actions such as giving loot to players for fishing, killing targets, and mining, as well as inserting loot at specific positions. The loot distribution is based on loot tables, and the system...
```python from typing import List class LootDistributionSystem: def __init__(self): # Initialize loot tables and other necessary data structures self.loot_tables = { "fish_loot_table": {...}, # Define loot table for fishing "mine_loot_table": {...}, # Define loot table for...
magicoder
python
You are tasked with creating a Python script to automate the setup and management of a service on a Linux system. The script should perform the following tasks: 1. Run the command `systemctl daemon-reload` to reload systemd manager configuration. 2. Enable a service named `ttbot` using the command `systemctl enable ttb...
```python import os import click def setup_and_start_service(): os.system('systemctl daemon-reload') os.system('systemctl enable ttbot') os.system('systemctl start ttbot') click.echo('Бот ВКЛючен') if __name__ == "__main__": setup_and_start_service() ``` In this solution, we define a function `set...
magicoder
python
You are tasked with creating a program that analyzes a given text file to count the occurrences of specific phrases. The program should read the text file and then prompt the user to input a phrase to search for. It should then output the number of times the phrase appears in the text file. Your program should follow ...
```python def count_phrase_occurrences(file_name, phrase): try: with open(file_name, 'r') as file: text = file.read() count = text.lower().count(phrase.lower()) return count except FileNotFoundError: return "File not found" except Exception as e: r...
magicoder
python
You are tasked with implementing a pattern matching algorithm to find occurrences of a given pattern within a text. The input consists of a text string and one or more patterns to search for within the text. Your goal is to efficiently find all occurrences of each pattern within the text and return their starting posit...
```python from typing import List def find_patterns(text: str, patterns: List[str]) -> List[List[int]]: def build_trie(patterns): trie = {} node_count = 0 for pattern in patterns: current_node = 0 for char in pattern: if (current_node, char) not in tr...
magicoder
python
You are tasked with implementing a custom string literal operator for the C++ programming language. The operator should be able to create `std::string` objects from string literals with a specific suffix. Your task is to create a string literal operator that appends a given suffix to the end of the string literal and r...
```cpp #include <iostream> #include <string> // Custom string literal operator std::string operator""_suffix(const char* str, size_t size, const char* suffix) { return std::string(str) + suffix; } int main() { // Using the custom string literal operator with different suffixes std::string str1 = "hello"_s...
magicoder
cpp
You are tasked with creating a function that calculates the time difference between a given date and the current date. The function should take in a date as input and return the time difference in seconds, minutes, hours, days, weeks, months, and years. You are provided with the following code snippet for inspiration:...
```swift import Foundation func calculateTimeDifference(from date: Date) -> (seconds: Int, minutes: Int, hours: Int, days: Int, weeks: Int, months: Int, years: Int) { let calendar = Calendar.current let now = Date() let components = calendar.dateComponents([.second, .minute, .hour, .day, .weekOfYear, .mont...
magicoder
swift
You are tasked with creating a library lookup system for a music streaming service. The library consists of various types of content, such as campuses, archives, and tracks. Each type of content has a unique URI associated with it. Your task is to implement a library class that can perform lookups based on the provided...
```python class Library: def __init__(self, client_mock): self.client_mock = client_mock def lookup(self, uri): if 'CAMPUS' in uri: return self._lookup_campus(uri) elif 'ARCHIVE_DAY' in uri: return self._lookup_archive_day(uri) else: return se...
magicoder
python
You are tasked with simulating a retry mechanism for sending HTTP GET requests to a server. Your goal is to implement a Python class that handles the retry logic for sending GET requests and ensure that the requests are retried a specific number of times in case of failure. You are provided with a code snippet that co...
```python import requests import time class RetryHttpClient: def __init__(self, base_url): self.base_url = base_url self.max_retries = 5 def send_get_request(self, url): retries = 0 while retries <= self.max_retries: try: response = requests.get(self...
magicoder
python