query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with creating a Python function that parses a configuration dictionary and returns a `Config` object. The `Config` object should contain specific attributes based on the keys and values in the input dictionary. If a key is missing or its value is `None`, default values should be used. Additionally, the f...
```python from enum import Enum from pathlib import Path class GitProvider(Enum): # Define GitProvider enum values here if needed pass class Config: def __init__(self, token, directory=Path("./"), host=None, owners=None, repos=None): self.token = token self.directory = directory se...
magicoder
python
You are tasked with creating a Rust function that simulates the decoding of a file to obtain a movie object using the Android Graphics Movie API. The function `decodeFile` takes an environment reference `__jni_env` and a file path `arg0` as input and returns a result containing either a movie object or an error. The fu...
```rust /// Simulates the decoding of a file to obtain a movie object using the Android Graphics Movie API. /// /// # Arguments /// /// * `env` - Reference to the JNI environment /// * `file_path` - Path to the file to be decoded /// /// # Returns /// /// * `Result` containing either a movie object or an error /// /// ...
magicoder
rust
You are tasked with implementing a Python function that emulates the behavior of the `scatter_nd` function from TensorFlow in PyTorch. The `scatter_nd` function takes three parameters: `indices`, `updates`, and `shape`. The `indices` parameter is a tensor containing the indices at which the `updates` tensor will be sca...
```python import torch def scatter_nd(indices, updates, shape): output = torch.zeros(shape, dtype=updates.dtype) indices = indices.unsqueeze(-1).expand(-1, *updates.shape[1:]) output.scatter_(0, indices, updates) return output ```
magicoder
python
You are tasked with implementing a GitHub action that enforces a rule allowing only organization members and collaborators to approve certain actions. The provided code snippet is part of the implementation and contains relevant context information and initial processing steps. Your task is to complete the implementat...
```typescript // Function to check if the commenter is an organization member or a collaborator function checkPermission(commenterLogin: string): boolean { // Implement logic to check if the commenter is an organization member or a collaborator // Example: Assuming orgMembers and collaborators are arrays containing...
magicoder
typescript
You are tasked with implementing a logging system for a Python application. The application has a function `load_infrastructure` that is responsible for loading various infrastructure modules using entry points. The function uses the `logging` module to create a logger named "karp" and logs information about the loaded...
```python import logging from pkg_resources import entry_points def load_infrastructure(): logger = logging.getLogger("karp") logger.setLevel(logging.INFO) # Create a file handler and set its formatter file_handler = logging.FileHandler("infrastructure.log") formatter = logging.Formatter('%(as...
magicoder
python
You are tasked with implementing a cache system for storing and retrieving topological metadata in a containerized environment. The provided code snippet is a Java class `BasicContainer` that extends a `Container` and includes a static `TopoMetaLRUCache` instance called `TOPO_META_CACHE`. Your task is to design and im...
```java import java.util.LinkedHashMap; import java.util.Map; public class TopoMetaLRUCache<K, V> { private final int capacity; private final LinkedHashMap<K, V> cache; public TopoMetaLRUCache(int capacity) { this.capacity = capacity; this.cache = new LinkedHashMap<>(capacity, 0.75f, true)...
magicoder
java
You are working on a web application that visualizes performance metrics for a machine learning model. The code snippet provided is a part of the application's frontend logic written in Rust using the Pinwheel and Tangram UI libraries. The `main` function initializes the application and sets up event listeners for two ...
```rust fn update_line_charts(date_window: &str, class: &str) { // Assuming the existence of functions to fetch and update the data for the line charts let precision_data = fetch_precision_data(date_window, class); let recall_data = fetch_recall_data(date_window, class); let f1_data = fetch_f1_data(date...
magicoder
rust
You are tasked with implementing a constraint propagation algorithm for a scheduling problem. The code snippet provided demonstrates the usage of the algorithm and the expected output. The `domains` vector contains pairs of DataType objects representing the minimum and maximum values for each domain. The Scheduler clas...
```cpp #include <vector> #include <utility> struct DataType { int value; // Constructor and other methods are omitted for brevity }; class Scheduler { public: Scheduler(const std::vector<std::pair<DataType, DataType>>& domains, const Product* product) : domains_(domains), product_(product) {} const std::vecto...
magicoder
cpp
You are tasked with creating a function that parses a TypeScript interface and extracts the names of all the properties defined within it. The function should return an array of property names in the order they appear in the interface. Write a function `extractPropertyNames` that takes a string representing a TypeScri...
```typescript function extractPropertyNames(interfaceString: string): string[] { const propertyRegex = /(\w+)(?=:)/g; const matches = interfaceString.match(propertyRegex); return matches ? matches : []; } // Test the function const interfaceString = ` interface Props { controlPanel?: React.ReactNode; ...
magicoder
typescript
You are tasked with implementing a Vector class in Python that supports basic operations such as indexing, length retrieval, and multiplication by another Vector or a scalar. Your task is to complete the implementation of the Vector class by adding the following methods: 1. `__getitem__(self, index: int) -> int`: This...
```python from typing import Union class Vector: def __init__(self, vector_tuple: tuple): self.__vector_tuple = vector_tuple def __getitem__(self, index: int) -> int: return self.__vector_tuple[index] def __len__(self) -> int: return len(self.__vector_tuple) def __mul__(s...
magicoder
python
You are tasked with implementing a packet management system for a network simulation. The system should handle the creation, transmission, and reception of packets between network nodes. Each packet has a unique identifier and a time-to-live (TTL) value, indicating the maximum number of network hops it can traverse bef...
```java import java.util.UUID; class Packet { private UUID identifier; private int timeToLive; private long creationTime; public Packet(UUID identifier, int timeToLive) { this.identifier = identifier; this.timeToLive = timeToLive; this.creationTime = System.currentTimeMillis();...
magicoder
java
You are tasked with implementing a message repository class that utilizes Doctrine ORM for managing message entities. The provided code snippet is part of a test case setup for the message repository class. Your task is to complete the implementation of the message repository class and ensure that it correctly interact...
```php use Doctrine\ORM\EntityRepository; use Doctrine\ORM\Mapping\Driver\AnnotationDriver; use Doctrine\Common\Annotations\AnnotationReader; class MessageRepository extends EntityRepository { public function __construct($entityManager) { $reader = new AnnotationReader(); $metadataDriver = new ...
magicoder
php
You are tasked with creating a Python function that generates a parameter file for a spectroscopic analysis tool called MOOG. The function should allow the user to customize various parameters and optionally display the parameter file on the screen. Your task is to implement the `param_file` function according to the f...
```python def param_file(linelist, atmosphere=0, molecules=1, lines=0, flux=0, damp=0, plot=0, units=0, verbose=False): param_file_content = f"{linelist}\n" param_file_content += f"atmosphere {atmosphere}\n" param_file_content += f"molecules {molecules}\n" param_file_content += f"lines ...
magicoder
python
You are tasked with implementing a method for updating a record in a database using a PHP class. The method should take in the record ID, an array of updates, an array of key-value pairs for a specific field, and a boolean flag for whether to publish the changes. Your task is to write a PHP method that accomplishes thi...
```php public function updateRecord($id, $updates, $qnaPairs, $publish) { // Assuming $this refers to the database class instance // Step 1: Update the record with the given ID in the database $record = $this->findRecordById($id); // Assuming a method to find the record by ID if ($record) { // ...
magicoder
php
You are tasked with creating a Python function that removes all lines containing a specific string from a given file. Your function should take two parameters: the string to be removed and the file name. The function should open the file, remove the lines containing the specified string, and save the modified content b...
```python def remove_lines_with_string(string: str, file: str) -> None: with open(file, 'r') as input_file: lines = input_file.readlines() with open(file, 'w') as output_file: for line in lines: if string not in line: output_file.write(line) ``` The `remove_lines_wi...
magicoder
python
You are tasked with creating a Python function that calculates the topocentric distance between an observer on Earth and a celestial object, given the observer's location and the celestial object's coordinates. The function should take into account the observer's latitude, longitude, and the celestial object's right as...
```python import math def calculate_topocentric_distance(observer_lat, observer_lon, celestial_ra, celestial_dec): observer_lat_rad = math.radians(observer_lat) celestial_dec_rad = math.radians(celestial_dec) celestial_ra_rad = math.radians(celestial_ra) observer_lon_rad = math.radians(observer_lon) ...
magicoder
python
You are tasked with implementing a function that converts a given Metal texture (MTLTexture) to a Core Graphics image (CGImage) in a Swift environment. The function should take the Metal texture and a completion block as input and return the corresponding Core Graphics image. The function signature is as follows: ```s...
```swift import Metal import CoreGraphics func convertMTLTextureToCGImage( _ texture: MTLTexture, completionBlock: (CGImage) -> Void ) -> CGImage { let bytesPerPixel: Int = 4 let bytesPerRow: Int = bytesPerPixel * texture.width let byteCount: Int = bytesPerRow * texture.height var pixelData = ...
magicoder
swift
You are tasked with implementing a memory management system for a custom deployment scheduler. The scheduler is responsible for allocating and deallocating resources for various deployments. However, the system has a strict requirement that no garbage collection (GC) should be performed during the deployment process. T...
```python class DeploymentManager: def __init__(self, scheduler): self.scheduler = scheduler self.memory_pool = {} # Dictionary to track allocated memory for deployments def allocate_memory(self, deployment_id, memory_size): # Allocate memory for a deployment if deployment_id n...
magicoder
python
You are working on a project that involves visualizing geographical data using the `geoplotlib` library in Python. As part of this project, you need to create a program that reads a CSV file containing geographical data and generates a 2D histogram based on the data. The `geoplotlib` library provides functions for visu...
```python import geoplotlib from geoplotlib.utils import read_csv, BoundingBox def visualize_geographical_data(csv_file, colorscale='sqrt', binsize=8, bounding_box=BoundingBox.DK): # Read the CSV file containing geographical data data = read_csv(csv_file) # Create a 2D histogram based on the data geop...
magicoder
python
You are tasked with implementing a Python class method that formats a given string with indentation based on the value of the class attribute `self.i`. The method should also have an optional parameter `auto_break` which, if set to `True`, will automatically insert a line break after the formatted string. Your task is ...
```python class IndentationFormatter: def __init__(self, i): self.i = i def format_string(self, pre, auto_break=False): indent = self.i * '\t' + pre if auto_break: return indent + '\n' else: return indent ``` The `format_string` method constructs the `in...
magicoder
python
You are tasked with creating a Python function that simulates a simplified version of a swing-up control problem in a gym environment. The swing-up control problem involves controlling a pendulum to swing from a downward position to an upright position. The code snippet provided initializes the environment for the swin...
```python import gym def simulate_swingup_control(env_name, **kwargs): kwargs['swingup'] = True # Set the swingup option to True env = gym.make(env_name, **kwargs) # Initialize the environment with the specified name and keyword arguments total_reward = 0 # Initialize total reward # Simulate the sw...
magicoder
python
You are tasked with implementing a module system for a JavaScript application. The code snippet provided is an example of a module export statement in JavaScript. When using the `export` keyword in JavaScript, it allows the module to export functions, objects, or primitive values to be used in other modules. The `expor...
```javascript // Define the modules const TrackListItem = { track1: 'Song 1', track2: 'Song 2' }; const Playlist = { playlist1: ['Song 1', 'Song 2'], playlist2: ['Song 3', 'Song 4'] }; // Function to get module exports function getModuleExports(moduleName) { if (moduleName === 'TrackListItem') { return ...
magicoder
javascript
You are tasked with implementing a Python class that inherits from an abstract model and defines a specific type of neural network layer. Your goal is to complete the implementation of the class `BayesianConv2Pool2` by adding the necessary methods and attributes to create a Bayesian convolutional layer followed by a ma...
```python from models.abstract_model import AbstractModel import torch.nn as nn import torch.nn.functional as F class BayesianConv2Pool2(AbstractModel): def __init__(self, in_channels, out_channels, kernel_size, stride, padding): super(BayesianConv2Pool2, self).__init__() self.in_channels = in_chan...
magicoder
python
You are tasked with implementing a sentiment analysis bot using a pre-trained model and GloVe word embeddings. The bot is loaded from a saved model file and then used to analyze responses from a data source. Additionally, the GloVe word embeddings are loaded using a GloVeLoader class. Your task is to complete the imple...
```python def main(): model, tags = load_bot() df_responses = read_all_responses() activation = torch.nn.Softmax(1) gl = GloVeLoader() # Process each response using GloVe word embeddings processed_responses = [] for response in df_responses: processed_response = gl.process(response)...
magicoder
python
You are tasked with creating a custom error page in a Django web application. The provided code snippet is a view function in a Django application that renders a custom error page for HTTP status code 500 (Internal Server Error). The `view_500` function takes a `request` object and returns the rendered error page with ...
```python # views.py from django.shortcuts import render from django.http import HttpResponseNotFound def view_500(request): return render(request, 'django_tutorial/error_pages/page_500.html', status=500) def view_404(request): return render(request, 'django_tutorial/error_pages/page_404.html', status=404) #...
magicoder
python
You are tasked with creating a shell script that automates the process of creating multiple directories and files within them. Your script should take in a list of directory names as arguments and for each directory, create the directory itself and then create three files within it. The names of the files should be "fi...
```bash #!/bin/sh die () { echo "*** mkall.sh: $*" 1>&2 } # Check if there are arguments if [ $# -eq 0 ]; then die "No directory names provided" exit 1 fi # Loop through each directory name provided as argument for dir in "$@"; do # Create the directory if mkdir "$dir"; then echo "Directory '$dir' creat...
magicoder
shell
You are tasked with implementing a Python function that evaluates and checks the correctness of a given lambda calculus expression. Lambda calculus is a formal system in mathematical logic for expressing computation based on function abstraction and application using variable binding and substitution. The given express...
```python import re import ast def check_lambda_expression(expression: str) -> bool: # Extract the annotated evaluation tree from the expression match = re.search(r'# CHECK-TREE: (.+)', expression) if match: expected_tree = match.group(1) else: return False # Annotation not found ...
magicoder
python
You are tasked with implementing a sorting algorithm for a hierarchical data structure. The data structure consists of nodes, each of which has a title and may have children nodes. The goal is to sort the children of each node based on their titles. The sorting should be performed in a specific context, determined by a...
```swift // Define the Node structure struct Node { let title: String var children: [Node] } // Function to sort nodes based on their titles func sortNodes(root: Node, groupByLanguage: Bool) -> Node { var sortedRoot = root if groupByLanguage { sortedRoot.children = sortedRoot.children.map { lan...
magicoder
swift
You are tasked with creating a program that simulates a simplified version of a dialog system using asynchronous programming in C#. The program should utilize the provided code snippet as a starting point and implement the necessary logic to handle user input and generate appropriate responses. Your task is to create ...
```csharp using System; using System.Threading.Tasks; public class DialogSystem { public async Task Main() { // Initialize the LUIS service and retrieve context ID and prompt LuisService luisService = InitializeLuisService(); string contextId = GetContextId(); string prompt = Ge...
magicoder
csharp
You are tasked with creating a Python program to control a robot equipped with a distance sensor. The robot is programmed to move forward until it detects an obstacle within a certain range, at which point it should stop and print the distance reading. Your program should continuously read the distance sensor and stop ...
```python import easygopigo3 as easy import di_sensors import time def main(): gpg = easy.EasyGoPiGo3() my_distance_sensor = gpg.init_distance_sensor() threshold_distance_mm = 200 # Define the threshold distance in mm try: while True: distance_reading = my_distance_sensor.read_mm...
magicoder
python
You are given a set of n distinct keys, each with an associated frequency of occurrence. Your task is to construct an optimal binary search tree (OBST) using these keys such that the total search cost is minimized. The search cost for a key is the depth of the key multiplied by its frequency. The depth of a key in the ...
```python def minSearchCost(keys, freq): n = len(keys) dp = [[0] * n for _ in range(n)] for i in range(n): dp[i][i] = freq[i] for L in range(2, n + 1): for i in range(n - L + 1): j = i + L - 1 dp[i][j] = float('inf') for r in range(i, j + 1): ...
magicoder
python
You are tasked with implementing a function that validates the declaration of a HashMap in a programming language. The HashMap must adhere to specific rules, and any deviation from these rules should result in an exception being raised. The code snippet provided is a part of the validation process for declaring a HashM...
```python class StructureException(Exception): pass class DataLocation: STORAGE = "STORAGE" MEMORY = "MEMORY" # Add other data locations as needed class vy_ast: # Define the necessary classes and types from the abstract syntax tree (AST) def validate_hashmap_declaration(node, location): if ( ...
magicoder
python
You are tasked with implementing a generic service factory trait and its associated implementation for a specific service builder. The provided code snippet outlines the trait implementation and its associated constraints. Your task is to create a generic service factory trait and implement it for a specific service b...
```rust // Define the generic service factory trait trait ServiceFactory<St> { // Define the associated types and constraints type Response; type InitError; // Define the method for creating a service fn create_service(&self) -> Result<Self::Response, Self::InitError>; } // Implement the generic s...
magicoder
rust
You are tasked with implementing a TypeScript class that manages the lifecycle of a resource. The class should handle the creation, deletion, and retrieval of the resource, while also maintaining metadata about these operations. Your task is to complete the implementation of the class and write methods to manage the re...
```typescript class Resource { public name: string; public fingerprint: string; private 'created_at': Date | undefined; public deleted: boolean; private 'deleted_at': Date | undefined; public id: number; constructor(name: string, fingerprint: string, id: number) { this.name = name; ...
magicoder
typescript
You are tasked with designing a file browser management system for a cloud storage service. The system should allow users to open or activate a file browser dialog for a specific account and server repository. The `FileBrowserManager` class contains a method `openOrActivateDialog` that takes an `Account` object and a `...
```cpp FileBrowserDialog *FileBrowserManager::openOrActivateDialog(const Account &account, const ServerRepo &repo) { // Check if a dialog already exists for the specified account and repository for (FileBrowserDialog *dialog : activeDialogs) { if (dialog->getAccount() == account && dialog->getServerRepo...
magicoder
cpp
You are tasked with creating a script to automate the setup of a Kubernetes configuration file on a Windows system. The script should check for the existence of the Kubernetes configuration file, create it if it does not exist, and then copy the Windows configuration to the appropriate location. You are provided with a...
```bash # Check if the Kubernetes configuration file exists KUBECONFIG=~/.kube/config if [ -f "$KUBECONFIG" ]; then echo "Good: File '$KUBECONFIG' exists" else echo "WARNING: File '$KUBECONFIG' is not available, now trying to create it." echo echo "Copy windows config" echo mkdir -p ~/.kube ...
magicoder
shell
You are tasked with implementing a file patching algorithm to update a web application. The patching process involves applying a difference file to an existing version of the application to produce an updated version. The difference file is provided in the form of a ZIP archive, and the existing version of the applicat...
```java import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; public class PatchingUtility { public File applyPatch(File diffFile, File existingApplication) throws...
magicoder
java
You are tasked with implementing a currency conversion system in Swift. Your goal is to create a struct that represents a currency and a function to convert an amount from one currency to another. You are provided with a code snippet that defines the `GHS` (Ghana Cedi) currency as a struct conforming to the `CurrencyP...
```swift /// The Ghana Cedi (GHS) currency, as defined by ISO 4217. public struct GHS: CurrencyProtocol, CurrencyMetadata { public static var name: String { return "Ghana Cedi" } public static var alphabeticCode: String { return "GHS" } public static func convert(amount: Double, to targetCurrency: CurrencyProtoco...
magicoder
swift
You are tasked with implementing a logging system for a software application. The logging system should support writing log messages to a file and provide a mechanism for managing log levels. The log levels include DEBUG, INFO, WARNING, and ERROR, with DEBUG being the lowest and ERROR being the highest level. Additiona...
```java import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; public class WriteLog { private static WriteLog instance; private File logFile; private LogLevel logLevel; private WriteLog(File file) { ...
magicoder
java
You are tasked with implementing a function to calculate the distance correlation between two arrays, `x` and `y`. Distance correlation is a measure of dependence between two random variables and is based on the idea of comparing the distances between all pairs of points in the joint space of the variables. The given c...
```python import numpy as np def distance_correlation(x, y): def u_distance_correlation_sqr(a, b): # Implementation of u_distance_correlation_sqr function pass n = x.shape[0] a = np.reshape(x, (n, -1)) b = np.reshape(y, (n, -1)) with np.errstate(divide='ignore'): dcor_val ...
magicoder
python
You are tasked with implementing a C++ class that simulates a simple bank account. The class should have the following functionalities: 1. A default constructor that initializes the account balance to 0. 2. A parameterized constructor that allows the initial balance to be set. 3. A copy constructor that performs a deep...
```cpp #include <iostream> class BankAccount { private: double balance; public: // Default constructor BankAccount() : balance(0) {} // Parameterized constructor BankAccount(double initialBalance) : balance(initialBalance) {} // Copy constructor BankAccount(const BankAccount &other) : ba...
magicoder
cpp
You are tasked with creating a script to automate the generation of protocol buffer files for a project. Protocol buffers are a language-agnostic, efficient, and automated mechanism for serializing structured data. The provided code snippet is the beginning of a shell script (`build-gen-proto.sh`) that will handle the ...
```bash #!/bin/bash # Specify the directory containing the .proto files PROTO_DIR="path/to/proto/files" # Clear the TARGETS variable TARGETS="" # Find all .proto files in the specified directory and its subdirectories PROTO_FILES=$(find "$PROTO_DIR" -name "*.proto") # Iterate through each .proto file and generate l...
magicoder
shell
You are tasked with simulating a staking pool system for a cryptocurrency platform. The system involves depositing funds, staking them, and rebalancing the pool. Your goal is to implement a function that calculates the user's balance after a series of deposit, stake, and rebalance operations. You are provided with the...
The `calculateUserBalance` function simulates the deposit, stake, and rebalance operations in a staking pool system. It takes the initial user balance, deposit amount, and stake amount as input and returns the user's balance after the operations. The function first deposits the specified amount into the staking pool f...
magicoder
typescript
You are tasked with implementing a function that calculates the distance between two geographical coordinates using the Haversine formula. The Haversine formula is used to calculate the distance between two points on the Earth given their latitude and longitude in decimal degrees. The formula is as follows: ``` a = si...
```javascript function calculateDistance(lat1, long1, lat2, long2) { const R = 6371; // Radius of the Earth in kilometers const dLat = deg2rad(lat2 - lat1); const dLong = deg2rad(long2 - long1); const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * M...
magicoder
javascript
You are tasked with implementing a class that manages a grid system for a mapping application. The provided code snippet includes a property and a method related to the grid step unit, which determines the spacing between grid lines on the map. Your task is to create a Swift class that encapsulates the grid functionali...
```swift class GridManager { private var gridStepUnit_property: Int = 0 init() { self.gridStepUnit = 2286 } func resetGridStepUnitToDefaultValue() { self.gridStepUnit = 2286 } var gridStepUnit: Int { get { return self.gridStepUnit_property } private set { self....
magicoder
swift
You are tasked with implementing a custom data loader for a machine learning model. The data loader should be able to handle both training and testing datasets, and it should support batching and shuffling of the data. You are given a code snippet that initializes and returns the train and test data loaders using the ...
```python from torch.utils.data import DataLoader class CustomDataLoader: def __init__(self, data, batch_size, shuffle): self.data = data self.batch_size = batch_size self.shuffle = shuffle def load_data(self): return DataLoader(self.data, batch_size=self.batch_size, shuffle=se...
magicoder
python
You are given a directed graph represented as an adjacency list. Each node in the graph is labeled from 0 to n-1, where n is the number of nodes. Your task is to implement a depth-first search (DFS) algorithm to traverse the graph and determine the order in which the nodes are visited. Write a function `dfs` that take...
```rust fn dfs(graph: &Vec<Vec<usize>>, start_node: usize) -> Vec<usize> { let mut visited = vec![false; graph.len()]; let mut traversal_order = Vec::new(); dfs_helper(graph, start_node, &mut visited, &mut traversal_order); traversal_order } fn dfs_helper(graph: &Vec<Vec<usize>>, node: usize, visited: ...
magicoder
rust
You are tasked with creating a Python function that processes files within a specified directory and its subdirectories. The function should calculate the total size of all files with a specific file extension within the given directory and its subdirectories. You are provided with a code snippet that sets the `HOST_D...
```python import os def calculate_total_file_size(directory_path, file_extension): total_size = 0 for root, _, files in os.walk(directory_path): for file in files: if file.endswith(f".{file_extension}"): file_path = os.path.join(root, file) total_size += os.p...
magicoder
python
You are tasked with creating a program that manages a simple task list using Python. The program should allow users to add tasks, mark tasks as completed, view all tasks, and save the task list to a file using serialization. To achieve this, you need to implement a Task class with appropriate attributes and methods, as...
```python import pickle import time import uuid class Task: def __init__(self, description): self.id = uuid.uuid4() self.description = description self.completed = False def __str__(self): status = "Completed" if self.completed else "Pending" return f"Task ID: {self.id}...
magicoder
python
You are tasked with writing a script to automate the download and deployment of a specific OS image for Kubernetes nodes. The script should utilize the provided environment variables to download the image from the specified location and then deploy it to a target environment. The environment variables are as follows: ...
```bash #!/bin/bash # Check if the required environment variables are set if [ -z "$IMAGE_OS" ] || [ -z "$IMAGE_NAME" ] || [ -z "$IMAGE_LOCATION" ]; then echo "Error: Required environment variables are not set." exit 1 fi # Download the image from the specified location echo "Downloading $IMAGE_OS image from $IMA...
magicoder
shell
You are working on a project to develop a system that can detect drowsiness in individuals by analyzing facial landmarks. The system uses the concept of Eye Aspect Ratio (EAR) and Mouth Aspect Ratio (MAR) to determine if a person is yawning. The code snippet provided is a part of the system's implementation. The `shape...
```python def calculate_ear_mar(shape): # Extracting eye and mouth landmarks leftEye = shape[rStart:rEnd] rightEye = shape[lStart:lEnd] mouth = shape[mStart:mEnd] # Calculate Eye Aspect Ratio (EAR) leftEAR = eye_aspect_ratio(leftEye) rightEAR = eye_aspect_ratio(rightEye) ear = (leftEAR ...
magicoder
python
You are working on a data processing module for a biological experiment. The module receives experimental data and processes it based on predefined setups. The setups are defined in a dictionary `exp_to_setup`, where the keys are experiment names and the values are the corresponding setups. Additionally, there is a lis...
```python def process_setup_data(experimental_data: dict, exp_to_setup: dict, setups: list) -> dict: processed_data = {setup: {} for setup in setups} for exp, setup in exp_to_setup.items(): processed_data[setup][exp] = experimental_data[exp] return processed_data ```
magicoder
python
You are tasked with implementing a logo resolver class in PHP that utilizes an interface to provide the path for a customer's logo. The `LogoResolver` class should implement the `ResolverInterface` and utilize the `LogoPathProviderInterface` to retrieve the path for the customer's logo. Your task is to complete the imp...
```php class LogoResolver implements ResolverInterface { protected $logoPathProvider; public function __construct(LogoPathProviderInterface $logoPathProvider) { $this->logoPathProvider = $logoPathProvider; } public function resolve(): string { return $this->logoPathProvider->getLogoPat...
magicoder
php
You are given an array of integers `arr` and an integer `k`. Your task is to determine whether there are more than `k` subarrays in `arr` whose sum exceeds a given `max_sum`. A subarray is a contiguous sequence of elements within the array. Write a function `is_greater_than_k(max_sum, k, arr)` that takes in three para...
```python from typing import List def is_greater_than_k(max_sum: int, k: int, arr: List[int]) -> bool: subarray_count = 0 _sum = 0 for i in range(len(arr)): # Time O(N) _sum += arr[i] if _sum > max_sum: subarray_count += 1 if subarray_count == k and i != len(arr) - ...
magicoder
python
You are tasked with creating a function that processes a list of screenshots taken from a mobile application and returns the average color of all the pixels in the screenshots. Each screenshot is represented as a 2D array of RGB values, where each pixel is represented as an array of three integers (R, G, B). The functi...
```swift func averageColorOfScreenshots(screenshots: [[[Int]]]) -> [Int] { var totalR = 0 var totalG = 0 var totalB = 0 var totalPixels = 0 for screenshot in screenshots { for pixel in screenshot { totalR += pixel[0] totalG += pixel[1] totalB += pixel...
magicoder
swift
You are tasked with implementing a custom scrollable key-value grid view in a mobile application. The key-value grid view should display a set of key-value pairs in a scrollable manner. Each key-value pair should be displayed as a separate item within the grid view. The keys and values should be provided as input data ...
```swift import UIKit class KeyValueGridView: UIView { private let stackView: UIStackView = { let stackView = UIStackView() stackView.axis = .vertical stackView.spacing = 8 stackView.translatesAutoresizingMaskIntoConstraints = false return stackView }() init() { ...
magicoder
swift
You are tasked with implementing a custom generator function in Python that processes incoming frames and yields values based on certain conditions. The generator function should follow a specific sequence of operations and handle potential exceptions. Your task is to complete the implementation of the `process_frames...
```python class FrameProcessor: def __init__(self): # Initialize any required attributes self.shutdown_condition = False self.system_shutdown = False def recv(self, inbox): # Receive a frame from the specified inbox and return the frame # Implementation details not provi...
magicoder
python
You are tasked with creating a Python class that manages and executes operating system commands. Your task is to implement the `os_commands` class with the following requirements: 1. The class should have a class variable `instance_counter` that keeps track of the number of instances created. 2. The `__init__` method ...
```python import os import logging class os_commands: instance_counter = 0 def __init__(self, run_dir, params_dict, globals): self.run_dir = run_dir self.params_dict = params_dict self.globals = globals os_commands.instance_counter += 1 self.dirpath = os.path.dirname(os...
magicoder
python
You are tasked with implementing a simple in-memory cache system in Swift. The cache should have the ability to store key-value pairs and evict the least recently used item when the cache reaches its maximum capacity. You need to implement the `LRUCache` class with the following methods: 1. `init(_ capacity: Int)`: In...
```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 creating a Python package management system that can handle versioning and dependency resolution. Your system should be able to install, uninstall, and list packages, as well as handle dependencies between packages. You need to implement a class `PackageManager` with the following methods: - `insta...
```python class PackageManager: def __init__(self): self.packages = {} def install(self, package_name, version=None): if package_name in self.packages: print(f"{package_name} is already installed") return if package_name not in packages: print(f"Erro...
magicoder
python
You are tasked with simulating a simplified version of a streaming service's backend system. The system manages streams of content and needs to update and initialize streams based on incoming JSON data. Your task is to implement the logic for updating and initializing streams based on the provided JSON data. You are g...
```swift func processStreams(streamsJsonArr: [[String:Any]], streamsArr: [Stream], jsVirtualMachine: JSVirtualMachine, productVersion: String, jsUtilsStr: String) -> [Stream] { var newStreamsArr: [Stream] = [] for item in streamsJsonArr { if let streamJson = item as? [String:Any], let origName = stream...
magicoder
swift
You are tasked with simulating the Monty Hall problem, a famous probability puzzle. The Monty Hall problem is based on a game show scenario where a contestant is presented with three doors. Behind one door is a valuable prize, while the other two doors conceal goats. The contestant selects a door, and then the host, wh...
```rust use rand::prelude::*; struct SimulationResult { win: bool, switch: bool, } fn simulate(random_door: &u8, rng: &mut ThreadRng) -> SimulationResult { let prize_door = rng.gen_range(1, 4); let contestant_switches = rng.gen_bool(0.5); let win = *random_door == prize_door; let switch = if ...
magicoder
rust
You are working on a job scheduling system that uses the `qsub` command to submit jobs to a cluster. Each job is associated with a specific range of data processing. The command follows the format: ``` qsub -V -cwd -q <queue_name> -S /bin/bash -N <job_name> runOne.sh <script_name> <start_range> <end_range> ``` Where: -...
```python def generate_qsub_commands(script_name, start_range, end_range, num_jobs): commands = [] range_size = (end_range - start_range) // num_jobs for i in range(num_jobs): job_start = start_range + i * range_size job_end = job_start + range_size if i == num_jobs - 1: # Adjust th...
magicoder
python
You are tasked with implementing a custom decorator in TypeScript that logs the execution time of a method. Decorators are a powerful feature in TypeScript that can be used to modify or extend the behavior of classes, methods, or properties at design time. In this problem, you will create a decorator called `logExecuti...
```typescript // Define the logExecutionTime decorator function logExecutionTime(target: any, propertyKey: string, descriptor: PropertyDescriptor) { const originalMethod = descriptor.value; descriptor.value = async function (...args: any[]) { const start = Date.now(); const result = await originalMethod.ap...
magicoder
typescript
You are tasked with implementing a notification system in Python. The system should allow for the registration of notifiers for specific notification IDs and the triggering of notifications to the registered notifiers. You are provided with a partial implementation of the `NotificationManager` class, which includes a `...
```python class NotificationManager: def __init__(self): self.notifiers = {} def register_notifier(self, notification_id, notifier): self.notifiers[notification_id] = notifier def trigger_notification(self, notification_id, **kwargs): if notification_id in self.notifiers: ...
magicoder
python
You are tasked with implementing a C++ template meta-programming problem related to logical disjunction. The code snippet provided demonstrates the usage of a `disjunction` meta-function and a `STATIC_REQUIRE` macro to perform compile-time assertions. Your task is to create a C++ template meta-programming problem that...
```cpp #include <type_traits> namespace Rider { namespace Faiz { // Define the disjunction meta-function template <typename... Args> struct disjunction : std::false_type {}; template <typename T> struct disjunction<T> : T {}; template <typename T, typename... Args>...
magicoder
cpp
You are tasked with implementing a stack data structure in Swift using a protocol-oriented approach. The stack should support the following operations: push, pop, peek, and reset. Additionally, you need to create a coordinator rule protocol that defines the behavior for coordinating different stack operations. Your ta...
```swift enum StackOperation<T> { case push(T) case pop case peek case resetStack case none } protocol CoordinatorRule { associatedtype Element func coordinate(_ operation: StackOperation<Element>, on stack: inout [Element]) } struct Stack<Element>: CoordinatorRule { private var elemen...
magicoder
swift
You are given a Java interface `BimBoom` with two abstract methods: `long bim(long v)` and `String boom(String s)`. Your task is to implement a class `BimBoomImpl` that implements the `BimBoom` interface and provides the following functionalities: 1. The `bim` method should return the sum of the input `v` and the leng...
```java public interface BimBoom { long bim(long v); String boom(String s); } public class BimBoomImpl implements BimBoom { @Override public long bim(long v) { if (v > Long.MAX_VALUE - 1000) { return -1; // Handle integer overflow } return v + String.valueOf(v).lengt...
magicoder
java
You are tasked with implementing a custom macro in Rust that generates implementations for a trait for multiple types. The macro should generate code that allows the trait to be implemented for each specified type. Your task is to complete the implementation of the `impl_trait` macro. The macro should take a list of t...
```rust macro_rules! impl_trait { ($($ty:path),*) => { $( impl CustomTrait for $ty { fn write(&self, addr: u32, val: u32) { self.write(addr, val.to_be()); } } )* }; } ``` The completed `impl_trait` macro takes a list of...
magicoder
rust
You are tasked with implementing a custom asynchronous queue class in Python. The class should support the following functionalities: 1. Initialization: The class should be initialized with a set of keyword arguments using the `super()` function. It should also store a URL generated using the `Router.get_url()` method...
```python import asyncio import queue import tricks class CustomAsyncQueue: def __init__(self, host, port, type, peer, passwd, ssl_ctx, **kwargs): super().__init__(**kwargs) self.url = Router.get_url(host, port, type, peer, ssl_ctx) self.headers = Router.get_headers(passwd) self.ssl...
magicoder
python
You are tasked with implementing a memory statistics tracking system in C++. The given code snippet provides a partial implementation of the `StatisticsMemory` class, which is responsible for managing memory statistics and flushing memory data to a target. Your task is to complete the implementation of the `Statistics...
```cpp #include <cstdint> // Define the MemoryStatistics class to track memory statistics class MemoryStatistics { // Define necessary data members to track memory statistics // Example: int memoryUsage_; public: // Constructor to initialize memory statistics MemoryStatistics() : memoryUsage_(0) {...
magicoder
cpp
You are tasked with implementing a function to extract a hash index from a given occupancy bitboard using a magic number. In chess programming, a magic bitboard is a technique used to efficiently implement move generation for sliding piece attacks (rooks, bishops, and queens). The magic number is a precomputed constant...
```python def extract_hash_index(bitboard, magic): # Magic bit manipulation to extract hash index return (bitboard * magic) >> 60 ``` In the solution, the hash index is calculated by multiplying the occupancy bitboard with the magic number and then shifting the result to the right by 60 bits. This technique ef...
magicoder
python
You are given a code snippet that is part of a function `f` which takes several parameters: `idxL`, `idxR`, `num`, `l`, `r`, and `pw`. The function is designed to calculate a value `ans` based on the input parameters. The function iterates through a loop and performs some arithmetic operations to update the value of `a...
```java public int f(int idxL, int idxR, int num, int l, int r, int[] pw) { int ans = 0; for (int i = 0; i <= 9; i++) { if (i > 0 || idxL > 0) { int val = num + i * pw[idxL]; if (idxL < idxR) { val += i * pw[idxR]; } ans += f(idxL + 1, idxR...
magicoder
java
You are tasked with implementing a BsonParser in Rust, which is capable of parsing a byte stream into a BsonDocument. Bson (Binary JSON) is a binary-encoded format for representing JSON-like documents. The BsonParser should be able to convert a byte stream into a BsonDocument if the input is formatted correctly. Your ...
```rust use std::io::Read; // Define the BsonDocument type struct BsonDocument { // Define the fields and methods for BsonDocument // ... } // Define the BsonParser struct struct BsonParser<T> { stream: T, } impl<T: Read> BsonParser<T> { // Implement the BsonParser methods // ... } impl<T: Read>...
magicoder
rust
You are tasked with implementing a simplified version of a Latent Structured Output Support Vector Machine (Latent SOSVM) in C++. The Latent SOSVM is a machine learning algorithm used for structured prediction tasks, where the output is a complex structure rather than a single label. In this problem, we will focus on t...
```cpp #include <shogun/latent/LatentSOSVM.h> #include <shogun/structure/DualLibQPBMSOSVM.h> using namespace shogun; CLatentSOSVM::CLatentSOSVM() : CLinearLatentMachine() { // Register parameters SG_ADD(&m_so_solver, "so_solver", "Solver for solving the SOSVM optimization problem."); // Initialize member variabl...
magicoder
cpp
You are tasked with implementing a Python function that loads a model based on the provided configuration parameters. The function should read the configuration file, extract the necessary parameters, and then use them to initialize the model with the appropriate settings. Your task is to complete the `load_model` func...
```python import os from model import GenerativeClassifier # Assuming the model class is imported from the 'model' module def load_model(args, cfg): # Extracting relevant parameters from the cfg dictionary N_epochs = int(cfg['training']['n_epochs']) beta = float(cfg['training']['beta_IB']) train_nll =...
magicoder
python
You are working on a security application that needs to monitor the app names allowed by Exposure Notifications on an Android device. To achieve this, you decide to use Frida, a dynamic instrumentation toolkit, to interact with the Android device and retrieve the necessary information. Your task is to write a Python s...
```python import frida class FridaWrapper: @staticmethod def attach(device, process_name): session = device.attach(process_name) return session def list_allowed(): """List all the app names allowed by Exposure Notifications""" device = frida.get_usb_device() gms = FridaWrapper.att...
magicoder
python
You are tasked with creating a Bash script that processes a sequence of numbers and generates a specific output based on the input. The script should take a sequence of numbers as input and produce a JSON object as output. The JSON object should contain the following fields: - "hops": The input sequence - "name": A des...
```bash #!/bin/bash # Function to calculate the sum of divisors for a given number sum_divisors() { local n=$1 local sum=0 for ((i=1; i<=n/2; i++)); do if ((n % i == 0)); then sum=$((sum + i)) fi done echo $sum } # Function to process the input sequence and generate the JSON object process_seq...
magicoder
shell
You are tasked with implementing a diagnostic fixer for a code editor. The code snippet provided is part of a method that takes a `Document`, an immutable array of `Diagnostic` objects, a `SyntaxEditor`, and a `CancellationToken` as parameters. The method iterates through the `diagnostics` and performs some operations ...
```csharp public async Task FixDiagnosticsAsync(Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var generator = editor.Generator; foreach (var diagnostic in diagnostics) { if (diagnostic.Severity == DiagnosticSeverit...
magicoder
csharp
You are tasked with implementing a custom `forEach` function in Swift that iterates over an array of items and applies a given closure to each item. The `forEach` function should take an array of items and a closure as input, and it should apply the closure to each item in the array. The signature of the `forEach` fun...
```swift func forEach<T>(_ items: [T], _ closure: (T) -> Void) { for item in items { closure(item) } } // Test the forEach function let numbers = [1, 2, 3, 4] forEach(numbers) { number in print(number) } // Output: // 1 // 2 // 3 // 4 ```
magicoder
swift
You are tasked with creating a custom template tag in Django to display a list of the most recent articles on a website. The tag should take an optional parameter to specify the number of articles to display. Additionally, you need to create another custom template tag to display an archive of all published articles. ...
```python # Custom template tags implementation in Django # Import necessary modules from django import template from yourapp.models import Article # Import the Article model from your app # Register a new library for custom template tags register = template.Library() # Define the custom template tag to get recent ...
magicoder
python
You are tasked with creating a Python function that determines the absolute path of a file given its relative path and the current working directory. Your function should take in the relative path as a string and return the absolute path as a string. You can assume that the relative path is valid and does not contain a...
```python import os def get_absolute_path(current_directory: str, relative_path: str) -> str: absolute_path = os.path.abspath(os.path.join(current_directory, relative_path)) return absolute_path ``` The `os.path.join()` function is used to join the current directory and the relative path, and `os.path.abspath...
magicoder
python
You are tasked with creating a script to automate the configuration of Redis server instances on a Linux system. The script should read a list of Redis configuration files from a specified directory and start a Redis server for each configuration file. Additionally, the script should set the maximum number of pending c...
```bash #!/bin/bash # Check if the directory path is provided as an argument if [ $# -ne 1 ]; then echo "Usage: $0 <config_directory>" exit 1 fi config_dir=$1 # Iterate through each Redis configuration file in the specified directory for config_file in $config_dir/*.conf; do # Set the maximum number of pending...
magicoder
shell
You are tasked with implementing a function that processes an HTTP response and constructs an appropriate error message based on the response status and any encountered errors. The function should handle reading the response body, checking the response status, and constructing an error message if necessary. You are pr...
```rust use std::io::{Read, Error as IoError}; use hyper::StatusCode; struct ApiResponseError { status: StatusCode, message: String, body: String, } impl ApiResponseError { fn from_response(status: StatusCode, mut response: &mut dyn Read) -> Result<(), ApiResponseError> { let mut body = String...
magicoder
rust
You are tasked with implementing a custom data loader for a machine learning model using PyTorch. The data loader should be designed to handle a specific dataset and ensure that the loss can be computed accurately. Additionally, you need to initialize a neural network and allocate it to a specified device. Your task i...
```python import torch class CustomModel: def __init__(self, dataset, batch_size, n_job_dataloader, device): # make dataloader (with drop_last = True to ensure that the loss can be computed) self.train_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, ...
magicoder
python
You are working on a computer vision project and need to implement a mean Average Precision (mAP) evaluation metric for object detection. The mAP is a popular metric used to evaluate the performance of object detection algorithms. It measures the precision-recall curve and computes the average precision across multiple...
```python import os import numpy as np def compute_map(path_to_test_images: str, path_to_gt: str, map_at: int): # Load test images and ground truth annotations test_images = load_images(path_to_test_images) ground_truth = load_annotations(path_to_gt) # Perform object detection on the test images d...
magicoder
python
You are tasked with implementing a function to calculate the sum of a list of numbers based on certain conditions. The function `sumListWork` takes in four parameters: `allowRepetitions` (a boolean indicating whether repetitions are allowed), `workingBase` (an integer representing the base for the sum calculation), and...
```csharp private static long sumListWork(bool allowRepetitions, int workingBase, int[] numbers) { // Base case: If the numbers array is empty, return 0 if (numbers.Length == 0) { return 0; } // Initialize a variable to store the sum long sum = 0; // Create a helper function to calcula...
magicoder
csharp
You are tasked with creating a program that simulates a simple file path resolver. The program should take a file path as input and resolve it to the corresponding executable file path based on a predefined mapping. You are given a mapping of file extensions to their corresponding executable file paths in a PHP associ...
```php function resolveFilePath($filePath, $executableMapping) { $fileExtension = pathinfo($filePath, PATHINFO_EXTENSION); if (array_key_exists($fileExtension, $executableMapping)) { return $executableMapping[$fileExtension]; } else { return "Unknown file extension"; } } // Example usag...
magicoder
php
You are tasked with creating a scheduling system for a company that manages employee shifts. The system should be able to assign employees to different shifts based on their availability and the company's scheduling requirements. To achieve this, you need to implement a class called `ShiftScheduler` that will handle th...
```python from typing import List, Dict from .schedule import Schedule from .employee import Employee class ShiftScheduler: def __init__(self): self.schedule = Schedule() def add_employee(self, employee: Employee): # Add the employee to the schedule self.schedule.add_employee(employee)...
magicoder
python
You are tasked with creating a secure authentication system for an admin panel. The code snippet provided is a part of the authentication process in a PHP application using the Laravel framework. The `Admin` model represents the administrators of the system. The snippet shows a query to check the existence of an admin ...
To securely hash the password before comparing it in the query, you can use the `bcrypt` function provided by Laravel. The `bcrypt` function automatically generates a secure hash for the given password using a strong one-way hashing algorithm. Here's the solution to complete the authentication process: ```php // Assu...
magicoder
php
You are tasked with implementing a custom word entry enumerator class in C++ that interfaces with a MySQL database. The class should be able to iterate through word entries retrieved from the database and store them for further processing. Your task is to complete the implementation of the `WordEntryEnumerator_MySQL` ...
```cpp #include <iostream> #include <vector> namespace Solarix { // Assume the LS_ResultSet_MySQL and WordEntries_MySQL classes are defined elsewhere class LS_ResultSet_MySQL {}; class WordEntries_MySQL {}; class WordEntryEnumerator_MySQL { private: LS_ResultSet_MySQL* rs; WordEntr...
magicoder
cpp
You are tasked with creating a Python function that identifies and prints all prime numbers within a given range. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Your function should take two integer inputs, `start` and `end`, representing the inclusive range wit...
```python def prime_test(number): if number < 2: return False for i in range(2, int(number ** 0.5) + 1): if number % i == 0: return False return True def print_primes(start, end): for num in range(start, end + 1): if prime_test(num): print(num) # Test th...
magicoder
python
You are tasked with creating a Python class that simulates a lazy bucket for uploading data to a cloud storage service. The class should have methods for uploading data from both strings and files. Additionally, the class should be tested using the `unittest` framework to ensure that the appropriate methods are called ...
```python import unittest from unittest.mock import Mock class LazyBucket: def __init__(self, bucket): self.bucket = bucket def upload_from_string(self, name, data): return self.bucket.upload_from_string(name, data) def upload_from_file(self, name, file_path): with open(file_path,...
magicoder
python
You are tasked with implementing a function to delete a node from a binary search tree. The function should take the root of the tree and the value of the node to be deleted as input, and return the root of the modified tree. A binary search tree (BST) is a binary tree where for each node, all elements in its left sub...
```python class TreeNode: def __init__(self, value=0, left=None, right=None): self.value = value self.left = left self.right = right def delete_node(root: TreeNode, value: int) -> TreeNode: if not root: return root if value < root.value: root.left = delete_node(root...
magicoder
python
You are tasked with implementing a thread-safe dictionary data structure in C++. The dictionary should support the following operations: 1. Insertion of a key-value pair. 2. Retrieval of a value given a key. 3. Removal of a key-value pair. 4. Checking if a key exists in the dictionary. You are provided with a partial ...
```cpp void arLanguage::insert(const std::string& name, arDataTemplate* data) { std::lock_guard<std::mutex> guard(_mutex); _dictionary[name] = data; } void arLanguage::remove(const std::string& name) { std::lock_guard<std::mutex> guard(_mutex); _dictionary.erase(name); } bool arLanguage::exists(const ...
magicoder
cpp
You are tasked with creating a Python function that simulates a database migration process. In database migration, alterations to the structure of a database are defined in a series of scripts, and these alterations are applied to the database in a specific order. Each alteration script contains a set of operations to ...
```python from typing import List, Dict, Union, Any def apply_migration(operations: List[Dict[str, Union[str, Dict[str, Union[str, Any]]]]]) -> Dict[str, Any]: database_schema = {} # Initialize an empty database schema for operation in operations: if operation['operation'] == 'AlterField': ...
magicoder
python
You are tasked with implementing a game move validation system. The game has a set of legal moves, and the user's input needs to be validated against these legal moves before being processed. The code snippet provided is a part of the move validation function. The function takes user input, validates it against the leg...
```csharp public Move ValidateMove(string input, Rules rules) { bool isValid; isValid = int.TryParse(input, out var x); // Attempt to parse the input as an integer if (isValid) isValid = rules.LegalMoves.Any(m => m.X == x); // Check if the parsed integer is a legal move if (isValid) return new Move(x); ...
magicoder
csharp
You are tasked with implementing a complex number class in Python. A complex number is a number that comprises a real part and an imaginary part. The class should support addition of two complex numbers using the `+` operator. You are given a code snippet that represents the addition of two complex numbers. Your task ...
```python class Complex: def __init__(self, re, im): self.re = re self.im = im def __add__(self, rhs): return Complex(self.re + rhs.re, self.im + rhs.im) # Create instances of Complex class c1 = Complex(3, 4) c2 = Complex(1, 2) result = c1 + c2 print(result.re, result.im) # Output: 4 ...
magicoder
python
You are tasked with implementing a function that calculates the sum of all prime numbers within a given range. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The function should take two parameters, `start` and `end`, representing the inclusive range within whic...
```rust fn is_prime(num: i32) -> bool { if num <= 1 { return false; } for i in 2..=(num as f64).sqrt() as i32 { if num % i == 0 { return false; } } true } fn sum_of_primes(start: i32, end: i32) -> i32 { let mut sum = 0; for num in start..=end { if...
magicoder
rust
You are tasked with implementing a Python function that constructs a neural network backbone for semantic segmentation. The backbone is chosen based on the input parameters and is responsible for extracting features from the input image. The function should return the appropriate backbone model based on the specified a...
```python from semantic_segmentation.models.backbone import resnet, xception, drn def build_backbone(in_channels, backbone, output_stride, BatchNorm): if backbone == "resnet": return resnet.ResNet101(in_channels, output_stride, BatchNorm) elif backbone == "xception": return xception.AlignedXcep...
magicoder
python