query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with automating the deployment of multiple microservices in a Kubernetes environment using OpenShift command-line tools. The provided code snippet is a part of a deployment script and is responsible for processing a service template file and applying it to the cluster for each microservice. The script re... | ```bash
#!/bin/bash
# Check if dotnet environment name is provided as a parameter
if [ -z "$1" ]; then
echo "Error: Parameter 1 must be set and should be the dotnet environment name (e.g., hgpoc, hgdev, hgtest, Production)"
exit 1
fi
dotnet_env=$1
namespace_tools="your_tools_namespace" # Replace with the actual ... | magicoder | shell |
You are tasked with implementing a function to process operations for a system with a specified number of modes. The function should initialize a list of operations for each mode and check if the system is purely electronic.
You are given a Python class with an incomplete `op_setup` method. The method should initializ... | ```python
def op_setup(self):
"""
Initialize the list of operations for each mode and check if the system has modes other than electronic.
"""
self.ops = [[] for i in range(self.nmodes)] # Initialize ops as a list of empty lists for each mode
if 'modes' in self.term: # Check if the system has mode... | magicoder | python |
You are tasked with implementing a custom user details service in a Spring Boot application. The user details service should retrieve user information from a database and provide it to the Spring Security framework for authentication and authorization purposes.
Your task is to create a class `CustomUserDetailsService`... | ```java
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class CustomUserDetailsServic... | magicoder | java |
You are tasked with creating a configuration parser for a Python application. The configuration settings are defined as a dictionary where each key represents a configuration parameter and its corresponding value is another dictionary containing the parameter's type and default value. Your goal is to implement a functi... | ```python
def parse_config(config_dict, input_dict):
parsed_dict = {}
for key, value in config_dict.items():
if key in input_dict:
if value["type"] == int:
parsed_dict[key] = int(input_dict[key])
elif value["type"] == str:
parsed_dict[key] = str(in... | magicoder | python |
You are tasked with creating a Python program that interacts with a remote server using the ASN.1 protocol. ASN.1 (Abstract Syntax Notation One) is a standard interface description language for defining data structures that can be serialized and deserialized in a cross-platform way. Your program needs to establish a co... | ```python
import socket
from pprint import pprint
import asn1tools
# Define the ASN.1 schema for the message format
schema = '''
MyProtocol DEFINITIONS ::= BEGIN
Message ::= SEQUENCE {
id INTEGER,
data OCTET STRING
}
END
'''
# Create a socket and establish a connection to the remote server
ser... | magicoder | python |
You are tasked with implementing a visitor pattern for a simple tree data structure. The tree consists of nodes that can be of different types, such as `LeafNode` and `CompositeNode`. Each node type has its own specific behavior when visited by a visitor.
The `PrintVisitor` class is responsible for visiting the nodes ... | ```java
import java.io.PrintStream;
public class PrintVisitor {
private int indentLevel;
private char indentChar;
private PrintStream outputStream;
public PrintVisitor(int indent, char indentChar, PrintStream out) {
this.indentLevel = indent;
this.indentChar = indentChar;
this.... | magicoder | java |
You are tasked with creating a Python function to calculate the maximum revolutions per minute (RPM) for a given propeller diameter to ensure that the tip speed does not exceed 0.7 times the speed of sound at sea level. The speed of sound at sea level can be calculated using the formula:
\[ speed\_of\_sound = \sqrt{\g... | ```python
import math
def calculate_max_RPM(diameter):
gamma = 1.4 # adiabatic index for air
R = 287 # specific gas constant for dry air in J/(kg·K)
T = 288.15 # standard sea level temperature in Kelvin
speed_of_sound = math.sqrt(gamma * R * T) # calculate speed of sound
max_RPM = (0.7 * speed... | magicoder | python |
You are tasked with implementing a custom view in Swift that displays an image and a title label. The provided code snippet contains a custom view class with two methods: `layoutSubviews` and `setUI`. The `layoutSubviews` method is responsible for setting the frames of the `imageView` and `titleLabel`, while the `setUI... | ```swift
override func layoutSubviews() {
super.layoutSubviews()
imageView.frame = CGRect(x: 5, y: 15, width: width - 10, height: height - 40)
titleLabel.frame = CGRect(x: 5, y: height - 20, width: imageView.width, height: 10)
}
fileprivate func setUI() {
imageView = UIImageView()
imageView.content... | magicoder | swift |
You are tasked with implementing a function that calculates the minimum workspace size required for various operations in a numerical library. The provided code snippet contains template definitions for determining the minimum workspace size for different types of operations based on the input parameters.
Your task is... | ```cpp
#include <iostream>
#include <algorithm>
// Function to calculate the minimum workspace size required for a given operation type and input parameters
int calculateMinWorkspaceSize(char job, int ldwork, int n) {
if (job == 'E') {
return 1; // Minimum workspace size for eigenvalue problem
} else ... | magicoder | cpp |
You are tasked with implementing a program to decipher a ciphertext using the Vigenere Cipher method. The Vigenere Cipher is a method of encrypting alphabetic text by using a simple form of polyalphabetic substitution. It uses a keyword to shift the letters in the plaintext to create the ciphertext. In this problem, yo... | ```python
def vigenere_decipher(ciphertext, keyword, alpha_list):
result = ''
keyword = keyword.upper()
keyword_index = 0
for char in ciphertext:
if char.isalpha():
shift = alpha_list.index(keyword[keyword_index])
if char.islower():
result += alpha_list[(... | magicoder | python |
You are working on a bioinformatics project that involves analyzing genetic data. You have a file named `${PREF}-head.txt` containing data related to genetic molecules. The code snippet provided is a part of a shell script that processes this genetic data. The script iterates over three genes (a, b, c) and for each gen... | ```python
def generate_plot_commands(PREF: str) -> str:
cmd = ""
sep = ""
for i in range(3): # iterating over genes a, b, c
for j in ['a', 'b', 'c']: # 3 variants of each kind, corresponding to the 3 genes
mol = f"{i+1}{j}" # constructing the genetic molecule identifier
wi... | magicoder | python |
You are tasked with creating a program that securely stores and retrieves LinkedIn login credentials. Your program should implement a class that allows users to set their LinkedIn email and password, encrypt and store this information, and then retrieve and decrypt it when needed. The encryption and decryption should b... | ```python
import hashlib
from cryptography.fernet import Fernet
class LinkedInCredentials:
def __init__(self):
self.key = None
self.encrypted_credentials = None
def set_credentials(self, email, password):
self.credentials = f"Email: {email}, Password: {password}"
def encrypt_crede... | magicoder | python |
You are tasked with implementing a module for calculating the thickness of a material based on its density and volume. The module should provide a function that takes the density of the material and the desired volume, and returns the required thickness to achieve the given volume.
You are provided with the following ... | ```python
# thickness.py
import math
def calculate_thickness(density, volume):
# Calculate the area using a predefined formula
area = 10 * math.sqrt(volume) # Example formula for area calculation
# Calculate the thickness using the provided formula
thickness = volume / area
return thickness
```... | magicoder | python |
You are tasked with creating a script to automate the testing of a command-line tool for genetic analysis. The script will take in four parameters: the binary directory, a seed value, a bin number, and the haplotype count. The script will then execute two commands, `cli_test_input.sh` and `cli_test_input.sh`, passing t... | ```bash
#!/bin/bash
# Check if all required parameters are provided
if [ "$#" -ne 4 ]; then
echo "Usage: $0 <binary_dir> <seed> <bin_number> <haplotype_count>"
exit 1
fi
# Assign input parameters to variables
BINARY_DIR=$1
SEED=$2
BIN_NUMBER=$3
HAPLOTYPE_COUNT=$4
# Execute the first command
$BINARY_DIR/build... | magicoder | shell |
You are tasked with implementing a Django model for a ticketing system. The model should include a foreign key relationship with the Site model, a custom string representation method, and a save method that triggers email notifications under certain conditions.
Your task is to create a Django model for the Ticket clas... | ```python
from django.db import models
from django.contrib.sites.models import Site
class Ticket(models.Model):
sites = models.ForeignKey(Site, verbose_name=_("Webs"), related_name="related_sites")
title = models.CharField(max_length=100)
assigned_to = models.ForeignKey(User, on_delete=models.CASCADE, rel... | magicoder | python |
You are tasked with creating a Java program that parses a collection of SGF (Smart Game Format) files and extracts specific information from them. SGF is a text-based format for storing board game data, particularly for Go, chess, and similar games. Your program should be able to read an SGF file and extract the number... | ```java
package com.toomasr.sgf4j.parser;
import com.toomasr.sgf4j.Sgf;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.nio.file.Path;
public class SgfParser {
public int getNumberOfMoves(Path filePath) {
Sgf sgf = Sgf.parse(filePath);
Object gameTree = sgf.getGameTree... | magicoder | java |
You are tasked with implementing a custom form validation method for a Django class-based view. The view has a `post` method that calls the `form_valid` method to handle form validation. Your task is to complete the `form_valid` method to perform custom validation logic and return an appropriate response.
The `form_va... | ```python
def form_valid(self, form):
# Perform custom validation logic on the submitted form data
if custom_validation_logic(form): # Replace with actual custom validation logic
# If form data passes custom validation, return a success response
return super().form_valid(form) # Call the paren... | magicoder | python |
You are tasked with implementing a function to retrieve all the node editors in a given 3D animation software environment. In this environment, a global progress bar is accessible through a provided function. Your task is to create a Python function that can identify and return a list of all the node editors present in... | ```python
def get_node_editors():
gMainProgressBar = mel.eval('$tmp = $gMainProgressBar') # Access the global progress bar
found = []
# Assuming the node editors are stored in a variable named 'node_editors'
node_editors = get_node_editors_from_environment() # Function to retrieve node editors from th... | magicoder | python |
You are tasked with creating a web application that displays a dashboard with user information. The user information is stored in a JavaScript object and needs to be dynamically rendered on the dashboard using HTML and JavaScript.
You are given the following JavaScript object representing user information:
```javascri... | ```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Dashboard</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
.container {
mar... | magicoder | html |
You are tasked with optimizing the performance of a data loader used in a machine learning pipeline. The given code snippet initializes a data loader using PyTorch for a test set with a large number of classes. The data loader is set to load data in batches, with specific configurations for batch size, shuffling, pinni... | ```python
import math
def optimize_data_loader(num_classes: int) -> dict:
batch_size = min(1000, math.ceil(num_classes / 2)) # Set batch size to a maximum of 1000 or half the number of classes
shuffle = True if num_classes > 100 else False # Enable shuffling if the number of classes is large
pin_memory =... | magicoder | python |
You are given a Python script that aims to reconstruct chopped trees from a tracker. The script imports a module called `PlotLineageTree` and then attempts to process data from two files: `cellIDdetails_raw.txt` and `tracks_type2.xml`. The script iterates through the lines of the `cellIDdetails_raw.txt` file, splitting... | ```python
# Import necessary modules
import sys
sys.path.append("../")
from Cell_IDs_Analysis.Plotter_Lineage_Trees import PlotLineageTree
def reconstruct_trees(raw_file, xml_file):
# Initialize a PlotLineageTree object
lineage_tree = PlotLineageTree()
# Read and process the cell ID details from the raw f... | magicoder | python |
You are tasked with implementing a Python class that handles the enveloping and wrapping of data structures for communication over a network. The class contains two methods: `envelope_wrap` and `envelope_send`. The `envelope_wrap` method takes a denormalized data structure, a network connection, and a message ID as inp... | ```python
class EnvelopeHandler:
def __init__(self, protocol):
self.protocol = protocol
def envelope_wrap(self, denormalized_struct, connection, message_id):
if isinstance(denormalized_struct, NormalizedData):
enveloped_struct = denormalized_struct.struct_normalize(self, connection)... | magicoder | python |
You are tasked with creating a program that processes software license information. The program should read a string containing the maintainer's name and email, as well as the license type and its optional parameters. The maintainer's name and email are separated by "<<EMAIL>>", and the license type and its parameters ... | ```python
def parse_license_info(info):
maintainer, license_info = info.split(" <<EMAIL>>:")
license_type, parameters = license_info.split(":")
return {
"maintainer": maintainer,
"email": "<<EMAIL>>",
"license_type": license_type,
"parameters": parameters
}
# Test the fu... | magicoder | python |
You are tasked with implementing a custom text interpolation feature for a Swift application. The custom text interpolation should allow for the inclusion of special formatting within a `Text` object. The goal is to create a function that can handle custom interpolation syntax and produce the expected output.
Your tas... | ```swift
class Text {
private var content: String
init(_ content: String) {
self.content = content
}
func interpolatedText(_ interpolation: String) -> String {
return content.replacingOccurrences(of: "\\(.*?\\)", with: interpolation, options: .regularExpression)
}
static func ... | magicoder | swift |
You are tasked with creating a Python class that simulates a simple banking system. The class should have methods for depositing funds, withdrawing funds, and checking the current balance. Additionally, the class should keep track of the transaction history, including the date, type of transaction (deposit or withdrawa... | ```python
from datetime import datetime
class BankAccount:
def __init__(self):
self.balance = 0
self.transaction_history = []
def deposit(self, amount):
if amount > 0:
self.balance += amount
self.transaction_history.append({"date": datetime.now(), "type": "depos... | magicoder | python |
You are tasked with implementing a user authentication system for a web application using Python and Flask. The provided code snippet contains two Flask routes: one for rendering the index page and setting a cookie, and another for handling user registration.
Your task is to create a Flask route for user login and imp... | ```python
@main.route("/login", methods=['POST', 'GET'])
def login():
if request.method == 'POST':
form = request.form
username = form.get('username')
password = form.get('password')
authenticated_user = User.authenticate(username, password)
if authenticated_user:
... | magicoder | python |
You are given two strings, `a` and `b`. Your task is to implement a function or method to find the length of the longest common subsequence (LCS) of `a` and `b`. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. Th... | ```rust
fn longest_common_subsequence(a: &str, b: &str) -> usize {
let a_chars: Vec<char> = a.chars().collect();
let b_chars: Vec<char> = b.chars().collect();
let mut dp = vec![vec![0; b_chars.len() + 1]; a_chars.len() + 1];
for i in 1..=a_chars.len() {
for j in 1..=b_chars.len() {
... | magicoder | rust |
You are tasked with implementing a smooth scrolling feature for a RecyclerView in an Android application. The smooth scrolling is achieved using a SmoothScroller object, which is responsible for animating the scrolling behavior. The provided code snippet is a part of the implementation of the smooth scrolling functiona... | ```java
public class RecyclerView {
public class SmoothScroller {
public class Action {
public void runIfNecessary(RecyclerView recyclerView) {
// Implement smooth scrolling logic here
int targetPosition = getTargetPosition(); // Assume getTargetPosition() returns... | magicoder | java |
You are tasked with implementing a Python class that manages the display range of a graph. The class should inherit from another class and override certain methods to achieve the desired functionality.
You are given the following code snippet as a starting point:
```python
class DisplayAll:
def __init__(self, ax,... | ```python
class DisplayRange(DisplayAll):
def set_display(self, x_values, y_values):
self.ax.set_xlim(min(x_values), max(x_values))
self.line.set_ydata(y_values)
self.line.set_xdata(x_values)
```
In the `DisplayRange` class, the `set_display` method is overridden to set the x-axis limits usi... | magicoder | python |
You are tasked with implementing a function that processes product images for a given product. The function should take a `ProductItem` object and an array of images as input, and perform image processing operations on the product's images. The goal is to resize and optimize the images before saving them.
You are prov... | ```php
/**
* Processes and saves product images for the given product.
*
* @param ProductItem $product
* @param array $images
*/
function processAndSaveProductImages(ProductItem $product, array $images): void {
// Define the target dimensions for resized images
$targetWidth = 800;
$targetHeight = 600;
... | magicoder | php |
You are tasked with implementing a Python function that processes a dictionary of parameters and returns a formatted string representing the key-value pairs. The function should handle nested dictionaries and output the key-value pairs in a specific format.
You are given the following code snippet as a starting point:... | ```python
def format_params(params, parent_key='', sep='.'):
items = []
for key, value in params.items():
new_key = f"{parent_key}{sep}{key}" if parent_key else key
if isinstance(value, dict):
items.extend(format_params(value, new_key, sep=sep).items())
else:
item... | magicoder | python |
You are working on a software system that manages a collection of labels. Each label has an associated boolean value, and the system allows for the removal of labels based on certain conditions. You are given a code snippet that performs label removal based on a random selection and the associated boolean value.
Your ... | ```java
public void removeLabel(List<String> l, List<Boolean> t, boolean b, Random r) {
List<Boolean> selectedList = b ? t : t2; // Select the appropriate boolean list based on the value of b
int index = r.nextInt(l.size()); // Generate a random index within the range of the label list
if (selectedList.get(... | magicoder | java |
You are tasked with implementing a function that extracts the class names from a given HTML code snippet. The function should take the HTML code as input and return a list of unique class names found within the code.
Function Signature: `def extract_class_names(html_code: str) -> List[str]`
Example:
For the given HTM... | ```python
from typing import List
import re
def extract_class_names(html_code: str) -> List[str]:
class_names = re.findall(r'class="([^"]+)"', html_code) # Extracts the content within the class attribute
unique_class_names = set()
for names in class_names:
unique_class_names.update(names.split()) ... | magicoder | python |
You are tasked with implementing a generic data structure that supports type-safe storage and retrieval of elements. The data structure should allow storing elements of any type and provide a mechanism to retrieve the stored elements with their original type information intact. Your task is to implement the `TypedStora... | ```swift
class TypedStorage {
private var storage: [ObjectIdentifier: Any] = [:]
func storeValue<T>(_ value: T) {
let typeID = ObjectIdentifier(T.self)
storage[typeID] = value
}
func retrieveValue<T>(_ type: T.Type) -> T? {
let typeID = ObjectIdentifier(T.self)
return s... | magicoder | swift |
You are tasked with creating a Python function that generates a schedule for renewing quote cards in a financial data processing system. The function should take in the start date, schedule interval, and default arguments, and return a schedule configuration in the form of a Directed Acyclic Graph (DAG) object.
The sc... | ```python
import pendulum
from airflow import DAG
def generate_quote_card_schedule(start_date, schedule_interval, default_args):
quote_card_renew = DAG(
"quote_card_renew",
catchup=False,
start_date=start_date,
schedule_interval=schedule_interval,
default_args=default_args
... | magicoder | python |
You are tasked with creating a Python script that manipulates JSON data. Your script should perform the following tasks:
1. Read data from a JSON file named `example.json`.
2. Remove a specific key-value pair from the JSON data.
3. Write the modified JSON data back to the same file.
Your script should handle the case ... | ```python
import json
import os
def remove_json_key(file_path, key_to_remove):
with open(file_path, 'r') as file:
data = json.load(file)
if key_to_remove in data:
del data[key_to_remove]
with open(file_path, 'w') as file:
json.dump(data, file, indent=2)
# Example usage
re... | magicoder | python |
You are required to implement a Python class `Solution` that contains a method `subsets` which takes a list of integers `nums` as input and returns all possible subsets of the input list.
For example, given the input `nums = [1, 2, 3]`, the method should return a list of lists containing all possible subsets: `[[], [1... | ```python
class Solution:
def subsets(self, nums):
result = []
self.backtrack(nums, 0, [], result)
return result
def backtrack(self, nums, start, subset, result):
result.append(subset[:])
for i in range(start, len(nums)):
subset.append(nums[i])
se... | magicoder | python |
You are tasked with implementing a function that processes images based on certain conditions. The function takes in three parameters: `im` (an input image), `args` (a dictionary of arguments), and `im_size_max` (the maximum size of the image). The function first checks if the value of `args.crop` is not equal to "True... | ```python
import cv2
def process_image(im, args, im_size_max):
if not args.crop == "True":
# scale down if bigger than max size
re_scale = (float(args.max_edge) / float(im_size_max))
im = cv2.resize(im, None, None, fx=re_scale, fy=re_scale,
interpolation=cv2.INTER_LI... | magicoder | python |
You are tasked with creating a context manager in Python that logs the time taken for a specific operation using the `logging` module. The context manager should also handle exceptions that may occur during the operation and log them appropriately. Additionally, the context manager should support the use of different d... | ```python
import logging
from contextlib import contextmanager
from typing import Any, Dict, Generator, TypeVar, Union
import time
import torch
from composer.core import Precision
from composer.trainer.devices.device import Device, T_nnModule
logger = logging.getLogger(__name__)
T = TypeVar('T')
@contextmanager
def... | magicoder | python |
You are tasked with implementing a custom data structure in Swift that mimics the behavior of a stack but has an additional method to efficiently retrieve the minimum element in the stack. You need to design the data structure to support the following operations:
1. `push(val)`: Add an element `val` to the top of the s... | ```swift
class MinStack {
private var stack: [(val: Int, min: Int)] = []
func push(_ val: Int) {
if stack.isEmpty {
stack.append((val, val))
} else {
let minVal = min(val, stack.last!.min)
stack.append((val, minVal))
}
}
func pop() {
... | magicoder | swift |
You are tasked with creating a script to process a set of files using a command-line tool and then display a summary message. The script should iterate through a list of files in a specific directory, apply a command-line tool called "minim" to each file, and suppress any output from the tool. Once all files have been ... | ```bash
#!/bin/bash
# Iterate through files in the "examples" directory
for file in examples/*; do
# Apply "minim" tool to each file and discard output
../minim "$file" > "/dev/null"
done
# Print completion message
echo "Done."
```
In this solution, a Bash script is created to iterate through all files in the... | magicoder | shell |
You are tasked with implementing a custom list view in a mobile app using SwiftUI. The app should display a list of navigation links, each leading to a different page. Each navigation link should have a label with an icon and, optionally, a subtitle. Your task is to create a SwiftUI view that fulfills these requirement... | ```swift
import SwiftUI
struct CustomListView: View {
var body: some View {
NavigationView {
List {
NavigationLink(destination: Text("Page 1")) {
HStack {
Image(systemName: "house")
Text("Home")
... | magicoder | swift |
You are tasked with creating a Python function that processes data related to COVID-19 deaths and makes predictions using different methods. The function takes in a dataframe `df`, a string `method` indicating the prediction method, and other relevant parameters. The code snippet provided is a part of the function and ... | ```python
import numpy as np
def fit_and_predict(df, method, mode, outcome, demographic_vars, target_day):
if method == 'exponential':
# Fit an exponential model to the data and make predictions
# Implement the exponential model fitting and prediction logic here
preds = np.exp(df['previous_... | magicoder | python |
You are tasked with parsing and extracting data from HTML table cells. Given an HTML table row represented by the following code snippet:
```html
<tr>
<td style="width: 3%"><p style="font-size: 12px; margin-left: 10px">3.</p></td>
<td style="width: 40%"><p style="font-size: 12px; margin-left: 1px">Tindakan yan... | ```javascript
function parseHTMLTableRow(htmlTableRow) {
const parser = new DOMParser();
const doc = parser.parseFromString(htmlTableRow, 'text/html');
const tdElements = doc.getElementsByTagName('td');
const number = parseInt(tdElements[0].querySelector('p').textContent);
const description = tdEle... | magicoder | javascript |
You are tasked with creating a Python function that establishes a secure connection to a CockroachDB instance hosted on Google Cloud Platform (GCP). The function should utilize the provided connection parameters to establish a secure connection to the database.
The connection parameters are as follows:
- `password`: T... | ```python
import psycopg2
from psycopg2 import sql
def connect_to_cockroachdb(password, sslmode, sslrootcert, sslkey, sslcert, port, host):
try:
conn = psycopg2.connect(
dbname='defaultdb',
user='root',
password=password,
sslmode=sslmode,
sslrootc... | magicoder | python |
You are tasked with implementing a function that calculates the average score of students in a class. The function should take in a list of student scores and return the average score rounded to the nearest integer. If the average score is exactly halfway between two integers, it should be rounded up.
Function Signatu... | ```python
from typing import List
def calculate_average_score(scores: List[int]) -> int:
total_score = sum(scores)
average_score = total_score / len(scores)
return round(average_score)
```
The `calculate_average_score` function first calculates the total score by summing all the scores in the input list. ... | magicoder | python |
You are tasked with implementing a parser for a custom Extended Context-Free Grammar (ECFG) format. The ECFG format is a variation of the traditional Context-Free Grammar (CFG) used in formal language theory. The grammar consists of a set of production rules, each defining how a non-terminal symbol can be expanded into... | ```python
import re
class ECFGParser:
def __init__(self):
self.rules = []
def add_rule(self, rule: str) -> None:
self.rules.append(rule)
def validate_ecfg(self) -> bool:
for rule in self.rules:
if not re.match(r'^[A-Z]\s*->\s*(([a-z]|[A-Z])|(\{[ab\|\*\.]+\}))*\s*(\|(((... | magicoder | python |
You are tasked with creating a Python decorator that checks if a user has the required roles to access a specific function. The `role_required` decorator takes in four boolean parameters: `student`, `teacher`, `cd` (course director), and `admin`, indicating whether the user must have these roles to access the decorated... | ```python
from functools import wraps
class role_required:
"""
Check if user has the required roles
"""
def __init__(self, student=False, teacher=False, cd=False, admin=False):
self.student = student
self.teacher = teacher
self.cd = cd
self.admin = admin
def __call... | magicoder | python |
You are working for a sports analytics company that wants to analyze the performance of basketball players based on their average score, handedness, and other attributes. The company has provided you with a dataset in the form of a pandas DataFrame named `df`. The DataFrame contains the following columns: 'name' (playe... | ```python
import pandas as pd
def analyze_basketball_data(df):
# Grouping by 'avg_category' and 'handedness', and calculating the sum of numerical columns
avg_handedness_count_df = df.drop(['height', 'weight', 'avg'], axis=1).groupby(by=['avg_category', 'handedness']).sum().reset_index()
# Grouping by... | magicoder | python |
You are tasked with implementing a genetic algorithm to solve a simple optimization problem. The genetic algorithm operates on a population of candidate solutions, where each candidate solution is represented as a chromosome. The genetic algorithm involves parent selection and variation to produce new candidate solutio... | ```python
class GeneticAlgorithm:
# Other methods and attributes are omitted for brevity
def _make_child(self):
# Perform parent selection to choose two parents from the population
parent1 = self._select_parent()
parent2 = self._select_parent()
# Apply crossover to create a chi... | magicoder | python |
You are tasked with implementing a program to solve the "Mastermind" game. In this game, one player (the "codebreaker") tries to guess the secret code chosen by the other player (the "codemaker"). The secret code is a sequence of four colored pegs chosen from six possible colors. After each guess, the codemaker provide... | ```python
def make_guess(init_possible_codes, guesses):
if not guesses:
return 1122 # Start with initial guess 1122
# Implement the codebreaker's strategy to determine the next guess
# For example, you can use an algorithm like Knuth's algorithm to make an optimal guess based on the previous feedb... | magicoder | python |
You are tasked with implementing a class that processes and manipulates data strings based on a given character bound. The class should have a property for the character bound and another property for the data string. The character bound represents the maximum Unicode code point value allowed in the data string. You ne... | ```csharp
public class DataProcessor
{
public virtual uint BoundCY { get; set; }
public virtual string DataString { get; set; }
public void ProcessDataString(char replacementChar)
{
StringBuilder processedString = new StringBuilder();
foreach (char c in DataString)
{
... | magicoder | csharp |
You are tasked with creating a program that analyzes the frequency of words in a given text and returns the most frequently occurring word(s). Your program should ignore common English words (e.g., "the", "and", "is") and be case-insensitive. If there are multiple words with the same highest frequency, return all of th... | ```python
from collections import Counter
from typing import List
def most_frequent_words(text: str, ignore_words: List[str]) -> List[str]:
# Convert text to lowercase and split into words
words = text.lower().split()
# Remove punctuation and ignored words
words = [word.strip(",.") for word in wor... | magicoder | python |
You are tasked with implementing a function to validate user nicknames based on the following criteria:
1. The nickname must be at least 6 characters long.
2. The nickname can only contain alphanumeric characters (a-z, A-Z, 0-9).
3. The nickname must start with an uppercase letter.
You need to implement the function `... | ```rust
fn valid_nick(nickname: &str) -> bool {
if nickname.len() < 6 {
return false;
}
if !nickname.chars().next().map_or(false, |c| c.is_ascii_alphabetic() && c.is_ascii_uppercase()) {
return false;
}
if !nickname.chars().all(|c| c.is_ascii_alphanumeric()) {
return false;
... | magicoder | rust |
You are given a set of sensor data that includes sensor IDs, timestamps, and sensor readings. The sensor IDs are randomly generated integers between 1001 and 2000. The timestamps are generated at 15-minute intervals for a period of 1000 intervals starting from the current date and time. The sensor readings are generate... | ```python
import random
import datetime
import numpy as np
# Generate faulty sensor data
id = random.randint(1001, 2000)
Today = datetime.datetime.today()
date_list = [Today + datetime.timedelta(minutes=15*x) for x in range(0, 1000)]
range_list = np.linspace(1, 2, 1000)
# Calculate the average sensor reading
average_... | magicoder | python |
You are tasked with implementing a trait for a bitmap font in Rust. The trait, `ToBitmapFont`, has three methods: `bitmap_height`, `bitmap_width`, and `font_size`. Your goal is to create a struct that implements this trait and returns the appropriate values for each method.
The `ToBitmapFont` trait is defined as follo... | ```rust
// Define a struct representing a bitmap font
struct BitmapFont {
height: u32,
width: u32,
size: u32,
}
// Implement the ToBitmapFont trait for the BitmapFont struct
impl ToBitmapFont for BitmapFont {
fn bitmap_height(&self) -> u32 {
self.height
}
fn bitmap_width(&self) -> u32 ... | magicoder | rust |
You are tasked with implementing a disassembler for a custom instruction set architecture (ISA). The disassembler should be able to convert machine code instructions into human-readable assembly language mnemonics. The provided code snippet imports a module named "disassembler" which contains the necessary functionalit... | ```python
# disassembler.py
def disassemble_instruction(instruction):
opcode = instruction >> 26 # Extracting the opcode from the instruction
if opcode == 0b000000:
return "ADD" # Example: Opcode 0b000000 corresponds to the ADD instruction
elif opcode == 0b000010:
return "SUB" # Example:... | magicoder | python |
You are tasked with creating a program that utilizes the AWS Rekognition service to detect labels in images. The AWS Rekognition service provides an API for image analysis, including label detection, facial analysis, and text recognition. In this problem, you will be focusing on the label detection functionality.
Your... | ```python
import boto3
from botocore.exceptions import NoCredentialsError
from typing import List
def detect_labels(image_file: str) -> List[str]:
# Initialize the Rekognition client
rekognition_client = boto3.client('rekognition')
try:
# Detect labels in the image
with open(image_file, 'r... | magicoder | python |
You are tasked with creating a PHP class that can parse XML data and extract specific information from it. Your class should be able to handle XML data from a Sonos music system and extract details about the music library.
Your task is to create a class called `SonosXmlParser` with a method `getMusicLibrary` that take... | ```php
class SonosXmlParser
{
public function getMusicLibrary(string $xml): array
{
$library = [];
$dom = new DOMDocument();
$dom->loadXML($xml);
$artists = $dom->getElementsByTagName('Artist');
foreach ($artists as $artist) {
$artistName = $artist->getElemen... | magicoder | php |
You are working for a biotechnology company that is conducting research on the production of certain genes under different temperature conditions. The company has collected data on the production levels of each gene under two different temperature conditions and the associated induction costs. Your task is to write a P... | ```python
import numpy as np
def most_cost_effective_gene(production, costs):
# Calculate the total cost for each gene under each temperature condition
total_cost_cond1 = production["production_cond1"] * costs["cost"]
total_cost_cond2 = production["production_cond2"] * costs["cost"]
# Find the index o... | magicoder | python |
You are tasked with implementing a blockchain network using Python and Flask. The provided code snippet is a part of a Flask web application that handles the replacement of the blockchain chain in response to a GET request to the '/replace_chain' endpoint. The `replace_chain` function is called when this endpoint is ac... | ```python
def replace_chain():
global blockchain # Assuming 'blockchain' is the variable holding the current chain
new_chain = request.get_json().get('new_chain') # Assuming the new chain is received as JSON in the request
if new_chain is None:
return False # No new chain received, so no replacem... | magicoder | python |
You are tasked with creating a Bash script that automatically installs the Git Tab Completion script from a specified link. The script should be able to download the script from the provided URL and install it in the appropriate directory.
Your task is to write a Bash script that accomplishes the following:
1. Set the... | ```bash
#!/bin/bash
# Set BASEDIR to the absolute path of the directory containing the script
BASEDIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Define the URL for the Git Tab Completion script
LINK="https://raw.githubusercontent.com/git/git/v2.17.1/contrib/completion/git-completion.bash"
# Download the scrip... | magicoder | shell |
You are tasked with creating a script to automate the installation of essential web development tools on a Linux system. The script should install Node.js, Apache, and MySQL. Your script should handle the installation process for each tool, including any necessary dependencies and system updates.
Your script should pe... | ```bash
#!/bin/bash
# Update system packages
sudo apt-get update
# Install Node.js
curl -fsSL https://deb.nodesource.com/setup_current.x | sudo -E bash -
sudo apt-get install -y nodejs
# Install Apache
sudo apt-get install -y apache2
# Install MySQL (not shown in the code snippet)
# Example: sudo apt-get install -y... | magicoder | shell |
You are tasked with implementing a function to reconstruct a 32-bit integer from a given set of operations and bit manipulations. The function `_bit_reconstruction_and_f` takes an optional boolean parameter `xor_x4` and returns an integer or None. The function utilizes several helper functions and variables, including ... | ```python
from typing import Union
def _bit_reconstruction_and_f(xor_x4=False) -> Union[int, None]:
def _lfsr(index: int) -> int:
# Implementation of the LFSR function
pass
def _get_h_l(high_index: int, low_index: int) -> int:
# Implementation of getting high and low bits
pass
... | magicoder | python |
You are tasked with implementing a function that processes a series of graph queries and returns the results based on the given graph structure. The graph is represented using the OdinGraph library, which provides methods for querying and manipulating graph data.
The graph consists of nodes and directed edges, where e... | ```javascript
function processGraphQueries(graph, queries) {
const results = [];
for (const query of queries) {
const result = eval(`graph.${query.operation}`);
results.push(result.length);
}
return results;
}
```
The `processGraphQueries` function takes the `graph` object and an array of `queries` as ... | magicoder | javascript |
You are tasked with implementing a program to find all prime numbers up to a given limit using the Sieve of Eratosthenes algorithm. The Sieve of Eratosthenes is an ancient algorithm for finding all prime numbers up to a specified integer. It works by iteratively marking the multiples of each prime number starting from ... | ```rust
use std::io;
// Function to find all prime numbers up to n using Sieve of Eratosthenes
fn sieve_of_eratosthenes(n: usize) -> Vec<bool> {
let mut is_prime: Vec<bool> = vec![true; n + 1];
is_prime[0] = false;
is_prime[1] = false;
for i in 2..=(n as f64).sqrt() as usize {
if is_prime[i] {... | magicoder | rust |
You are given a 2D image represented as a 2D array of integers. Your task is to implement a function `pixelate(image_array, pixel_size, gradation_number)` that pixelates the image by replacing each pixel block with the average color value of that block. The pixelation process involves dividing the image into non-overla... | ```python
import numpy as np
def pixelate(image_array, pixel_size, gradation_number):
height = len(image_array)
width = len(image_array[0])
grey_step = 256 // gradation_number
for i in range(0, height, pixel_size):
for j in range(0, width, pixel_size):
summa = np.sum(image_array[i:i... | magicoder | python |
You are tasked with simulating a simple text formatting and printing system. The system provides a set of commands to control the formatting and printing of text. Your goal is to implement a program that processes a sequence of commands and text content, and produces the formatted output.
The commands available are:
-... | ```python
class TextPrinter:
def __init__(self):
self.justification = "L"
self.font_size = "S"
self.underline = False
def justify(self, mode):
self.justification = mode
def setSize(self, size):
self.font_size = size
def println(self, text):
if self.just... | magicoder | python |
You are given a Python code snippet that performs clustering using either KMeans or LouvainB algorithm. The code snippet is part of a larger program that processes data and performs clustering based on certain criteria. Your task is to implement a function that takes the clustering results and calculates the silhouette... | ```python
from sklearn.metrics import silhouette_score
import networkx as nx
from networkx.algorithms.community.quality import modularity
def calculate_clustering_score(clustering_algorithm, clustering_results, data):
if clustering_algorithm == 'KMeans':
silhouette = silhouette_score(data, clustering_resul... | magicoder | python |
You are working on a project to convert Keras models to ONNX format for interoperability with other deep learning frameworks. As part of this project, you need to implement a function that extracts the computational graph from a Keras model and converts it to ONNX format.
You are given a code snippet that shows part o... | ```python
def convert_to_onnx(model):
scope = Scope() # Assume Scope class is defined for managing variables and operations
topology = Topology() # Assume Topology class is defined for representing the computational graph
def _parse_keras(topology, scope, model, node):
# Implement the logic to pa... | magicoder | python |
You are tasked with creating a custom JSON serializer for a Java class using Google's Gson library. The class `Person` represents a person's information and has the following fields:
- `name` (String): the person's name
- `age` (int): the person's age
- `email` (String): the person's email address
Your task is to crea... | ```java
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import java.io.IOException;
class Person {
@SerializedName(... | magicoder | java |
You are tasked with implementing a function that processes binary data to populate a nested HashMap structure in Rust. The function is expected to read binary data and construct a HashMap with String keys and nested HashMap values containing usize keys and String values. The provided code snippet serves as a starting p... | ```rust
use std::collections::HashMap;
use anyhow::{anyhow, Result};
use scroll::{Pread, LE};
struct DwarfData {
code_registration_offset: Option<u32>,
// Other fields as per the actual implementation
}
struct BinaryBuf {
// Implementation details for reading binary data
}
struct CodeRegistration {
/... | magicoder | rust |
You are tasked with creating a command-line interface (CLI) for a screen capture application. The application should allow users to specify various configuration options through command-line arguments. Your task is to implement a parser for these command-line arguments using the C++ library `CLI11`.
The provided code ... | ```cpp
#include <CLI/CLI.hpp>
struct Config {
std::string screen_capture_file;
std::string screen_capture_connection_id;
int screen_capture_width = 960;
};
int main(int argc, char** argv) {
Config config;
CLI::App app{"Screen Capture Application"};
app.add_option("--screen-capture-file",
... | magicoder | cpp |
You are tasked with creating a program that processes SVG (Scalable Vector Graphics) data to extract and manipulate specific attributes. SVG data is represented as a string containing various attributes and values. For this problem, you need to extract the `viewBox` attribute and the `fill` attribute from the SVG data ... | ```python
def processSVG(svgData: str) -> dict:
attributes = svgData.split()
viewBox = list(map(int, attributes[1].strip('viewBox="').split()))
fill = attributes[3].strip('fill="')
return {'viewBox': viewBox, 'fill': fill}
``` | magicoder | python |
You are tasked with creating a custom storage class for a Django project that will store media files on Amazon S3 using the `S3Boto3Storage` backend. Your custom storage class should have the following features:
1. The class should be named `CustomMediaStorage`.
2. It should inherit from `S3Boto3Storage`.
3. The media... | ```python
from storages.backends.s3boto3 import S3Boto3Storage
class CustomMediaStorage(S3Boto3Storage):
location = 'media'
file_overwrite = False
```
The `CustomMediaStorage` class inherits from `S3Boto3Storage` and sets the `location` attribute to 'media' and the `file_overwrite` attribute to `False`, as pe... | magicoder | python |
You are tasked with implementing a function to compute the Cavg (average cost) for a given set of language recognition pairs. The Cavg is calculated using several threshold bins within a specified score range. The function `get_cavg` takes the following parameters:
- `pairs`: A list of language recognition pairs, where... | ```python
def get_cavg(pairs, lang_num, min_score, max_score, bins=20, p_target=0.5):
''' Compute Cavg, using several threshold bins in [min_score, max_score].
'''
cavgs = [0.0] * (bins + 1)
precision = (max_score - min_score) / bins
for section in range(bins + 1):
threshold = min_score + se... | magicoder | python |
You are tasked with creating a Django signal handler that automatically creates a corresponding `UserSocialAuth` instance whenever a new `User` instance is created. The `User` model is provided by the `django.contrib.auth.models` module, and the `UserSocialAuth` model is provided by the `social_django.models` module.
... | ```python
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from social_django.models import UserSocialAuth
@receiver(post_save, sender=User)
def create_user_social_auth(sender, instance, created, **kwargs):
if created:
UserSocia... | magicoder | python |
You are tasked with implementing a function to generate a message for posting on a social media platform. The message should be created based on a set of predefined rules and should be suitable for posting on a user's feed. The function should take into account the user's preferences and generate a message accordingly.... | ```python
def create_msg():
# Implement the create_msg function based on the user's preferences
# Example:
user_preferences = get_user_preferences(test_user_id)
if user_preferences['theme'] == 'travel':
message = "Exploring new destinations! #travel"
elif user_preferences['theme'] == 'food':... | magicoder | python |
You are tasked with implementing a log hierarchy builder for a dataset containing Huawei device logs. The given code snippet is a part of this implementation. The `huawei_df` dataframe contains the Huawei device logs, and the goal is to construct a log hierarchy based on certain relevant columns. The `tqdm` function is... | To complete the implementation of the log hierarchy builder, you can extend the given code snippet to build a hierarchical structure based on the log data. Here's a possible solution using Python and pandas:
```python
import pandas as pd
from tqdm import tqdm
# Sample data for demonstration
data = {
'relevant_log... | magicoder | python |
You are tasked with creating a Bash script that configures proxy settings based on user input. The script should take three arguments: proxy type, proxy address, and port number. If the script is executed with fewer than three arguments, it should display an error message and exit. If the script receives the correct nu... | ```bash
#!/bin/bash
if [ $# -lt 3 ]; then
echo "No Proxy configuration provided"
exit 0
else
proxy_type=$1
proxy_address=$2
port_number=$3
# Configure proxy settings based on the provided arguments
# Example: Set HTTP and HTTPS proxy
export http_proxy="$proxy_type://$proxy_address:$port_number"
expo... | magicoder | shell |
You are tasked with creating a Python script that interacts with various .NET libraries to perform geometric operations within the context of Autodesk Revit. The script should utilize the `clr` module to add references to the required .NET assemblies and import necessary namespaces to access the functionality provided ... | ```python
import clr
from System.Collections.Generic import List
from Autodesk.DesignScript.Geometry import Point, Polygon
from Revit.Elements import Element, GeometryElement
def create_revit_polygon(points: List[Point]) -> Element:
clr.AddReference('ProtoGeometry')
clr.AddReference("RevitNodes")
import Re... | magicoder | python |
You are tasked with implementing a Python function that can determine the execution order of a series of functions based on their dependencies. Each function has a unique identifier and may depend on the output of other functions. Your task is to create a function that takes a list of tuples, where each tuple represent... | ```python
def determine_execution_order(functions):
graph = {f: set(deps) for f, deps in functions}
execution_order = []
def dfs(node, visited, stack):
visited.add(node)
for neighbor in graph[node]:
if neighbor not in visited:
dfs(neighbor, visited, stack)
... | magicoder | python |
You are tasked with implementing a custom asynchronous wait mechanism in Java. Your task is to create a class that provides a method for waiting until a specified condition is met. The condition will be checked repeatedly until it evaluates to true.
You are provided with the following interface:
```java
public interf... | ```java
import java.util.concurrent.TimeUnit;
public class WaitUtil {
public static void await(Condition condition, long timeout, TimeUnit timeUnit) {
long endTime = System.currentTimeMillis() + timeUnit.toMillis(timeout);
while (System.currentTimeMillis() < endTime) {
if (condition.eva... | magicoder | java |
You are tasked with creating a program that simulates a simple text-based game. The game involves a character navigating through a series of challenges and making decisions based on input. The character's goal is to reach a specific destination by following a set of rules.
The provided code snippet is a part of the ga... | ```rust
use std::io;
fn main() {
let mut input = String::new();
let mut output = String::new();
loop {
writeln!(io::stdout(), "Enter your next move: ").unwrap();
io::stdin().read_line(&mut input).unwrap();
// Process the input and make decisions based on the game's rules
l... | magicoder | rust |
You are given a list of integers `a` of length `n`. Your task is to write a function to calculate the median of the list. The median of a list of numbers is the middle number when the list is sorted. If the list has an odd number of elements, the median is the middle element. If the list has an even number of elements,... | ```python
def calculate_median(a):
a.sort()
s = len(a)
if s % 2 == 0:
median = (a[int(s/2) - 1] + a[int(s/2)]) / 2
else:
median = a[int(s/2)]
return median
```
The `calculate_median` function first sorts the input list `a`. Then, it checks if the length of the list is even or odd. If... | magicoder | python |
You are tasked with implementing a C++ template meta-programming problem. Your goal is to create a meta-function that takes a set of sequences and an index, and returns a new sequence containing the elements at the specified index from each input sequence.
You are provided with a code snippet that contains a partial i... | ```cpp
namespace metal {
/// \cond
namespace detail {
template<class num, class... seqs>
struct transformer_impl {
template<template<class...> class expr>
using type = expr<at<seqs, num>...>;
};
template<template<class...> class expr, class... seqs>
... | magicoder | cpp |
You are tasked with implementing a file management system for a survey application. The system should allow users to remove files and manage the validity of different sections of the survey. The application variables `answers` and `sectionsValidity` are used to store the survey responses and the validity status of diff... | ```javascript
function manageFile(fileType, action, key, value) {
if (fileType === "answer" && action === "remove") {
onRemoveFile(key);
} else if (fileType === "sectionValidity" && action === "update") {
sectionsValidity[key] = value;
}
return sectionsValidity;
}
``` | magicoder | javascript |
You are tasked with writing a Python function that parses a given HTML text and extracts the content within the `<span>` tags. The function should return a list of strings containing the text within the `<span>` tags in the order they appear in the HTML text.
Write a function `extract_span_content(html_txt: str) -> Li... | ```python
from typing import List
import re
def extract_span_content(html_txt: str) -> List[str]:
span_content = re.findall(r'<span.*?>(.*?)</span>', html_txt, re.DOTALL)
return span_content
``` | magicoder | python |
You are tasked with creating a simple authentication middleware for an Apollo GraphQL server. The middleware should intercept incoming requests, check for a valid authentication token, and attach the authenticated user's information to the request context before passing it to the resolver functions.
The provided code ... | ```javascript
const { ApolloServer, AuthenticationError } = require('apollo-server');
const { ApolloLink, concat } = require('apollo-link');
const { HttpLink } = require('apollo-link-http');
const { InMemoryCache } = require('apollo-cache-inmemory');
// Define the authentication middleware function
const authMiddlewar... | magicoder | javascript |
You are tasked with implementing a module for handling quoted strings in a programming language. The module should provide functionality to parse and manipulate quoted strings in a given input.
Your task is to implement the `quoted_string` module with the following requirements:
1. The module should contain a function... | ```rust
pub mod quoted_string {
pub fn parse_quoted_string(input: &str) -> (Option<String>, &str) {
let mut chars = input.chars();
if let Some('"') = chars.next() {
let mut parsed = String::new();
let mut escape = false;
for c in chars {
match c {
... | magicoder | rust |
You are tasked with creating a Python class that represents a podcast channel and its episodes. The class should have methods to add episodes, generate an XML feed, and generate an HTML representation of the channel.
Your task is to implement the `PodcastChannel` class with the following requirements:
- The class shou... | ```python
import jinja2
from xml.sax.saxutils import escape
class PodcastChannel:
def __init__(self, title, description, link, root_url):
self.title = title
self.description = description
self.link = link
self.root_url = root_url
self.episodes = []
def add_episode(self,... | magicoder | python |
You are tasked with creating a Python program that interacts with the Baidu AI NLP (Natural Language Processing) API to analyze the parts of speech of Chinese words. The given code snippet demonstrates the usage of the AipNlp client to process the Chinese sentence "我爱米思齐" (which translates to "I love Messi") and extrac... | ```python
import json
from aip import AipNlp
def analyze_parts_of_speech(app_id, api_key, secret_key, sentence):
# Initialize the AipNlp client
client = AipNlp(app_id, api_key, secret_key)
# Define the mapping of part of speech tags to their meanings
word_mapping = {"r": "代词", "v": "动词", "nr": "名词... | magicoder | python |
You are given a Python code snippet that involves the creation of grid cells using the `addGridCell` method. The method takes several parameters to define the position and boundaries of the grid cell. Your task is to create a program that simulates the behavior of the `addGridCell` method and its associated grid cells.... | ```python
class GridManager:
def __init__(self):
self.gridCells = {}
def addGridCell(self, x, y, left, right, bottom, top):
for cell_id, cell_data in self.gridCells.items():
if (x == cell_data['x'] and y == cell_data['y']) or \
(left <= cell_data['right'] and right >=... | magicoder | python |
You are tasked with implementing a function to calculate the presentation timestamp (PTS) of video frames based on the given code snippet. The code snippet is a part of a video decoding process and involves the use of FFmpeg library functions. Your task is to write a function that takes the necessary input parameters a... | ```c
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
double calculatePresentationTimestamp(AVCodecContext *pCodecCtx, AVFrame *frame, AVPacket packet, AVFormatContext *pFormatCtx, double current_time) {
int frameFinished;
avcodec_decode_video2(pCodecCtx, frame->data, &frameFinished, &packet);... | magicoder | c |
You are tasked with implementing a graph data structure in Python. Specifically, you need to create a method to add an edge to a vertex in the graph. The graph is represented using an adjacency list, and each vertex has a list of edges incident to it.
You are given the following code snippet for the `add_edge` method ... | ```python
class Edge:
def __init__(self, v_from, v_to):
self.v_from = v_from
self.v_to = v_to
class Vertex:
def __init__(self, value):
self.value = value
self.edges = []
def add_edge(self, e):
""" Adds an edge to this vertex """
if self != e.v_from and self ... | magicoder | python |
You are tasked with implementing a tile caching system for a navigation mesh in a game development project. The provided code snippet initializes a navigation mesh and a tile cache, and then returns the tile cache instance. Your goal is to complete the implementation by defining the necessary parameters and processes f... | ```java
// Define the TileCacheStorageParams class
class TileCacheStorageParams {
int order;
String cCompatibility;
public TileCacheStorageParams(int order, String cCompatibility) {
this.order = order;
this.cCompatibility = cCompatibility;
}
}
// Define the TileCacheCompressorFactory c... | magicoder | java |
You are tasked with creating a script to automate the generation of PBS (Portable Batch System) job scripts for running a series of Vaa3D image processing tasks in a high-performance computing environment. The script should take into account the specific file paths and parameters required for each job script.
Your tas... | ```python
def generate_pbs_scripts(start_index, end_index, pbs_template_path, output_directory, vaa3d_executable_path):
with open(pbs_template_path, 'r') as template_file:
template_content = template_file.read()
for i in range(start_index, end_index + 1):
job_script_content = template_content.r... | magicoder | python |
You are tasked with implementing a command-line tool for managing a gargantua, a powerful entity in a fictional universe. The tool should support creating or starting a gargantua, stopping it, and destroying it. Additionally, it should provide an option to display a help message.
The tool should accept the following c... | ```python
import sys
def manage_gargantua(command):
if command == "up":
print("Gargantua created or started.")
elif command == "stop":
print("Gargantua stopped.")
elif command == "destroy":
print("Gargantua destroyed.")
elif command == "-h" or command == "--help":
print(... | magicoder | python |
You are tasked with implementing a custom dataset class for image classification using PyTorch. The dataset class, named `FollowSuit`, should be designed to load image indexes and class label annotations from a CSV file. Your task is to complete the `FollowSuit` class by implementing the necessary methods to load and p... | ```python
import torch
from torch.utils.data import Dataset
import pandas as pd
from PIL import Image
class FollowSuit(Dataset):
def __init__(self, csv_file):
"""
Args:
csv_file (string): Path to the csv file with image indexes and class label annotations.
"""
self.data ... | magicoder | python |
You are given a string representing a grid of seats in a movie theater. Each character in the string represents a seat, where 'L' indicates an empty seat and '.' indicates an occupied seat. The grid is represented as a single string, with each row of the theater concatenated together.
Your task is to write a function ... | ```python
def findEmptySeats(grid: str) -> int:
return grid.count('L')
```
The `findEmptySeats` function simply uses the `count` method of strings to count the occurrences of 'L' in the grid, which represents the empty seats. This provides the total number of empty seats in the theater and returns the count as the ... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.