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 calculate the total number of lines of code in a Python file, excluding comments and empty lines. The function should take the file path as input and return the total number of lines of executable code. You are given a Python file named `example.py` as an example input. T...
```python def count_executable_lines(file_path): with open(file_path, 'r') as file: lines = file.readlines() executable_lines = 0 in_multiline_comment = False for line in lines: line = line.strip() if not line or line.startswith('#'): continue if lin...
magicoder
python
You are tasked with implementing a user search feature in a web application using Django. The provided code snippet includes a template loading and a view function for user search. Your task is to complete the implementation of the user search functionality by creating a view that handles the search query and returns t...
```python from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.http import HttpResponse @login_required def UserSearch(request): if 'query' in request.GET: query = request.GET['query'] # Perform the search based on the query against the user data...
magicoder
python
You are tasked with implementing a simplified version of a UUID (Universally Unique Identifier) generator. A UUID is a 128-bit number used to uniquely identify information. It is typically represented as a 32-character hexadecimal string, such as "550e8400-e29b-41d4-a716-446655440000". Your task is to create a functio...
```python import random def generateUUID(): hex_chars = '0123456789abcdef' uuid = '' sections = [8, 4, 4, 4, 12] for section in sections: for _ in range(section): uuid += random.choice(hex_chars) if section != 12: uuid += '-' return uuid ``` The `g...
magicoder
python
You are tasked with automating the deployment and configuration of Apache Kafka and Apache Flink on a server. Your goal is to write a Bash script that performs the following tasks: 1. Extracts the Kafka and Flink tarballs. 2. Starts the Zookeeper server for Kafka. 3. Starts the Kafka server. 4. Creates two Kafka topic...
```bash #!/bin/bash # Extract Kafka tar -xvf kafka.tgz kafka_path=/opt/tsap/kafka_2.11-1.1.0/ # Start Zookeeper server ${kafka_path}bin/zookeeper-server-start.sh ${kafka_path}config/zookeeper.properties > /dev/null 2>&1 & # Start Kafka server ${kafka_path}bin/kafka-server-start.sh ${kafka_path}config/server.properti...
magicoder
shell
You are tasked with implementing a feed simulation system for a social media app. The system should handle the display of images in a feed and simulate the loading of new images as the user scrolls through the feed. You are given a partial implementation of the `FeedViewController` class and the `simulateFeedImageViewN...
```swift import UIKit class FeedViewController: UIViewController { var feedImages: [URL] = [] var feedImageViews: [UIImageView] = [] override func viewDidLoad() { super.viewDidLoad() // Initialize and configure feed image views for _ in 0..<feedImages.count { let im...
magicoder
swift
You are tasked with implementing a Swift protocol to create a filter for drawing crosshatch shadows. The protocol, `C7FilterProtocol`, is used to define the structure for various filters in the ATMetalBand framework. Your goal is to complete the implementation of the `C7Crosshatch` struct, which conforms to the `C7Filt...
```swift import Foundation /// 绘制阴影线 public struct C7Crosshatch: C7FilterProtocol { public func apply(to input: C7Image) -> C7Image { // Implement the crosshatch shadow drawing algorithm here // Your implementation should produce the desired crosshatch shadow effect // Use the input C7Image...
magicoder
swift
You are tasked with implementing a news processing system that handles the retrieval and processing of news articles. The system should be designed to handle various types of news articles and perform specific actions based on the type of news. You are provided with a PHP code snippet that represents the constructor an...
```php // Define a base News class and specific subclasses for different types of news articles class News { // Common properties and methods for news articles } class SportsNews extends News { // Specific properties and methods for sports news articles } class TechnologyNews extends News { // Specific pr...
magicoder
php
You are tasked with implementing a cache management system for a mobile application. The cache should support inserting, deleting, and retrieving items efficiently. Your task is to design and implement a cache system that satisfies the following requirements: 1. The cache should be able to store key-value pairs, where...
```swift class LRUCache { class Node { let key: Int var value: Int var prev: Node? var next: Node? init(_ key: Int, _ value: Int) { self.key = key self.value = value } } var capacity: Int var cache: [Int: Node] var...
magicoder
swift
You are tasked with designing a Java class for managing items in a shopping cart system. The class should represent an item that can be added to a shopping cart, and it should contain various attributes and annotations for database mapping. Your task is to create a Java class named `CartItem` that includes the followi...
```java import javax.persistence.*; @Entity @Table(name = "cart_item") public class CartItem { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private Long idCarrito; @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @JoinColumn(name = "carrito_item_product...
magicoder
java
You are tasked with implementing a Python function that interacts with a RESTful API for user authentication. The function should handle the retrieval of an access token, use it to fetch user data, and update the client's headers for subsequent requests. You are provided with a code snippet that demonstrates the usage ...
```python import requests def fetch_user_data(client, user_data, token_response): token_response.raise_for_status() token = token_response.json() response = client.get( '/api/auth/users/me/', headers={'Authorization': f'Bearer {token["access_token"]}'}) response.raise_for_status() ...
magicoder
python
You are tasked with creating a navigation system for a mobile application. The application uses a navigation service to move between different views. The snippet provided is a part of the code that handles the navigation logic. The `_navigationService.NavigateTo` method is used to navigate to a specific view, in this ...
```csharp using System; using System.Collections.Generic; using System.Text; public class NavigationService { public string ConstructNavigationUri(string viewName, Dictionary<string, string> parameters) { StringBuilder uriBuilder = new StringBuilder("/Views/"); uriBuilder.Append(viewName).Appen...
magicoder
csharp
You are tasked with creating a program that analyzes the frequency of words in a given text file. Your program should read a text file and output the frequency of each word in the file, sorted in descending order based on their frequency. For the purpose of this problem, a word is defined as a sequence of alphanumeric ...
```python import re # Read the input file and store its content in a string with open('input.txt', 'r') as file: text = file.read() # Convert the entire text to lowercase for case-insensitive comparison text = text.lower() # Use regular expression to find all words in the text words = re.findall(r'\b\w+\b', text...
magicoder
python
You are tasked with implementing a network serialization configuration system. The system should allow users to define and configure the serialization format for network communication. The serialization configuration should support various data formats such as JSON, XML, and binary, and it should be extensible to accom...
```python from typing import Any class SerializationConfig: def __init__(self): self.format = "json" # Default serialization format def set_format(self, format: str): self.format = format def get_format(self) -> str: return self.format def serialize(self, data: Any) -> bytes...
magicoder
python
You are tasked with creating a web application for managing job categories. The application has a page that displays a table of existing job categories and a form to add new job categories. The table is populated with data from a backend server and allows users to delete existing job categories. The frontend code snipp...
The provided PHP code establishes a connection to the MySQL database and fetches all existing job categories to display them in a table. It also implements the functionality to delete a job category when the corresponding "delete" button is clicked and adds a new job category when the form is submitted. The code uses ...
magicoder
sql
You are tasked with implementing a function to parse and extract specific information from a given data structure representing an SVG image. The data structure is represented as an array in a specific format. The array contains the SVG tag followed by its attributes and nested elements represented as arrays. Each neste...
```javascript function extractSVGInfo(svgData) { const viewBox = svgData[1].viewBox.split(" ").map(Number); const pathCount = svgData.filter(item => item[0] === "path").length; return { viewBox, pathCount }; } ```
magicoder
javascript
You are given a partially obfuscated C code snippet that contains some variables and random characters. Your task is to reverse engineer the code and identify the variables and their types, and then write a function to perform a specific operation using those variables. The variables in the code snippet are: - ab - Pg...
```c #include <stdio.h> float performOperation(int ab, int Pg, int nK, int dO, int S, int tK8d, int r5c) { if (S + tK8d == 0) { printf("Error: Division by zero\n"); return 0; } return (ab * Pg) + ((float)(nK - dO) / (S + tK8d)) - r5c; } int main() { int ab = 5, Pg = 3, nK = 10, dO = 2,...
magicoder
c
You are working on a geographic information system (GIS) project and need to develop a function to calculate the area of overlap between two raster images. The raster images are represented as grids of pixels, and each pixel has a geographic location defined by its latitude and longitude coordinates. Your task is to wr...
```python import gdal import math def calculate_overlap_area(min_lat1, max_lat1, min_long1, max_long1, min_lat2, max_lat2, min_long2, max_long2): # Calculate the overlapping area between two rectangles defined by their geographic boundaries # Calculate the overlapping latitude range overlap_lat_min = max(...
magicoder
python
You are given a Python class `PuzzleSolver` with a method `solve(self)`. The `solve` method is intended to solve a puzzle, but it currently lacks the implementation for solving the puzzle when it is not already solved. Your task is to complete the `solve` method by implementing the puzzle-solving logic. The `PuzzleSol...
```python class PuzzleSolver: def __init__(self): # Initialize puzzle-specific attributes pass def is_solved(self): # Implement the logic to check if the puzzle is already solved pass def solve(self): if self.is_solved(): return # Implement the p...
magicoder
python
You are tasked with creating a Python class that parses and processes data from two different types of MINIDUMP files. The MINIDUMP files contain information about a process, including its ID, creation time, user time, kernel time, and, in the case of the second type of file, the maximum processor frequency. Your task...
```python class MiniDumpParser: def __init__(self): self.parsed_data = {} def parse_chunk(self, chunk): if is_minidump_misc_info(chunk): misc = MINIDUMP_MISC_INFO.parse(chunk) self.parsed_data['ProcessId'] = misc.ProcessId self.parsed_data['ProcessCreateTime'...
magicoder
python
You are tasked with implementing a data structure that can efficiently store and retrieve key-value pairs. The data structure should have the ability to keep a strong reference to the data source, ensuring that the data is not prematurely deallocated. Your task is to design and implement a class that fulfills these req...
```java import java.util.HashMap; public class StrongReferenceDataStructure<K, V> { private DataStructure dataSource; private HashMap<K, V> map; public StrongReferenceDataStructure(DataStructure dataSource) { this.dataSource = dataSource; this.map = new HashMap<>(); } public void ...
magicoder
java
You are tasked with creating a Python class that implements a simple version of a priority queue using a list. The priority queue should support the following operations: 1. `insert(value, priority)`: Insert a value into the priority queue with the given priority. 2. `pop()`: Remove and return the value with the highes...
```python class PriorityQueue: def __init__(self): self.queue = [] def insert(self, value, priority): self.queue.append((value, priority)) self.queue.sort(key=lambda x: x[1], reverse=True) def pop(self): if not self.is_empty(): return self.queue.pop(0)[0] d...
magicoder
python
You are tasked with implementing a simple text-based game where the player navigates through a maze. The maze is represented as a 2D grid, where each cell can be either a wall ('#') or an empty space ('.'). The player starts at the top-left corner of the maze and must reach the bottom-right corner. The player can move ...
```python from typing import List def canReachEnd(maze: List[List[str]]) -> bool: rows, cols = len(maze), len(maze[0]) dp = [[False] * cols for _ in range(rows)] dp[0][0] = True # Starting point is reachable # Fill in the first row for col in range(1, cols): if maze[0][col] == '....
magicoder
python
You are given a program that checks whether a given number is divisible by 4, 3, or 2. The program prints a message based on the divisibility of the number. Your task is to complete the program by writing a function that takes an integer as input and returns a message based on the divisibility of the number. The funct...
```rust fn check_divisibility(num: i32) -> String { if num % 4 == 0 { return String::from("number is divisible by 4"); } else if num % 3 == 0 { return String::from("number is divisible by 3"); } else if num % 2 == 0 { return String::from("number is divisible by 2"); } else { ...
magicoder
rust
You are working on a ticket management system for a customer support application. The system uses Laravel framework, and you are responsible for implementing access control using Laravel's Gate feature. The `Ticket` model is located in the `App\Model\Customer` namespace. The `Ticket` model has various attributes such a...
```php // Define the gate policy in the AuthServiceProvider use App\Model\Customer\Ticket; use Illuminate\Support\Facades\Gate; public function boot() { $this->registerPolicies(); Gate::define('manage-ticket', function ($user, $ticket) { if ($user->role === 'admin') { return true; // Admi...
magicoder
php
You are tasked with optimizing the performance of a data loading operation in a reading list application. The application uses an object store to manage the reading list data. The provided code snippet includes two test functions: `testLoadData` and `testLoadDataPerformance`. The `testLoadData` function initializes the...
To optimize the performance of loading data from the object store, we can utilize lazy initialization and caching techniques. By lazily initializing the object store and caching the reading list data, we can reduce unnecessary object store reinitialization and improve overall performance. Here's a solution using lazy ...
magicoder
swift
You are tasked with implementing a text formatting function for a styling language. The function should take an array of styling tokens and produce a formatted text output based on the token types and content. The styling tokens consist of three types: `StyleTokenType.TEXT`, `StyleTokenType.STYLE`, and `StyleTokenType....
```typescript function formatStylingTokens(tokens: StylingToken[]): string { const LINE_SPLITE = '\n'; const spaces = ' '; return tokens.map(item => { if (item.type === StyleTokenType.TEXT) { return endTextJoin(spaces, '', ' ', item.content as string) + LINE_SPLITE; } ...
magicoder
typescript
You are tasked with creating a program that analyzes the frequency of words in a given text file. Your program should read a text file and output the top N most frequently occurring words along with their frequencies. For the purpose of this problem, a word is defined as a sequence of characters separated by spaces or ...
```python import re from collections import Counter def analyze_word_frequency(file_path, N): # Read the text file and convert the content to lowercase with open(file_path, 'r') as file: text = file.read().lower() # Extract words using regular expression words = re.findall(r'\b\w+\b', text) ...
magicoder
python
You are tasked with implementing a custom iterator for a simplified version of the `SmallIndexMap` data structure. The `SmallIndexMap` is a map that stores key-value pairs in insertion order and provides constant-time access to its elements. Your goal is to create an iterator that allows for iterating over the key-valu...
```rust // Import necessary traits and types use std::slice::Iter; // Implement the custom iterator type struct Iter<'a, K, V> { inner_iter: Iter<'a, (K, V)>, } // Implement the Iterator trait for the custom iterator type impl<'a, K, V> Iterator for Iter<'a, K, V> { type Item = (&'a K, &'a V); fn next(&m...
magicoder
rust
You are tasked with implementing a traffic simulation system using object-oriented programming in Python. The system will model the movement of vehicles on a road and will utilize simulation parameters to control the behavior of the simulation. You are provided with a code snippet that includes a reference to a `vehic...
```python class Vehicle: def __init__(self, position): self.position = position self.successor = None def place_vehicle(self, predecessor): if predecessor.successor is not None: self.successor = predecessor.successor predecessor.successor = self # Example usage # Cr...
magicoder
python
You are given a code snippet that uses a custom programming language called "Ath" and its interpreter "TildeAthInterp". Your task is to understand the given code and answer a question related to its behavior. The code snippet initializes a statement list `stmts` and contains a series of Ath statements and loops. The s...
The solution to this problem cannot be determined solely from the provided code snippet, as it references custom language constructs and an interpreter that are not defined in the snippet. To accurately determine the output, a complete understanding of the "Ath" language and the behavior of the "TildeAthInterp" interpr...
magicoder
python
You are working on a project to develop a federated learning system using TensorFlow Federated (TFF). In this system, you need to calculate aggregates per client and build an aggregation function. The code snippet provided is a part of this project. Your task is to complete the aggregation function and ensure that it c...
```python # Calculate the aggregates per client client_aggregates = tff.federated_map(tff_count_by_key, tff_client_dataset) # Start to build the aggregation function @tff.tf_computation() def build_zeros(): key_size = len(key_list_t) return tf.zeros([key_size], tf.int32) @tff.federated_computation(tf.int32, tf.i...
magicoder
python
You are tasked with implementing a Base64 encoding and decoding algorithm. Base64 is a binary-to-text encoding scheme that represents binary data in an ASCII string format by translating it into a radix-64 representation. The encoding process involves taking a sequence of bytes and converting it into a string of ASCII ...
```cpp #include <iostream> #include <string> #include <unordered_map> std::string base64Encode(const std::string &input) { const std::string base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; std::string encoded; int val = 0; int bits = -6; const unsigned int mask = 0...
magicoder
cpp
You are given a string containing a license text. Your task is to write a program to extract the license information from the text and display it in a structured format. Your program should extract the following information: 1. License type (e.g., MIT, Apache 2.0, GPL) 2. License text (the actual license terms and con...
```python import re def extract_license_info(input_string): # Define regular expression patterns to match license type and license text license_type_pattern = r'Licensed under the (.+?)\n' license_text_pattern = r'// (.+)' # Extract license type license_type_match = re.search(license_type_pattern,...
magicoder
python
You are given two binary trees `s` and `t`. Write a function `isSubtree` to determine if `t` is a subtree of `s`. A subtree of a tree `s` is a tree consisting of a node in `s` and all of this node's descendants. The tree `s` could also be considered as a subtree of itself. The `TreeNode` class is defined as follows: ...
```python class Solution: def isSubtree(self, s: TreeNode, t: TreeNode) -> bool: def is_same_tree(s: TreeNode, t: TreeNode) -> bool: if not s and not t: return True if not s or not t: return False return s.val == t.val and is_same_tree(s.le...
magicoder
python
You are tasked with implementing a 2D point class in C++ to represent coordinates on a map. The class should have the following functionalities: 1. A constructor that takes x and y coordinates as input and initializes the point. 2. Methods to get and set the x and y coordinates. 3. A method to calculate the distance be...
```cpp #include <iostream> #include <cmath> namespace Logy { namespace Maps { namespace Geometry { class Point2D { double x, y; public: Point2D(double x, double y) : x(x), y(y) {} double getX() const { return x; ...
magicoder
cpp
You are tasked with implementing a function that takes a string as input and performs a specific set of operations on it. The function should first check if the input string contains only alphabetic characters. If the string passes this check, the function should then convert all the lowercase letters to uppercase and ...
```python def testing(myString): if myString.isalpha(): # Check if the string contains only alphabetic characters modified_string = myString.swapcase() # Convert lowercase to uppercase and vice versa return modified_string else: return "Input string should contain only alphabetic chara...
magicoder
python
You are tasked with implementing a version comparison algorithm that compares two version strings and determines which one is greater. A version string consists of a series of dot-separated numeric components, followed by an optional series of dot-separated alphanumeric pre-release identifiers. The comparison should fo...
```csharp using System; using System.Collections.Generic; public class VersionComparer { public static int CompareVersions(string version1, string version2) { string[] v1Components = version1.Split('-'); string[] v2Components = version2.Split('-'); string[] v1Numeric = v1Components[0]....
magicoder
csharp
You are tasked with implementing a class-validator for the given TypeScript class. The class represents a location with a title, description, and address. Your goal is to use class-validator to ensure that the provided properties meet specific criteria. The TypeScript class is as follows: ```typescript import { ApiPr...
```typescript import { ApiProperty } from '@nestjs/swagger'; import { IsNotEmpty, IsString, MinLength } from 'class-validator'; export class Location { @ApiProperty({ description: 'Name of the Place', }) @IsNotEmpty() @IsString() public title: string; @ApiProperty() @IsString() @MinLength(10) pu...
magicoder
typescript
You are given a stack data structure and are required to implement a function that sorts the stack in ascending order using only one additional stack. The original stack should be modified to be sorted without using any other data structures such as arrays or lists. You need to implement the following function: ```cp...
```cpp void sortStack(std::stack<int>& s) { std::stack<int> tempStack; while (!s.empty()) { int temp = s.top(); s.pop(); while (!tempStack.empty() && tempStack.top() > temp) { s.push(tempStack.top()); tempStack.pop(); } tempStack.push(temp); ...
magicoder
cpp
You are tasked with simulating a simple URL producer-consumer system using Python's threading module. The system consists of a producer thread and multiple consumer threads. The producer thread generates URLs and adds them to a shared queue, while the consumer threads retrieve URLs from the queue and process them. You...
```python import threading import queue import time import random class UrlProducer(threading.Thread): def __init__(self, semaphore, shared_queue): super(UrlProducer, self).__init__() self.semaphore = semaphore self.shared_queue = shared_queue def run(self): urls = ["https://ww...
magicoder
python
You are tasked with implementing a class for managing players in a multiplayer game. The provided code snippet is a part of the class that retrieves the players present in a specific game room. The `getPlayersInRoom` method takes a room as a parameter and is expected to return a list of players currently in that room. ...
```python class Player: def __init__(self, name, room): self.Name = name self.Room = room class GameMap: def __init__(self): self.rooms = {} def getRoom(self, room_name): return self.rooms.get(room_name, None) class GameManager: def __init__(self): self.Players...
magicoder
python
You are tasked with implementing a program to perform 2D Delaunay triangulation on a set of points. Delaunay triangulation is a method for creating a triangulated irregular network (TIN) from a set of points in the plane, such that no point is inside the circumcircle of any triangle in the network. The program should t...
```python from scipy.spatial import Delaunay def delaunay_triangulation(points): tri = Delaunay(points) triangles = [] for simplex in tri.simplices: triangle = [points[i] for i in simplex] triangles.append(triangle) return triangles ``` The `delaunay_triangulation` function uses the `D...
magicoder
python
You are tasked with implementing a URL routing system for a web application using Python's Django framework. The given code snippet represents a list of URL patterns and their corresponding view functions. Each URL pattern is associated with a specific view function and has a unique name. Your task is to create a func...
```python def find_view_function(url_path: str) -> str: for pattern in urlpatterns: pattern_path = pattern[0] view_function = pattern[1] if pattern_path == url_path: return pattern[2] elif "<str:" in pattern_path: pattern_prefix = pattern_path.split("<str:")[0...
magicoder
python
You are tasked with creating a Python program that processes a given C++ header file and generates a modified version with specific annotations. The program should read the input C++ header file, identify certain elements, and apply the required annotations before writing the modified content to a new file. Your task ...
```python import os from az_code_gen.base import * from AzReflectionCpp import format_cpp_annotations class AZEBusInline_Driver(TemplateDriver): def generate_annotated_cpp_file(input_file, output_file): try: with open(input_file, 'r') as file: input_content = file.read() ...
magicoder
python
You are tasked with implementing a rotary encoder class in Python. A rotary encoder is an electromechanical device used to convert the angular position of a shaft or axle to an analog or digital code. The provided code snippet is a part of the rotary encoder class and includes some initialization and a method for obtai...
```python class RotaryEncoder: def __init__(self, pin_a, pin_b): self.pin_a = pin_a self.pin_b = pin_b self.steps = 0 self.last_delta = 0 self.r_seq = self.rotation_sequence() self.steps_per_cycle = 4 self.remainder = 0 def rotation_state(self): a...
magicoder
python
You are given a Python class `SegmentTree` that implements a segment tree data structure. The segment tree is represented as an array `SEG` of size `2*n-1`, where `n` is the number of elements in the input array. The class also contains a method `func` that takes two arguments and performs a specific operation on them....
```python from typing import List class SegmentTree: def __init__(self, arr: List[int]): self.n = len(arr) self.SEG = [0] * (2 * self.n - 1) self.construct_segment_tree(arr, 0, self.n - 1, 0) def construct_segment_tree(self, arr: List[int], start: int, end: int, pos: int) -> int: ...
magicoder
python
You are tasked with implementing a simplified version of the Bitcoin block header validation algorithm. The Bitcoin block header contains several fields, including the extended private key prefix, the maximum target, the genesis block hash, and the genesis block bits. The extended private key prefix is a hexadecimal v...
```python from hashlib import sha256 from binascii import unhexlify def validate_block_header(block_header_hash, target_bits, max_target, genesis_block_hash, genesis_block_bits, extended_private_key_prefix): header_bytes = unhexlify(block_header_hash) header_hash = sha256(sha256(header_bytes).digest()).digest(...
magicoder
python
You are given a code snippet in Swift that defines a generic class `A` and a protocol `B`. The class `A` has a weak reference to an object of type `T`, where `T` must be a subclass of `AnyObject`. The protocol `B` is defined as a class protocol. The code then attempts to print the value of the weak reference `a` of the...
The given code snippet will print `nil` when executed. This is because the weak reference `a` in the `A` class is not holding a strong reference to any object, and since the array is empty, accessing the weak reference will result in `nil`. The code snippet creates an empty array of type `A` with the generic parameter...
magicoder
swift
You are tasked with implementing a function that calculates the size of a given data type in bytes. The function should take a single argument representing the data type and return the size of that data type in bytes. You are provided with a code snippet that includes a match arm for the `f64` data type, which returns ...
```rust use std::mem; enum DataType { I32, F64, Bool, Char, // Add more data types as needed } fn calculate_size(data_type: DataType) -> usize { match data_type { DataType::I32 => mem::size_of::<i32>(), DataType::F64 => mem::size_of::<f64>(), DataType::Bool => mem::size...
magicoder
rust
You are tasked with implementing a simple 2D rendering system for a game engine. The provided code snippet is part of the rendering pipeline and involves the functions `Begin2D`, `DrawRateStuff`, `GLRenderer->Flush`, and `Swap`. The `Begin2D` function is used to initialize the 2D rendering context, and it takes a boo...
```cpp void Begin2D(bool clearScreen) { // Initialize 2D rendering context // ... if (clearScreen) { // Clear the screen // ... } } void Swap() { // Swap front and back buffers // ... } ``` In the `Begin2D` function, the 2D rendering context should be initialized, and if the `c...
magicoder
cpp
You are tasked with implementing a parser for numerical expressions with signed numbers. Your task is to create a class that can parse and evaluate expressions containing signed integers. The class should handle both positive and negative integers and perform the necessary operations based on the signs. Your task is t...
```csharp internal sealed class NumericalSignedRunner : ParseRunner { private NumericalSignedRunner() { } public override ParseRunner Run(ParseRunnerContext context, Token token) { var sign = context.GetAndClearPreSignToken().Symbol.ToString(); switch (token) { case...
magicoder
csharp
You are working on a Java application that utilizes the Gson library for JSON serialization and deserialization. The given code snippet is part of a utility class that manages Gson instances and type adapters. Your task is to implement a method to unregister a type adapter from the Gson builder and provide a new method...
```java import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.TypeAdapter; import java.lang.reflect.Type; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class GsonUtility { private static final GsonBuilder GSON_BUILDER = new GsonBuilder(); private ...
magicoder
java
You are tasked with implementing a class hierarchy for light transformers in a home automation system. The provided code snippet is a part of the implementation of the `LightOutput` class, which is responsible for creating default transitions for light effects. Your task is to design and implement the necessary classes...
```cpp #include <memory> // Base class for light transformers class LightTransformer { public: virtual void transform(/* light effect parameters */) = 0; virtual ~LightTransformer() = default; }; // Derived class implementing default transition behavior class LightTransitionTransformer : public LightTransform...
magicoder
cpp
You are tasked with implementing a function that removes all occurrences of a specific character from a given string. Your function should take in the original string and the character to be removed, and then return the modified string with all instances of the specified character removed. You are to write a function ...
```cpp #include <string> std::string removeCharacter(const std::string& original, char toRemove) { std::string result; for (char c : original) { if (std::tolower(c) != std::tolower(toRemove)) { result += c; } } return result; } ``` The `removeCharacter` function iterates th...
magicoder
cpp
You are tasked with implementing a Particle Swarm Optimization (PSO) algorithm to optimize a given graph. The PSO algorithm maintains a population of particles, each representing a potential solution. The particles move through the search space, adjusting their positions based on their own best position and the best po...
```python import numpy as np class Particle: def __init__(self, graph, omega, phi_particle, phi_global): self.position = np.random.rand(len(graph.nodes)) # Initialize particle's position randomly self.velocity = np.zeros(len(graph.nodes) # Initialize particle's velocity to zero self.fitne...
magicoder
python
You are tasked with implementing a logging system for a Python application. The code snippet provided is a part of a logging function that calculates the time taken by a specific method and stores it in a dictionary. The `kw` dictionary contains various logging parameters, and the `te` and `ts` variables represent the ...
```python def log_method_time(method, te, ts, **kw): if 'log_name' in kw: name = kw.get('log_name', method.__name__.upper()) kw['log_time'][name] = int((te - ts) * 1000) else: name = method.__name__.upper() kw['log_time'][name] = int((te - ts) * 1000) ``` In this solution, the `l...
magicoder
python
You are tasked with creating a middleware function for a Redux store in a React application. The middleware should handle routing, state persistence, and action whitelisting. Your task is to implement the middleware function using the provided code snippet as a reference. The middleware function should perform the fol...
The `createReduxMiddleware` function takes `history` and `USER_LOGIN_SUC` as parameters and returns the composed middleware function to be used with the Redux store. It first creates a router middleware using the `routerMiddleware` function, then creates a storage engine using the `createEngine` function and filters ou...
magicoder
jsx
You are tasked with implementing a user throttling mechanism for an API using Python and Django Rest Framework. The provided code snippet includes the definition of a custom user throttle class called `OncePerDayUserThrottle`, which inherits from `UserRateThrottle` and sets the throttling rate to '1/day'. Additionally,...
```python from rest_framework.throttling import UserRateThrottle from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status class OncePerDayUserThrottle(UserRateThrottle): rate = '1/day' @api_view(['GET']) @throttle_classes([OncePerDayUserThrottle...
magicoder
python
You are tasked with creating a Python function that processes HTML content and extracts specific information using BeautifulSoup and requests libraries. The function should take a URL as input, navigate to a specific link within the page, retrieve the content of that link, and then switch to using BeautifulSoup version...
```python import requests from bs4 import BeautifulSoup import logging def process_html(url: str) -> str: # Function to grab HTML content from a URL def grab_url(link: str) -> str: response = requests.get(link) return response.text try: response = requests.get(url) soup = B...
magicoder
python
You are tasked with implementing a logging system for a distributed database management system. The system consists of multiple nodes, each running a MariaDB instance. The goal is to create a centralized logging mechanism that captures important events and status updates from each node. You are provided with a Python ...
```python import logging class MariaDBCluster: def __init__(self): self.logger = logging.getLogger('MariaDBCluster') def start_node(self, ipv4): self.logger.info({'action': 'start_node', 'ipv4': ipv4, 'message': f'Node {ipv4} started'}) def shutdown_node(self, ipv4): self.logger.i...
magicoder
python
You are tasked with implementing a Python code analyzer that can traverse and process different types of nodes in an abstract syntax tree (AST). Your goal is to extend the functionality of the existing code analyzer by implementing specific visit methods for different types of nodes. You are provided with a partial co...
```python class CodeAnalyzer: def visit_importfrom(self, node): # Implement functionality to handle the importfrom node # Example: Process the "from ... import ..." statement pass # Placeholder for the actual implementation def visit_for_statement(self, node): # Implement funct...
magicoder
python
You are working on a data processing task involving astronomical data. You have been given a file containing records of stars, each identified by a Hipparcos Catalogue number (HIP). The records are stored in a dictionary called `data`, where the keys are HIP numbers and the values are corresponding star records. Each r...
```python import numpy as np def process_astronomical_data(data, fill_item): record = np.dtype([ ('SpType', 'U10'), ('r_SpType', 'U10') ]) # Step 1: Check for duplicate records seen_hip = set() for hip in data: if hip in seen_hip: print('Error: Duplicate Records...
magicoder
python
You are tasked with implementing a simple interpreter for a custom programming language. The interpreter is responsible for processing lines of code and storing the results in memory. The code snippet provided is a part of the interpreter's logic for processing and storing values in memory. The interpreter has a `memo...
```python import re class Interpreter: number = re.compile(r'^\d+$') def __init__(self): self.memory = {} def interpret_code(self, code_lines): for index, line in enumerate(code_lines): line = line.rstrip("\n") if Interpreter.number.match(line): sel...
magicoder
python
You are tasked with creating a custom exception class in C# that extends the functionality of the base Exception class. Your custom exception, named `KuttException`, should have the following features: - It should inherit from the base Exception class. - It should have a constructor that takes a string message as a par...
```csharp using System; public class KuttException : Exception { public KuttException(string message) : base(message) { } public override string StackTrace => ""; // Override StackTrace property to return an empty string } public class Program { public static void Main() { try ...
magicoder
csharp
You are tasked with creating a Swift function that interacts with the Uniswap V2 API to retrieve token information based on a given array of token addresses. The Uniswap V2 API uses GraphQL for querying data. Your function should take an array of token addresses as input, construct a GraphQL query, send a request to th...
```swift import Foundation func fetchTokenInfo(tokenAddresses: [String]) -> [String: Any] { let query = """ query($tokenIds: [String]!) { tokens(where: { id_in: $tokenIds }) { id name symbol derivedETH totalSupply totalLiquidity ...
magicoder
swift
You are tasked with implementing a function that can parse and extract information from a given JavaScript code snippet. The code snippet represents a React component and includes a call to `getStaticProps` function. Your task is to extract the name of the function being exported and the name of the function being pass...
```javascript function parseReactComponent(codeSnippet) { const exportedFunctionRegex = /export\s+default\s+([a-zA-Z_$][0-9a-zA-Z_$]*)\s*;/; const getStaticPropsRegex = /export\s+const\s+getStaticProps\s*=\s*([a-zA-Z_$][0-9a-zA-Z_$]*)\s*;/; const exportedFunctionMatch = codeSnippet.match(exportedFunctionRe...
magicoder
javascript
You are tasked with creating a program to process user input for a mode menu in a game using Python and the Pygame library. The mode menu consists of four input fields labeled 'mode_input_1', 'mode_input_2', 'mode_input_3', and 'mode_input_4'. When the user types in the input boxes and presses the Enter key, the progra...
```python import pygame class ModeMenu: def __init__(self): self.active_menu = 'mode_input_1' self.input_box_1 = '' self.input_box_3 = '' self.value_list = [] def process_mode_menu_input(self, event): if event.type == pygame.KEYDOWN: if event.key == pygame.K...
magicoder
python
You are tasked with implementing a simple command-line argument parser in C++ to parse and process user input. The parser should support parsing both options with values and standalone arguments. Your task is to write a function `parseArguments` that takes a vector of strings representing command-line arguments and re...
```cpp #include <iostream> #include <vector> #include <string> #include <map> std::pair<std::map<std::string, std::string>, std::vector<std::string>> parseArguments(const std::vector<std::string>& arguments) { std::map<std::string, std::string> parsedOptions; std::vector<std::string> standaloneArguments; ...
magicoder
cpp
You are tasked with implementing a simplified version of a live auction system in Swift. The system involves creating a view model for auctions and defining a default auction view model creator function. The provided code snippet includes a class and a function related to this task. Your goal is to complete the impleme...
```swift // Define the AuctionViewModel protocol protocol AuctionViewModel { var sale: Sale { get } var currentLotSignal: Signal<Lot> { get } var biddingCredentials: BiddingCredentials { get } func startAuction() } // Implement the LiveAuctionViewModel class conforming to AuctionViewModel class LiveAuc...
magicoder
swift
You are tasked with creating a Python function that processes an audio file to calculate the Root Mean Square (RMS) amplitude of the audio signal. The RMS amplitude is a measure of the power of the signal and is commonly used in audio processing applications. You are provided with a code snippet that loads an audio fi...
```python import numpy as np import soundfile as sf def calculate_rms_amplitude(wav_path): audio_blk = sf.blocks(wav_path, blocksize=1024, overlap=512) # Divide the audio into blocks rms = [np.sqrt(np.mean(block**2)) for block in audio_blk] # Calculate RMS amplitude for each block return rms # Return th...
magicoder
python
You are tasked with implementing a custom list class in C# that extends the functionality of the built-in `List<T>` class. The custom list class, named `CustomList`, should have additional methods for sorting and filtering elements based on certain criteria. Your task is to implement the `CustomList` class with the fo...
```csharp using System; using System.Collections.Generic; public class CustomList<T> : List<T> { public void SortDescending(Comparison<T> comparison) { Sort(comparison); Reverse(); } public CustomList<T> Filter(Predicate<T> predicate) { CustomList<T> filteredList = new Cust...
magicoder
csharp
You are tasked with creating a function that processes a given HTML code snippet and extracts the labels of all the form fields present in the snippet. The HTML code snippet will contain various form elements such as input fields, checkboxes, radio buttons, and select dropdowns, each wrapped in their respective form fi...
```javascript function extractFormLabels(htmlCode) { const parser = new DOMParser(); const doc = parser.parseFromString(htmlCode, 'text/html'); const formFieldLabels = Array.from(doc.querySelectorAll('mwc-formfield[label]')).map(field => field.getAttribute('label')); return formFieldLabels.filter(label => label...
magicoder
javascript
You are tasked with creating a Python class that can parse a YAML file and provide specific functionality for accessing and manipulating the data within it. Your class should be able to load the YAML file, retrieve specific values, update existing values, and save the modified data back to the file. Your task is to i...
```python import yaml class YamlParser: def __init__(self, yaml_path): self.yaml_path = yaml_path self.yaml_data = None def load(self): try: with open(self.yaml_path, encoding='utf8') as fin: self.yaml_data = yaml.safe_load(fin) except FileNotFoundEr...
magicoder
python
You are tasked with creating a function that processes an input array and returns a modified array or a null value. Your task is to implement the `foo` function in PHP, which takes an array as input and returns either a modified array or null. The function signature is as follows: ```php function foo($x) : ?array { ...
```php function foo($x) : ?array { if (empty($x)) { return null; } else { foreach ($x as &$value) { $value += 1; } return $x; } } ``` The `foo` function first checks if the input array is empty using the `empty` function. If the array is empty, the function retur...
magicoder
php
You are tasked with creating a program that analyzes the frequency of words in a given text file. Your program should read a text file and output the top N most frequently occurring words along with their frequencies. The program should ignore common stop words (e.g., "the", "and", "is") and should be case-insensitive ...
```python from typing import List, Tuple import re from collections import Counter def top_n_words(file_path: str, n: int) -> List[Tuple[str, int]]: with open(file_path, 'r', encoding='utf-8') as file: text = file.read().lower() words = re.findall(r'\b\w+(?:-\w+)*\b', text) stop_words = {'t...
magicoder
python
You are tasked with simulating a simple booking system for rooms in a building. The building has multiple floors (referred to as "geschosses"), and each floor contains multiple rooms. The goal is to create a program that can efficiently manage the booking of rooms on each floor. You are given a code snippet that initi...
```python class Room: def __init__(self, room_type): self.room_type = room_type self.book = {} class Geschoss: def __init__(self, num_rooms): self.rooms = [Room("kontakt") for _ in range(num_rooms)] self.book = {} class Building: def __init__(self, num_geschosse, num_rooms_...
magicoder
python
You are tasked with creating a Rust program that utilizes WebAssembly to implement asynchronous functions. Your goal is to write an asynchronous function in Rust and then call it from JavaScript using WebAssembly. Your task is to complete the Rust function and the JavaScript code to properly handle the asynchronous b...
Rust code implementation: ```rust // async_functions.rs use wasm_bindgen::prelude::*; #[wasm_bindgen] pub async fn perform_async_operation(input: i32) -> i32 { input * 2 } ``` JavaScript code implementation: ```javascript // index.js import init from './wasm_module.js'; async function callAsyncFunction(input) ...
magicoder
rust
You are tasked with implementing a pagination service for a user profile system. The system contains a list of recommended users, and the goal is to create a function that returns a paginated list of these recommended users. The function should take into account the page number, page size, and any optional filtering cr...
```csharp public async Task<List<UserDto>> GetRecommendedUsers(int pageNumber, int pageSize, Expression<Func<User, bool>> filter = null) { var query = _userRepository.GetRecommendedUsers(); if (filter != null) { query = query.Where(filter); } var totalUsers = await query.CountAsync(); ...
magicoder
csharp
You are tasked with implementing a function that takes a list of ranges and returns a list of all the numbers within those ranges. The ranges are represented as tuples, where each tuple contains two integers representing the start and end of the range (inclusive). If a range contains only one number, that number should...
```python from typing import List, Tuple def get_allowed_numbers(ranges: List[Tuple[int, int]]) -> List[int]: allowed_list = [] for range_start, range_end in ranges: if range_start == range_end: continue elif range_start < range_end: allowed_list += list(range(range_star...
magicoder
python
You are tasked with creating a Python function that simulates the process of adding a user to a group. The function should take two parameters: a username and a group name. The function should then return a string indicating the success or failure of adding the user to the group. The function signature should be: ```p...
```python def add_user_to_group(username: str, groupname: str) -> str: # Simulate the process of adding a user to a group groups = { "docker": ["user1", "user2", "vagrant"], "admin": ["user3", "user4"] } if groupname in groups: if username in groups[groupname]: retur...
magicoder
python
You are tasked with implementing a simplified version of a batch call system for asynchronous operations. The system should allow adding calls to a batch and then executing them concurrently, returning a future that resolves once all the batched calls have been executed. You are provided with a partial code snippet fo...
```rust use serde::Serialize; use futures::future::{Future, join_all}; use std::result::Result; use std::sync::{Arc, Mutex}; struct BatchExecutor { batched_calls: Arc<Mutex<Vec<Box<dyn Future<Output = Result<()>> + Send>>>> } impl BatchExecutor { fn new() -> Self { BatchExecutor { batched_...
magicoder
rust
You are tasked with implementing a simplified version of a message bus system using Rust. The message bus will be used to facilitate communication between different components of a system. The bus will support sending and receiving messages, and it will be thread-safe to allow concurrent access from multiple threads. ...
```rust use std::sync::{Arc, Mutex}; use std::sync::mpsc::{channel, Sender, Receiver}; // Placeholder for the response type struct SignaldResponse; // Generic message bus type struct Bus<T> { sender: Sender<T>, receiver: Receiver<T>, } impl<T> Bus<T> { fn new() -> Bus<T> { let (sender, receiver) ...
magicoder
rust
You are tasked with implementing a file processing system that involves a `FileHelper` and a `StarsHelper`. The `FileHelper` interface provides methods for reading and writing files, while the `StarsHelper` interface offers functionality related to star ratings. You are given a code snippet that declares two variables:...
```swift // Implementing the FileHelperInterface protocol class FileHelper: FileHelperInterface { var filePath: String init(filePath: String) { self.filePath = filePath } func readFile() -> String? { // Implement logic to read file at filePath return nil } ...
magicoder
swift
You are tasked with creating a Python function that downloads a function file from an API and saves it to a specified output path. The function will take in the function name, function ID, version ID, and output path as parameters. You need to implement the function to perform the following steps: 1. Construct a notic...
```python import requests import os def format_uuid(uuid): # Implementation of format_uuid function pass def api_call(api_function, f_uuid, v_uuid): # Implementation of api_call function pass def download_function(f_name, f_id, v_id, output_path): notice_msg = 'Downloading the function with the f...
magicoder
python
You are working on a project that involves processing stellar abundance data. You have been given a code snippet that contains a function `_prepare_pdf_data` which is responsible for preparing probability density function (PDF) data based on the means, standard deviations, and range of the stellar abundances. The funct...
```python import numpy as np from scipy.stats import norm as gauss_norm def _prepare_pdf_data(means, stds, range, norm=True): x_vals = np.linspace(range[0], range[1], 250) y_vals = np.zeros_like(x_vals) # create and sum all PDF of stellar abundances for d_m, d_s in zip(means, stds): if np.isfin...
magicoder
python
You are tasked with implementing a modified binary search algorithm to find the index of a target element in a rotated sorted array. The array has been rotated at an unknown pivot point, and it may contain duplicate elements. Your task is to write a function `search_in_rotated_array` that takes an array of integers `ar...
```rust pub fn search_in_rotated_array(arr: &[isize], targ: isize) -> Option<usize> { if arr.is_empty() { return None; } let (mut left, mut right) = (0, arr.len() - 1); while left <= right { let mid = left + (right - left) / 2; if arr[mid] == targ { return Some(mid...
magicoder
rust
You are tasked with implementing a custom data structure in Rust that simulates a fixed-size circular buffer. A circular buffer is a data structure that uses a single, fixed-size buffer as if it were connected end-to-end. When the buffer is full and a new element is inserted, it overwrites the oldest element. The circu...
```rust use core::fmt::Write; use core::mem::size_of; struct CircularBuffer { buffer: Vec<u8>, size: usize, read_index: usize, write_index: usize, } impl CircularBuffer { fn new(size: usize) -> CircularBuffer { CircularBuffer { buffer: vec![0; size], size, ...
magicoder
rust
You are tasked with implementing a function that executes a specified callback within a transaction on a given IndexedDB store. IndexedDB is a low-level API for client-side storage of significant amounts of structured data, including files/blobs. The provided code snippet contains a helper function that wraps the trans...
```javascript function executeInTransaction(db, name, callback, options = { mode: 'read' }) { return new Promise((resolve, reject) => { const mode = options.mode; const transaction = db.transaction(name, mode); const store = transaction.objectStore(name); transaction.oncomplete = () => { resolv...
magicoder
javascript
You are tasked with creating a program that processes a list of GitHub repositories and calculates the average number of stars for repositories within a specified range. You are given a list of GitHub repositories in the following format: ``` <gh_stars>10-100 export * from './has-class'; ``` Each line represents a Git...
```python def calculate_average_stars(input_list): stars_count = {} stars_total = {} stars_repos_count = {} for line in input_list: range_str, stars = line.split('<gh_stars>') start, end = map(int, range_str.split('-')) stars = int(stars) for i in range(star...
magicoder
python
You are tasked with implementing a function to calculate the contour plots for a specific engineering analysis. The function `contour_2d` takes three arguments: a dictionary of parameters, a string specifying the type of analysis, and a subplot axis for visualization. The parameters in the dictionary include "plate_imp...
```python import matplotlib.pyplot as plt import lambda02 # Assuming lambda02 is a module containing the contour_2d function def contour_2d(params, analysis_type, ax): # Implementation of the contour_2d function pass # Placeholder for the actual implementation def generate_contour_plots(): fig, ax = plt...
magicoder
python
You are tasked with implementing a function that processes time series data to calculate quantiles. The function takes an InstantVector representing the time series data, an optional Aggregate label, and a parameter of type f64. The function should return an InstantVector representing the quantile calculation based on ...
```rust fn calculate_quantile( vector: InstantVector, labels: Option<Aggregate<'_>>, parameter: f64, ) -> InstantVector { let InstantVector(old_vec) = vector; let new_vec = match labels { Some(l) => format!("quantile {} ({}, {})", l.to_string(), parameter, old_vec), None => format!(...
magicoder
rust
You are given an array `input` of stock prices for a particular stock, where `input[i]` represents the price of the stock on the `i`-th day. Your task is to write a function to determine the maximum profit that can be obtained by buying and selling the stock at most once. You need to implement the function `int maxPr...
```java public int maxProfit(int[] input) { int length = input.length; if (length == 0) { return 0; // No profit can be made with an empty array } int min_price = input[0]; // min price seen till now (on left) int max_profit = 0; for (int i = 1; i < length; i++) { int current_p...
magicoder
java
You are tasked with creating a database schema for a company's employee management system. The schema should include a table for employees with specific fields and constraints. Create an SQL schema for the employee table with the following fields and constraints: - id: an auto-incrementing primary key - nome: a string...
```sql CREATE TABLE employees ( id INT AUTO_INCREMENT PRIMARY KEY, nome VARCHAR(100), datanascimento DATE, sexo VARCHAR(20), cpf VARCHAR(15) UNIQUE, endereco VARCHAR(100), cargo VARCHAR(40) ); ALTER TABLE employees ADD CONSTRAINT fk_filial FOREIGN KEY (id) REFERENCES filials(id)...
magicoder
sql
You are tasked with implementing a function to update an invoice with new line items. The function will take in the following parameters: - `$invoiceId` (integer): The ID of the invoice to be updated. - `$lineItems` (array): An array of line items to be added to the invoice. Each line item is represented as an associat...
```php function updateInvoice($invoiceId, $lineItems) { // Implementing the updateInvoice function // Assume the existence of a function to update the invoice in the system // Pseudo code for updating the invoice with line items // $uri = "invoices/" . $invoiceId; // Make a request to the system to...
magicoder
php
You are working on a natural language processing (NLP) project and need to implement a function that processes entity and relation vectors to create a graph vector. The function takes in entity vectors, relation vectors, and a case ID, and returns a graph vector. You are given the following code snippet as a starting ...
```python import numpy as np def generate_graph_vector(ent1_vector, rel_vector, ent2_vector, lens, case_id): ent2_vector = np.array(ent2_vector / lens) # Normalize ent2_vector vector = np.concatenate((ent1_vector, rel_vector, ent2_vector), axis=-1) # Concatenate the vectors graph_vector = {case_id: vecto...
magicoder
python
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 turns. However, if the player's score exceeds a certain threshold, the score for that turn is reduced to the threshold value. Write a function to calculate the final sco...
```python from typing import List def calculate_final_score(scores: List[int], threshold: int) -> int: final_scores = [min(scores[0], threshold), min(scores[1], threshold)] for i in range(2, len(scores)): current_score = scores[i] + final_scores[i-1] + final_scores[i-2] final_scores.append(min(...
magicoder
python
You are tasked with implementing a simple text-based user interface for displaying data. The provided code snippet is a part of a Python class that manages the display of data in a text-based window. The class has a method `draw` that is responsible for rendering the data in the window. If the data is not available, it...
```python def draw(self): if not self.showing: return Window.draw(self) if not self.data: self.window.addstr(1, 1, "No data") else: # Display the available data in the window # Assuming self.data is a string, you can display it at pos...
magicoder
python
You are given a set of asteroids in a 2D plane, each represented by its coordinates (x, y). The goal is to determine the 200th asteroid to be vaporized when a laser starts at a specific location and rotates around the asteroids in a clockwise direction. Write a function `find_200th_vaporized` that takes in a dictionar...
```python def find_200th_vaporized(asteroids): vaporised_coords = set() last_angle = None vaporised = 0 for asteroid, info in sorted(asteroids.items(), key=lambda x: x[1]): angle = info if angle == last_angle or asteroid in vaporised_coords: continue last_angle = angl...
magicoder
python
You are tasked with creating a whitelist filter for function names based on a given set of rules. The rules are defined using regular expressions, and any function name that matches the whitelisted patterns should be included in the final whitelist. Write a function `filterFunctionNames` that takes a list of function ...
```python import re from typing import List def filterFunctionNames(function_names: List[str], whitelisted_patterns: List[str]) -> List[str]: filtered_functions = [] for function_name in function_names: for pattern in whitelisted_patterns: if re.match(pattern, function_name): ...
magicoder
python
You are given a 2D array representing a matrix of integers. Your task is to write a function that rotates the matrix 90 degrees clockwise. For example, given the input matrix: ``` [[1, 2], [3, 4]] ``` The function should return: ``` [[3, 1], [4, 2]] ``` You need to implement a function `rotateMatrix(matrix)` that t...
```python def rotateMatrix(matrix): n = len(matrix) for i in range(n // 2): for j in range(i, n - i - 1): temp = matrix[i][j] matrix[i][j] = matrix[n - 1 - j][i] matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j] matrix[n - 1 - i][n - 1 - j] = matrix[j][n...
magicoder
python