query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with creating a program that can parse and execute commands from a script file. The script file may contain commands written in a specific language, and the program should be able to interpret and execute these commands. Your task is to implement a script parser and executor that can handle the followin...
```python import subprocess def execute_script(script_file): with open(script_file, 'r') as file: lines = file.readlines() interpreter = None commands = [] for line in lines: if line.startswith("#!"): interpreter = line[2:].strip() else: ...
magicoder
python
You are tasked with implementing a function to compare two vectors of fractions. A fraction is represented as a pair of integers, where the first integer is the numerator and the second integer is the denominator. The function should take two vectors of fractions as input and return a comparison result based on their b...
```rust fn compare_fractions(a: Vec<Fraction>, b: Vec<Fraction>) -> std::cmp::Ordering { let ab: Vec<u8> = a.iter().flat_map(|f| to_bytes(f)).collect(); let bb: Vec<u8> = b.iter().flat_map(|f| to_bytes(f)).collect(); ab.cmp(&bb) } ``` The `compare_fractions` function takes two vectors of fractions as inpu...
magicoder
rust
You are tasked with creating a program that processes and analyzes data from an ArcGIS Tiled Map Service Layer. The ArcGIS Tiled Map Service Layer is a type of map layer that provides access to cached map tiles from a map service. Your program needs to extract specific information from this layer and perform calculatio...
```csharp using System; using System.Collections.Generic; using System.Threading.Tasks; public sealed partial class ArcGISTiledMapServiceLayerSample : Page { // Method to retrieve elevation data from the ArcGIS Tiled Map Service Layer public async Task<List<double>> RetrieveElevationDataAsync() { t...
magicoder
csharp
You are tasked with implementing a function that calculates the total number of unique paths to reach the bottom-right corner of a grid from the top-left corner. You can only move either down or to the right at any point in time. The grid is represented as a 2D array, where 1 indicates an obstacle and 0 indicates an em...
```python from typing import List def uniquePaths(grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) dp = [[0] * n for _ in range(m)] for i in range(m): for j in range(n): if grid[i][j] == 1: # obstacle dp[i][j] = 0 elif i == 0 and j == 0: # sta...
magicoder
python
You are tasked with implementing a keyboard class that simulates a virtual keyboard with a grid of keys. The class has several attributes and methods for selecting keys and performing operations. Your task is to complete the implementation of the `set_selected_other` method and the `get_selected_key` method. The `Keyb...
```python class Keyboard: def __init__(self, keys, current_keyboard): self.keys = keys self.current_keyboard = current_keyboard self.selected_col = 0 self.selected_row = 0 self.selected_others = -1 self.set_selected_other() def set_selected_other(self): i...
magicoder
python
You are tasked with implementing a simple transaction scheduler for a banking system. The system maintains a schedule of transactions and processes operations based on the type of operation. The code snippet provided is a part of the transaction scheduler's implementation. The `schedule.transactions[transaction_id] = ...
```cpp void processCommitOperation(Operation op, Schedule& schedule) { if (op.type == OpType::commit) { int transaction_id = /* retrieve transaction id from op */; auto it = schedule.transactions.find(transaction_id); if (it != schedule.transactions.end()) { Transaction& transact...
magicoder
cpp
You are tasked with creating a Python function that parses a given text file and extracts the copyright information from it. The copyright information is typically found in the header of the file and follows a specific format. The copyright notice starts with a comment symbol (#) followed by the copyright statement, wh...
```python def extract_copyright_info(file_path: str) -> str: with open(file_path, 'r') as file: for line in file: if line.strip().startswith('# Copyright'): return line.strip('#').strip() return "No copyright information found" ``` The `extract_copyright_info` function opens...
magicoder
python
You are tasked with creating a custom Angular directive that dynamically generates breadcrumb navigation based on the current route. The directive should be able to parse the route hierarchy and display a breadcrumb trail for easy navigation within the application. Your task is to implement the `NgxCrumbDirective` tha...
```typescript import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core'; import { ActivatedRoute, NavigationEnd, Router } from '@angular/router'; import { filter } from 'rxjs/operators'; @Directive({ selector: '[ngxCrumb]' }) export class NgxCrumbDirective { constructor( private router: R...
magicoder
typescript
You are tasked with implementing a string cleaning function in Python. The function should remove any occurrences of the string "NaN" and leading/trailing whitespace from the input string. Additionally, if the input string is `None`, it should be treated as an empty string. Your task is to implement the `clean_string`...
```python from typing import Optional def clean_string(s: Optional[str]) -> str: if s is None: return "" cleaned_str = s.replace("NaN", "").strip() return cleaned_str ```
magicoder
python
You are tasked with implementing a priority queue using a Python class. The priority queue should support the following operations: 1. `insert(item: Response, priority: int)`: Insert a new item with a given priority into the priority queue. 2. `pop_highest_priority() -> Response`: Remove and return the item with the hi...
```python from typing import Tuple Response = str Priority = int class PriorityQueue: def __init__(self): self.queue = [] def insert(self, item: Response, priority: Priority) -> None: self.queue.append((item, priority)) self.queue.sort(key=lambda x: x[1]) def pop_highest_priority...
magicoder
python
You are tasked with creating a function that retrieves a list of contacts from a database using an asynchronous operation. However, the provided code snippet contains a logical error that prevents the successful retrieval of contacts. Your task is to identify and fix the error in the code to ensure that the contacts ar...
The logical error in the provided code snippet is the unconditional `return res;` statement before the conditional check `if (res) { ... } else { ... }`. This unconditional return statement prevents the conditional check from being executed, and the function always returns the value of `res` without considering the con...
magicoder
javascript
You are tasked with creating a Django migration for a web application that manages educational content. The application has a model representing different levels of titles for educational panels. The code snippet provided is a part of a Django migration file that alters a field in the database schema. Your task is to c...
```python from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('yourappname', 'previous_migration_number'), # Replace 'yourappname' and 'previous_migration_number' with actual values ] operations = [ migrations.AlterField( model_na...
magicoder
python
You are tasked with creating a script that determines the platform architecture of a given system. The script should be able to identify whether the system is running on a 32-bit or 64-bit architecture. You are provided with a code snippet that sets up the initial environment and includes a reference to a platform-arch...
platform-arch.sh: ```bash #!/bin/bash get_platform_arch() { if [ "$(uname -m)" = "x86_64" ]; then echo "64-bit" else echo "32-bit" fi } ``` script.sh: ```bash #!/bin/bash set -eu ex_dir="$(dirname "$0")" . "$ex_dir/platform-arch.sh" platform_arch=$(get_platform_arch) echo "Platform architecture: $pla...
magicoder
shell
You are tasked with implementing a program to simulate a simple banking system. The system should be able to create and manage bank accounts, allowing for deposits, withdrawals, and balance inquiries. Each bank account should have a unique account number, and the system should be able to handle multiple accounts. Your...
```python class BankAccount: account_counter = 0 def __init__(self, initial_balance): BankAccount.account_counter += 1 self.account_number = BankAccount.account_counter self.balance = initial_balance def deposit(self, amount): self.balance += amount def withdraw(self, ...
magicoder
python
You are tasked with implementing a custom data structure in C++ that supports the following operations efficiently: 1. `push_back(int val)`: Add an integer `val` to the end of the data structure. 2. `pop_back()`: Remove the last element from the data structure. 3. `get_min()`: Retrieve the minimum value from the data ...
```cpp #include <vector> #include <stack> #include <limits> namespace elang { namespace { typedef std::vector<int> IntVector; class MinStack { private: std::stack<int> dataStack; std::stack<int> minStack; public: void push_back(int val) { ...
magicoder
cpp
You are tasked with implementing a function that takes in a list of integers and returns the maximum sum of a contiguous subarray within the list. The function should be able to handle both positive and negative integers. You need to implement the following function: ```python def max_subarray_sum(arr: List[int]) -> ...
```python from typing import List def max_subarray_sum(arr: List[int]) -> int: max_sum = float('-inf') # Initialize max_sum to negative infinity current_sum = 0 # Initialize current_sum to 0 for num in arr: current_sum = max(num, current_sum + num) # Update current_sum to be the maximum of the ...
magicoder
python
You are tasked with implementing a multithreaded program that simulates a self-driving car system. The program consists of two threads: a main control thread and a pilot thread. The main control thread is responsible for managing the overall system, while the pilot thread is responsible for controlling the car's naviga...
```cpp #include <iostream> #include <thread> #include <mutex> namespace noisepage::selfdriving { // Define a mutex for synchronization std::mutex mutex_; // Main control thread function void MainControlThread() { // Main control thread logic } // Pilot thread function void PilotThreadLoop() { while (true) {...
magicoder
cpp
You are tasked with implementing a function to calculate the cosine similarity matrix between two sets of vectors. Given two sets of vectors `view1` and `view2`, the cosine similarity between each pair of vectors (one from `view1` and one from `view2`) is calculated using the cosine similarity formula. The cosine simil...
```python import torch def cosine_similarity_matrix(view1, view2): view1_norm = torch.norm(view1, p=2, dim=1, keepdim=True) view2_norm = torch.norm(view2, p=2, dim=1, keepdim=True) dot_sim = torch.mm(view1, view2.transpose(0, 1)) norm_mat = torch.mm(view1_norm, view2_norm.transpose(0, 1)) cosine_...
magicoder
python
You are tasked with creating a Python function that processes seismic focal mechanism data using spherical harmonics. The function should take in a set of seismic focal mechanism solutions and classify them based on their mechanism type. The seismic focal mechanism solutions are represented in a hash format and need to...
```python from typing import List from focal_mech.io.read_hash import read_hash_solutions from focal_mech.lib.classify_mechanism import classify, translate_to_sphharm def process_focal_mechanism(file_path: str) -> List[str]: # Read seismic focal mechanism solutions from hash format seismic_solutions = read_has...
magicoder
python
You are tasked with implementing a function that takes in a string and returns the longest substring without repeating characters. For example, given the input "abcabcbb", the function should return "abc", as it is the longest substring without repeating characters. If there are multiple longest substrings without repe...
```rust fn longest_substring(s: &str) -> String { let mut max_len = 0; let mut start = 0; let mut result = String::new(); let mut char_indices = HashMap::new(); for (i, c) in s.chars().enumerate() { if let Some(prev_index) = char_indices.get(&c) { start = start.max(*prev_index +...
magicoder
rust
You are tasked with implementing a Python class method that sets up a detector for a scanning system. The method, `setup_detector`, takes in several parameters and is responsible for configuring the detector based on the provided context and parameters. Your task is to complete the implementation of the `setup_detector...
```python def setup_detector( self, context: Context, completed_steps: scanning.hooks.ACompletedSteps, steps_to_do: scanning.hooks.AStepsToDo, num_images: int, duration: float, part_info: scanning.hooks.APartInfo, initial_configure: bool = True, **kwargs: Any, ) -> None: if initi...
magicoder
python
You are tasked with implementing a simple API server using Rust's async/await functionality. The provided code snippet outlines a partial implementation of an `Api` struct and its associated methods. Your goal is to complete the implementation by adding the necessary code to handle incoming HTTP requests and respond wi...
```rust use warp::Filter; pub struct Api { listen_address: String, launcher_tx: Box<dyn LauncherTx>, } impl Api { pub async fn run(self) { let routes = self.routes(); warp::serve(routes).run(self.listen_address.parse().unwrap()).await; } fn routes(self) -> impl Filter<Extract = im...
magicoder
rust
You are tasked with implementing a simple game control system using Python. The game involves moving a character on a grid-based map using the arrow keys. The code snippet provided below captures the input for moving the character upwards. ```python while True: key = ord(getch()) if key == 119: # W # p...
```python def move_character(direction, current_position): x, y = current_position if direction == "up": return x, y - 1 elif direction == "down": return x, y + 1 elif direction == "left": return x - 1, y elif direction == "right": return x + 1, y else: ra...
magicoder
python
You are tasked with implementing a custom data structure that efficiently supports skipping elements during iteration. The data structure should allow for skipping a specified number of elements and then resuming iteration from the next element. Your task is to implement the `SkipIterator` class in Python, which will t...
```python from typing import List class SkipIterator: def __init__(self, nums: List[int]): self.nums = nums self.index = 0 self.skip_count = 0 def hasNext(self) -> bool: return self.index + self.skip_count < len(self.nums) def next(self) -> int: if not self.hasNext...
magicoder
python
You are tasked with creating a script to automate the extraction of files from multiple zip archives into specific output directories based on the region codes. The script should be able to handle a variable number of zip files and output directories, and it should follow a consistent naming convention for the output d...
```python import os import zipfile from typing import List def extract_zip_files(zip_files: List[str], output_dirs: List[str]) -> None: for zip_file, output_dir in zip(zip_files, output_dirs): region_code = os.path.splitext(os.path.basename(zip_file))[0] output_dir = os.path.abspath(output_dir) ...
magicoder
python
You are tasked with implementing a user cache system to store user information for a web application. The user cache should support operations for adding, retrieving, and removing user information. Each user is identified by a unique username and has associated attributes such as name, email, and role. You need to imp...
```python class UserCache: def __init__(self): self.users = {} def add_user(self, username, name, email, role): self.users[username] = {'name': name, 'email': email, 'role': role} def get_user(self, username): return self.users.get(username) def remove_user(self, username): ...
magicoder
python
You are tasked with implementing a solution to the "Marble Highscore" problem. In this problem, you are given a game scenario and are required to calculate the high score achieved by the players. The game is played with a circle of marbles, and players take turns placing a new marble into the circle. The marbles are n...
```rust fn marble_highscore(game: &(usize, usize)) -> usize { let (players, last_marble) = *game; let mut circle = vec![0]; let mut scores = vec![0; players]; let mut current_player = 0; let mut current_marble = 0; for marble in 1..=last_marble { if marble % 23 == 0 { curren...
magicoder
rust
You are tasked with creating a Python class that simulates the behavior of a simple rocket. The rocket is subject to aerodynamic forces, and you need to implement the calculation of dynamic pressure, lift, and drag forces. The provided code snippet is a part of a larger system that models these forces in an engineering...
```python class RocketModel: def __init__(self, reference_area, lift_coefficient, drag_coefficient): self.S = reference_area # Reference area in square meters self.CL = lift_coefficient # Lift coefficient self.CD = drag_coefficient # Drag coefficient def calculate_dynamic_pressure(se...
magicoder
python
You are tasked with designing a Rust program that involves trait objects and their interactions. You are given two traits, `Foo` and `Bar`, each with a lifetime parameter `'a`. Your goal is to implement a function that takes a reference to an object implementing the `Foo` trait and attempts to treat it as an object imp...
The given code snippet attempts to perform a trait object conversion from `&dyn Foo<'static>` to `&dyn Bar<'static>`. However, this conversion is not valid in Rust due to the following reasons: 1. Lifetime Mismatch: The lifetime parameter `'static` used in the conversion implies that the resulting reference will have ...
magicoder
rust
You are working on a data processing module for a scientific imaging system. The module receives a dictionary `info` containing information about the detector dimensions, the number of frames, and calibration data. The calibration data can be stored in two different formats: either as a single set of calibration data f...
```python import numpy as np def process_calibration_data(info): width = info['DetectorDimensions'][0] if 'Calibration_data_for_frame_1' in info: calibration = np.ndarray((info['NumberOfFrames'], width)) for f in range(len(calibration)): key = 'Calibration_data_for_frame_{:d}'....
magicoder
python
You are tasked with implementing a thread-safe database connection manager in Python. The provided code snippet is a part of a class that manages a SQLite database connection and a mutex for ensuring thread safety. Your task is to complete the implementation of this class by adding methods for executing SQL queries and...
```python import sqlite3 import os from typing import List, Tuple import threading class DB: def __init__(self, db_path: str, db_mutex: threading.Lock): self.db_conn = sqlite3.connect(os.getcwd() + db_path, detect_types=sqlite3.PARSE_DECLTYPES) self.db_mutex = db_mutex def execute_query(self, ...
magicoder
python
You are tasked with implementing a function that performs padding on an image based on a specified padding mode. The function should handle both grayscale and color images, and it should validate the input parameters to ensure that the padding is applied correctly. Write a function `perform_padding(img, padding_mode, ...
```python import numpy as np def perform_padding(img, padding_mode, fill) -> np.ndarray: if padding_mode == 'constant': if len(fill) == 3 and len(img.shape) == 3: # Color image with RGB fill assert img.shape[-1] == 3, 'Image should have 3 channels for RGB' assert isinstance(fill, t...
magicoder
python
You are tasked with creating a Python package that retrieves and processes financial data from the Finviz website. Your package should include a function to fetch the current stock price for a given ticker symbol. Additionally, you need to implement a function to calculate the average price of a stock over a specified ...
```python # stock.py import requests from datetime import datetime class Stock: def __init__(self, ticker): self.ticker = ticker def get_current_price(self): # Fetch the current stock price for the given ticker response = requests.get(f"https://api.finviz.com/quote.ashx?t={self.ticker}...
magicoder
python
You are tasked with implementing a memory manager for a gaming console. The memory manager is responsible for allocating and deallocating memory for game profiles. Each game profile has a unique identifier and a certain amount of memory associated with it. The memory manager should be able to switch between different g...
```java public class MemoryManager { private int currentProfileId; private int currentMemoryAllocated; public void switchProfile(int profileId, int memorySize) { if (currentProfileId != 0) { deallocateMemory(currentProfileId); } currentProfileId = profileId; curr...
magicoder
java
You are given a list of integers, but the code snippet provided to process the list has a bug. Your task is to identify the bug and fix it to correctly output the three smallest numbers in the list. You are given a list of integers separated by spaces. The first integer, <gh_stars>, represents the number of stars a Gi...
```python gh_stars = int(input()) numbers = list(map(int, input().split())) numbers.sort() print(str(numbers[0]) + ' ' + str(numbers[1]) + ' ' + str(numbers[2])) ```
magicoder
python
You are given an array of floating-point numbers representing grayscale pixel values of an image. Each value ranges from 0 to 1, where 0 represents black and 1 represents white. Your task is to write a function to convert these grayscale values to their corresponding RGB values. Write a function `grayscaleToRGB` that ...
```python def grayscaleToRGB(grayscale_values): rgb_values = [] for value in grayscale_values: rgb = [round(value * 255)] * 3 rgb_values.append(rgb) return rgb_values ``` The `grayscaleToRGB` function iterates through the input grayscale values, multiplies each value by 255 and rounds it to...
magicoder
python
You are tasked with creating a custom error boundary component in a React application. An error boundary is a React component that catches JavaScript errors anywhere in its child component tree, logs those errors, and displays a fallback UI instead of the component tree that crashed. Your goal is to implement the `Erro...
```javascript import * as React from 'react'; interface ErrorBoundaryProps { message?: string; } export class ErrorBoundary extends React.Component< ErrorBoundaryProps, { info?: React.ErrorInfo; error?: Error } > { static defaultProps: ErrorBoundaryProps = { message: 'Something went wrong.', ...
magicoder
javascript
You are tasked with creating a Python class that simulates a simple banking system. The class should include methods for depositing funds, withdrawing funds, and checking the current balance. Additionally, the class should implement a feature to calculate interest on the account balance. Your task is to create a Pytho...
```python class BankAccount: def __init__(self): self.balance = 0 def deposit(self, amount): self.balance += amount def withdraw(self, amount): if amount <= self.balance: self.balance -= amount else: print("Insufficient funds") def get_balance(s...
magicoder
python
You are tasked with writing a Python function that merges data from two CSV files and returns the combined data as a list of lists. The function should take two file paths as input and merge the data based on a specific condition. The CSV files contain data in the following format: - Each row represents a record, with...
```python import csv def merge_csv_files(filepath1, filepath2): dest_rows = [] with open(filepath1) as csv_file1: csv_reader1 = csv.reader(csv_file1, delimiter=',') src_csv_rows = [["", "", "file_label", ""]] for row in csv_reader1: src_csv_rows.append(row) with open(fi...
magicoder
python
You are tasked with implementing a Python class that can draw shapes using the PDF format. The class should have a method to add an ellipse to the path of the PDF. The ellipse should be defined by its center coordinates (x, y), width, and height. You are provided with a code snippet that shows the method signature and ...
```python class PDFDrawer: def __init__(self): self.path = [] def _curves(self, curves): self.path.extend(curves) def ellipse(self, x, y, width, height): """adds an ellipse to the path""" # Using pdfgeom.bezierArc to create the Bezier arc representing the ellipse ar...
magicoder
python
You are tasked with creating a program that analyzes the copyright and license information from a given source code file. The program should be able to extract the copyright holder's name and email, as well as the license information from the file header. You are given a code snippet as an example of the header format...
```python import re def extract_copyright_and_license(file_path: str) -> dict: with open(file_path, 'r') as file: content = file.read() match = re.search(r'\(c\) (.+?) <(.+?)>\n.*?please view the (.+?) file', content, re.DOTALL) if match: return { "name": match.group(1), ...
magicoder
python
You are working on a project that involves using various software packages. One of the requirements is to install and configure the ImageMagick software using the Chocolatey package manager on a Windows system. Your task is to write a script that automates the installation and configuration process. Write a PowerShell...
```powershell # Install ImageMagick using Chocolatey try { choco install imagemagick -y Write-Host "ImageMagick installed successfully." } catch { Write-Host "Error: Failed to install ImageMagick using Chocolatey." } # Set the MAGICK_HOME environment variable $installDir = (Get-Command convert).Source.Repl...
magicoder
powershell
You are tasked with implementing a function that extracts and processes facial landmark data from a given input string. The input string contains information about facial landmarks in the format of HTML attributes. Your goal is to parse the input string and extract the name of the facial landmark, then write it to an o...
```python def process_facial_landmarks(input_string, output_file, start_index, end_index): attr = "name='" output_data = [] i = 0 while i < len(input_string): i = input_string.find(attr, i) if i == -1: break j = input_string.find("'", i + len(attr) + 1) name ...
magicoder
python
You are tasked with creating a world generation algorithm for a simple 2D game. The algorithm should generate a path through a grid-based world, ensuring that the path is continuous and does not intersect itself. The grid is represented as a 2D array, where each cell can be either empty (0) or occupied (1). The path sh...
```python def worldgen_path(grid): n = len(grid) directions = [(1, 0), (0, 1), (-1, 0), (0, -1), (1, 1), (-1, 1), (1, -1), (-1, -1)] def is_valid_move(x, y): return 0 <= x < n and 0 <= y < n and grid[x][y] == 0 def find_path(x, y, visited): if (x, y) in visited or not is_valid_...
magicoder
python
You are tasked with creating a program that reads and processes a file's contents. Your program should read the contents of a given file and count the occurrences of specific words within it. You are required to implement a function that takes a file path and a list of words as input, and returns a mapping of each word...
```rust use std::collections::HashMap; use std::fs::File; use std::io::{BufReader, Read}; use std::path::Path; fn count_word_occurrences(file_path: &str, words: &[&str]) -> HashMap<String, usize> { let mut word_counts: HashMap<String, usize> = HashMap::new(); let file = File::open(file_path).unwrap(); let ...
magicoder
rust
You are tasked with implementing a simple drawing application using the ImGui library. The provided code snippet demonstrates the setup for a canvas area where users can draw shapes and interact with the mouse. Your task is to extend this code to allow users to draw rectangles on the canvas by clicking and dragging the...
```cpp // Define a structure to hold information about the drawn rectangles struct DrawnRectangle { ImVec2 start; // Starting position of the rectangle ImVec2 end; // Ending position of the rectangle ImColor fillColor; // Filled color of the rectangle ImColor borderColor; // Border color of the re...
magicoder
cpp
You are tasked with creating a program that interacts with Git repositories using the LibGit2Sharp library. Your goal is to implement a method that clones an existing Git repository and then creates a new repository in a specified path. You are provided with a code snippet that contains a method call to `CloneReposito...
```csharp using LibGit2Sharp; using System; class GitRepositoryManager { static void Main() { string sourceRepositoryUrl = "https://github.com/exampleuser/sourcerepo.git"; string destinationPath = "C:/path/to/destination"; CloneRepository(sourceRepositoryUrl, destinationPath); ...
magicoder
csharp
You are tasked with implementing a simple interpreter for a custom instruction set architecture (ISA) that includes two specific instructions: `jumpsToMachineCodeRoutine` and `clearScreen`. The `jumpsToMachineCodeRoutine` instruction takes an address as a parameter and returns a string indicating that it calls the mach...
```swift func interpretInstruction(_ instruction: CustomInstruction) -> String { switch instruction { case let .jumpsToMachineCodeRoutine(address): return "calls the machine language subroutine at \(String(address, radix: 16))" case .clearScreen: return "clears the screen" } } ``` The `...
magicoder
swift
You are tasked with creating a Rust program to manage groups within an organization. The program should define a struct representing a group, with various fields such as description, charter, ad (administrator), time, group_type, comments, parent, and state. Additionally, you need to implement a function to validate th...
```rust use chrono::{DateTime, Utc}; use serde::Deserialize; #[derive(Deserialize)] struct DocumentUri; #[derive(Deserialize)] struct PersonUri; #[derive(Deserialize)] struct GroupTypeUri; #[derive(Deserialize)] struct GroupStateUri; #[derive(Deserialize)] fn deserialize_time<'de, D>(deserializer: D) -> Result<Dat...
magicoder
rust
You are tasked with creating a Python program that involves reading and writing matrices to a file. Your program should perform the following steps: 1. Read a single line of input containing three space-separated integers: `length`, `rows`, and `cols`. 2. Create a matrix list using the `CreateMatrix.createMatrixList` f...
```python import struct class CreateMatrix: @staticmethod def createMatrixList(length, rows, cols): matrix_list = [] for _ in range(length): matrix = [[0 for _ in range(cols)] for _ in range(rows)] matrix_list.append(matrix) return matrix_list class WriteMatrix:...
magicoder
python
You are tasked with implementing a cache management system for a web application. The cache is used to store frequently accessed data to improve performance. Your task is to create a class that manages the cache and ensures it is properly closed when the application stops. You are provided with a partial code snippet ...
```java // Define the Cache interface public interface Cache { void close(); } // Implement a sample cache class public class SampleCache implements Cache { // Implement the close method to properly close the cache @Override public void close() { // Add code to close the cache resources ...
magicoder
java
You are tasked with implementing a simplified version of a location manager in a mobile application. The provided code snippet is a part of the implementation and is responsible for stopping location updates and invoking a callback function with potential error information. Your task is to create a function that encap...
```swift func stopLocationUpdates(callback: ((Any?, Error?) -> Void)?) { manager.stopUpdatingLocation() // Assuming manager is an instance of the location manager if let callback = callback { let error = // Create or retrieve an appropriate error object callback(nil, error) } } ```
magicoder
swift
You are tasked with implementing a function that calculates the total number of ways to reach the top of a staircase. You can climb the staircase by either taking one step or two steps at a time. Write a function `countWaysToReachTop` that takes an integer `n` as input, representing the total number of steps in the sta...
```python def countWaysToReachTop(n): if n <= 1: return n a, b = 1, 2 for _ in range(2, n): a, b = b, a + b return b ``` The `countWaysToReachTop` function efficiently calculates the total number of distinct ways to reach the top of the staircase using dynamic programming. It iterates th...
magicoder
python
You are tasked with creating a Python function that generates a heatmap visualization for a given dataframe using matplotlib and seaborn libraries. The function should take a dataframe as input and produce a heatmap with appropriate x and y tick marks, representing the columns of the dataframe. The function should be ...
```python import matplotlib.pyplot as plt import seaborn as sns def generate_heatmap(df): plt.figure(figsize=(8, 6)) sns.heatmap(df, annot=True, cmap='coolwarm', linewidths=0.5) tick_marks = [i + 0.5 for i in range(len(df.columns))] plt.xticks(tick_marks, df.columns, rotation='vertical') plt.yticks...
magicoder
python
You are tasked with optimizing the performance of a Python program that calculates the aperture sum of a 2D array. The aperture sum of a pixel in a 2D array is the sum of the values within a square-shaped aperture centered at that pixel. The size of the aperture is specified by a parameter `aperture_size`, which determ...
To optimize the performance of the aperture sum calculation using Cython, you can make use of parallel processing and efficient memory access. Here's a comprehensive solution to achieve this optimization: ```python # Import necessary modules from Cython.Build import cythonize from setuptools import setup, Extension im...
magicoder
python
You are tasked with designing a database schema for a boundary management system. The system needs to store information about boundaries and their sets. Each boundary belongs to a specific set, and each set can have multiple boundaries. Additionally, each boundary within a set must have a unique combination of a slug a...
```python # Define the models in Django's ORM from django.db import models class BoundarySet(models.Model): # Model for the set to which boundaries belong # Add any additional fields as required # ... class Boundary(models.Model): # Model for the boundary entity slug = models.CharField(max_lengt...
magicoder
python
You are working on a software development project and need to implement a method for managing starting and repeated methods within a system. The system uses a table to store cells, each of which contains source and destination information. Your task is to create a program that can identify starting methods and handle r...
The solution involves creating a program that can effectively manage the starting and repeated methods within the system. This can be achieved by implementing the logic for identifying starting methods and handling repeated methods based on the provided code snippet. Here's a possible solution in Python: ```python cl...
magicoder
python
You are tasked with creating a Python function that calculates the total duration of events scheduled in a conference room within a specified time range. The function should take in the room ID, start time, and end time as input parameters and return the total duration of events scheduled in the room within the given t...
```python from gbe.models import Event from gbe.functions import get_current_conference from datetime import datetime, timedelta from settings import GBE_TIME_FORMAT def calculate_total_event_duration(room_id, start_time, end_time): total_duration = 0 conference = get_current_conference() # Assuming this func...
magicoder
python
You are tasked with creating a Python function that processes incoming HTTP requests and sets the rating for a specific node in a web application. The function should be designed to handle POST requests and should interact with a module called `metafilter.model.nodes` to set the rating for a node. Your task is to impl...
```python from flask import Flask, request, jsonify from metafilter.model.nodes import set_rating app = Flask(__name__) @app.route('/set_rating', methods=["POST"]) def set_rating(): try: node_id = request.form.get('node_id') rating = request.form.get('rating') # Call the function from met...
magicoder
python
You are tasked with creating a script to automate the transfer of files between two Google Cloud instances using the `gcloud compute scp` command. The script should take two arguments: the name of the file to be transferred and the destination directory on the second instance. The script should also handle the naming c...
```bash #!/bin/bash # Check if the correct number of arguments is provided if [ "$#" -ne 2 ]; then echo "Usage: $0 <source_file> <destination_directory>" exit 1 fi source_file=$1 destination_directory=$2 # Extract the suffix from the source file name suffix=$(echo "$source_file" | awk -F'.' '{print $NF}') #...
magicoder
shell
You are tasked with implementing a data validation function for a data science library. The function should validate that a dataframe read from a data source matches the dataframe that was written to the same source. Additionally, the function should handle cases where a user forgets to set a specific parameter when re...
```python class DataFrameMismatchException(Exception): pass class RubiconException(Exception): pass def validate_dataframe(read_dataframe, written_dataframe): if read_dataframe.id != written_dataframe.id: raise DataFrameMismatchException("Dataframes do not match") if getattr(read_dataframe, '...
magicoder
python
You are tasked with creating a Python function that processes a list of configuration documents associated with a sales order in an ERP system. The function should take a sales order as input and return a list of configuration documents to be deleted. Each configuration document is represented as a list containing its ...
```python def delete_configuration_doc(sales_order, method): # Retrieve configuration documents associated with the sales order configuration_docs = frappe.get_all("Configuration Document", filters={"sales_order": sales_order}, fiel...
magicoder
python
You are tasked with implementing a constraint evaluator for a custom programming language. The provided code snippet includes imports and some function and type aliases. Your goal is to complete the implementation of the constraint evaluator by defining the missing functions and types. The constraint evaluator is resp...
```rust use super::{ field::{self, mul, add}, TraceState, FlowOps, UserOps, is_binary, binary_not, are_equal, EvaluationResult, CYCLE_MASK_IDX, PREFIX_MASK_IDX, PUSH_MASK_IDX, }; // CONSTRAINT EVALUATOR // ================================================================================================ stru...
magicoder
rust
You are tasked with implementing a DNS message decoder in Rust. The provided code snippet is a part of a DNS message decoder and contains a method for decoding the algorithm type of a DNS resource record (RR). The `Decoder` struct has a method `rr_algorithm_type` that reads an unsigned 8-bit integer from the input buff...
```rust use super::Header; use crate::rr::{ AlgorithmType, DigestType, DNSKEY, DNSKEY_ZERO_MASK, DS, SECURE_ENTRY_POINT_FLAG, ZONE_KEY_FLAG, }; use crate::{decode::Decoder, DecodeError, DecodeResult}; use std::convert::TryFrom; impl<'a, 'b: 'a> Decoder<'a, 'b> { fn rr_algorithm_type(&mut self) -> DecodeResult<...
magicoder
rust
You are tasked with creating a PHP function that dynamically loads and instantiates a class based on user input. The function should handle the conversion of a URL-encoded class name to its corresponding PHP namespace format and then check if the class exists before instantiating it. Write a PHP function `loadAndInsta...
```php function loadAndInstantiateClass($request) { $className = urldecode($request->param('ClassName')); $className = str_replace('-', '\\', $className); if (!class_exists($className)) { throw new InvalidArgumentException(sprintf( "Class '%s' not found", $className )); } ...
magicoder
php
You are tasked with creating a function that validates a phone number input in a web form. The phone number input is represented by the HTML code snippet below: ```html <div class="form-group"> <label for="username" class="cols-sm-2 control-label">Nomor Telpon</label> <div class="cols-sm-10"> <div clas...
```javascript function validatePhoneNumber(phoneNumber) { // Remove non-numeric characters from the input const numericPhoneNumber = phoneNumber.replace(/\D/g, ''); // Validate the length and format of the phone number if (numericPhoneNumber.length >= 10 && numericPhoneNumber.length <= 12) { if...
magicoder
javascript
You are tasked with creating a function that validates the properties of a given React component. The component is expected to have specific styling properties defined in its style object, and it should also include a child component with certain props. Your task is to write a function that checks whether the given com...
```javascript function validateComponent(component) { if (component && component.props && component.props.style) { const { style } = component.props; if ( typeof style.paddingLeft === 'number' && typeof style.paddingRight === 'number' && typeof style.paddingTop === 'number' ) { con...
magicoder
javascript
You are tasked with creating a function that simulates the behavior of a web automation script. The script interacts with a web page using the Selenium WebDriver API in JavaScript. The provided code snippet is a part of the script that selects and clicks on a "Filters" button on the web page. Your task is to implement...
```javascript async function clickFiltersButton(browser, By, Until) { // Define the XPath for the "Filters" button let obj_span_Filters = By.xpath("//span[contains(text(),'Filters')]"); // Wait until the "Filters" button is visible await browser.wait(Until.elementIsVisible(obj_span_Filters)); ...
magicoder
javascript
You are tasked with creating a Python class that processes a YAML file to generate a list of images to push. Your task is to complete the implementation of the `Generator` class by adding a method to filter the images based on certain criteria. You are provided with the following code snippet as a starting point: ```...
```python import yaml class Generator: def __init__(self, profilePath=""): self.profilePath = profilePath def generateFromProfile(self): if self.profilePath == "": print("Error: profile path is null") with open(self.profilePath, 'r') as f: self.images_to_push ...
magicoder
python
You are tasked with implementing a notification system for a web application. The system should allow users to subscribe to different notification channels and receive notifications based on their preferences. You need to create a class that represents a notification and its associated channels. You are provided with ...
```php class Notification { /** @var string */ public $token; public function __construct(string $token) { $this->token = $token; } /** * Get the notification's channels. * * @param mixed $notifiable * @return array */ public function getChannels($notifiabl...
magicoder
php
You are tasked with creating a program to process and analyze musical notes stored in a file. The file contains a series of musical notes, each represented by a string in the format "Note Octave", where "Note" is a letter representing the musical note (A, B, C, D, E, F, or G) and "Octave" is a number representing the o...
```rust use std::fs::File; use std::io::{BufRead, BufReader}; use std::io; fn load(filename: &str) -> Vec<(String, u8)> { let file = File::open(filename).unwrap(); let reader = BufReader::new(file); let mut notes = Vec::new(); for line in reader.lines() { let line = line.unwrap(); let...
magicoder
rust
You are tasked with implementing a Python function that extracts the version number from a given filename. The version number is denoted by a lowercase 'v' followed by a sequence of digits. The function should take a filename as input and return the extracted version number. If the filename is empty or does not contain...
```python from typing import Optional def get_version_number(filename: str) -> Optional[str]: if filename: tx_list = filename.split('_') # Split the filename by underscore tx_list.reverse() # Reverse the list to search for version number from the end for tx in tx_list: if tx.s...
magicoder
python
You are given a simplified code snippet representing a maze-solving algorithm. The algorithm uses a depth-first search to navigate through a maze represented by a grid. The grid contains cells, some of which are blocked and cannot be traversed. The algorithm aims to find a path from the start cell to the end cell, avoi...
```python from typing import List def has_valid_path(maze: List[List[str]]) -> bool: rows, cols = len(maze), len(maze[0]) directions = [(0, 1), (0, -1), (1, 0), (-1, 0)] def is_valid(x, y): return 0 <= x < rows and 0 <= y < cols and maze[x][y] != '#' def dfs(x, y): if maze[x][y] == 'E...
magicoder
python
You are tasked with implementing a Swift class for making HTTP requests with specific content type headers. Your goal is to create a `JSONRequest` class that inherits from a base `HTTPRequest` class and ensures that the request headers include the "Content-Type" header with a value of "application/json". Your task is ...
```swift class JSONRequest: HTTPRequest { override init() { super.init() headers["Content-Type"] = "application/json" } } ``` In the solution, the `JSONRequest` class is implemented as a subclass of `HTTPRequest`. The initializer is overridden to set the "Content-Type" header to "application/js...
magicoder
swift
You are tasked with creating a Python function that utilizes the `astropy.coordinates` and `pytest` libraries to calculate the separation angle between two celestial coordinates. The function should take two sets of coordinates as input and return the angular separation between them in degrees. Your task is to impleme...
```python import astropy.coordinates as coord def calculate_angular_separation(ra1, dec1, ra2, dec2): # Create SkyCoord objects for the input coordinates coord1 = coord.SkyCoord(ra1, dec1, unit=('deg', 'deg')) coord2 = coord.SkyCoord(ra2, dec2, unit=('deg', 'deg')) # Calculate the angular separati...
magicoder
python
You are tasked with creating a Python function that interacts with a machine learning platform API to train a model, make predictions, and monitor the status of the training and prediction jobs. The API client `c` provides methods for training, getting job output, making predictions, and checking job status. The code s...
```python def train_and_predict(c, train_data, test_data): # Train a model train_response = c.train("weka", "regression", train_data) print(train_response) # Get the job output for training train_job_output_response = c.job_output(train_response['data']['jobId']) print(train_job_output_resp...
magicoder
python
You are tasked with implementing a class that splits rows of a table into individual cells based on certain delimiters and escape sequences. The class `RowSplitter` has been provided with some initial attributes and a constructor method. Your task is to complete the implementation of the `RowSplitter` class by adding a...
```python class RowSplitter(object): _comment_mark = '#' _empty_cell_escape = '${EMPTY}' _line_continuation = '...' _setting_table = 'setting' _tc_table = 'test case' _kw_table = 'keyword' def __init__(self, cols=8, split_multiline_doc=True): self.cols = cols self.split_mult...
magicoder
python
You are tasked with implementing a simplified version of a key-value store using a hash table. The hash table should support the following operations: inserting a key-value pair, retrieving the value associated with a given key, and deleting a key-value pair. Additionally, the hash table should support negative values ...
```java import java.util.HashMap; class KeyValueStore { private HashMap<String, Long> store; public KeyValueStore() { this.store = new HashMap<>(); } public void rawPut(String key, String value, long data) { store.put(key, data); } public String bulkString(String key) { ...
magicoder
java
You are given a Python code snippet that processes linguistic data. The code snippet involves iterating through a list of `parses`, sorting them based on a `collation_key`, and then printing the sorted parses along with their corresponding counts. Your task is to understand the code and implement a function that achiev...
```python def process_parses(parses, counts): lines = [] sorted_parses = sorted(parses, key=lambda ending: (len(collation_key(ending)), ending)) for ending in sorted_parses: indentation = " " * (len(collation_key(ending)) - 1) line = indentation + "-" + ending + ":" parse_counts =...
magicoder
python
You are tasked with implementing a simple blockchain data structure in Python. A blockchain is a distributed ledger that records transactions across a network of computers. Each block in the blockchain contains a list of transactions, a timestamp, and a reference to the previous block, forming a chain of blocks. Your g...
```python import hashlib import time class Block: def __init__(self, index, data, previous_hash): self.index = index self.timestamp = time.time() self.data = data self.previous_hash = previous_hash self.hash = self.calculate_hash() def calculate_hash(self): bloc...
magicoder
python
You are tasked with implementing a Python function that processes a dataset and generates a histogram plot using the HoloViews library. The function should take in the dataset, number of bins, and other optional keyword arguments, and produce a histogram plot with specific formatting options. Write a Python function `...
```python import holoviews as hv import numpy as np def generate_histogram_plot(dataset, num_bins, kwargs={}): # Create histogram plot using HoloViews hist = np.histogram(dataset, bins=num_bins) histogram = hv.Histogram(hist, kdims=[hv.Dimension('Value')]) # Apply formatting options from kwargs if...
magicoder
python
You are tasked with implementing a simple server management system in Python. The provided code snippet sets up a socket for a server and initializes a server manager. Your task is to complete the server management system by implementing the logic for handling incoming client connections and managing client inputs and ...
```python import socket as sckt import select as slct import sys class ServerManager: def __init__(self): self.inputs = [] self.outputs = [] def add_input(self, input_source): self.inputs.append(input_source) def remove_input(self, input_source): self.inputs.remove(input_s...
magicoder
python
You are tasked with creating a program that optimizes WebAssembly (Wasm) files using the `wasm-opt` tool and then runs the optimized Wasm files using a specified Wasm runner. The optimization process involves enabling SIMD (Single Instruction, Multiple Data) and sign extension, applying various optimization levels, inl...
```python import os wasm_files_directory = "target/wasm32-wasi/*/deps/" wasm_runner = "$CARGO_TARGET_WASM32_WASI_RUNNER" # Step 1: Iterate through all Wasm files in the specified directory for wasm_file in os.listdir(wasm_files_directory): if wasm_file.endswith(".wasm"): wasm_file_path = os.path.join(wasm...
magicoder
python
You are tasked with implementing a Python class that facilitates model manipulation for a machine learning framework. The class, named `ModelManipulator`, is designed to handle operations such as retrieving a specific model from a given module and freezing the model's parameters before training. The class contains the ...
```python class ModelManipulator: def __init__(self, model_name): self.model_name = model_name.split(".") def get_model(self, pl_module): model = pl_module for model_name in self.model_name: model = getattr(model, model_name) return model def freeze_before_train...
magicoder
python
You are given a list of integers representing the scores of a game. The game has a special rule for scoring where the score of each player is the sum of their scores in the current and the previous round. If a player has no previous round, their score is just the score of the current round. Your task is to write a func...
```python from typing import List def calculate_total_scores(scores: List[int]) -> List[int]: total_scores = [] prev_score = 0 for score in scores: total_score = score + prev_score total_scores.append(total_score) prev_score = total_score return total_scores ``` The `calculate_...
magicoder
python
You are given a Python code snippet that includes an `else` block with three `print` statements. The code snippet is as follows: ```python else: print('NOT found 42') # found apple # NOT found a # NOT found 42 ``` Your task is to write a Python function that takes a list of strings as input and processes them ba...
```python def process_strings(strings): for s in strings: if "apple" in s: print("found apple") elif "a" in s.lower(): print("NOT found a") elif "42" in s: print("NOT found 42") # Example usage input_strings = ["I like apples", "There is an orange", "42 i...
magicoder
python
You are tasked with implementing a function to validate and search a request object in a web application framework. The function should handle cases where the request object is null or does not contain a query. You are given the following code snippet as a starting point: ```python def test_search_06_validate_and_sea...
```python ERR_VALIDATE_SEARCH_NULL = "ERR_VALIDATE_SEARCH_NULL" ERR_VALIDATE_SEARCH_NO_QUERY = "ERR_VALIDATE_SEARCH_NO_QUERY" def validate_and_search(sp, request): if request is None: return ERR_VALIDATE_SEARCH_NULL elif "query" not in request: return ERR_VALIDATE_SEARCH_NO_QUERY else: ...
magicoder
python
You are tasked with creating a script to automate the encryption and packaging of firmware updates for a secure IoT device. The script should perform the following steps: 1. Read the first 5 bytes from the file "tboxfwver" and append them to a file named "randkey.bin". 2. Generate 118 random bytes and append them to "...
```bash #!/bin/bash # Step 1: Read the first 5 bytes from "tboxfwver" and append to "randkey.bin" dd if=tboxfwver bs=1 count=5 >> randkey.bin # Step 2: Generate 118 random bytes and append to "randkey.bin" openssl rand 118 >> randkey.bin # Step 3: Convert "randkey.bin" to base64 and save as "key.bin" base64 randkey....
magicoder
shell
You are given a code snippet that appears to be part of a macro expansion in a Rust program. The macro `crate::unit_impl_ops!` seems to be generating implementations for various operations on different types. Your task is to understand the code snippet and create a programming problem based on its context. Write a Rus...
```rust fn perform_operation<T: std::ops::Add<Output = T> + std::ops::Sub<Output = T> + std::ops::Mul<Output = T> + std::ops::Div<Output = T>>(a: &mut T, b: &T) -> T { *a + *b // Implementing the addition operation as an example } ``` In the given code snippet, the macro expansion seems to be defining implementat...
magicoder
rust
You are tasked with implementing a simple entity builder system for a game using Rust. The provided code snippet is a part of the entity builder module and demonstrates the `build_default` function for creating a default Shulker entity. The `build_default` function takes a mutable reference to an `EntityBuilder` and a...
```rust // Necessary imports use quill_common::entities::Shulker; use quill_common::entities::EntityKind; // Assuming EntityKind is defined in quill_common::entities module // Definition of EntityBuilder type struct EntityBuilder; impl EntityBuilder { // Method to add Shulker entity and specify its kind fn ad...
magicoder
rust
You are tasked with implementing a function that performs natural comparison of strings. Natural comparison is a sorting algorithm that compares strings in a way that is more human-friendly, taking into account both alphabetical order and numerical values within the strings. Your task is to implement the `naturalCompar...
```cpp #include <cctype> #include <string> class NaturalCmp { public: static bool isSpace(char c) { return std::isspace(static_cast<unsigned char>(c)); } static int naturalCompare(const std::string& str1, const std::string& str2) { const char *s1 = str1.c_str(); const char *s2 = st...
magicoder
cpp
You are tasked with implementing a custom convolutional neural network (CNN) block in PyTorch. The block will be a variation of the SimpleFire block, which is a type of convolutional block used in CNN architectures. Your task is to create a Python class that represents this custom CNN block. The custom CNN block shoul...
```python import torch.nn as nn class CustomCNNBlock(nn.Module): def __init__(self, growth_rate, block=SimpleFire): super(CustomCNNBlock, self).__init__() self.growth_rate = growth_rate self.block = block def forward(self, x): # Assuming x is the input tensor out_channe...
magicoder
python
You are tasked with creating a Python function that generates a dataset of images and corresponding angles from PDF files. The function should handle exceptions and display a progress bar if specified. You are given a code snippet as inspiration, which includes a loop for generating the dataset, handling exceptions, an...
```python import numpy as np from pathlib import Path from progressbar import Progbar # Assuming Progbar is imported from a library def generate_dataset(ds_size, output_dir, all_pdf_paths, output_res, show_progbar): def openPDF(src_path): # Function to open and process the PDF file pass def g...
magicoder
python
You are tasked with creating a function that generates all possible beautiful strings of a given size using a list of letters. A beautiful string is defined as a string that contains only English words. You are provided with a code snippet that initializes an English dictionary and a function `possible_permutations` th...
```python import enchant from itertools import permutations language = enchant.Dict("en_US") def possible_permutations(letter_list, beautiful_size): perm = permutations(letter_list, beautiful_size) for i in list(perm): word = ''.join(i) if language.check(word): print(word) ``` The...
magicoder
python
You are given a 2D grid representing a map with different types of tiles. Each tile can be either a wall or an empty space. The map is represented by a 2D array of integers, where 0 represents an empty space and 1 represents a wall. Your task is to write a function that calculates the number of walls surrounding each e...
```csharp public int[,] CountSurroundingWalls(int[,] map) { int rows = map.GetLength(0); int cols = map.GetLength(1); int[,] wallCount = new int[rows, cols]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (map[i, j] == 0) // Empty space tile ...
magicoder
csharp
You are tasked with creating a Python class that simulates a simple login system and a message listener for a websocket. Your task is to implement the missing methods in the given class template. You are provided with a partial code snippet for a Python class that represents a client for a websocket-based service. The...
```python from time import perf_counter from asyncio import sleep class WebsocketClient: def __init__(self): self.logged_in = False async def login(self, checking_interval: float = 0.001, wait_for: int = 5) -> None: """Attempt to log in and wait for a specified duration before asserting the su...
magicoder
python
You are tasked with creating a simple timer app using SwiftUI. The app should display the elapsed time in seconds and provide buttons to start, pause, and reset the timer. You need to implement the `TimerModel` class to manage the timer logic and update the UI accordingly. The `TimerModel` class should have the follow...
```swift import SwiftUI class TimerModel: ObservableObject { @Published var currentTime: Int = 0 var timer: Timer? func startTimer() { timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in self.currentTime += 1 } } func pauseTimer() { timer?.i...
magicoder
swift
You are tasked with creating a Python script that simulates a simple web server and a client making a secure HTTPS request to it. The server will require client certificate authentication, and the client must use a specific set of headers in the request. Your goal is to write a Python script that sets up the server, se...
```python import subprocess # Set up the server using openssl to create an HTTPS server with client certificate authentication ssl_dir = "/path/to/ssl/dir" s_server_port = 443 # Replace with the desired port number server_process = subprocess.Popen( f"openssl s_server -www -key {ssl_dir}/server1.pem -cert {ssl_di...
magicoder
python
You are tasked with implementing a rendering system for a 2D game. The game world is composed of tiles, each of which has a specific appearance and may be occupied by various entities. Your goal is to render the tiles and any associated entities onto the game screen. You are provided with a code snippet that demonstra...
```rust // Define the render_tile function to render the tile and associated entities onto the scene fn render_tile(tile: Option<&Tile>, scene: &mut Scene, x: i32, y: i32, player_roof: &PlayerRoof) { if let Some(tile) = tile { // Render the tile onto the scene scene.set_point(x, y, tile.background_c...
magicoder
rust
You are tasked with implementing a reactive data fetching mechanism using RxJS in an Angular application. The provided code snippet is a part of an Angular component that interacts with a REST API to fetch and display data in a paginated and sorted manner. The code snippet demonstrates the usage of RxJS operators and ...
```typescript import { Component, OnInit, ViewChild } from '@angular/core'; import { MatSort, MatPaginator, MatTableDataSource } from '@angular/material'; import { merge, of } from 'rxjs'; import { startWith, switchMap, catchError, map, finalize } from 'rxjs/operators'; import { DataService } from 'path-to-data-service...
magicoder
typescript