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 number of combinations of n items taken p at a time. The formula for calculating combinations is given by the mathematical expression C(n, p) = n! / (p! * (n - p)!), where n! denotes the factorial of n. You need to write a function that takes two integers n a...
```c #include <stdio.h> unsigned long long fact(int num) { unsigned long long factorial = 1; for (int i = 1; i <= num; ++i) { factorial *= i; } return factorial; } unsigned long long calculateCombinations(int n, int p) { if (n < 0 || p < 0 || p > n) { return 0; // Invalid input, re...
magicoder
c
You are tasked with implementing a region factory for deferred column regions in a software system. A deferred region serves as a placeholder, constructing the actual region on first access. Your goal is to design and implement the region factory to support this deferred behavior. Your task is to create a class `Defer...
```java // Interface for the actual region interface Region { void construct(); } // Deferred region class class DeferredRegion<T extends Region> { private T actualRegion; private boolean constructed; public void access() { if (!constructed) { actualRegion.construct(); ...
magicoder
java
You are tasked with implementing a Swift structure to represent Ethereum transactions. The structure should include properties for the transaction index position in the block, the block hash, block number, cumulative gas used, and gas used by the transaction. Additionally, you need to implement a method to calculate th...
```swift struct Transaction { let transactionIndex: Quantity let blockHash: EthData let blockNumber: Quantity let cumulativeGasUsed: Quantity let gasUsed: Quantity func totalGasCost() -> Quantity { return cumulativeGasUsed - gasUsed } } ``` In the solution, the `Transaction` struct...
magicoder
swift
You are tasked with implementing a simple image cropping functionality in a mobile application. The code snippet provided is a part of a custom view controller that handles the image cropping feature. The `rotationEnabled` variable is a boolean flag that determines whether the user can rotate the cropped area. The `loa...
```swift import UIKit class CropView: UIView { var cropRect: CGRect = CGRect.zero var rotationEnabled: Bool = false override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.clear isUserInteractionEnabled = true } required init?(coder aDecod...
magicoder
swift
You are tasked with simulating the behavior of a robot in a virtual environment. The robot is equipped with various sensors and actuators, and it needs to navigate through a maze to locate and report victims. The robot's behavior is governed by the provided code snippet, which contains logic for handling the front sens...
```python def simulateRobotBehavior(frontDistance: float, colorValue: int, victimDetected: bool) -> None: # for front sensor if frontDistance < 0.05: spin() # if on black, turn away if colorValue < 80: spin() wheel_left.setVelocity(speeds[0]) wheel_right.setVelocity(spee...
magicoder
python
You are tasked with implementing a graph data structure in C#. The graph should support the addition of vertices and edges, as well as the ability to perform depth-first search (DFS) and breadth-first search (BFS) traversal algorithms. Your task is to create a class `Graph` that supports the following operations: 1. `...
```csharp using System; using System.Collections.Generic; namespace Graphs { public class Graph { private Dictionary<int, List<int>> adjacencyList; public Graph() { adjacencyList = new Dictionary<int, List<int>>(); } public void AddVertex(int vertex) ...
magicoder
csharp
You are tasked with implementing a function to create an IP policy within a network management system. The function should validate the input parameters and raise specific exceptions for invalid subnet or network IDs. The input to the function includes a context, a dictionary containing IP policy details, and a plugin ...
```python def create_ip_policy(context, ip_policy_details, plugin): # Validate subnet IDs for subnet_id in ip_policy_details.get('subnet_ids', []): if not plugin.is_subnet_exists(subnet_id): raise exceptions.SubnetNotFound # Validate network existence for subnet_id in ip_policy_deta...
magicoder
python
You are working on a deep learning project and need to implement a custom linear layer with a softmax activation function. Your task is to create a Python class that represents this custom layer and write methods to train and evaluate it. Additionally, you need to write unit tests to ensure that the layer behaves as ex...
```python import torch import torch.nn as nn import unittest class LinSoftmax(nn.Module): def __init__(self, input_dim, output_dim): super(LinSoftmax, self).__init__() self.linear = nn.Linear(input_dim, output_dim) def forward(self, x): return nn.functional.softmax(self.linear(x), dim=...
magicoder
python
You are tasked with creating a program that simulates a simple text-based adventure game. The game will involve the player making choices that lead to different outcomes. The player will start in a specific location and will have the option to move to different locations, interact with objects, and make decisions that ...
```python class Location: def __init__(self, name, description, actions): self.name = name self.description = description self.actions = actions class Object: def __init__(self, name, description, effect): self.name = name self.description = description self.effe...
magicoder
python
You are tasked with simulating the behavior of a network overlay system that utilizes Open vSwitch (OVS) and the Open Network Operating System (ONOS). The given code snippet is part of a larger system that manages network interfaces, verifies links, adds Virtual Extensible LAN (VxLAN) ports, and establishes VxLAN chann...
```python def add_vxlan_ip_ports(interface_name): # Simulate the behavior of adding VxLAN IP ports based on the given interface name # Replace this with actual implementation based on the system requirements vxlan_port = simulate_vxlan_port_addition(interface_name) return vxlan_port def simulate_vxlan_...
magicoder
python
You are tasked with implementing a custom React component that mimics the functionality of the `Select` component from a popular UI library. The `Select` component is used to create a dropdown menu for selecting options. Your custom component should have similar functionality, including the ability to handle `onChange`...
```jsx import React from 'react'; const CustomSelect = ({ options, onChange, value, defaultValue }) => { const handleSelectChange = (event) => { onChange(event.target.value); }; return ( <select onChange={handleSelectChange} value={value ?? defaultValue}> {options.map((option) => ( <option...
magicoder
jsx
You are tasked with implementing a function that takes in a list of HTML table rows and returns the data in a structured format. Each row in the input list is represented as a string containing the HTML tags for a table row (`<tr>...</tr>`). The function should parse the input and return a list of dictionaries, where e...
```python def parse_html_table(html_rows): # Extract column headers from the first row headers = [header.strip('</td>') for header in html_rows[0].split('<td>')[1:-1]] # Initialize an empty list to store the parsed data parsed_data = [] # Iterate through the remaining rows to extract data for ...
magicoder
python
You are tasked with creating a Python program that simulates a simple game of rock-paper-scissors. The program should allow a user to play against the computer and keep track of the score. The game should continue until the user decides to quit. Your task is to complete the Python program by implementing the missing f...
```python import random def get_user_choice(): while True: choice = input("Enter your choice (rock, paper, scissors, quit): ").lower() if choice in ["rock", "paper", "scissors", "quit"]: return choice else: print("Invalid choice. Please try again.") def get_computer...
magicoder
python
You are tasked with implementing a Python function that processes a list of message IDs and performs a specific operation on them. The function should handle asynchronous processing and provide the ability to interrupt the operation gracefully. Write a function `process_messages` that takes in the following parameters...
```python def process_messages(client, targets, key, block): msg_ids = [] # Construct integer ID list targets = client._build_targets(targets)[1] # Retrieve message IDs for each engineid and append to msg_ids for index, engineid in enumerate(targets): msg_ids.extend(client.pull(key...
magicoder
python
You are tasked with implementing a caching mechanism for a parser function in Python. The given code snippet demonstrates a global variable `GLOBAL_GRAMMAR` being used to cache the result of a parser function. If the variable is `None`, the parser function is called to initialize it, and subsequently, the cached gramma...
```python import functools def cache_result(func): cache = {} @functools.wraps(func) def wrapper(*args, **kwargs): key = (args, frozenset(kwargs.items())) if key in cache: return cache[key] try: result = func(*args, **kwargs) cache[key] = result ...
magicoder
python
You are tasked with creating a Python class that simulates a simple vendor management system. The system should allow for the registration of vendors and provide functionality to retrieve and display information about the registered vendors. Your task is to implement the `VendorManager` class with the following specif...
```python class VendorManager: def __init__(self): self.registered_vendors = {} def register_vendor(self, vendor_name): if vendor_name not in self.registered_vendors: self.registered_vendors[vendor_name] = {"name": vendor_name} print(f"{vendor_name} has been registered s...
magicoder
python
You are tasked with implementing a function to create chart options for a box plot visualization based on the statistics of people in different cohorts. The function takes an array of `Person` objects and a `CohortMap` object as input and returns the chart options for the box plot. The `Person` class has the following...
```typescript class Person { name: string; age: number; cohort: string; } type CohortMap = { [cohort: string]: Person[] }; interface ChartOptions { xAxis: { categories: string[], title: { text: string } }; series: { data: number[] }[]; } function calculateCohortStatistics(people: Person[], cohorts: CohortM...
magicoder
typescript
You are tasked with creating a Python function that processes a given mode parameter and an absolute path to a target output file. The function should handle different modes of operation and perform specific actions based on the mode provided. The mode parameter is accessed from a dictionary named `params` using the ke...
```python def process_output_file(output_file_path: str, params: dict) -> str: mode = params.get('MODE') # Accessing the mode parameter from the params dictionary if mode == 'read': with open(output_file_path, 'r') as file: content = file.read() return f'Read content from {output_f...
magicoder
python
You are tasked with creating a program that simulates the behavior of the `mkdir` command in a Unix-like operating system. The `mkdir` command is used to create directories within the file system. Your program should take a list of directory paths as input and create the corresponding directories in the file system. Y...
```python import os def createDirectories(directory_paths): for path in directory_paths: try: os.makedirs(path) print(f"Directory created: {path}") except FileExistsError: print(f"Directory already exists: {path}") # Test the function directory_paths = ["root", ...
magicoder
python
You are tasked with creating a Python function that calculates the average of a list of numbers, excluding any outliers. An outlier is defined as a number that is either significantly larger or smaller than the rest of the numbers in the list. To determine outliers, you will use the concept of z-scores. The z-score of ...
```python import statistics def calculate_average_without_outliers(numbers, threshold): mean = statistics.mean(numbers) std_dev = statistics.stdev(numbers) if len(numbers) > 1 else 0 # Avoid division by zero for single-element lists filtered_numbers = [num for num in numbers if abs((num - mean) / std_dev)...
magicoder
python
You are tasked with creating a Python function that interacts with a database using HTTPS and handles various authentication and certificate options. Your goal is to implement the `execute_query_https` function, which takes a SQL query string and optional parameters for user authentication and SSL certificate validatio...
```python import requests class DatabaseQueryError(Exception): pass def execute_query_https(query: str, user: str = None, enable_ssl_auth: bool = True, cert_name: str = None) -> str: try: if enable_ssl_auth: if cert_name: response = requests.get("https://database-url", veri...
magicoder
python
You are tasked with writing a Python function to process LIDAR (Light Detection and Ranging) data obtained from a robot's sensor. The LIDAR data is represented as an array of distances from the sensor to objects in its vicinity. The function should calculate the average distance of the middle 10 readings from the LIDAR...
```python from typing import List def calculate_average_distance(distances: List[float]) -> float: center_index = len(distances) // 2 mid_10_distances = distances[center_index - 5: center_index + 5] average_distance = sum(mid_10_distances) / len(mid_10_distances) return average_distance ``` The `calcu...
magicoder
python
You are tasked with implementing a function that takes a string as input and returns the same string with all consecutive duplicate characters collapsed into a single character. For example, the input string "aaabbbcccd" should be transformed into "abcd". Write a function `collapse_duplicates` that takes a single stri...
```python def collapse_duplicates(s: str) -> str: if not s: return s result = s[0] for char in s[1:]: if char != result[-1]: result += char return result ```
magicoder
python
You are tasked with implementing a Python class that generates a grid with surrounding walls and assigns random colors to the cells. The grid is represented as a 2D array, and the walls are represented by the outermost cells of the grid. The colors for the non-wall cells are chosen from a predefined list. Your task is...
```python import random class GridGenerator: def __init__(self): self.grid = None self.colors = ['green', 'purple', 'orange'] def generate_grid(self, width, height): self.grid = [['wall' for _ in range(width + 2)] for _ in range(height + 2)] # Initialize grid with walls for i...
magicoder
python
You are tasked with creating a GraphQL mutation resolver for a newsletter subscription feature. The provided code snippet is a partial representation of a GraphQL mutation query. Your task is to complete the mutation query by adding the necessary fields and arguments to implement the subscription functionality. You ne...
```graphql query = """ mutation($email: String!) { subscribeToNewsletter(input: { email: $email }) { success message } } """ ``` In the solution, the `subscribeToNewsletter` mutation is defined with an input object containing the `email` field of type ...
magicoder
graphql
You are working on a software system that manages type descriptions for various data types. The system provides a set of functions to interact with type descriptions and a repository for storing them. Your task is to implement a method that finds the common super type name for two given type descriptions. You are give...
```java public class TypeDescriptionManager { public String getCommonSuperTypeName(ITypeDesc typeDesc1, ITypeDesc typeDesc2) { Class<?> type1 = getTypeClass(typeDesc1); Class<?> type2 = getTypeClass(typeDesc2); if (type1 == null || type2 == null) { return null; } ...
magicoder
java
You are tasked with creating a Python function to manage ban appeals in a Discord bot. The function should check if a user is banned, and if not, create a new ban entry in the database. Additionally, the function should ensure that the appeal guild is set up properly by finding the "appeal-here" channel within the guil...
```python # Complete the checkAppealGuild function async def checkAppealGuild(bot, os): appealguild = bot.get_guild(int(os.getenv('appealguild'))) appealchannel = None for channel in appealguild.channels: if channel.name == "appeal-here": appealchannel = channel break ret...
magicoder
python
You are tasked with creating a Java program that utilizes reflection to analyze and manipulate classes and their members. In this problem, you will be working with a class named `PacketPlayOut` and its subclasses. The `PacketPlayOut` class is an abstract class that serves as a base for various packet classes used in a ...
```java import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class PacketAnalyzer { public static void analyzePacketClass(C...
magicoder
java
You are working on a Django web application that utilizes middleware for processing requests and responses. The middleware is responsible for intercepting and processing HTTP requests before they reach the view, and also for processing the response before it's returned to the client. Your task is to implement a functio...
```python def get_middleware_insertion_point(): """ Returns the attribute name and collection object for the Django middleware. If middleware cannot be found, returns None for the middleware collection. """ # Assuming the Django middleware stack is defined in a settings file # Replace 'settings...
magicoder
python
You are tasked with designing a REST API for an ATM system. The given code snippet is a part of a Django REST framework serializer for creating a new ATM user. The serializer includes fields for card number, password, cash amount, block status, withdrawal amount, and version. Additionally, it contains a `create` method...
```python from yourapp.models import ATMUser, Operation def create_atm_user(validated_data): atmuser = ATMUser.objects.create_user(**validated_data) op = Operation(code=Operation.CARD_CREATED, atmuser=atmuser, cash=atmuser.cash) op.save() return atmuser ``` In the solution, the `create_atm_user` func...
magicoder
python
You are tasked with implementing a training system for a machine learning model. The training process involves optimizing the model's parameters using a given dataset. The `run_training()` function is responsible for orchestrating this process. It is expected to perform the following steps: 1. Load the training dataset...
```python def run_training(): # Step 1: Load the training dataset from a file dataset = load_dataset('training_data.csv') # Step 2: Preprocess the data to prepare it for training preprocessed_data = preprocess_data(dataset) # Step 3: Initialize the machine learning model model = initialize_mod...
magicoder
python
You are tasked with implementing a prioritized experience replay buffer for a reinforcement learning algorithm. The experience replay buffer is a crucial component in training reinforcement learning agents, as it stores and samples experiences for training. In this problem, you will need to implement the `memorize` met...
```python class ExperienceReplayBuffer: def __init__(self, buffer_size, with_per=False): if with_per: self.alpha = 0.5 self.epsilon = 0.01 self.buffer = SumTree(buffer_size) else: self.buffer = deque() self.count = 0 self.with_per = wit...
magicoder
python
You are tasked with implementing a data structure and a method for updating a plot in a scientific visualization application. The data structure is a queue with a maximum size, and the method is responsible for updating a plot with new data points and error bars. Your task is to write a class that encapsulates the queu...
```python from collections import deque import matplotlib.pyplot as plt class PlotUpdater: def __init__(self, maxdata): self.maxdata = maxdata self.queue = deque(maxlen=maxdata) def update_plot(self, plot_id, xdata, ydata, yerr, xlabel, ylabel, title): if len(self.queue) > self.maxdata...
magicoder
python
You are tasked with implementing a function to calculate the area of a 2D polygon given its vertices. The vertices are represented as a list of 2D points in clockwise or counterclockwise order. The area of a polygon can be calculated using the shoelace formula, which involves summing the products of the x-coordinates a...
```python from typing import List, Tuple def calculate_polygon_area(vertices: List[Tuple[float, float]]) -> float: n = len(vertices) area = 0.0 for i in range(n): j = (i + 1) % n area += vertices[i][0] * vertices[j][1] area -= vertices[j][0] * vertices[i][1] return abs(area) / 2...
magicoder
python
You are working on a facial detection algorithm that processes bounding boxes to identify faces in an image. The given code snippet is a part of the algorithm that processes the bounding boxes and extracts relevant information. Your task is to complete the implementation of the facial detection algorithm by writing a f...
```python import numpy as np from typing import List, Union def largest_bounding_box_area(bounding_boxes: np.ndarray, detect_multiple_faces: bool) -> Union[int, List[int]]: areas = (bounding_boxes[:, 2] - bounding_boxes[:, 0]) * (bounding_boxes[:, 3] - bounding_boxes[:, 1]) max_area = np.max(areas) if det...
magicoder
python
You are tasked with creating a function that simulates a simple timer component for a running application. The timer should display the elapsed time in a specific format and update every second. Your task is to implement the `Timer` class with the following requirements: - The `start` method should initiate the timer. ...
```javascript class Timer { constructor() { this.startTime = 0; this.pausedTime = 0; this.isRunning = false; } start() { if (!this.isRunning) { this.startTime = Date.now() - this.pausedTime; this.isRunning = true; this.intervalId = setInterval(() => { // Update UI with t...
magicoder
javascript
You are tasked with creating a Python class that represents a simple banking system. The class should have methods for depositing funds, withdrawing funds, and checking the current balance. Additionally, the class should keep track of the account holder's name and account balance. Create a Python class named `BankAcco...
```python class BankAccount: def __init__(self, account_holder): self._account_holder = account_holder self._balance = 0 def deposit(self, amount): if amount > 0: self._balance += amount else: print("Invalid amount for deposit") def withdraw(self, am...
magicoder
python
You are tasked with implementing a function that generates SQL code for creating a table with a primary key in a PostgreSQL database. The function should handle the specifics of PostgreSQL's primary key implementation, ensuring that the generated SQL code is compatible with PostgreSQL's requirements. Your task is to c...
```php function generateCreateTableSQL($tableName, $columnDefinitions, $primaryKeyColumnName) { $sql = "CREATE TABLE $tableName ("; // Add column definitions foreach ($columnDefinitions as $columnName => $columnType) { $sql .= "$columnName $columnType, "; } // Add primary key const...
magicoder
php
You are tasked with creating a script to automate the process of downloading a dataset and extracting its contents. The dataset is the IMDb movie review dataset, which is available for download as a compressed file from the URL `http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz`. Your script should downloa...
```bash #!/bin/bash echo "Downloading..." # Download the dataset wget --no-check-certificate http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz # Check if download was successful if [ $? -ne 0 ]; then echo "Download failed. Exiting." exit 1 fi echo "unzipping..." # Extract the dataset tar xvf a...
magicoder
shell
You are tasked with creating a script to automate the deployment of a Dockerized API service. The script should remove any existing container for the API, then bring up a new container using Docker Compose. You are provided with the following variables: - `${API_CONTAINER_NAME}`: The name of the existing container for...
```bash #!/bin/bash # Assigning values to variables API_CONTAINER_NAME="your_api_container_name" PROJECT_NAME_API="your_project_name_api" # Removing existing container for the API docker rm "${API_CONTAINER_NAME}" # Bringing up a new container for the API using Docker Compose docker-compose -p "${PROJECT_NAME_API}" ...
magicoder
shell
You are tasked with creating a Python program that interacts with the Twitter API to retrieve and analyze a user's tweets. Your program should take a Twitter username as a command-line argument and then use the Twitter API to fetch the most recent tweets posted by that user. You will then perform some analysis on the r...
```python import twitter import argparse def fetch_user_tweets(username, key, secret, access_key, access_secret): api = twitter.Api(consumer_key=key, consumer_secret=secret, access_token_key=access_key, access_token_secret=access_secret) user_tweets = api.GetUserTimeline(screen_name=username) return user_t...
magicoder
python
You are tasked with implementing a simple event management system in Swift. The system should include a class for managing upcoming events and a protocol for event panel delegates. Your task is to create a Swift class called `UpcomingEventManager` that manages upcoming events and conforms to the `UpcomingEventPanelDel...
```swift // Define the UpcomingEventPanelDelegate protocol protocol UpcomingEventPanelDelegate: AnyObject { func didUpdateEvents() } // Define the UpcomingEvent structure to represent an upcoming event struct UpcomingEvent { let title: String let date: String let location: String } // Define the Upcom...
magicoder
swift
You are tasked with creating a custom hook for handling OAuth errors in a React application. The hook should utilize the `useEffect` hook to parse location parameters and extract any OAuth error codes. If an error code is found, it should be stored in the component's state for further processing. Your task is to imple...
```javascript import { useEffect, useState } from 'react'; import { parse, OAuthError } from 'some-oauth-library'; // Replace 'some-oauth-library' with the actual library name const useOAuthErrorHandling = (locationParams) => { const [errorCode, setErrorCode] = useState(null); useEffect(() => { if (locationPa...
magicoder
javascript
You are tasked with implementing a graph data structure in Rust. The graph will consist of vertices and edges, with each vertex having an identifier and a value. The edges will be directed and weighted, connecting two vertices and carrying a specific weight. Your goal is to create a Rust implementation for this graph d...
```rust use std::collections::HashMap; struct Graph { vertices: HashMap<Id, PValue>, edges: HashMap<(Id, Id), f64>, } impl Graph { fn new() -> Self { Graph { vertices: HashMap::new(), edges: HashMap::new(), } } fn add_vertex(&mut self, id: Id, value: PValue...
magicoder
rust
You are tasked with creating a script to automate the setup of a Microsoft SQL Server database for a chat application. The script should wait for the SQL Server to be available, create a new database named "openfire," and then execute a SQL script to initialize the database schema. The script should also handle potenti...
```bash #!/bin/bash # Wait for SQL Server to be available /scripts/wait-for-it.sh 127.0.0.1:1433 # Create database and initialize schema for i in {1..3}; do /opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P $SA_PASSWORD -d master -Q "CREATE DATABASE openfire;" if [ $? -eq 0 ]; then /opt/mssql-tools/bi...
magicoder
shell
You are tasked with creating a Python function that interacts with an external search service using the `search_by_query` function from the `algolia` module. The `search_by_query` function takes two arguments: a query string and a list of filters. It returns a list of search results based on the query and filters provi...
```python from typing import List, Dict, Any def process_search_results(query: str, filter: str) -> List[str]: search_results = search_by_query(query, [filter]) processed_results = [] for result in search_results: if filter in result['category']: processed_results.append(f"{result['titl...
magicoder
python
You are tasked with implementing a simple text formatting system. The system should support the following formatting options: bold, italic, and underline. The input text will contain special characters to denote the formatting, and your task is to process the input and produce the formatted text. The input will consis...
```python def format_text(input_text): stack = [] formatted_text = "" i = 0 while i < len(input_text): if input_text[i:i+3] == "<B>": stack.append("B") i += 3 elif input_text[i:i+4] == "</B>": stack.pop() i += 4 elif input_text[i:i+...
magicoder
python
You are tasked with creating a program that validates email addresses using regular expressions. An email address is considered valid if it follows the standard format of local-part@domain. The local-part can contain alphanumeric characters, dots, hyphens, and underscores. The domain can contain alphanumeric characters...
```python import re def validate_email(email): regex = r'^[\w.-]+@[a-zA-Z0-9-]+\.[a-zA-Z]{2,4}$' return bool(re.match(regex, email)) # Test cases print(validate_email("john.doe@example.com")) # Output: True print(validate_email("alice_123@google-mail.com")) # Output: True print(validate_email("john.doe@exam...
magicoder
python
You are tasked with implementing a memory management system for a virtual machine. The system should support reading and writing operations, as well as provide information about the memory configuration. You are given a partial code snippet for a `MemoryManager` class in C#. The class has a constructor and an overridd...
```csharp public class MemoryManager { public string Name { get; set; } public long Size { get; set; } public int WordSize { get; set; } public string EndianType { get; set; } public bool Writable { get; set; } public MemoryManager(string name, long size, int wordSize, string endianType, bool w...
magicoder
csharp
You are tasked with implementing a performance monitoring middleware for a Sanic web application. The middleware should calculate the time taken to execute each request and add this information as a custom header to the response. You are provided with a code snippet that defines the `add_performance_header` function, ...
```python import time from sanic import Sanic from sanic.response import text def add_performance_header(sanic_app): """ Add a header to sanic responses that contains the number of seconds it took to execute the request. """ async def request(req): start_time = time.time() # Record the sta...
magicoder
python
You are tasked with implementing a TypeScript function that parses a given code snippet and extracts the namespaces and types defined within it. The code snippet is a TypeScript declaration file containing JSDoc comments. You need to create a function `parseCodeSnippet(code: string): { namespaces: string[], types: str...
```typescript function parseCodeSnippet(code: string): { namespaces: string[], types: string[] } { const namespaces: string[] = []; const types: string[] = []; const regexNamespace = /@namespace\s+([\w.]+)/g; const regexType = /@docid\s*\n\s*@type\s+([\w]+)/g; let match; while ((match = regexNamespace.exe...
magicoder
typescript
You are tasked with implementing a PHP class method that checks if a given ability is authorized for a specific class and attribute based on the provided arguments. The method should adhere to the following requirements: You are given a code snippet representing the beginning of a PHP class. The class has the followin...
```php public function authorize(): bool { // Implementing the authorization logic based on the provided arguments // Example logic (replace with actual authorization logic): // Check if the $ability is authorized for the $className and $attribute based on the $guard // Return true if authorized, false ...
magicoder
php
You are tasked with implementing a C++ class that manages a command queue for a DirectX 12 (DX12) graphics engine. The provided code snippet is the beginning of the declaration of the `DX12CommandQueue` class, which is a subclass of `ICommandQueue`. Your task is to complete the implementation of the `DX12CommandQueue` ...
```cpp #include "graphics/DX12CommandQueue.hpp" DX12CommandQueue::DX12CommandQueue(ID3D12Device* device, D3D12_COMMAND_LIST_TYPE type) : mFenceValue(0), mCommandListType(type) { D3D12_COMMAND_QUEUE_DESC queueDesc = {}; queueDesc.Type = type; queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; queueDes...
magicoder
cpp
You are tasked with creating a Python program that analyzes a given directory and its subdirectories to find all Python files and count the occurrences of specific keywords within those files. The keywords to be counted are provided in a list. Your program should output the total count of each keyword found in all the ...
```python import os import re def count_keywords_in_files(directory, keywords): keyword_counts = {keyword: 0 for keyword in keywords} for root, _, files in os.walk(directory): for file in files: if file.endswith('.py'): file_path = os.path.join(root, file) w...
magicoder
python
You are tasked with implementing a Java interface for a car park management system. The interface, `MeterDAO`, provides methods for managing parking meters and their schedules. The `ScheduleItem` class represents a scheduled event for a parking meter. Your task is to implement the `MeterDAO` interface with the followi...
```java import java.util.ArrayList; import java.util.List; public class MeterDAOImpl implements MeterDAO { private List<ScheduleItem> scheduleItems; public MeterDAOImpl() { this.scheduleItems = new ArrayList<>(); } @Override public void createMeter(ScheduleItem entity) { scheduleI...
magicoder
java
You are tasked with creating a custom assertion function for testing React components using the Jest testing framework. The function should validate whether a given element has a specific combination of CSS classes applied to it. You are required to implement the `toHaveClass` custom assertion function and use it to te...
```javascript // Custom assertion function to test if an element has the expected CSS classes expect.extend({ toHaveClass(element, expectedClasses) { const classes = element.getAttribute('class'); const pass = classes.split(' ').some(className => expectedClasses.split(' ').includes(className)); if (pass) ...
magicoder
javascript
You are tasked with implementing a color utility function that converts color values from various formats to a standardized RGB format. The function should support the conversion of color values from hexadecimal, RGB, and named color formats to RGB format. Write a function `convertToRGB` that takes a color value as a ...
```javascript const defaultColors = { primary: '#083d8c', secondary: '#666ea0', success: '#42a53b', critical: 'rgb(213, 32, 26)', neutral: 'rgb(144, 144, 144)', }; function convertToRGB(color) { if (color.startsWith('#')) { const r = parseInt(color.slice(1, 3), 16); const g = parseInt(color.slice(3...
magicoder
javascript
You are given a list of strings representing file paths and directories. Your task is to write a function to process these paths and return a set of unique directory paths. You are to implement the following function: ```python def unique_directories(suffixes: List[str]) -> Set[str]: pass ``` **Input:** - `suff...
```python from typing import List, Set def unique_directories(suffixes: List[str]) -> Set[str]: retval = set({}) for s in suffixes: if s.endswith('/'): retval.add(s[:-1]) else: retval.add(s) return retval ``` The `unique_directories` function iterates through the inp...
magicoder
python
You are tasked with implementing a function that handles the click event on an icon. The function should toggle the visibility of a password input field and emit a custom event for non-password input fields. You are provided with a code snippet that partially implements this functionality. Your task is to complete the ...
```typescript const handleIcon = (e: MouseEvent, props: { password: boolean }, inputType: { value: string }, emit: (event: string, payload: MouseEvent) => void) => { if (props.password) { inputType.value = inputType.value === "password" ? "text" : "password"; } else { emit("on-click-icon", e); } }; ``` I...
magicoder
typescript
You are tasked with implementing a parallel processing system for evaluating machine learning models on multiple datasets with varying parameters. The provided code snippet is a simplified version of the parallel processing logic. Your task is to design a function that can efficiently distribute the workload across mul...
```python import multiprocessing import queue def worker_function(task_queue, result_queue): while True: try: task = task_queue.get_nowait() # Execute the task and put the result in the result queue result = execute_task(task) result_queue.put(result) ...
magicoder
python
You are tasked with creating a script to automate the process of managing user accounts on a Linux system. The script should check the output of a command and take action based on the presence of a specific message. Your script should monitor the output of a command and, if the output contains the message "Created ne...
```bash #!/bin/bash # Function to perform specific action perform_action() { # Add your specific action here echo "Performing specific action" } # Main script while true; do output=$(your_command_here) # Replace with the command whose output needs to be monitored if [[ "$output" == *"Created new acco...
magicoder
shell
You are tasked with implementing a function that performs a specific type of array manipulation. The function takes an input array `x` and an integer `flipping_axis`, and then applies a series of operations to the array based on the flipping axis. The operations involve swapping axes and reversing the order of elements...
```python import numpy as np def flip_axis_fra(x, flipping_axis): pattern = [flipping_axis] pattern += [el for el in range(x.ndim) if el != flipping_axis] inv_pattern = [pattern.index(el) for el in range(x.ndim)] x = np.asarray(x).swapaxes(flipping_axis, 0) # Swap flipping axis with the first axis ...
magicoder
python
You are given a list of tasks and their dependencies in the form of a directed acyclic graph (DAG). Each task has a unique identifier, and the dependencies are represented as directed edges between tasks. Additionally, each edge is associated with a weight representing the time it takes to complete the dependency. You...
```python from typing import List, Tuple from collections import defaultdict def min_completion_time(tasks: List[str], dependencies: List[Tuple[str, str, int]]) -> int: graph = defaultdict(list) in_degree = {task: 0 for task in tasks} time_taken = {task: 0 for task in tasks} for dependency in dependen...
magicoder
python
You are working on a project that involves analyzing trajectory data from ocean drifters. The code snippet provided is a part of a Python script that imports a module called `ACC_tools` and sets the directory for trajectory data and the number of days for the analysis. The `experiment_files` dictionary is expected to c...
```python import os import pandas as pd def calculate_average_velocity(trajdir, tdays): total_displacement = 0 total_time = 0 # Iterate through files in the directory for filename in os.listdir(trajdir): if filename.endswith(".csv"): # Assuming trajectory data is stored in CSV files ...
magicoder
python
You are tasked with creating a Python function that reads a text file, splits its content into words, and then returns the unique words in a sorted list. The function should take the file path as input and handle any potential file-related errors. You are given the following code snippet as a starting point: ```python...
```python def load_split_word(file_path): try: with open(file_path, 'r') as file: content = file.read() words = content.split() unique_words = sorted(set(words)) return unique_words except FileNotFoundError: print(f"File '{file_path}' not found.") ...
magicoder
python
You are tasked with implementing a function that processes a binary file's section headers. The function should calculate the total size of the section headers and return it. You are provided with a class `SectHdrsWrapper` that encapsulates the logic for accessing the section headers of a Portable Executable (PE) file....
```cpp bufsize_t SectHdrsWrapper::getSize() { if (this->m_PE == nullptr) return 0; size_t secCount = getFieldsCount(); offset_t hdrOffset = m_PE->secHdrsOffset(); offset_t fileSize = m_PE->getRawSize(); offset_t endOffset = hdrOffset + (secCount * sizeof(IMAGE_SECTION_HEADER)); if (endOffset ...
magicoder
cpp
You are tasked with creating a Python function that simulates a custom range function. The function should take in one, two, or three integer arguments and behave similarly to Python's built-in `range` function. The function should support the following argument combinations: 1. `range(stop)`: Generate a sequence of nu...
```python def custom_range(*args) -> list: num_args = len(args) if num_args == 1: return list(range(args[0])) elif num_args == 2: return list(range(args[0], args[1])) elif num_args == 3: return list(range(args[0], args[1], args[2])) else: raise ValueError("Invalid num...
magicoder
python
You are tasked with creating a SQL query to analyze job run data that includes information about job runs and associated crashes. The provided code snippet is a part of a larger SQL query and demonstrates the use of a common table expression (CTE) to aggregate crash data for each job run. Your task is to complete the ...
```sql WITH JobRunWithConcatedCrashes AS ( SELECT job_runs.id AS job_run_id, job_runs.start_time, job_runs.end_time, ARRAY_CONCAT_AGG(crashes.crash_type) AS aggregated_crashes FROM job_runs LEFT JOIN crashes ON job_runs.id = crashes.job_run_id GROUP BY job_runs.id, job_runs.start_time, job_runs....
magicoder
sql
You are tasked with creating a time processing function for a scheduling application. The function should take a start time, a duration, and a list of days as input and return the end time after processing the duration. The start time is given in the format "HH:MM AM/PM", the duration is given in the format "HH:MM", an...
```python def process_time(start_time, duration, days): # Split the start time into hours, minutes, and period (AM/PM) start_hour, start_minute = [int(t) for t in start_time.split(':')] start_minute, period = start_minute.split() start_hour = int(start_hour) start_minute = int(start_minute) # S...
magicoder
python
You are tasked with creating a program to manage image resizing using a custom `ImageWand` class. The `ImageWand` class represents an image and provides functionality for resizing and checking image properties. Your task is to implement the `resize` method, which takes a file name and type as input, opens the image fil...
```swift class ImageWand { var data: Data? var size: Size init(data: Data?, size: Size) { self.data = data self.size = size } } struct Size { var width: Int var height: Int } class ImageManager { private func open(file: String, ofType type: String) -> ImageWand? { ...
magicoder
swift
You are tasked with implementing a password management system for a web application. The system should include functions for checking the validity of a password and encrypting a password for storage. You are provided with the following code snippet: ```python from app.helpers import check_password, encrypt_password ``...
```python # Import necessary libraries for encryption import hashlib import os def check_password(input_password, stored_password): # Split the stored password into its components salt, hashed_password = stored_password.split('$') # Hash the input password using the stored salt input_hashed_passwo...
magicoder
python
You are tasked with implementing a thread-safe conversation ID factory in C#. The factory should generate unique conversation IDs for each conversation and ensure that the IDs are stored and accessed in a thread-safe manner. You are provided with a partial implementation of the `SkillConversationIdFactory` class, whic...
```csharp using System; using System.Collections.Concurrent; public class SkillConversationIdFactory : SkillConversationIdFactoryBase { private readonly ConcurrentDictionary<string, string> _conversationRefs = new ConcurrentDictionary<string, string>(); public string GenerateConversationId(string reference) ...
magicoder
csharp
You are tasked with creating a Unity script that dynamically loads different scenes based on user input. The script should allow for the switching of scenes within a mixed reality application. Your task is to complete the implementation of the `SceneChanger` class by adding a method that will load a specified scene whe...
```csharp using Microsoft.MixedReality.Toolkit.SceneSystem; using UnityEngine; using UnityEngine.SceneManagement; namespace HoloLensCameraSample { /// <summary> /// コンテンツシーンを変更するためのクラス /// </summary> public sealed class SceneChanger : MonoBehaviour { IMixedRealitySceneSystem sceneSystem; ...
magicoder
csharp
You are tasked with implementing a simplified version of the Griffin-Lim algorithm, which is commonly used in audio signal processing for phase retrieval. The Griffin-Lim algorithm aims to reconstruct a complex-valued signal from its magnitude spectrogram by iteratively updating the phase of the signal. In this problem...
```python from typing import List import numpy as np def griffin_lim(magnitude: List[float], iterations: int) -> List[complex]: # Initialize the phase of the complex-valued signal randomly phase = np.exp(2j * np.pi * np.random.rand(len(magnitude))) for _ in range(iterations): # Compute the complex...
magicoder
python
You are tasked with implementing a function to parse CPU information from a file and extract specific features. The CPU information is stored in a file named "/proc/cpuinfo" in a specific format. The function should read this file, extract the required features, and return them as a data structure. You are given a par...
```cpp CpuFeatures ParseCpuInfo() { CpuFeatures cpuFeatures; cpuFeatures.smp = false; cpuFeatures.isA53 = false; std::ifstream cpuInfoFile("/proc/cpuinfo"); if (cpuInfoFile.is_open()) { std::string line; while (std::getline(cpuInfoFile, line)) { if (line.find("processor") != std::string::npos) ...
magicoder
cpp
You are tasked with implementing a function that calculates the total area of rectangles in a given list. Each rectangle is represented by an object with the following properties: `x`, `y`, `width`, and `height`. The function should return the sum of the areas of all the rectangles in the list. Function Signature: `fu...
```javascript function calculateTotalArea(rectangles) { let totalArea = 0; for (let i = 0; i < rectangles.length; i++) { const { width, height } = rectangles[i]; totalArea += width * height; } return totalArea; } // Test const rectangles = [{x: 1, y: 2, width: 3, height: 4}, {x: 2, y: 3, width: 5, heig...
magicoder
javascript
You are given a directed graph and a starting vertex. Your task is to find the lexicographically smallest Eulerian path in the graph, ensuring that a solution exists. An Eulerian path is a path in a graph that visits every edge exactly once. The lexicographically smallest path is the one that, when represented as a se...
```python def findLexicographicallySmallestEulerianPath(graph, start): def dfs(node): while graph[node]: next_node = graph[node].pop(0) dfs(next_node) path.append(node) path = [] dfs(start) return path[::-1] ``` The `findLexicographicallySmallestEulerianPath` fu...
magicoder
python
You are tasked with creating a Python class that manages button signals in a GUI application. The class should handle the connections between various buttons and their corresponding signals. Your task is to implement the `ButtonManager` class with the following requirements: - The `ButtonManager` class should have a m...
```python from PyQt5.QtCore import QObject, pyqtSignal class ButtonManager: def __init__(self): self.button_signal_map = {} def connect_button_signal(self, button, signal): if not isinstance(button, QObject) or not isinstance(signal, pyqtSignal): raise ValueError("Invalid button or...
magicoder
python
You are tasked with implementing a custom version of the RandomUnderSampler class for imbalanced learning. The custom version will only accept a dictionary for the ratio argument and will support float values indicating the proportional sampling. You need to create a Python class, CustomRandomUnderSampler, with the fo...
```python from collections import defaultdict import random class CustomRandomUnderSampler: def __init__(self, ratio): self.ratio = ratio def perform_sampling(self, dataset): undersampled_data = [] class_counts = defaultdict(int) for data_point in dataset: ...
magicoder
python
You are tasked with implementing a function that creates an action sheet with customizable options in a Swift iOS app. The function `openActionSheet` takes in various parameters to customize the action sheet, including the title, message, option titles, selection status, and corresponding actions for each option. The ...
```swift func openActionSheet(title: String, message: String, firstTitle: String, secondTitle: String?, thirdTitle: String?, firstSelected: Bool, secondSelected: Bool, thirdSelected: Bool, firstAction: (()->())?, secondAction: (()->())?, thirdAction: (()->())?) { let actionSheetController = UIAlertController(title:...
magicoder
swift
You are tasked with implementing a function that converts a string representation of a number with a unit suffix (K, M, G, T) into its corresponding integer value. The function should handle cases where the input string may contain a unit suffix, and it should return the integer value after applying the appropriate con...
```python def convert_with_unit(stripped: str, conv_factor: dict) -> int: try: return int(stripped) except ValueError: if stripped[-1] in conv_factor: return int(int(stripped[:-1]) * conv_factor[stripped[-1]]) else: raise ValueError(f"Invalid unit {stripped[-1]}")...
magicoder
python
You are tasked with implementing a function that processes a given result and returns a formatted character object. The function should take the result as input and return a `Character` object with specific attributes populated from the input result. The `Character` class has the following attributes: - `id`: The ID o...
```python from typing import Optional from epicteller.core.util import ObjectDict from epicteller.core.util.enum import ExternalType from epicteller.core.util.seq import get_id class Character: def __init__(self, id, url_token, member_id, name, avatar, description): self.id = id self.url_token = ur...
magicoder
python
You are tasked with implementing a custom permission class for a Django REST framework view. The permission class should check if the user has a specific permission based on the action being performed on a model. The given code snippet provides a starting point for the permission class. It uses the `permissions` dicti...
```python from rest_framework.permissions import BasePermission from django.contrib.auth.models import get_permission_codename class StorageHasPermission(BasePermission): def has_permission(self, request, view): permissions = { 'view': 'view_storage', 'add': 'add_storage', ...
magicoder
python
You are tasked with creating a Python function that extracts and returns the author's name, email, and date from a given code snippet. The code snippet will always follow the format shown below: ```python __author__ = '<NAME>' __email__ = '<EMAIL>' __date__ = '<DATE>' ``` Your function should take the code snippet as...
```python import re def extract_metadata(code_snippet: str) -> dict or None: author_match = re.search(r'__author__ = \'(.*?)\'', code_snippet) email_match = re.search(r'__email__ = \'(.*?)\'', code_snippet) date_match = re.search(r'__date__ = \'(.*?)\'', code_snippet) if author_match and email_match a...
magicoder
python
You are working on a computer vision project and need to implement a function to create staggered quads based on certain criteria. The function `make_staggered_quads` takes in a grayscale image `gt`, a binary mask `gt_hist` derived from the histogram of `gt`, and two integer parameters `quad_size` and `step_size`. The ...
```python import numpy as np from typing import List, Tuple def make_staggered_quads(gt: np.ndarray, gt_hist: np.ndarray, quad_size: int, step_size: int) -> List[Tuple[int, int, int, int]]: non_empty_quads = [] height, width = gt.shape for y in range(0, height - quad_size + 1, step_size): for x in ...
magicoder
python
You are tasked with implementing a job scheduling system that manages the execution of tasks based on a given schedule and maintains the state of all jobs in progress. The system consists of two main components: Scheduler and Registry. The Scheduler is responsible for initializing from schedule data pulled by Schedule...
```python class ScheduleFinder: def pull_schedule_data(self): # Implementation to pull schedule data from a data source pass class Scheduler: def __init__(self, schedule_data): self.schedule_data = schedule_data def should_run_task(self, task, argument): # Check if the task...
magicoder
python
You are tasked with creating a script to automate the download and verification of software packages. Your script should download a package from a specified URL, retrieve its checksum from another URL, and then verify the integrity of the downloaded package by comparing its checksum with the expected value. Your scrip...
```bash #!/bin/bash # Define the URLs and file paths download_url="https://example.com/package.tar.gz" checksum_url="https://example.com/package_checksum.txt" kanister_sum_file="package_checksum.txt" KANISTER_TMP_FILE="package.tar.gz" KANISTER_TMP_ROOT="/tmp" # Step 1: Print a message indicating the start of the down...
magicoder
shell
You are given a list of South American and Central American countries, along with French Guiana, in no particular order. Your task is to write a program that sorts the countries in alphabetical order and groups them by the first letter of each country. Additionally, you need to count the number of countries that start ...
```python # Given list of countries countries = [ "Bolivia", "Brazil", "Chile", "Colombia", "Ecuador", "French Guiana", "Guyana", "Paraguay", "Peru", "Suriname", "Uruguay", "Venezuela", "Belize", "Costa Rica" ] # Create a dictionary to store countries grouped by the first letter country_groups = {} # Sort...
magicoder
python
You are tasked with creating a Django migration for a human resources management system. The system has two models: `Position` and `Department`. The `Position` model represents job positions, while the `Department` model represents organizational departments. The `Department` model uses the `django-mptt` library to imp...
```python from django.db import migrations, models import mptt.fields import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('yourappname', 'previous_migration_number'), # Replace 'yourappname' and 'previous_migration_number' with actual values ] operations = [...
magicoder
python
You are tasked with implementing a method for extrapolating data in a spreadsheet. The method `TryExtrapolate` takes in several parameters: `cell`, `currentCell`, `selectionCell`, `autoFillRef`, and an `out` parameter `result`. The method should extrapolate the value of the `cell` based on the values of neighboring cel...
```csharp public bool TryExtrapolate( CellRef cell, CellRef currentCell, CellRef selectionCell, CellRef autoFillRef, out object result) { int selMinRow = Math.Min(currentCell.Row, selectionCell.Row); int selMaxRow = Math.Max(currentCell.Row, selectionCell.Row); int selMinCol = Math.Min(currentCell.Colum...
magicoder
csharp
You are tasked with creating a Python class that processes and analyzes data from an agent's last run. The class should have a method that deserializes a summary file and returns a nested dictionary object with the deserialized data and statistics. If the method is unable to retrieve or deserialize the summary data, it...
```python import yaml class AgentAnalyzer: def __init__(self, summary_file): self.summary_file = summary_file def process_summary(self): run_summary = None try: with open(self.summary_file, 'r') as summary_file: run_summary = yaml.safe_load(summary_file) ...
magicoder
python
You are tasked with implementing a Python class to generate Pascal's triangle. Pascal's triangle is a triangular array of binomial coefficients, where each number is the sum of the two directly above it. The first few rows of Pascal's triangle look like this: ``` 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 ``` Your task is...
```python class Solution: def generate(self, num_rows: int) -> List[List[int]]: if num_rows == 0: return [] elif num_rows == 1: return [[1]] result = [[1]] for i in range(1, num_rows): prev_row = result[-1] new_row = [1] fo...
magicoder
python
You are tasked with implementing a custom navigation system for a mobile application. The provided code snippet is a part of a custom navigation controller class, which includes a method for dismissing view controllers to the root view controller. The `dismissToRoot` method is intended to dismiss all the presented vie...
```swift func dismissToRoot(animated: Bool = true, completion: Completion?) { guard let rootViewController = viewControllers.first else { assertionFailure("Root View Controller is missing") return completion?() ?? () } if let presented = presentedViewController { presented.dismi...
magicoder
swift
You are tasked with developing a video processing pipeline using the Bitmovin API. The provided code snippet initializes various configurations and inputs for the video processing. Your task is to complete the code by adding the necessary components to create a video encoding configuration and output settings. Given t...
```python # Import necessary classes and methods from bitmovin.resources.models import H264CodecConfiguration, AACCodecConfiguration, S3Output, Encoding, Stream, EncodingOutput, H264Profile from bitmovin.resources import SelectionMode, StreamInput from bitmovin import Bitmovin, BitmovinApiLogger, BitmovinApiLoggerConfi...
magicoder
python
You are tasked with creating a Python coroutine that interacts with a PostgreSQL database using the `aiopg` library. Your coroutine should perform the following tasks: 1. Establish a connection pool to the PostgreSQL database using `aiopg.create_pool`. 2. Use a cursor from the connection pool to execute a SQL query tha...
```python import aiopg async def fetch_data(dsn): async with aiopg.create_pool(dsn) as pool: async with pool.acquire() as conn: async with conn.cursor() as cur: await cur.execute("SELECT 1") ret = await cur.fetchone() return ret[0] if ret else Non...
magicoder
python
You are tasked with creating a Python function that parses a given source code file and extracts the copyright information from it. The copyright information is typically found within comments at the beginning of the file and follows a specific format. The function should return the name of the author(s) and the licens...
```python import re def extract_copyright_info(file_path): with open(file_path, 'r') as file: first_line = file.readline() if re.match(r'# Copyright \d+ (.+)', first_line): author_match = re.search(r'Copyright \d+ (.+)', first_line) author = author_match.group(1).strip() ...
magicoder
python
You are tasked with creating a Python package management system that can handle the installation and removal of packages. Your system should support adding new packages, removing existing packages, and displaying the list of installed packages. To achieve this, you need to implement a class `PackageManager` with the fo...
```python class PackageManager: def __init__(self): self.installed_packages = set() def add_package(self, package_name): if package_name not in self.installed_packages: self.installed_packages.add(package_name) def remove_package(self, package_name): if package_name in ...
magicoder
python
You are tasked with implementing a DNA storage system in Rust. The system will store DNA definitions and provide methods for managing and accessing these definitions. The provided code snippet includes a partial implementation of the `DnaDefBuf` struct and the `DnaStore` trait for the real DNA store. Your task is to c...
```rust // Define the DnaDef type representing the definition of a DNA sequence pub struct DnaDef { // Define the fields of the DnaDef type as per the requirements // For example: // name: String, // sequence: String, } // Implement the missing methods for the DnaDefBuf struct to manage DNA definitions...
magicoder
rust
You are tasked with implementing a Python function that generates a header file for a C++ program. The header file should contain forward declarations for certain types based on specific conditions. You are given a code snippet that includes a function for determining if a type needs a forward declaration and a functio...
```python def needsForwardDeclaration(type): return isInterfaceType(type) or (type.kind == 'native' and type.specialtype is None) def getTypes(classes, map={}): # Implementation of getTypes function is not provided pass def generateHeaderFile(classes): forward_declarations = set() types = getTypes...
magicoder
python
You are tasked with creating a Python function that processes a given string containing code snippets and extracts information about the imported modules. The function should return a dictionary where the keys are the imported module names and the values are lists of the functions or classes imported from each module. ...
```python import ast def extract_imported_modules(code: str) -> dict: imported_modules = {} tree = ast.parse(code) for node in ast.walk(tree): if isinstance(node, ast.Import): for alias in node.names: imported_modules[alias.name] = [] elif isinstance(node, ast.I...
magicoder
python