query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with implementing a function to update a plugin, retrieve the result, and send it as a response over a network connection. The given code snippet is a part of a larger system and provides some context for the task. The `cr_plugin_update` function is responsible for updating the plugin, and the result is ...
The `updateAndSendResponse` function is implemented to update the plugin using `cr_plugin_update`, retrieve the result from the `m_ctx` context, create a TCP packet with the result as the payload and set the packet signature to RESPONSE, and finally send the packet over a network connection using the `client.write` fun...
magicoder
python
You are tasked with creating a React component that fetches and displays hourly weather data based on the user's current location. The component should utilize the `useState` hook to manage state and the `loadData` function to fetch weather data from an API. The fetched data should include the current temperature, weat...
```javascript const [hours, setHours] = useState([]); const loadData = (pos) => { const apiKey = 'YOUR_API_KEY'; // Replace with your actual API key const apiUrl = `https://api.weather.com/hourlyforecast/v1/geocode/${pos.latitude}/${pos.longitude}/forecast/hourly/12hour.json?apiKey=${apiKey}`; fetch(apiUrl) ...
magicoder
javascript
You are tasked with creating a program that will recursively search through a specified directory and its subdirectories to find all files that are not in the .docx format. For each non-.docx file found, the program should convert it to the .docx format by opening it in Microsoft Word and then re-saving it as a .docx f...
```csharp using System; using System.IO; using Microsoft.Office.Interop.Word; class Program { static void Main(string[] args) { if (args.Length > 0) { string path = args[0]; ConvertToDocx(path); } else { Console.WriteLine("Please provi...
magicoder
csharp
You are tasked with creating a Flask application for tracking fitness goals, weight, and calorie intake. The code snippet provided imports the necessary modules and endpoints for the application. Your task is to implement the endpoints for the application using Flask and Flask-RESTful. You need to create a Flask Bluep...
```python from flask import Blueprint from flask_restful import Api from .endpoints.goal import Goal from .endpoints.weight import Weight from .endpoints.calories import Calories # Create a Flask Blueprint for the fitness tracking application fitness_blueprint = Blueprint('fitness', __name__) # Create a Flask-RESTful...
magicoder
python
You are tasked with implementing a custom annotation processor for a Java web framework. The framework uses annotations to mark classes that serve as RESTful API controllers. Your goal is to create a processor that identifies classes annotated with `@RestController` and generates corresponding controller mappings for t...
```java import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.tools.Diagnostic; import java.io.IOException;...
magicoder
java
You are tasked with implementing a function that simulates a simple memory management system. The function should allocate and deallocate memory blocks based on a given sequence of memory requests. Each memory request is represented by a string in the format "A x" or "D x", where "A" denotes allocation and "D" denotes ...
```swift func memoryManagement(_ requests: [String]) -> [Int] { var memoryAllocated = 0 var memoryUsage: [Int] = [] for request in requests { let components = request.components(separatedBy: " ") if components.count == 2, let size = Int(components[1]) { if components[0] == "...
magicoder
swift
You are tasked with creating a Python function that takes a file path as input and returns the size of the file in a human-readable format. The function should convert the file size to kilobytes (KB) or megabytes (MB) as necessary and return the formatted size along with the corresponding unit. Your task is to impleme...
```python import os def get_formatted_filesize(filepath): filesize = os.path.getsize(filepath) kb_factor = 1 << 10 mb_factor = 1 << 20 if filesize < kb_factor: size_string = "B" formatted_filesize = float(filesize) elif kb_factor <= filesize < mb_factor: size_string = "KB" ...
magicoder
python
You are tasked with creating a Python package management system that can handle dependencies and versioning. Your task is to implement a function that resolves the dependencies for a given package and returns a list of all the dependencies in the correct order. You are given a code snippet from a package called `my_pa...
```python import importlib import os def resolve_dependencies(package_name): package_path = os.path.dirname(__import__(package_name).__file__) dependencies = [] def find_dependencies(file_path): with open(file_path, 'r') as file: for line in file: if line.startswith('fr...
magicoder
python
You are tasked with implementing a reinforcement learning environment for a simulated robotic arm. The environment consists of multiple instances, each representing a different robotic arm. The code snippet provided is a part of the environment's step function, which takes in a batch of actions and executes them for ea...
```python class RoboticArmEnvironment: def __init__(self, envs): self._envs = envs def step(self, action_batch, qout=None): if qout is not None: for (idx, env) in enumerate(self._envs): env.step(action_batch[idx], qout[idx]) else: for (idx, env) i...
magicoder
python
You are given an array `nums` of n integers. Your task is to find all unique triplets in the array which sum up to zero. In other words, you need to find all sets of three numbers (a, b, c) in the array such that a + b + c = 0. The solution should not contain duplicate triplets. For example, given the input array `num...
```python from typing import List def threeSum(nums: List[int]) -> List[List[int]]: nums.sort() # Sort the array to easily handle duplicates and for efficient traversal result = [] for i in range(len(nums) - 2): if i > 0 and nums[i] == nums[i - 1]: # Skip duplicate elements conti...
magicoder
python
You are tasked with implementing a function that processes the data received from a successful AJAX request. The function should handle the data appropriately and produce the desired output. You are given the following code snippet from the success callback of an AJAX request: ```javascript success: function(data) { ...
```javascript function processData(data) { if (Array.isArray(data)) { return data.join(', '); } else if (typeof data === 'string') { return data; } else if (typeof data === 'number') { return data.toString(); } else if (typeof data === 'object') { return Object.keys(data)...
magicoder
javascript
You are tasked with creating a Python class that handles asynchronous HTTP requests and responses. Your class should include a method for sending a request and handling the response. The code snippet provided is a part of the method that sends the request and processes the response. Your task is to complete the impleme...
```python import models # Assume the existence of the models module with the ErrorException class class AsyncHttpClient: def __init__(self, client): self._client = client async def async_send_request(self, url, query_parameters, header_parameters, operation_config): # Construct and send reque...
magicoder
python
You are tasked with creating a Python function that simulates a simplified version of a smart home system. The function should handle the re-authentication process for a configuration entry, triggering a specific flow when the entry encounters an authentication error. You are given a code snippet that partially implem...
```python from unittest.mock import patch from your_module import setup_entry, InvalidCookies, ENTRY_STATE_SETUP_ERROR, DOMAIN, CONF_SOURCE, SOURCE_REAUTH async def test_config_entry_reauth(hass: HomeAssistant, mock_service) -> None: """Test the configuration entry needing to be re-authenticated.""" with patch...
magicoder
python
You are tasked with testing a function that interacts with a server and various client tools. The function is responsible for retrieving data from the server and transforming it using client tools. Your goal is to write unit tests to ensure that the function behaves as expected. The function interacts with the followi...
```javascript // Import necessary modules and functions for testing const { create, find } = require('serverMock'); const { createTools } = require('requestContextMock'); const { getFindResultWithSingleHit, getFindResultStatusEmpty } = require('mockData'); // Import the function to be tested const functionToTest = req...
magicoder
javascript
You are working on a data management system that involves importing and updating datasets. Your task is to create a Python function that handles the import of data into a dataset using the Domo platform. The function should be able to handle both importing data from a DataFrame and importing data from a CSV file. You w...
```python import pandas as pd import domo # Assuming the Domo Python SDK is imported def import_data_to_domo(dataset_name, dataset_df, csv_file_path, CLIENT_ID, CLIENT_SECRET, API_HOST): if dataset_df is not None: print('new columns will be used') change_schema(dataset_name, dataset_df, csv_file_p...
magicoder
python
You are tasked with implementing a function that processes a custom programming language's type system. The language has various types, including unresolved integers, unresolved floats, symbols, class objects, classes, and parameters. Your goal is to write a function that takes a type as input and returns specific info...
```rust fn process_type(t: semantics::Type, navigator: &mut Navigator) -> Option<String> { match t { semantics::Type::UnresolvedInteger(_, _) => None, semantics::Type::UnresolvedFloat(_, _) => None, semantics::Type::Symbol(_) => None, semantics::Type::ClassObject(_) => None, ...
magicoder
rust
You are given a list of integers representing the profits of a company over a series of days. Your task is to write a function that finds the maximum possible profit that can be achieved by buying and selling the company's stock at most once. You need to implement the function `maximizeProfit(prices: [Int]) -> Int` w...
```swift func maximizeProfit(prices: [Int]) -> Int { var maxProfit = 0 var minPrice = Int.max for price in prices { if price < minPrice { minPrice = price } else if price - minPrice > maxProfit { maxProfit = price - minPrice } } return maxPro...
magicoder
swift
You are tasked with implementing a chain of functions in Rust. Given a series of functions that return a struct or an object, you need to chain these functions together to perform a sequence of operations. Your task is to create a function that can be called in a chain, similar to method chaining in other programming l...
```rust // Define a struct that will be returned by the functions struct MyStruct; impl MyStruct { fn my_long_function(self) -> Self { // Perform operations for my_long_function self } fn my_even_longer_function(self) -> Self { // Perform operations for my_even_longer_function ...
magicoder
rust
You are tasked with implementing a context manager in Python to handle the monkey patching of an object's attributes. Monkey patching is a technique used to dynamically modify or extend the behavior of code at runtime. Your task is to create a context manager called `patch` that temporarily changes the attributes of an...
```python class patch: def __init__(self, obj, **attrs): self.obj = obj self.attrs = attrs self.stored = {} def __enter__(self): for name in self.attrs: if hasattr(self.obj, name): self.stored[name] = getattr(self.obj, name) setattr(self.o...
magicoder
python
You are tasked with creating a Python program that utilizes the `fixer_base` and `fixer_util` modules to implement a specific fix for a given pattern in Python code. The `fixer_base` module provides the base class for the fixer, while the `fixer_util` module offers utility functions for working with the fixer. Addition...
```python from lib2to3 import fixer_base from lib2to3.fixer_util import Call, Name from lib2to3 import patcomp context = patcomp.compile_pattern("power< 'eval' trailer< '(' any ')' > >") class FixInput(fixer_base.BaseFix): PATTERN = "power< 'eval' trailer< '(' any ')' > >" ``` In the solution, the `FixInput` clas...
magicoder
python
You are working on a project that involves using TensorFlow for various operations. You have imported several modules from the `diplomacy_research.utils.tensorflow` package, including `tensor_shape`, `array_ops`, `gen_array_ops`, `control_flow_ops`, `embedding_lookup`, and `math_ops`. Your task is to create a custom Te...
```python import tensorflow as tf from diplomacy_research.utils.tensorflow import tensor_shape from diplomacy_research.utils.tensorflow import array_ops from diplomacy_research.utils.tensorflow import gen_array_ops from diplomacy_research.utils.tensorflow import control_flow_ops from diplomacy_research.utils.tensorflow...
magicoder
python
You are tasked with implementing a reinforcement learning algorithm to solve a simple decision-making problem. The problem involves an agent making sequential decisions over a horizon of time steps. The agent receives a reward at each time step, and the goal is to maximize the cumulative reward over the horizon. The pr...
```cpp #include <iostream> #include <vector> // Define the reward function based on the problem file std::vector<int> parseProblemFile() { // Replace this with actual code to read the problem file and obtain the rewards for each time step return {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // Example rewards for each tim...
magicoder
cpp
You are given a code snippet that appears to be a part of a larger software project. Your task is to analyze the given code and identify potential issues or improvements that could be made to enhance its quality and maintainability. Your goal is to identify at least three potential issues or improvements in the given ...
1. Lack of Code Comments: Issue: The code lacks sufficient comments to explain its purpose, functionality, and any complex logic. This can make it difficult for other developers to understand and maintain the code in the future. Solution: Add descriptive comments to explain the purpose of each function, method, or comp...
magicoder
python
You are tasked with implementing a function that calculates the size of a struct in memory, given its definition in Rust. The struct is defined in the provided code snippet as `Info`, and you need to write a function that determines the size of this struct in bytes. Your task is to create a function `calculate_struct_...
```rust fn calculate_struct_size(struct_definition: &str) -> usize { // Parse the struct definition to determine the size of the struct // For simplicity, let's assume a 64-bit architecture where a pointer occupies 8 bytes let pointer_size = 8; // Calculate the size of the struct based on its fields an...
magicoder
rust
You are tasked with creating a custom implementation of a database table class in PHP. Your goal is to extend the provided `AbstractDbTable` class to create a specific table class called `ActivityFeedTypeTable`. The `ActivityFeedTypeTable` class should inherit from the `AbstractDbTable` and implement the necessary func...
```php use MCommons\Model\DbTable\AbstractDbTable; class ActivityFeedTypeTable extends AbstractDbTable { protected $tableName = 'activity_feed_types'; public function fetchAllActivityFeedTypes() { $select = $this->select(); return $this->fetchAll($select); } public function insertActi...
magicoder
php
You are tasked with implementing a function that translates document types into their corresponding strings. The function should take a document type as input and return the associated string based on the given mapping. The document types and their corresponding strings are defined within a switch statement in the prov...
```swift enum SecureIdRequestedAddressDocument { case rentalAgreement case bankStatement // Add other document types as needed } struct PresentationStrings { let Passport_Identity_TypeInternalPassport: String let Passport_Identity_TypeIdentityCard: String let Passport_Identity_TypeDriversLicens...
magicoder
swift
You are tasked with implementing a simplified version of the Model-View-Controller (MVC) pattern in Rust. Your goal is to create a view function that updates the view to represent the updated model. The view function takes a mutable reference to the model and a sender for communicating messages related to the model. Y...
```rust fn view(&mut self, model: &Model, sender: Sender<<Model as Model>::Msg>) { // Your implementation of updating the view based on the model goes here // Example: // update_view_with_model_data(&model); // Your implementation of utilizing the sender to communicate messages goes here // Exampl...
magicoder
rust
You are tasked with creating a Python function that determines the appropriate directory path for the PYSDL2 DLL file based on the system's architecture. The function should take no input parameters and return the correct directory path as a string. The code snippet provided initializes the PYSDL2 DLL path based on th...
```python import os import platform def get_pysdl2_dll_path(): if platform.architecture()[0] == '32bit': return "./SDL2/x86" else: # Set the PYSDL2 DLL path for 64-bit systems return "./SDL2/x64" # Example path for 64-bit systems # Test the function print(get_pysdl2_dll_path()) # Out...
magicoder
python
You are tasked with debugging and fixing a PHP function that interacts with a Redis server. The function is intended to establish a connection to the Redis server using the provided configuration. However, there are issues in the code that need to be identified and resolved. The given code snippet is part of a PHP cla...
The given code snippet contains several issues that need to be addressed to establish a successful connection to the Redis server. Here's the corrected and debugged version of the code: ```php /** * Establishes a connection to the Redis server using the provided configuration. */ public function Redis() { $redis...
magicoder
php
You are tasked with creating a program that processes a list of source code files and generates a visualization of the file dependencies using the DOT language for graph description. The DOT language is commonly used to represent directed graphs. Each source code file will be represented as a node in the graph, and the...
```python import sys import re def determine_fill_color(file_content): if re.search('[a-zA-Z]', file_content): return "white" else: return "black" def generate_dot_output(file_paths): nodes = [] edges = [] for file_path in file_paths: with open(file_path, 'r') as file: ...
magicoder
python
You are tasked with creating a unit testing framework for a compiler. The framework should be able to load and run test fixtures and then assert the results of the compilation process. The code snippet provided is a part of the unit test suite for the compiler. The `LoadAndRunFixtures` method loads and runs the test fi...
```csharp public class Compiler { public Result Result { get; private set; } public void LoadAndRunFixtures() { // Implement the logic to load and run the test fixtures // Update the Result property with the appropriate values // For example: // this.Result = new Result ...
magicoder
csharp
You are tasked with creating a Python function that processes and executes child queries within a parent query. The function should take in a list of child queries, execute each query, and then replace the child query tokens with the corresponding table names in the parent query. The child queries are represented as o...
```python import json from typing import List class ChildQuery: def __init__(self, query_id, data_source, table, token): self.query_id = query_id self.data_source = data_source self.table = table self.token = token def create_table(connection, table_name, results): # Implementa...
magicoder
python
You are tasked with creating a script that automates the process of building and releasing an Android application. The script should be able to run on both MacOS and Windows operating systems. The provided code snippet is a starting point for the script and contains some placeholders that need to be filled in. Your ta...
```bash #!/bin/bash # Determine the operating system if [[ "$OSTYPE" == "darwin"* ]]; then # MacOS build_command="npm run android_release" elif [[ "$OSTYPE" == "msys" ]]; then # Windows build_command="npm run win_android_release" else echo "Unsupported operating system" exit 1 fi # Set the pro...
magicoder
shell
You are tasked with creating a Django web application that displays a list of blog posts and allows users to view the details of each post. The application should have two views: one to display all blog posts and another to display the details of a specific blog post. The code snippet provided is a starting point for t...
```python # Create a new file named urls.py in the blog app directory and define the URL patterns from django.urls import path from . import views urlpatterns = [ path('', views.allblogs, name='allblogs'), # URL for displaying all blog posts path('<int:blog_id>/', views.detail, name='detail'), # URL for disp...
magicoder
python
You are tasked with creating a Python program to parse data from a website using a custom parser. The program should utilize object-oriented programming and error handling to ensure robustness and reliability. Your task is to implement the `KedemRuParser` class, which will be responsible for parsing data from the Kede...
```python import requests from bs4 import BeautifulSoup class KedemRuParser: def __init__(self): self.parsed_data = None def parse(self): try: url = 'https://www.kedem.ru' # Example URL for parsing response = requests.get(url) response.raise_for_status() #...
magicoder
python
You are tasked with implementing a communication protocol for a custom hardware device. The device has a communication interface that allows reading and writing data. The provided code snippet is a part of the communication module for this device. Your task is to complete the implementation of the communication module ...
```rust use std::io::{self, Read, Write}; use std::time::Duration; #[derive(Debug)] enum CommunicationError { Timeout, IoError(io::Error), } struct CommunicationDevice { // Add any necessary fields here } impl CommunicationDevice { fn flush(&mut self) { let mut buf = Vec::new(); let _...
magicoder
rust
You are tasked with creating a function to map an object representing an apprenticeship vacancy to a data transfer object (DTO) for further processing. The input object contains information about the location and type of apprenticeship, and the function should map this information to the corresponding fields in the DTO...
```csharp public class Address { // Properties and methods for the Address class } public class ApprenticeshipVacancyDto { public Address Location { get; set; } public int ApprenticeshipTypeId { get; set; } public string ApplicationUrl { get; set; } } public class VacancyMapper { public Apprentice...
magicoder
csharp
You are tasked with creating a program to manage a library system. The library contains books, each of which has a unique identifier, title, author, and availability status. The program should allow users to perform various operations such as adding new books, removing books, borrowing books, returning books, and listi...
```python class Book: def __init__(self, book_id, title, author): self.book_id = book_id self.title = title self.author = author self.availability_status = True class Library: def __init__(self): self.books = [] def add_book(self, book_id, title, author): ne...
magicoder
python
You are tasked with creating a function that performs integer division and remainder operations using LLVM IR (Intermediate Representation) code generation. The function should take two integer inputs and produce the quotient and remainder as outputs. You are provided with a code snippet that demonstrates the usage of ...
```python def generate_integer_division_code(dividend, divisor): llvm_ir_code = f"define i32 @integer_division(i32 %{dividend}, i32 %{divisor}) {{\n" llvm_ir_code += "entry:\n" llvm_ir_code += f" %0 = sdiv i32 %{dividend}, %{divisor}\n" llvm_ir_code += f" %1 = srem i32 %{dividend}, %{divisor}\n" l...
magicoder
python
You are tasked with implementing a simple text-based game where players can issue orders to units on a grid. The game interface is handled through a console user interface (UI). The provided code snippet is a part of the game logic responsible for processing player moves and orders. Your task is to implement the logic...
```cpp // Define a structure to represent an order struct Order { int id; int x; int y; int unitId; }; // Function to process player orders void processOrders() { Move res; _consoleUI.clear(); _consoleUI.logState(_game, _reporter); _consoleUI.makeMove(_game); Order* order = nullptr;...
magicoder
cpp
You are given a string `lbar` containing a list of species names and their corresponding FASTA file identifiers. Each species name is followed by an underscore and a FASTA file identifier, and the entries are separated by spaces. Your task is to write a function `extract_species_names` that extracts and returns a list ...
```python from typing import List def extract_species_names(lbar: str) -> List[str]: species_names = set() entries = lbar.split() for entry in entries: species_name = entry.split('_')[0] species_names.add(species_name) return list(species_names) ```
magicoder
python
You are tasked with creating a simple HTML parser that extracts the text content from a given HTML snippet. Your parser should be able to handle basic HTML tags such as `<h1>`, `<p>`, and `<div>`, and should ignore any other HTML elements or attributes. The extracted text should be returned as a single string, with all...
```python import re def parseHTML(html): # Use regular expression to remove HTML tags clean_text = re.sub('<[^<]+?>', '', html) return clean_text.strip() # Test the function with the given HTML snippet html_snippet = """ <div> <h1>About Me</h1> <p>Lorem, ipsum dolor sit amet consectetur adipisicin...
magicoder
python
You are tasked with creating a Python class that represents a simple task management system. The class should have a method to add a new task with a timestamp and another method to retrieve all tasks created after a certain time. You are provided with a code snippet that demonstrates the usage of the `fields.DateTime(...
```python from datetime import datetime class TaskManager: def __init__(self): self.tasks = [] def add_task(self, description): timestamp = datetime.now() self.tasks.append((description, timestamp)) def get_tasks_created_after(self, timestamp): filtered_tasks = [task[0] fo...
magicoder
python
You are working on a project that involves processing and manipulating multidimensional arrays using Python and the NumPy library. As part of this project, you need to implement a function to perform a specific type of array manipulation. You are given a NumPy array `arr` of shape (n, m, p) and a positive integer `k`....
```python import numpy as np def custom_permute_and_mask(arr: np.ndarray, k: int) -> np.ndarray: # Permute the dimensions of the array according to the order (2, 0, 1) arr_permuted = np.transpose(arr, (2, 0, 1)) # Apply a masking operation to the array, replacing any occurrences of NaN with 0 arr_...
magicoder
python
You are tasked with implementing a custom authorization attribute in a C# ASP.NET MVC application. The custom authorization attribute should restrict access to a specific controller action based on the user's role. You are given the following code snippet as a starting point: ```csharp [Authorize()] public class HomeC...
```csharp using System; using System.Web; using System.Web.Mvc; [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)] public class CustomAuthorize : AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { if (httpCon...
magicoder
csharp
You are tasked with implementing a function that processes a given dictionary of city-parent relationships and returns a nested dictionary representing the hierarchical structure of the cities within their respective parent provinces. Each city is uniquely identified by a city code, and its parent province is identifie...
```python def build_city_hierarchy(city_parent_dict): city_names = { 'C001': 'City1', 'C002': 'City2', 'C003': 'City3', 'C004': 'City4', 'C005': 'City5' } city_hierarchy = {} for city, province in city_parent_dict.items(): if province in city_hierarch...
magicoder
python
You are given a Python function `uniq_kmers(kmers)` which takes a list of DNA k-mers as input. The function is intended to find unique k-mers and their reverse complements. However, the function contains some errors and is incomplete. Your task is to complete the function `uniq_kmers` so that it correctly finds unique ...
```python def find_reverse(kmer): complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'} reverse = ''.join(complement[base] for base in reversed(kmer)) return reverse def uniq_kmers(kmers): unique_pairs = [] didthat = [] for kmer in kmers: if kmer not in didthat: didthat...
magicoder
python
You are tasked with implementing a custom error handling system for a Rust application. The goal is to create an enum `Error` with specific variants to represent different encoding errors that may occur in the application. Each variant should contain relevant data to provide detailed information about the error. Your ...
```rust use std::fmt; use std::io; /// Encoding Errors. #[derive(Debug)] pub enum Error { InvalidCharacter(char), InvalidFormat(String), IOError(io::Error), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Error::InvalidCharact...
magicoder
rust
You are tasked with creating a Java program that processes a given file and extracts specific information from it. The program should read the contents of the file, identify certain patterns, and then output the occurrences of these patterns along with their positions in the file. You are provided with a code snippet ...
```java import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; public class FilePatternMatcher { public static void main(String[] args) { String sourceFilePath = UIUtils.getSelectedFile(fileEditorManager, fileDoc...
magicoder
java
You are tasked with creating a Python script that automates the process of building a PEX (Python EXecutable) file for a specific package and its dependencies. A PEX file is a self-contained executable Python environment that includes all the necessary dependencies, allowing for easy distribution and execution. Your s...
```python import subprocess def build_pex_file(package_name, requirements_file, entry_point, output_file): command = [ '~/.local/bin/pex', '-vvvvvvvv', package_name, '-r', requirements_file, '-f', 'dist', '-e', entry_point, '-o', ...
magicoder
python
You are tasked with implementing a Python function that calculates the natural logarithm of 1 plus the input value using a specific transformation. The transformation involves using the `explin` function, which returns 1 plus the input if the input is greater than or equal to 0, and otherwise returns the exponential of...
```python import numpy as np def explin(x): return np.where(x >= 0, 1 + x, np.exp(x)) def log_exp1p(x: float) -> float: if x >= 0: return np.log1p(x) else: return np.log(explin(x)) ``` The `log_exp1p` function first checks if the input `x` is greater than or equal to 0. If it is, the func...
magicoder
python
You are tasked with implementing a Python class that manages the communication between two peers using asynchronous messaging. The class, named `AsyncCommunicator`, should support sending and receiving Python objects between the peers. The class should have the following methods: 1. `__init__(self)`: Initializes the c...
```python class UCXError(Exception): pass class AsyncCommunicator: def __init__(self): self._finished_recv_count = 0 async def recv_obj(self, n): if n < self._finished_recv_count: raise UCXError( "`n` cannot be less than current recv_count: %d (abs) < %d (abs)" ...
magicoder
python
You are tasked with creating a program to calculate the lift and drag forces acting on an airfoil at various velocities. The lift and drag forces are determined by the airfoil's geometry, velocity, and aerodynamic properties. The program will take input parameters such as airfoil thickness, chord length, orientation an...
```python import math def calculate_forces(inputs): Rho = inputs['Rho'] Thickness = inputs['Thickness'] Ori_1 = inputs['Ori_1'] Ori_2 = inputs['Ori_2'] Chord = inputs['Chord'] SectionLength = inputs['SectionLength'] Vmin = inputs['Vmin'] Vmax = inputs['Vmax'] Vstep = inputs['Vstep']...
magicoder
python
You are tasked with implementing a class that interacts with a cloud storage service. The class, named `Storage`, should have the ability to initialize with a bucket name, file key, and an optional endpoint. The endpoint is used to specify the storage service's location. Your task is to complete the `Storage` class by ...
```python class Storage: def __init__(self, bucket, file_key, endpoint=None): self.bucket = bucket self.file_key = file_key self.endpoint = endpoint def generate_url(self, expiration): if self.endpoint: return f"{self.endpoint}/{self.bucket}/{self.file_key}?expires={...
magicoder
python
You are working on a web application that uses a Python backend to handle HTTP requests. Your task is to implement a function that sanitizes the user-agent header to prevent code injection attacks. The user-agent header is a string that represents the client application making the request to the server. The potential c...
```python import re def sanitize_user_agent(user_agent: str) -> str: # Define a regular expression pattern to match potentially harmful characters pattern = r'[;`\'"]' # Use the sub() function from the re module to replace potentially harmful characters with an empty string sanitized_user_agent = re.s...
magicoder
python
You are tasked with creating a Python class that simulates a simple online shopping cart. The class should have methods for adding items to the cart, removing items from the cart, calculating the total cost of the items in the cart, and checking out. Additionally, the class should have a method for applying a discount ...
```python class ItemNotInCartError(Exception): pass class ShoppingCart: def __init__(self): self.cart = {} def add_item(self, item_name, quantity, price_per_unit): if item_name in self.cart: self.cart[item_name][0] += quantity else: self.cart[item_name] = [q...
magicoder
python
You are tasked with creating a program to manage a schedule of events for a given year. Each event is represented by a class that inherits from a base class `Day` and is named in the format `DayX_YYYY`, where `X` is the day number and `YYYY` is the year. The events are added to a list called `days` in chronological ord...
```python class Day: pass # Base class for events class Day2_2018(Day): pass # Implementation for Day 2, 2018 class Day3_2018(Day): pass # Implementation for Day 3, 2018 # Implementations for Day4_2018, Day5_2018, ..., Day16_2018 def find_event_by_date(year, day_number): event_name = f"Day{da...
magicoder
python
You are tasked with creating a Python function that processes data from a gaming performance monitoring tool and generates visualizations for framerate and frametimes using the Bokeh library. You are given a code snippet that outlines the creation of two charts: one for frametimes and one for framerate. The `CreateLin...
```python from bokeh.models import Panel, Tabs from bokeh.plotting import figure from bokeh.layouts import column def CreateLineDiagram(x_data, y_data, width, title, x_label, y_label): p = figure(title=title, x_axis_label=x_label, y_axis_label=y_label, plot_width=width) p.line(x_data, y_data) return p def...
magicoder
python
You are tasked with creating a Python class that represents a 3D ball in a game environment. The ball has various attributes such as location, rotation, velocity, and angular velocity. Your goal is to implement the class and its methods to manipulate and retrieve information about the ball. You are given a code snippe...
```python import ctypes class Vector3(ctypes.Structure): _fields_ = [("x", ctypes.c_float), ("y", ctypes.c_float), ("z", ctypes.c_float)] class Rotator(ctypes.Structure): _fields_ = [("pitch", ctypes.c_float), ("yaw", ctypes.c_float), ("roll", ct...
magicoder
python
You are tasked with implementing a function that calculates the missing document offsets in a file based on a given dictionary and access control list (ACL). The function should take the file, dictionary, and ACLs as input and return the missing document offsets as a list of tuples containing the offset and ACL. The f...
```swift struct File { // Define the File structure and properties } struct ACL { // Define the ACL structure and properties } func missingDocOffsets(in file: File, dict: [String: Any], acls: [ACL]) -> [(Int, ACL)] { var missingOffsets: [(Int, ACL)] = [] // Iterate through the file's structure and co...
magicoder
swift
You are tasked with implementing a Java class for managing university students. The class should have methods to set and get the student's ID and UIC (University Identification Code). The UIC is a unique identifier for each student and should be a string value. Your task is to complete the implementation of the `Studen...
```java public class Student { private int id; private String uic; public void setId(int id) { this.id = id; } public void setUic(String uic) { this.uic = uic; } public String getUic() { return uic; } } ``` In the solution, the `Student` class is completed with...
magicoder
java
You are tasked with implementing a Python function that constructs a distribution package for a software module using the Autotools build system. The Autotools suite (Autoconf, Automake, and Libtool) is commonly used to facilitate the building and installation of software on Unix-like systems. You need to complete the...
```python def _autotools_dist_builder(module): import os import subprocess source_dir = module.get_source_dir() os.chdir(source_dir) # Change to the source directory # Run the Autotools commands to build the distribution package subprocess.run(["autoreconf", "-i"]) # Run autoreconf to genera...
magicoder
python
You are tasked with implementing a function to process DNA sequencing data from a Fastq file. The function should read the Fastq file and extract the DNA sequences for further analysis. The Fastq file contains DNA sequences and their corresponding quality scores. Each sequence is represented by four lines in the file: ...
```python from typing import List def process_fastq_file(file_path: str) -> List[str]: dna_sequences = [] with open(file_path, 'r') as file: lines = file.readlines() for i in range(0, len(lines), 4): # Extract DNA sequence from the second line of every group of 4 lines d...
magicoder
python
You are tasked with implementing a password validation function for a user registration system. The function should take in a password as input and return a boolean value indicating whether the password meets the specified criteria. The password validation criteria are as follows: 1. The password must be at least 8 ch...
```python import re def validatePassword(password: str) -> bool: # Check if the password length is at least 8 characters if len(password) < 8: return False # Check if the password contains at least one uppercase letter, one lowercase letter, one digit, and one special character if not re.s...
magicoder
python
You are given two lists: `quality` and `wage`, where `quality[i]` is the quality of the `i-th` worker and `wage[i]` is the minimum wage expectation for the `i-th` worker. You need to hire exactly `k` workers to form a paid group. For the `i-th` worker to be paid their desired wage, they must be paid at least their mini...
```python from heapq import heappush, heappop from typing import List class Solution: def mincostToHireWorkers(self, quality: List[int], wage: List[int], k: int) -> float: n = len(quality) workers = sorted((wage[i] / quality[i], quality[i]) for i in range(n)) ans = float('inf') heap...
magicoder
python
You are tasked with creating a Python function that renders a table from a given 2D grid. The `render_table` function should take a 2D list of strings as input and return a formatted string representing the table. Each inner list represents a row in the table, and the strings within each inner list represent the cells ...
```python from typing import List def render_table(grid: List[List[str]]) -> str: # Find the maximum width of each column col_widths = [max(len(cell) for cell in col) for col in zip(*grid)] # Format each row with proper alignment formatted_rows = [] for row in grid: formatted_row = ' '...
magicoder
python
You are tasked with implementing a user authentication system for a web application. The system should send a verification email to new users upon signing up and then set the user data upon successful user creation. You are provided with a code snippet that demonstrates the invocation of the `SendVerificationMail()` fu...
```javascript // Definition of the SendVerificationMail() function function SendVerificationMail() { return new Promise((resolve, reject) => { // Send verification email logic here // For example, using a third-party email service // Replace the following line with actual email sending logic setTimeou...
magicoder
javascript
You are tasked with implementing a Java class that manages metadata for various artifacts. The class should provide methods to retrieve and update metadata for the artifacts. You are given a code snippet that retrieves metadata for an artifact using a service. Your task is to complete the implementation of the `Artifac...
```java import java.io.InputStream; // Define the Metadata class class Metadata { // Define metadata properties private String name; private String version; // Other metadata properties // Constructor and methods to access and modify metadata properties } // Implement the ArtifactMetadataServ...
magicoder
java
You are tasked with creating a Discord bot command that processes and stores student information. The bot command should be able to handle requests in a specific format and purge any incorrect requests after a short delay. Your task is to implement a Python function that processes the user's request and handles the pu...
```python import asyncio async def process_request(ctx, request): if request.startswith("%request"): parts = request.split() if len(parts) == 3: name = parts[1] school = parts[2] # Store the student's name and school in a data structure for future use ...
magicoder
python
You are tasked with implementing a function that processes scene configurations for a mobile application. The scene configurations are represented by the `UISceneConfiguration` class, which contains a name and a session role. The `UISceneConfiguration` class is defined as follows: ```swift class UISceneConfiguration {...
```swift func processSceneConfigurations(_ configurations: [UISceneConfiguration]) -> [String: Int] { var uniqueConfigurations: [String: Set<String>] = [:] for config in configurations { if var roles = uniqueConfigurations[config.name] { roles.insert(config.sessionRole) uniq...
magicoder
swift
You are working on a project that involves low-level programming and need to understand how register values are moved to memory locations in x86 assembly language. Your task is to write a C function that takes 11 input arguments and moves the values of the first 11 CPU registers (`r15`, `r14`, `r13`, `r12`, `rbx`, `rbp...
```c void moveRegistersToMemory(void *mem0, void *mem1, void *mem2, void *mem3, void *mem4, void *mem5, void *mem6, void *mem7, void *mem8, void *mem9, void *mem10) { asm volatile ( "mov %%r15, %0\n" "mov %%r14, %1\n" "mov %%r13, %2\n" "mov %%r12, %3\n" "mov %%rbx, %4\n" ...
magicoder
c
You are tasked with creating a script to automate the build process for a software project. The script should handle cleaning the project, resetting any configurations, and scrubbing any unnecessary files before building the project. After the initial setup, the script should execute the build process and create a pack...
```bash #!/bin/bash # Clean the project dev-tools/build clean # Reset project configurations dev-tools/build reset # Scrub unnecessary files dev-tools/build scrub # Build the project dev-tools/build all # Create packed archive RELEASE_VERSION="1.0" # Replace with actual release version mkdir -p output/target tar ...
magicoder
shell
You are working on a project that involves managing Git repositories and performing operations using Git commands. Your task is to write a script that automates the process of splitting a subtree from a specific directory, creating a new branch, and pushing the changes to the remote repository. You are given the follo...
```bash #!/bin/bash # Step 1: Split the subtree from the directory Build/Release into a new branch named upm git subtree split -P Build/Release -b upm # Step 2: Retrieve the commit hash of the latest commit in the upm branch TAG_BRANCH_COMMIT=$(git log -n 1 upm --pretty=format:"%H") # Step 3: Print the commit hash o...
magicoder
shell
You are tasked with creating a Python command-line tool that utilizes the `click` library to interact with the NFL Team Game Finder (TGF) module. The TGF module provides functionality to search for NFL team game data based on various criteria. Your task is to implement a command-line interface that allows users to spec...
```python import click from nfl.tgf import TeamGameFinder # Define the command-line interface using the click library @click.command() @click.option('--team', prompt='Enter team name', help='Specify the team name for game search') @click.option('--season', prompt='Enter season', type=int, help='Specify the season for ...
magicoder
python
You are tasked with creating a program that converts a given text representation into a specific format. The input text contains lines of text, and the program should convert each line according to a specified format. The format to be used is called "text-orig-unicode," which utilizes Cuneiform Unicode characters to re...
```python def convert_to_text_orig_unicode(lines): cuneiform_numerals = { "1": "𐏑", "2": "𐏁", "3": "𐏂", "4": "𐏃", "5": "𐏄", # Add more numerals as needed } converted_lines = [] for ln in lines: converted_ln = "" for char in ln: ...
magicoder
python
You are tasked with creating a Python program to calculate the required diameter of a pipe for different pressure ratios. The program should utilize the given code snippet as a starting point and implement the necessary calculations to determine the diameter based on the specified pressure ratios. The given code snipp...
```python class PipeDiameterCalculator: def __init__(self, ks, L, Q): self.ks = ks # thermal conductivity self.L = L # length self.Q = Q # flow rate def calculate_diameter(self, pressure_ratios): for ratio in pressure_ratios: # Assuming the pressure ratio is u...
magicoder
python
You are tasked with implementing a function that reverses the order of words in a given string. Your function should take a string as input and return a new string with the words in reverse order. A word is defined as a sequence of non-space characters. For example, given the input string "hello world", the function s...
```csharp public string ReverseWords(string s) { string[] words = s.Split(' '); // Split the input string into an array of words Array.Reverse(words); // Reverse the order of the words return string.Join(" ", words); // Join the reversed words into a new string } ```
magicoder
csharp
You are tasked with implementing a function to lexically analyze lines of text, but the existing implementation has a flaw. The function `lex_origx` is intended to take a line number, a line of text, and a row number as input, and return a `LexItem` or an error message. However, the function is currently failing when i...
The issue with the existing `lex_origx` function is that it lacks the logic to handle incorrect numbers in the line. To fix this, we need to add error handling for incorrect numbers and return the appropriate `Result` based on the input. ```rust struct LexItem { // Define the structure of LexItem } fn lex_origx(l...
magicoder
rust
You are tasked with creating a Python program that simulates a secure HTTP server using SSL/TLS encryption. Your program should utilize the provided code snippet as a starting point and extend it to include additional functionality. Your program should include the following features: 1. Accept a command-line argument ...
```python import BaseHTTPServer import SimpleHTTPServer import ssl import sys import logging from datetime import datetime class CustomRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def log_request(self, code='-', size='-'): log_entry = '{} - - [{}] "{} {}"'.format(self.client_address[0], self....
magicoder
python
You are tasked with implementing a function that parses command line arguments to determine a skill level. The skill level can be represented either as a numerical value or as experience points (XP). The code snippet provided is a part of a larger program and contains a match statement that handles the parsing of skill...
```rust enum Skill { Level(u32), Xp(u32), } fn parse_skill_from_args(args: Vec<String>) -> Option<Skill> { if args.len() < 2 { eprintln!("Insufficient command line arguments provided."); return None; } let arg1 = &args[1]; match arg1.parse::<u32>() { Ok(value) => { ...
magicoder
rust
You are tasked with creating a simple chat client using Java and the Netty library. Your goal is to establish a connection to a chat server and send and receive messages using a custom protocol. Your task is to implement a Java class that establishes a connection to a chat server and sends and receives messages. The c...
```java package com.terwergreen.chat; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio....
magicoder
java
You are given a list of integers representing the scores of a game. The game has a rule that a player's score is the sum of the scores of the last two moves. The player starts with a score of 0. You need to write a function that calculates the maximum possible score that can be achieved by the player. Write a function...
```python from typing import List def maxPossibleScore(scores: List[int]) -> int: if len(scores) <= 2: return sum(scores) dp = [0] * len(scores) dp[0] = scores[0] dp[1] = scores[1] for i in range(2, len(scores)): dp[i] = max(dp[i-1], dp[i-2]) + scores[i] return ma...
magicoder
python
You are tasked with creating a Python function that checks whether a specific OpenGL extension is supported and retrieves the value of a constant associated with that extension. The function should take the extension name as input and return the constant value if the extension is supported, or a message indicating that...
```python from OpenGL import extensions from OpenGL.GL import glget import ctypes from typing import Union def check_extension_support(extension_name: str) -> Union[int, str]: if extensions.has_extension(extension_name): constant_value = glget.GLint() glget.glGetIntegerv(extensions.GL_DEPTH_COMPONE...
magicoder
python
You are given a snippet of code that appears to be part of a method for manipulating a linked list. Your task is to implement a method to delete a node at a given position in a doubly linked list. The code snippet provided seems to be a part of the implementation, but it is incomplete and lacks context. Your task is to...
```javascript class Node { constructor(data, prev = null, next = null) { this.data = data; this.prev = prev; this.next = next; } setPrev(prev) { this.prev = prev; } setNext(next) { this.next = next; } getPrev() { return this.prev; } getNext() { return this.next; } } ...
magicoder
javascript
You are tasked with implementing a simple text-based game called "Rock, Paper, Scissors" in Python. The game will be played against the computer, and the winner will be determined based on the choices made by the player and the computer. Your task is to write a Python program that simulates the game. The program shoul...
```python import random class RockPaperScissorsGame: def __init__(self): self.USER_POINTS, self.COMPUTER_POINTS = 0, 0 self.w, self.h = 100, 100 self.comp_center_coords = (170, self.h//2 - 80) self.computer_choice, self.user_choice = "other", "paper" self.countdown_started =...
magicoder
python
You are tasked with implementing a custom quantization module for a neural network. The module takes in various parameters and initializes different quantizers based on a specified quantization type. The quantization process involves quantizing both the activation and weight tensors using either symmetric or asymmetric...
```python class CustomQuantizationModule: def __init__(self, kernel_size, stride, padding, dilation, groups, bias, q_type, a_bits, w_bits, out_channels, first_layer): self.kernel_size = kernel_size self.stride = stride self.padding = padding self.dilation = dilation self.grou...
magicoder
python
You are tasked with creating a Python function that simulates a train scheduling system. The function should take in a list of train schedules and return the maximum number of trains that can run simultaneously without conflicting schedules. Each train schedule is represented as a tuple containing the start time and en...
```python from typing import List, Tuple def max_simultaneous_trains(train_schedules: List[Tuple[int, int]]) -> int: events = [] for start, end in train_schedules: events.append((start, 1)) # 1 represents the start of a train journey events.append((end, -1)) # -1 represents the end of a trai...
magicoder
python
You are tasked with creating a Python program to extract and process data from a social media platform. The program will utilize a generator function to yield individual answer items, and it will handle pagination by checking a boolean variable `is_end`. Each answer item will contain information such as the number of c...
```python import datetime def extract_answer_items(): # Assume answer_data is a list of answer dictionaries obtained from the social media platform answer_data = [...] # Populate with actual data is_end = False # Assume this variable is set based on pagination logic for answer in answer_data: ...
magicoder
python
You are tasked with creating a Python script to automate the process of cleaning up a directory by removing specific files and directories. Your script should remove the following items from the current directory: - The "build" directory - The "dist" directory - Any "__pycache__" directories - The "RotateRoIAlign.egg-i...
```python import os # List of items to be removed items_to_remove = ['build', 'dist', '__pycache__', 'RotateRoIAlign.egg-info'] # Function to remove items def clean_up_directory(): for item in items_to_remove: if os.path.exists(item): if os.path.isdir(item): os.system(f'rm -r {...
magicoder
python
You are given a list of sentences, each containing words with their respective parts of speech tagged. Your task is to extract pairs of words from the sentences based on certain conditions and print them in a specific format. You need to write a function or method that takes the following inputs: - `sentences`: a list...
```python from typing import List, Dict def extract_word_pairs(sentences: List[List[Dict[str, str]]], chunk: List[int]) -> List[str]: pairs = [] for i, sentence in enumerate(sentences): modifier_pos = [morph['pos'] for morph in sentence[chunk[i]].morphs] modifiee_pos = [morph['pos'] for morph i...
magicoder
python
You are tasked with creating a Python function to handle duplicate records in a MongoDB database. The function should take in a list of collection names, connect to the MongoDB client, and then for each collection in the list, find and delete duplicate records based on a specified field. You are given the following in...
```python from pymongo import MongoClient def find_duplicate(col): # Function to find duplicate records in the given collection # Assuming 'field_name' is the field used to identify duplicates duplicate_records = col.aggregate([ {"$group": {"_id": {"field_name": "$field_name"}, "count": {"$sum": 1}...
magicoder
python
You are working on a project that involves processing images using Python's NumPy and PIL libraries. Your task is to create a function that processes an image and generates a word cloud based on the text content within the image. The function should take the path to the image file as input and produce a word cloud base...
```python from wordcloud import WordCloud, STOPWORDS from PIL import Image import numpy as np import matplotlib.pyplot as plt def generate_word_cloud(image_path): img = np.array(Image.open(image_path)) stopwords = set(STOPWORDS) stopwords.add("said") # Extract text content from the image (Ass...
magicoder
python
You are working on a data processing script that reads a CSV file and converts it into a JSON format. The given code snippet is a part of this script. The script processes the CSV data and accumulates it into a nested dictionary `h`. Each line of the CSV file contains 13 elements, and the code processes specific elemen...
```python import json h = {} def process_csv_data(csv_data): global h for line_list in csv_data: h[line_list[7]] = h.get(line_list[7], {"oorsprong": {}, "profiel": {}}) h[line_list[7]]["oorsprong"][line_list[3]] = h[line_list[7]]["oorsprong"].get(line_list[3], 0) + int(line_list[12]) h...
magicoder
python
You are tasked with implementing a custom test case class for testing Kafka consumer configurations. The KafkaConsumerConfig class is responsible for setting up and configuring a Kafka consumer, and your goal is to create a test suite to ensure that the configuration is working as expected. Your task is to complete th...
```python import unittest from kafka import KafkaConsumer class TestKafkaConsumerConfig(unittest.TestCase): def test_valid_configuration(self): # Test the consumer with valid configuration settings consumer = KafkaConsumer(bootstrap_servers='localhost:9092', group_i...
magicoder
python
You are tasked with implementing a Python class that performs multiplication operations with enhanced functionality. The class should support both regular multiplication and multiplication with a specified factor. Additionally, it should provide a method to retrieve the result of the multiplication operation. You are ...
```python class Multiplication: def __init__(self, number): self.number = number def multiply(self, factor=None): if factor is not None: self.number *= factor return self.number def get_result(self): return self.number ``` The `Multiplication` class is implement...
magicoder
python
You are tasked with implementing a transaction pool management system for a blockchain network. The system should handle adding orphan transactions and proposed transactions to the transaction pool. You are given a partial code snippet from the transaction pool management module, which includes two functions: `add_orp...
```rust // Implementation of the add_orphan function fn add_orphan( &mut self, cycles: Option<Cycle>, size: usize, tx: Transaction, unknowns: Vec<OutPoint>, ) -> Option<DefectEntry> { trace_target!(crate::LOG_TARGET_TX_POOL, "add_orphan {:#x}", &tx.hash()); self.orphan.add_tx(cycles, size, t...
magicoder
rust
You are working on a video streaming platform and need to implement a function to retrieve the URL suffix for a video based on its duration. The function should take a list of video metadata dictionaries and a target duration as input, and return the URL suffix of the video that matches the duration or the closest dura...
```python def retrieve_video_url_suffix(metadata, target_duration): closest_duration_diff = float('inf') closest_url_suffix = None for video in metadata: duration_diff = abs(video['duration'] - target_duration) if duration_diff < closest_duration_diff or (duration_diff == closest_duration_d...
magicoder
python
You are tasked with creating a program to retrieve local gateway routes from an AWS EC2 client using the AWS SDK for Java. Your program should implement a method to search for local gateway routes based on specific filters and return the results. Your task is to implement the `searchLocalGatewayRoutes` method within t...
```java package com.amazonaws.ec2.localgatewayroute; import software.amazon.awssdk.services.ec2.Ec2Client; import software.amazon.awssdk.services.ec2.model.Filter; import software.amazon.awssdk.services.ec2.model.LocalGatewayRoute; import software.amazon.awssdk.services.ec2.model.SearchLocalGatewayRoutesRequest; impor...
magicoder
java
You are tasked with implementing a function that simulates a simple banking system. The system should support creating accounts, depositing funds, withdrawing funds, and transferring funds between accounts. Each account should have a unique account number, and the system should be able to handle multiple accounts. You...
```python class BankingSystem: def __init__(self): self.accounts = {} # Dictionary to store account_number: balance pairs self.account_number_counter = 1 # Counter to generate unique account numbers def create_account(self, name): account_number = self.account_number_counter s...
magicoder
python
You are tasked with implementing a custom multi-value attribute (MVA) feature in a search engine using SQL. An MVA allows an entity to have multiple values for a specific attribute, such as tags or categories. The given code snippet contains a commented-out configuration for an MVA called "tag" with a ranged query. You...
To implement the MVA feature for tags and categories, you can use the following SQL statements: 1. Define the MVA for tags: ```sql -- Define MVA for tags CREATE TABLE entity_tags ( entity_id INT, tag_id INT, FOREIGN KEY (entity_id) REFERENCES entities(id), FOREIGN KEY (tag_id) REFERENCES tags(id) ); ``...
magicoder
sql