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 class that manages a library's book inventory. The class should allow for adding new books, removing existing books, and displaying the current inventory. Additionally, you need to implement a method that calculates the total value of the inventory based on the individual book pric...
```python class BookInventory: def __init__(self): self.inventory = [] def add_book(self, title, price): self.inventory.append({"title": title, "price": price}) def remove_book(self, title): for book in self.inventory: if book["title"] == title: self.inv...
magicoder
python
You are tasked with creating a class for synthesizing sound waves in a music application. The class should include properties for waveform, phase distortion, pitch bend, vibrato depth, and vibrato rate. Additionally, the class should have properties for attack duration, decay duration, sustain level, and release durati...
```swift class SoundSynthesizer { let waveform: String let phaseDistortion: Double let pitchBend: Double let vibratoDepth: Double let vibratoRate: Double let attackDuration: Double let decayDuration: Double let sustainLevel: Double let releaseDuration: Double init(waveform: Stri...
magicoder
swift
You are tasked with implementing a program that simulates a simple banking system. The program should allow users to create accounts, deposit funds, withdraw funds, and check their balance. Each account should have a unique account number, and the program should support multiple accounts. Your task is to implement the...
```python class Bank: def __init__(self): self.accounts = {} self.account_number = 1 def create_account(self, name, initial_balance): self.accounts[self.account_number] = {'name': name, 'balance': initial_balance} account_num = self.account_number self.account_number += ...
magicoder
python
You are tasked with implementing a class that performs validation on an Entity-Relationship (ER) diagram for a database. The ER diagram consists of entities, attributes, and relationships between entities. Your task is to implement the `ERDiagramValidator` class, which contains the following methods: 1. `clear()`: A m...
```java import java.util.List; public class ERDiagramValidator { private List<String> errorList; private Database database; public void clear() { errorList.clear(); } public boolean validate(ERDiagram diagram) { errorList.clear(); // Clear any previous errors this.database...
magicoder
java
You are tasked with implementing a Python program to read a file containing JSONL (JSON Lines) data and write a modified version of the data to a new file. The input file contains a list of JSON objects, each representing a data record, and the program should modify the data before writing it to the output file. Your ...
```python import json from tqdm import tqdm input_file_path = "../data/amzn/train.jsonl" output_file_path = "../data/amzn/train_title.jsonl" def modify_and_write_jsonl(input_file, output_file): with open(input_file, "r") as fp, open(output_file, "w") as fout: total_lines = sum(1 for _ in open(input_file))...
magicoder
python
You are tasked with writing a script to automate the setup of a DNS deployment environment. The script should perform the following tasks: 1. Clone a Git repository from a specific URL to a local directory. 2. Check if two specific directories exist, and if not, print an error message and exit with a status code of 1....
```bash #!/bin/bash # Clone the Git repository git clone --origin vps5 ssh://git@vps5.dgt-bv.com:2221/opt/git/dns-de-graaffnet.git ./dns-de-graaffnet/ # Check if the directories exist, if not, print an error message and exit if [ ! -d "/home/jdg/dev/dns-deploy" ] ; then echo "Directory /home/jdg/dev/dns-deploy does...
magicoder
shell
You are tasked with creating a script to automate the installation of Nagios and its plugins on a Linux system. The script should download the specified versions of Nagios and Nagios plugins, compile and install them, and then configure the necessary settings for Nagios to run properly. Your script should perform the ...
```bash #!/bin/bash # Set the versions of Nagios and Nagios plugins NAGIOS_VERSION=4.1.1 NAGIOS_PLUGINS_VERSION=2.1.1 # Download and extract Nagios source code wget https://www.nagios.org/download/nagios-${NAGIOS_VERSION}.tar.gz tar -xzf nagios-${NAGIOS_VERSION}.tar.gz cd nagios-${NAGIOS_VERSION} # Compile and insta...
magicoder
shell
You are tasked with implementing a data encoding algorithm that converts a string of characters into a binary representation. The algorithm uses a custom encoding scheme that involves converting characters into binary sequences and then combining them into a single binary string. The custom encoding scheme works as fo...
```csharp public string CustomEncode(string input) { string _alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; int compensation = input.Length % 5 == 0 ? 0 : 5 - (input.Length % 5); byte[] bytes = System.Text.Encoding.ASCII.GetBytes(input); StringBuilder binaryString = new S...
magicoder
csharp
You are tasked with creating a Python class that manages a set of laboratory devices and their configurations. The class should have a method to generate configuration results for each device based on specific parameters. Your task is to implement the `LabManager` class and its method `generate_config_results`. The `L...
```python class LabManager: def __init__(self, labs): self.labs = labs def generate_config_results(self, LocalID, TimerCounterConfig, FIOAnalog, FIODirection, FIOState, EIOAnalog): config_results = [] for sernum, device in self.labs.items(): t_u3 = self.labs[sernum] ...
magicoder
python
You are tasked with implementing a program that simulates a simple inventory management system for a small retail store. The program should allow users to add, remove, and display items in the inventory. Each item in the inventory has a unique identifier, a name, a quantity, and a price. Your task is to implement the ...
```cpp #include <iostream> #include <map> class Inventory { private: struct Item { std::string name; int quantity; double price; }; std::map<int, Item> items; public: void add_item(int id, const std::string& name, int quantity, double price) { items[id] = {name, quanti...
magicoder
cpp
You are tasked with implementing a simplified version of a Generative Adversarial Network (GAN) in Python. A GAN consists of two neural networks, a generator and a discriminator, which are trained together to generate realistic data. The provided code snippet includes methods for moving the GAN and its components betwe...
```python class GAN(nn.Module): def __init__(self, generator, discriminator): super(GAN, self).__init__() self.generator = generator self.discriminator = discriminator def cuda(self): super(GAN, self).cuda() self.generator.cuda() self.discriminator.cuda() de...
magicoder
python
You are tasked with creating a Docker container for a Node.js application. The entrypoint for the container is defined in the `entrypoint.sh` script. Your goal is to write a Dockerfile that sets up the Node.js environment and uses the `entrypoint.sh` script as the entrypoint for the container. Your Dockerfile should p...
```Dockerfile # Use the official Node.js image as the base image FROM node:latest # Create a working directory in the container WORKDIR /app # Copy package.json and package-lock.json to the working directory COPY package*.json ./ # Install Node.js dependencies RUN npm install # Copy all application files to the wor...
magicoder
dockerfile
You are tasked with implementing a function that performs seamless cloning of an image. Seamless cloning is a technique used in image processing to blend the content from a source image into a target image in a seamless and natural manner. The function should take the source image, target image, and a mask as input, an...
```python import cv2 import numpy as np def seamless_clone(source_image, target_image, mask): # Convert the images and mask to the appropriate format for seamless cloning source_image = np.uint8(source_image) target_image = np.uint8(target_image) mask = np.uint8(mask) # Find the center of the mask...
magicoder
python
You are tasked with implementing a function that applies a given state to a view. The view is represented as a 2D array of integers, where each integer represents the height of a particular point on the view. The state is represented as a 2D array of integers of the same dimensions as the view. Each integer in the stat...
```java public int[][] applyStateToView(int[][] view, int[][] state) { int rows = view.length; int cols = view[0].length; int[][] result = new int[rows][cols]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { result[i][j] = view[i][j] + state[i][j]; resu...
magicoder
java
You are tasked with creating a Python plugin system for a task management application. The application should be able to load task plugins dynamically and execute them based on certain conditions. Each task plugin will have access to a set of predefined constants and will be required to implement a specific interface. ...
```python class TaskPlugin: def execute(self, input_data: dict) -> dict: raise NotImplementedError("Subclasses must implement execute method") PLUGIN_CONST = { "VERSION": "1.0", "AUTHOR": "Your Name" } def plugin_name() -> str: return "SamplePlugin" ``` In this solution, we have defined the ...
magicoder
python
You are tasked with creating a movie list application that allows users to click on a movie item to view its details. The code snippet provided is from the `onClick` method of a movie item click listener in an Android application. The `transitionName` is generated based on the position of the movie item in the adapter,...
```java void onMovieItemClick(int position, int movieId, ImageView movieImageView, String transitionName, int activityType) { // Create an intent to navigate to the movie details activity Intent intent = new Intent(context, MovieDetailsActivity.class); // Put the movie ID as an extra in the intent ...
magicoder
java
You are working on a messaging application that communicates with a server to retrieve user information. The server uses encryption and decryption methods to secure the data transmission. Your task is to implement a Python class that handles the encryption and decryption of data sent to and received from the server. Y...
```python from json import loads, dumps from requests import post class MessengerClient: def __init__(self, auth_key): self.auth = auth_key self.enc = Encryption() def getUserInfo(self, chat_id): request_data = { "api_version": "5", "auth": self.auth, ...
magicoder
python
You are tasked with creating a program that processes HTML code to extract information about different packages offered by a company. Each package is represented by a `div` element with the class `package` followed by a specific color class (e.g., `purple-package`). The package name is enclosed within an `h3` element w...
```python from bs4 import BeautifulSoup def extractPackages(htmlCode): package_info = [] soup = BeautifulSoup(htmlCode, 'html.parser') package_divs = soup.find_all('div', class_='package') for div in package_divs: package_title = div.find('h3', class_='package-title').text package_color...
magicoder
python
You are given a Java code snippet that manipulates a doubly linked list. Your task is to implement a method to insert a new node after a specified node in the list. The Node class is defined as follows: ```java class Node { Node prevNR; Node nextNR; boolean isInNR; int sizeNR; // Other methods...
```java public void insertAfter(Node headNR, Node newNode) { Node current = this; while (current != null) { if (current == headNR) { Node next = current.nextNR; current.nextNR = newNode; newNode.prevNR = current; newNode.nextNR = next; if (next...
magicoder
java
You are tasked with implementing a reference counting mechanism for a custom string class. The custom string class has a method `refs()` that returns the current reference count of the string object. The reference count represents the number of references to the string object. When a new reference to the string object ...
```cpp #include <iostream> #include <string> class CustomString { private: std::string* data; int* refCount; public: CustomString(const std::string& str) : data(new std::string(str)), refCount(new int(1)) {} CustomString(const CustomString& other) : data(other.data), refCount(other.refCount) { ...
magicoder
cpp
You are tasked with implementing a logging system for a Flask web application. The application should log all INFO level messages to a file named "flaskapi_info.log" located at "/var/log/uwsgi/". Additionally, the application should handle 404 errors by returning a JSON response with a 404 status code and a correspondi...
```python import logging from flask import Flask, json app = Flask(__name__) # Configure logging app.logger = logging.getLogger(__name__) app.logger.setLevel(level=logging.INFO) handler = logging.FileHandler("/var/log/uwsgi/flaskapi_info.log") handler.setLevel(logging.INFO) formatter = logging.Formatter( '%(ascti...
magicoder
python
You are tasked with implementing a subscription management system for handling events in a multi-tenant application. The system should allow adding, removing, and retrieving event handlers for specific events and virtual hosts. You are provided with a partial code snippet from the subscription management system, and yo...
```csharp using System; using System.Collections.Generic; public class SubscriptionManager { private readonly Dictionary<CompositeHandler, List<SubscriptionInfo>> _handlers; public SubscriptionManager() { _handlers = new Dictionary<CompositeHandler, List<SubscriptionInfo>>(); } public voi...
magicoder
csharp
You are tasked with creating a Python class to manage a stock portfolio. The class should have methods to track the buying and selling of stocks, calculate the profit from the transactions, and determine the profit rate. Your task is to implement the `StockPortfolio` class with the following methods: 1. `__init__(self...
```python class StockPortfolio: def __init__(self): self.positions = {'buy': [], 'sell': []} def buy(self, price): self.positions['buy'].append(price) def sell(self, price): self.positions['sell'].append(price) def calculate_profit(self, seed): total_profit = 0 ...
magicoder
python
You are tasked with implementing a function `unique_values(pairs)` that takes a list of pairs as input and returns a list of unique values from the pairs. Each pair is represented as a tuple with two elements, where the first element is the key and the second element is the value. If multiple pairs have the same value,...
```python def unique_values(pairs): unique_set = set() # Use a set to store unique values for pair in pairs: unique_set.add(pair[1]) # Add the second element of each pair to the set return list(unique_set) # Convert the set to a list and return ``` The `unique_values` function iterates through t...
magicoder
python
You are tasked with creating a program to help players of a video game find hidden collectibles scattered throughout the game world. The game world is represented as a 3D coordinate system, and each collectible is located at a specific coordinate. Additionally, each collectible has a description of its location to help...
```python import math class Vector3: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def find_closest_collectible(player_position, collectibles): closest_distance = float('inf') closest_collectible = None for collectible in collectibles: collectible_posit...
magicoder
python
You are given a 2D array `a` of size `n x m` containing integers. Your task is to find the maximum sum of a subarray within the 2D array. A subarray is defined as a contiguous block of elements within the 2D array. The maximum sum of a subarray is the largest possible sum that can be obtained by summing the elements of...
```cpp #include <iostream> #include <algorithm> using namespace std; const int Mmax = 1005; long long maxSumSubarray(int arr[], int n) { long long maxEndingHere = 0, maxSoFar = 0; for (int i = 0; i < n; i++) { maxEndingHere = max((long long)arr[i], maxEndingHere + arr[i]); maxSoFar = max(maxSo...
magicoder
cpp
You are tasked with implementing a custom data structure in Swift that mimics the behavior of a stack, but with an added feature to efficiently retrieve the minimum element in the stack at any given time. You need to create a class `MinStack` with the following methods: 1. `push(_ val: Int)`: Add an element to the sta...
```swift class MinStack { private var stack: [(val: Int, minVal: Int)] = [] func push(_ val: Int) { if stack.isEmpty { stack.append((val, val)) } else { let minVal = min(val, stack.last!.minVal) stack.append((val, minVal)) } } func pop() { ...
magicoder
swift
You are tasked with implementing a mission objective system for a simulation game. The objective system is represented by the `MissionObjectiveData` class, which contains various tunable parameters and constants. Your goal is to create a method within this class that determines the state of a mission objective based on...
```python class MissionObjectiveData(HasTunableSingletonFactory, AutoFactoryInit): # ... (other class members and methods) def determine_objective_state(self): if self.completes_mission and self.objective_state == self.MISSION_OBJECTIVE_COMPLETE: return self.MISSION_OBJECTIVE_COMPLETE ...
magicoder
python
You are tasked with creating a Django model and admin interface for managing recipes and their ingredients. Your task is to implement the necessary models and admin configurations to achieve this functionality. You are provided with the following code snippet as a starting point: ```python User = get_user_model() cl...
```python # models.py from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Recipe(models.Model): name = models.CharField(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name class RecipeI...
magicoder
python
You are tasked with implementing a B-tree leaf node iterator in Java. A B-tree is a self-balancing tree data structure that maintains sorted data and allows searches, sequential access, insertions, and deletions in logarithmic time. The leaf node iterator will be used to iterate through the leaf nodes of the B-tree dat...
```java /** * Represents an iterator for leaf nodes in a B-tree data structure. */ public class BtreeLeafNodeIterator { protected DataStoreBlock datablock; private long totalNumberOfBlocksToScan; private boolean hasNext; public BtreeLeafNodeIterator(DataStoreBlock datablock, long totalNumberOfBlocksT...
magicoder
java
You are tasked with creating a custom data loader for a machine learning project using PyTorch. The data consists of images and corresponding labels, and you need to implement a custom dataset class and a data loader to efficiently load and preprocess the data for training. Your custom dataset class should be named `C...
```python import torch from torch.utils.data import Dataset, DataLoader from torchvision import transforms from PIL import Image class CustomImageDataset(Dataset): def __init__(self, image_paths, labels): self.image_paths = image_paths self.labels = labels self.transform = transforms.Compos...
magicoder
python
You are tasked with creating a function to generate a unique payment ID for a payment system. The payment ID should consist of a specific format: a prefix character followed by a two-digit number. The function should retrieve the highest existing payment ID from the database, increment it by 1, and return the new payme...
```python import sqlite3 def generate_payment_id(prefix): # Connect to the database conn = sqlite3.connect('payment_database.db') cursor = conn.cursor() # Retrieve the highest existing payment ID cursor.execute("SELECT MAX(RIGHT(id_pembayaran, 2)) AS idmax FROM pembayaran") result = cursor.fet...
magicoder
python
You are working on a quantum computing simulation project and need to implement a function to process a sequence of quantum gates. Quantum gates are represented as strings, and the sequence of gates is stored as a list of lists. Each inner list represents a single gate sequence, and the outer list contains multiple gat...
```python import itertools class QuantumSimulator: def __init__(self): self.prev_gate_seq = [] def process_gate_sequence(self, gate_sequences): # Reverse each inner list in the outer list multi_gate_seq_reversed = [seq[::-1] for seq in gate_sequences] # Transpose the l...
magicoder
python
You are working on a machine learning project and need to implement a custom loss function for a neural network. The loss function is defined as the mean squared error (MSE) between the predicted values and the ground truth, with an additional regularization term. The regularization term penalizes the model for large g...
```python import numpy as np import torch def custom_loss(predicted, ground_truth): mse_loss = torch.mean((predicted - ground_truth)**2) gradients = torch.autograd.grad(mse_loss, predicted, create_graph=True)[0] regularization_term = torch.sum(gradients**2) total_loss = mse_loss + regularization_term ...
magicoder
python
You are given an integer `n` followed by `n` lines of space-separated integers. Each line contains `n` integers representing a square matrix `arr` of size `n x n`. Your task is to calculate and print an array `ans` of size `n` such that `ans[i]` is equal to the square root of the product of the elements in the `i`-th r...
```python import math n = int(input()) arr = [list(map(int, input().split())) for i in range(n)] ans = [0] * n ans[0] = int(pow((arr[0][1] * arr[0][2]) // arr[1][2], 0.5)) for i in range(1, n): ans[i] = (arr[0][i] // ans[0]) print(*ans) ``` The solution takes the input, calculates the array `ans` as described in t...
magicoder
python
You are tasked with implementing a function that optimizes a city tour algorithm. The algorithm takes an array of indexes representing the city tour and the time taken to complete the algorithm. The goal is to modify the algorithm to minimize the time taken to complete the tour. You are given the following code snippe...
```python from typing import Tuple import numpy as np def optimize_city_tour(city_tour: np.array, time_taken: float) -> Tuple[np.array, float]: # Implementing the necessary modifications to minimize the time taken to complete the city tour # Your solution code here optimized_tour = city_tour # Placeholder...
magicoder
python
You are given a set of points in a 3D space, represented as (x, y, z) coordinates. Your task is to implement a function that finds the maximum error point and then adds a new point within a hypercube around the maximum error point. The size of the hypercube should be equal to the distance to the nearest point from the ...
```python from typing import List, Tuple import math def distance(p1: Tuple[int, int, int], p2: Tuple[int, int, int]) -> float: return math.sqrt((p2[0] - p1[0])**2 + (p2[1] - p1[1])**2 + (p2[2] - p1[2])**2) def addPointWithinHypercube(points: List[Tuple[int, int, int]]) -> Tuple[int, int, int]: max_error_poin...
magicoder
python
You are tasked with implementing a custom pausable operator for a reactive programming framework. The pausable operator should allow pausing and resuming a sequence of values based on certain conditions. You are given a `pauserSubject` that emits `true` to pause the sequence and `false` to resume it. Additionally, you...
```swift extension ObservableType { func pausable(afterCount: Int, withPauser pauser: Observable<Bool>) -> Observable<Element> { return Observable.create { observer in var count = 0 var isPaused = false let disposable = CompositeDisposable() let pausableSubsc...
magicoder
swift
You are tasked with creating a Python program that utilizes the `pyttsx3` library to convert a given text into speech. The program should take user input for the text to be converted and then use the `pyttsx3` library to speak out the input text. Additionally, the program should allow the user to specify the speech rat...
```python import pyttsx3 def main(): engine = pyttsx3.init() # Prompt user for input text text = input("Enter the text to convert to speech: ") # Prompt user for speech rate while True: try: rate = int(input("Enter the speech rate (words per minute): ")) if...
magicoder
python
You are tasked with creating a program that simulates a simple build system. The build system takes a list of tasks and executes them concurrently using a specified number of threads. Each task can depend on other tasks, and the build system must ensure that tasks are executed in the correct order to satisfy their depe...
```python from typing import List from concurrent.futures import ThreadPoolExecutor from collections import defaultdict def execute_tasks(tasks: List[str], num_threads: int) -> List[str]: dependencies = defaultdict(list) tasks_completed = set() task_order = [] for task in tasks: task_name, *de...
magicoder
python
You are given a list of integers representing the scores of a game. Your task is to implement a function `highestScore(scores)` that returns the highest score achieved in the game. If the list is empty, the function should return 0. Example: For the list of scores: [75, 80, 95, 60, 85], the function should return 95.
```python def highestScore(scores): if not scores: return 0 return max(scores) ```
magicoder
python
You are tasked with implementing a function that calculates the total number of GitHub stars for a given user's repositories. You are provided with a code snippet that includes a function to handle key presses in a React application. Your task is to create a function `calculateTotalStars` that takes a GitHub username ...
```typescript import axios from 'axios'; async function calculateTotalStars(username: string): Promise<number> { try { const response = await axios.get(`https://api.github.com/users/${username}/repos`); const repositories = response.data; let totalStars = 0; for (const repo of repositories) { t...
magicoder
typescript
You are tasked with creating a Python function that interacts with a remote API to upload a file preview. The function should take the host URL, API key, and the file to be uploaded as input parameters. The provided code snippet serves as a starting point for your task. Your function should perform the following steps...
```python import requests import logging from typing import Optional def upload_preview(host: str, key: str, previewfile: str, connector: Optional[Connector] = None) -> str: url = f'{host}api/previews?key={key}' try: with open(previewfile, 'rb') as filebytes: result = requests.post(url, fil...
magicoder
python
You are tasked with implementing a simple memory management system for a game simulation. The game has various entities such as system, rooms, spawns, flags, and creeps, and each entity has its own memory storage. Your goal is to create a memory management system that initializes memory storage for these entities and c...
```javascript function initializeMemory() { console.log('[SETUP] Start...'); // add databases console.log('[SETUP] Create memory [system, rooms, spawns, flags and creeps]!'); Memory.system = {}; Memory.rooms = {}; Memory.spawns = {}; Memory.flags = {}; Memory.creeps = {}; // set co...
magicoder
javascript
You are tasked with implementing a custom documentation system for a programming language. The system should support the `@inheritdoc` tag, which allows a method or function to inherit documentation from another method or function. The `@inheritdoc` tag should be used in the documentation of a method or function to in...
```java import java.util.*; public class DocumentationResolver { public static List<String> resolveInheritDoc(List<String> documentation) { Map<String, String> methodDocs = new HashMap<>(); List<String> resolvedDocs = new ArrayList<>(); for (String doc : documentation) { if (do...
magicoder
java
You are given a list of daily temperatures, where temperatures are represented as an array of integers. Your task is to create a program that, for each day in the input, finds the next day where the temperature will be higher. If there is no such day, the output should be 0 for that day. For example, given the input a...
```python from typing import List def warmer_days(temperatures: List[int]) -> List[int]: stack = [] result = [0] * len(temperatures) for i in range(len(temperatures)): while stack and temperatures[i] > temperatures[stack[-1]]: idx = stack.pop() result[idx] = i - idx ...
magicoder
python
You are tasked with creating a program that processes files in a given directory and its subdirectories. The program should identify and list all the web font files present in the directory based on a specific regular expression pattern. Additionally, the program should have the option to exclude font files found withi...
```typescript import * as fs from 'fs'; import * as path from 'path'; function listWebFontFiles(outputDirectory: string, excludeNodeModules: boolean = false): string[] { const webFontRegex = /webfont\.(ttf|otf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/; const fontFiles: string[] = []; function traverseDirectory(director...
magicoder
typescript
You are tasked with creating a Python program that processes Java and C++ code files. The program should include a class for parsing Java code using the JavaParser library and a method for cleaning C++ code files. Your task is to complete the implementation of the Python program by writing the missing parts of the code...
```python class JavaParser: def __init__(self, stream): self.stream = stream def compilationUnit(self): # Implementation of parsing Java code pass # Placeholder for actual implementation class TemplateCodeRemover: @staticmethod def clean_file(cur_path, new_path, quiet=True, lo...
magicoder
python
You are tasked with creating a script to process and filter data from multiple trials using a set of parameters. The script should read in a set of trials, apply a specific key, and filter out any lines containing the strings "VAST" or "Both". The filtered results should be saved to separate files for each trial. You ...
```bash #!/bin/bash # Define the input trials and key trials="input1 input2 input3" key="specific_key" # Define the parameters array p=("param1" "param2" "param3") # Define the base name for output files results="filtered_results" # Iterate over each trial and process the data for name in $trials; do # Apply th...
magicoder
shell
You are tasked with creating a simple physics simulation program for a game. The program should simulate the behavior of falling objects with different shapes and materials. Your task is to implement a class hierarchy for different types of falling objects and their corresponding physics behaviors. You are provided wi...
```csharp using UnityEngine; // Abstract base class for falling objects public abstract class FallingObject : MonoBehaviour { public abstract void SimulateFall(); } // Subclass representing a spherical falling object public class SphereObject : FallingObject { private Rigidbody rb; private void Start() ...
magicoder
csharp
You are tasked with creating a Python function that calculates the total number of stars for a given GitHub repository. The function should take the repository name as input and return the total number of stars for that repository. You can assume that the repository name is a string and that the GitHub API can be used ...
```python import requests def get_repo_stars(repo_name): url = f'https://api.github.com/repos/{repo_name}' headers = {'Accept': 'application/vnd.github.v3+json'} response = requests.get(url, headers=headers) if response.status_code == 200: data = response.json() stars = data['stargazer...
magicoder
python
You are tasked with creating a function to extract color information from a given HTML string. The function should parse the HTML string and return a list of tuples, where each tuple contains the color code and the content enclosed within the corresponding font tag. You are provided with a partial code snippet that in...
```swift func extractColorList(from htmlString: String) -> [(String, String)] { var colorList = [(String, String)]() let regexString = "<font color=\\\"#+([.0-9a-zA-z]+)\\\">(.*?)</font>" do { let regex = try NSRegularExpression(pattern: regexString, options: []) let matches = regex.mat...
magicoder
swift
You are tasked with implementing a function to analyze video frames and track the movement of objects within the frames. The given code snippet is part of a larger program that processes video frames in iterations and records the movement of objects using centroid area history. Your task is to implement the `get_centr...
```python def get_centroid_area_history(files, debug=False, key_format="from_to"): area_movement_counter = {} for file in files: # Calculate centroid area history for each frame # Assuming the existence of a function to calculate centroid area history centroid_area_history = calculate_ce...
magicoder
python
You are tasked with creating a Python program to manage a library's book inventory using object-oriented programming. The program should allow the addition, removal, and display of books in the library's collection. Additionally, it should provide the functionality to register and manage library members' profiles. You...
```python class Book: def __init__(self, title, author, isbn): self.title = title self.author = author self.isbn = isbn class Profile: def __init__(self, name, member_id): self.name = name self.member_id = member_id class Library: def __init__(self): self.bo...
magicoder
python
You are tasked with implementing a generic function that takes a value of type `S` and converts it into a `String`. The function signature is as follows: ```rust fn convert_to_string<S: Into<String>>(value: S) -> String { // Your implementation here } ``` Your task is to implement the `convert_to_string` function...
```rust fn convert_to_string<S: Into<String>>(value: S) -> String { value.into() } fn main() { // Test cases assert_eq!(convert_to_string(5), "5"); assert_eq!(convert_to_string(3.14), "3.14"); assert_eq!(convert_to_string('a'), "a"); assert_eq!(convert_to_string("hello"), "hello"); } ``` The `...
magicoder
rust
You are tasked with implementing a value visitor/mapper in Java to process entries in a data structure. The data structure contains various entries, and the visitor/mapper is responsible for handling each entry based on its value. However, there is a need for a unique symbol to represent an unhandled entry. Your task i...
```java // UnhandledEntrySymbol class representing the unique symbol for unhandled entries public class UnhandledEntrySymbol { public static final UnhandledEntrySymbol INSTANCE = new UnhandledEntrySymbol(); private UnhandledEntrySymbol() { // Private constructor to prevent external instantiation } ...
magicoder
java
You are tasked with implementing the game of life, a cellular automaton devised by the British mathematician John Horton Conway. The game is a zero-player game, meaning that its evolution is determined by its initial state, requiring no further input. The game is played on an infinite two-dimensional grid of square cel...
```rust impl GameOfLife { pub fn update(&mut self) { let mut next = vec![vec![false; self.cols]; self.rows]; for i in 0..self.rows { for j in 0..self.cols { let live_neighbors = self.count_live_neighbors(i, j); next[i][j] = match (self.cells[i][j], live_ne...
magicoder
rust
You are tasked with implementing a Python function that generates training examples for a board game. The function takes in several parameters and returns a list of examples in a specific format. The function signature is as follows: ```python def generate_training_examples(episodeStep: int, tempThresholdStep: int) ->...
```python from typing import List, Tuple # Define the Board and Player types as per the game's specific implementation def generate_training_examples(episodeStep: int, tempThresholdStep: int) -> List[Tuple[Board, Player, Probability, Value]]: trainExamples = [] temp = 1 if episodeStep < tempThresholdStep else...
magicoder
python
You are tasked with creating a Python program that fetches data from a given URL and processes it to extract specific information. The program should utilize the `urllib` module to make a GET request to the URL and then parse the retrieved data to extract relevant details. Specifically, you need to extract the number o...
```python from urllib import request import re def fetch_and_process_words(url): try: response = request.urlopen(url) content = response.read().decode('utf-8') words = re.findall(r'\b\w+\b', content.lower()) unique_words = sorted(set(words)) for word in unique_words: ...
magicoder
python
You are tasked with creating a custom derive macro for a struct builder in Rust. The macro should generate a builder pattern for the given struct, allowing for fluent and ergonomic construction of instances of the struct with optional fields. Your task is to implement the custom derive macro `IBuilder` that generates ...
```rust use ibuilder::*; #[derive(IBuilder)] struct Foo(#[ibuilder(hidden)] i64); fn main() { // Using the generated builder pattern to construct an instance of Foo let foo = Foo::builder() .set_hidden(42) // Setting the value of the hidden field .build(); // Building the instance of Foo ...
magicoder
rust
You are working on a chemical database management system that stores thermodynamic data for various chemical compounds. Your task is to write a Python function that processes and inserts new thermodynamic data into the database. The function should take the following inputs: - `thermo`: An object containing thermodynam...
```python def insert_thermo_data(thermo, results_table, aug_inchi, model_chemistry, Hf298, S298): # Calculate the molar heat capacity at constant pressure (Cp) for the compound Cp1500 = thermo.Cpdata.value_si[6] / 4.184 # cal/mol/K # Check if there are existing entries in the results_table for the given a...
magicoder
python
You are tasked with implementing a function to process a list of payment transactions in Python. Each transaction is represented as a dictionary with the following keys: 'payer', 'iban', 'bic', 'id', and 'amount'. The 'payer' key holds the name of the payer in the format "Last, First Last". The 'iban' key holds the Int...
```python from decimal import Decimal def process_transactions(transactions): aggregated_info = { 'total_transactions': len(transactions), 'total_amount': sum(transaction['amount'] for transaction in transactions), 'unique_payers': list(set(transaction['payer'] for transaction in transactio...
magicoder
python
You are tasked with implementing a JavaScript function that calculates the distance between a point and a plane in 3D space. The plane is defined by its normal vector and a point it passes through. The function should take the coordinates of the point, the normal vector of the plane, and a point on the plane as input, ...
```javascript function distanceToPlane(pointX, pointY, pointZ, planeNormalX, planeNormalY, planeNormalZ, planePointX, planePointY, planePointZ) { // Calculate the distance using the formula: distance = |(point - planePoint) dot product planeNormal| / |planeNormal| const pointVector = new Cesium.Cartesian3(point...
magicoder
javascript
You are tasked with creating a neural network model using Keras for a specific problem. The model architecture involves various layers and configurations. Your goal is to implement the model architecture as described below. You are given the following requirements for the neural network model: 1. The input layer shoul...
```python import numpy as np from keras.models import Model from keras.layers import Input, Dense, Dropout, BatchNormalization, Activation from keras.optimizers import Adam # Define the input layer input_layer = Input(shape=(n, m)) # Add the first hidden layer with 64 units and ReLU activation hidden1 = Dense(64)(inp...
magicoder
python
You are tasked with implementing a Python function that simulates a simple text-based game. The game involves a player navigating through a grid-based world, collecting treasures, and avoiding obstacles. The player's goal is to reach the end of the grid while collecting as many treasures as possible. You are provided ...
```python class GridGame: def __init__(self, grid): self.grid = grid self.player_position = self.find_player_position() def find_player_position(self): for i in range(len(self.grid)): for j in range(len(self.grid[0])): if self.grid[i][j] == 'P': ...
magicoder
python
You are tasked with creating a Python function that generates a similarity map for visualizing the atomic contributions to the similarity between two molecules. The function should take as input a string in the SDF (Structure Data File) format containing exactly two molecules and produce a similarity map as output. Th...
```python import numpy as np import matplotlib.pyplot as plt def generate_similarity_map(sdf_text): # Parse the SDF text to extract atomic coordinates and properties for the two molecules # Calculate the similarity between the two molecules based on their atomic properties # Generate a similarity map to vi...
magicoder
python
You are tasked with implementing a Swift function that processes a collection of messages and extracts specific information from them. Each message is represented as an instance of a custom `Message` class, which contains various properties and methods for accessing its content. The function should filter the messages ...
```swift import Foundation func processMessages(_ messages: [Message]) -> (Double, UUID, String, Bool, Bool)? { guard let byTypeMessage = messages.first(where: { $0.addressPattern.fullPath.contains("byType") == true }) else { return nil } guard let numberString = byTypeMessage.number(), let do...
magicoder
swift
You are tasked with implementing a class that manages the reconnection attempts for a network service. The class should have an initializer that allows setting a multiplier for the reconnection time. Additionally, it should provide a method to calculate the time interval to wait before the next reconnection attempt bas...
```swift import Foundation class ReconnectionManager { var multiplier: Double init(multiplier: Double = 0.3) { self.multiplier = multiplier } func reconnectAfter(attempt: Int) -> TimeInterval? { return multiplier * exp(Double(attempt)) } } // Example usage let reconnectionManager...
magicoder
swift
You are tasked with implementing a 2D diffusion solver for a scientific simulation. The solver class, `SolveDiffusion2D`, needs to be initialized with physical parameters and an initial condition function. Your goal is to write the necessary code to fulfill these requirements. You are provided with a code snippet that...
```python class SolveDiffusion2D: def __init__(self): self.diffusion_coefficient = None self.domain_size = None self.time_step = None self.spatial_resolution = None self.initial_condition_function = None def initialize_domain(self, diffusion_coefficient, domain_size, tim...
magicoder
python
You are tasked with creating a function that parses HTML code to extract the URLs and their corresponding labels from a given sidebar menu. The HTML code for the sidebar menu is provided as a string. Each menu item is represented by a `<div>` element with the class "sidebar-item", containing an `<a>` element with the U...
```python import re def parseSidebarMenu(html): menu_items = re.findall(r'<div class="sidebar-item"><a href="([^"]+)".*?>(.*?)</a></div>', html) return menu_items # Test the function with the given example html_code = ''' <div class="sidebar-item"><a href="{{ url('world/awards') }}" class="{{ set_active('worl...
magicoder
python
You are tasked with implementing a simple event handling system for a graphical application. The application uses a library that provides a `Session` struct for managing the application's state and a `connect` object for handling events. The `connect` object has an `event` method that asynchronously waits for events an...
```rust // Define the Window struct to hold window state struct Window { dimensions: (u32, u32), // Other window state variables } impl Window { fn new(width: u32, height: u32) -> Self { Window { dimensions: (width, height), // Initialize other window state variables ...
magicoder
rust
You are tasked with creating a Python function that parses a given HTML code snippet and extracts the URLs and corresponding social media platform names from the embedded image tags. The function should return a dictionary containing the platform names as keys and their respective URLs as values. The HTML code snippet...
```python import re def extract_social_media_urls(html_code: str) -> dict: img_tags = re.findall(r'<img.*?src="(.*?)".*?\/>(?:\[(.*?)\])', html_code) url_tags = re.findall(r'\[(.*?)\]:\s(.*?)\n', html_code) platform_urls = {} for img_tag in img_tags: platform_name = img_tag[1] plat...
magicoder
python
You are tasked with implementing a Python function that approximates the square root of a given number using the Python values for perfect squares and the Chakravala method for non-perfect squares. The function should take two arguments: `n` (an integer representing the number for which the square root is to be approxi...
```python from fractions import Fraction def sqrt_app(n, eps): # Helper function to check if a number is a perfect square def is_perfect_square(num): sqrt_num = int(num ** 0.5) return sqrt_num * sqrt_num == num # Helper function to apply the Chakravala method for non-perfect squares de...
magicoder
python
You are tasked with creating a Python class that interacts with a CCG (Combinatory Categorial Grammar) parser service and performs various linguistic processing tasks. The CCG parser service is accessed through gRPC (Google Remote Procedure Call) and is initialized in the `setUp` method of the `PossessiveTest` class. Y...
```python from marbles.ie.ccg import parse_ccg_derivation2 as parse_ccg_derivation from marbles.ie.drt.drs import Rel from marbles.ie.semantics.ccg import process_ccg_pt, pt_to_ccg_derivation from marbles.ie.core.constants import * from marbles.ie.utils.text import preprocess_sentence from marbles.test import dprint im...
magicoder
python
You are tasked with implementing a custom hit collector for a search operation in a document retrieval system. The hit collector will use a bit array to store the matching document IDs. You are given a code snippet that initializes a bit array and uses an `IndexSearcher` to search for documents matching a given query....
```csharp // Import necessary namespaces using Lucene.Net.Search; using Lucene.Net.Index; // Define the AnonymousClassHitCollector class public class AnonymousClassHitCollector : Lucene.Net.Search.HitCollector { private System.Collections.BitArray bits; private IndexReader reader; // Constructor to initia...
magicoder
csharp
You are tasked with creating a custom regular expression matcher in Bash. The custom matcher should be able to validate a specific pattern within a given string. The custom matcher is defined in the "support/custom_matcher.sh" file and is imported by the "spec_helper.sh" file. Your task is to implement the custom regu...
```bash # support/custom_matcher.sh # Define the custom regular expression matcher custom_matcher() { local pattern=$1 local string=$2 if [[ $string =~ $pattern ]]; then echo "Match found: $pattern in $string" else echo "No match found: $pattern not in $string" fi } # spec_helper.sh # Import the cust...
magicoder
shell
You are tasked with implementing a type trait to determine if a given type is streamable to a `std::stringstream`. Streamability in this context refers to the ability to insert the type into a `std::stringstream` using the `<<` operator. Your task is to create a type trait `is_streamable` that, when provided with a typ...
```cpp #include <type_traits> #include <sstream> namespace rms { template <typename Stream, typename T, typename = void> struct is_streamable : std::false_type {}; template <typename Stream, typename T> struct is_streamable<Stream, T, decltype(void(std::declval<Stream&>() << std::declval<T>()))> : std::true_t...
magicoder
cpp
You are tasked with creating a Python function that processes a given code snippet to extract specific information about the user interface (UI) window and its components. The code snippet provided is a part of a larger script for creating a UI window using the Maya Python API (PyMEL). Your task is to write a function ...
```python import re def extract_ui_details(code_snippet): details = {} # Extract window name window_name_match = re.search(r'pm\.window\(\s*\"(.+?)\"', code_snippet) if window_name_match: details["window_name"] = window_name_match.group(1) # Extract window width window_width_m...
magicoder
python
You are tasked with creating a program that processes a list of test targets and their dependencies. Each test target is represented by a name and a list of its dependencies. Your goal is to write a function that takes in this list of test targets and their dependencies and organizes them into a hierarchical structure....
```swift func organizeTestTargets(_ testTargets: [TestTarget]) -> [String: [String]] { var dependencyMap: [String: [String]] = [:] // Create a map of test targets and their dependencies for target in testTargets { dependencyMap[target.name] = target.dependencies } // Function to recursivel...
magicoder
swift
You are tasked with creating a simple Desmos wallet generator. Desmos is a blockchain-based social network that utilizes a unique address format for its wallets. The address format is represented by a specific regular expression and is generated from a given mnemonic phrase. Your task is to implement a function that g...
```typescript import * as bip39 from 'bip39'; import * as bip32 from 'bip32'; import * as secp256k1 from 'secp256k1'; import * as bs58 from 'bs58'; class Wallet { address: string; publicKeyB64: string; privateKey: Buffer; constructor(address: string, publicKeyB64: string, privateKey: Buffer) { this.addres...
magicoder
typescript
You are tasked with creating a Python program that reads an Avro schema from a file, validates the schema, and then prints the fields and their corresponding data types. Avro is a data serialization system that provides rich data structures and a compact, fast, binary data format. The Avro schema is defined using JSON ...
```python import avro.schema from avro.datafile import DataFileReader from avro.io import DatumReader # Read the Avro schema from the file with open('user_schema.avsc', 'r') as schema_file: schema_str = schema_file.read() # Parse the Avro schema schema = avro.schema.Parse(schema_str) # Validate the schema avro.s...
magicoder
python
You are tasked with designing a database schema for a soccer (football) management system. The system needs to store information about soccer matches, including details about goals, yellow cards, and red cards. Your task is to create a database schema using the provided code snippet as a reference. The schema should i...
```sql CREATE TABLE Partida ( id INT PRIMARY KEY, -- Add other match details such as date, location, etc. ); CREATE TABLE Gol ( id INT PRIMARY KEY, partida_id INT, -- Add other goal details such as scorer, time, etc. FOREIGN KEY (partida_id) REFERENCES Partida(id) ); CREATE TABLE CartaoAmarelo ( id INT ...
magicoder
sql
You are tasked with creating a Python program that simulates a simplified file and project management system. Your program should parse input data, create a project, and perform specific operations on the project files. You are given a code snippet that includes a function `parse_and_create_project` which takes two pa...
```python import os class ArgsAndFileParser: def __init__(self, usage): self.usage = usage def parse_args_and_file(self, parse_file): # Implementation of parsing arguments and file pass class SigasiProjectCreator: def __init__(self, project_name): self.project_name = proje...
magicoder
python
You are tasked with implementing a custom control builder for a mobile web application. The control builder is responsible for parsing and processing the markup of mobile controls defined in the application. The provided code snippet is a partial implementation of the `MobileControlBuilder` class, which inherits from `...
```csharp public class MobileControlBuilder : ControlBuilder { public override bool AllowWhitespaceLiterals() { return false; } public override Type GetChildControlType(string tagName, IDictionary attributes) { if (String.Compare(tagName, typeof(DeviceSpecific).Name, true, CultureIn...
magicoder
csharp
You are working on a crime analysis system that utilizes a machine learning model to predict crime occurrences in a city. The model has been trained and is ready for deployment. The code snippet provided is a part of the system's workflow. The `no.run(model)` function is used to run the trained model, and the `model.cr...
```python import numpy as np import matplotlib.pyplot as plt def density_map(crimes, force): # Calculate the 2D density map based on crime occurrences x = crimes['longitude'] y = crimes['latitude'] heatmap, xedges, yedges = np.histogram2d(x, y, bins=100) # Apply force parameter to the density map ...
magicoder
python
You are tasked with implementing a SystemSleepPreventionToken class in Swift. The SystemSleepPreventionToken class is designed to prevent the system from entering sleep mode by acquiring a token and releasing it when it is no longer needed. The class should provide a mechanism to prevent the system from sleeping and al...
```swift class SystemSleepPreventionToken { let reason: String var isPreventingSleep: Bool = false init(reason: String) { self.reason = reason } func acquireToken() { if !isPreventingSleep { // Acquire the token and prevent system sleep isPreventingSleep = t...
magicoder
swift
You are tasked with implementing a custom annotation processor for a Java application. The annotation, `@FragmentScope`, is used to mark classes that should be scoped to a particular fragment in the application. Your goal is to create an annotation processor that processes classes annotated with `@FragmentScope` and ge...
```java import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.annotation.processing.SupportedSourceVersion; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; impor...
magicoder
java
You are tasked with implementing a function that takes in a SQL query and a set of values, and returns a formatted SQL query string with the provided values inserted into the query. The function should handle different types of SQL queries and values, ensuring that the resulting SQL query is properly formatted and safe...
```python def format_sql_query(sql, values): if isinstance(values, (list, tuple)): formatted_values = tuple("'" + str(val) + "'" if isinstance(val, str) else str(val) for val in values) else: formatted_values = "'" + str(values) + "'" if isinstance(values, str) else str(values) formatte...
magicoder
python
You are tasked with implementing a dependency ordering utility for a list of items. Each item has a key and an optional array of dependent keys. The goal is to order the items in such a way that no item comes before its dependencies. If there are multiple valid orderings, the utility should return any one of them. You ...
```typescript function orderDependents<T>(items: Orderable<T>[]): T[] { const graph: Map<T, Set<T>> = new Map(); const visited: Set<T> = new Set(); const result: T[] = []; // Build the dependency graph for (const item of items) { if (!graph.has(item.key)) { graph.set(item.key, new Set()); } ...
magicoder
typescript
You are tasked with creating a script to automate the setup of multipath devices on a Linux system. Multipath allows for the use of multiple physical paths between a server and storage to provide fault tolerance and performance enhancement. The script should detect the available multipath devices and set them up for us...
```bash #!/bin/bash # Check if dm-multipath module is loaded if lsmod | grep -q "dm_multipath"; then echo "dm-multipath module is already loaded" else modprobe dm-multipath echo "dm-multipath module loaded" fi # Identify available multipath devices multipath -l | while read line; do if [[ $line == *"(.*"* ]];...
magicoder
shell
You are tasked with implementing a function to decode a string containing Unicode escape sequences into their corresponding characters. Unicode escape sequences are represented as `\u` followed by a four-digit hexadecimal number, which represents the Unicode code point of the character. You need to write a function `d...
```python def decodeUnicode(s): return s.encode('utf-8').decode('unicode-escape') ``` The `decodeUnicode` function uses Python's built-in `encode` and `decode` methods to achieve the desired functionality. First, it encodes the input string `s` into bytes using the UTF-8 encoding. Then, it decodes the bytes using ...
magicoder
python
You are tasked with creating a Python function that processes a list of file paths and their associated GitHub stars, and returns a sorted list of file paths based on the range of GitHub stars provided. You are given a list of tuples, where each tuple contains a file path and the range of GitHub stars it has. The ran...
```python from typing import List, Tuple def sort_files_by_stars(file_star_tuples: List[Tuple[str, str]]) -> List[str]: def get_average_stars(star_range: str) -> int: min_stars, max_stars = map(int, star_range.split('-')) return (min_stars + max_stars) // 2 file_star_tuples.sort(key=lambda x: ...
magicoder
python
You are tasked with implementing a generic data structure in Rust that can store elements of any type. The data structure should support adding elements, removing elements, and checking if it contains a specific element. You need to implement the `GenericDataStructure` module with the following methods: 1. `new()`: Cre...
```rust pub mod generic { pub struct GenericDataStructure<T> { elements: Vec<T>, } impl<T> GenericDataStructure<T> { pub fn new() -> Self { GenericDataStructure { elements: Vec::new() } } pub fn add(&mut self, element: T) { self.elements.push(element...
magicoder
rust
You are tasked with implementing a C++ concept checker for ranges. A concept in C++ is a set of requirements for a type to be used in a particular way. In this problem, you are given a code snippet that uses the `models_not` macro to check if a given range does not model the `SizedRange` and `OutputRange` concepts. You...
```cpp // Solution for the models macro to check if the range models the View concept template <typename Range> constexpr bool models(concepts::View) { // Add your implementation here to check if the range models the View concept return /* your implementation */; } // Example usage // ::models<concepts::View>(...
magicoder
cpp
You are tasked with implementing a C++ class to manage properties of objects within a specific namespace, class, and instance. The class, named `properties`, should have the ability to store and manipulate properties associated with the objects. The `properties` class should have the following functionalities: 1. A de...
```cpp #include <iostream> #include <string> #include <unordered_map> class properties { private: std::unordered_map<std::string, std::string> mProperties; std::string mNamespace; std::string mClass; std::string mName; public: // Default constructor properties() : mProperties(), mNamespace("")...
magicoder
cpp
You are tasked with creating a program to manage a database of options for advertisements. Each advertisement option has a set of attributes that need to be stored in the database. Your task is to create a class or function that can take in the attributes of an advertisement option and store them in the database using ...
```php class AdvertisementOptionManager { public function createAdvertisementOption($name, $description, $price) { // Assuming the existence of a model class named AdOpciones in Laravel AdOpciones::create([ 'name' => $name, 'description' => $description, 'pric...
magicoder
php
You are tasked with implementing a function that generates a directed graph in the DOT language format based on a given set of dependencies between components. The DOT language is commonly used to describe graphs and is often visualized using tools like Graphviz. You are given a Python code snippet that initializes a ...
```python from graphviz import Digraph import logging LOGGER = logging.getLogger("pystructure.graphviz_plot") def dot_graph(deps): dot = Digraph(comment="Component Graph") for component, dependencies in deps.items(): dot.node(component) for dependency in dependencies: dot.edge...
magicoder
python
You are tasked with implementing a data caching system for a learning platform. The platform has a `LearnerCreator` class responsible for creating and managing learner data. The `LearnerCreator` class relies on a data cache, represented by the `ILearnerCreatorDataCache` interface, to store and retrieve learner data eff...
```csharp public class LearnerDataCache : ILearnerCreatorDataCache { private Dictionary<int, LearnerData> cache; // Using a dictionary for efficient data storage public LearnerDataCache() { cache = new Dictionary<int, LearnerData>(); } public LearnerData GetLearnerData(int learnerId) {...
magicoder
csharp
You are working on a text editor application and need to implement a feature for handling key button presses. The application uses the `nk` and `kb` libraries for handling user interface and keyboard input, respectively. The provided code snippet shows part of the implementation for handling key button presses in the a...
```rust fn on_key_button_press(state: &mut State, key: kb::Key) { match state.pairs.last_mut() { Some(pair) => match pair.1 { Some(_) if key.scan_code != 0 => state.pairs.push((Some(key.clone()), None)), None => if pair.0.as_ref().unwrap() != &key { pair.1 = Some(key.clone()) } else ...
magicoder
rust
You are tasked with implementing a function to compute the centroids of clusters based on given data points and their assigned clusters. The function signature is as follows: ```cpp template<typename DATA_t = double, typename INDEX_t = int, typename CLUSTER_t = int, class V> void compute_centroids(int ndim, INDEX_t no...
```cpp template<typename DATA_t = double, typename INDEX_t = int, typename CLUSTER_t = int, class V> void compute_centroids(int ndim, INDEX_t nobs, const DATA_t* data, CLUSTER_t ncenters, DATA_t* centers, const CLUSTER_t* clusters, const V& sizes) { // Initialize arrays to store the sum of data points and the count...
magicoder
cpp