query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are working with a Python script that processes single-cell RNA sequencing data using the Anndata library. The code snippet provided is part of a function that calculates signatures for different cell types based on the specified data location. The function takes in the Anndata object `adata`, a list of cell type l... | ```python
def calculate_signatures(adata, cell_type_labels, data_loc, save_path=None):
signatures = {}
for cell_type in cell_type_labels:
if data_loc == "X":
signatures[cell_type] = adata[adata.obs[cell_type_labels] == cell_type].X.mean(axis=0)
elif data_loc == "raw":
sig... | magicoder | python |
You are tasked with implementing a Python class that manages the allocation of hidden states to different CUDA devices. The class, named `DeviceManager`, contains a method `allocate_to_device` that takes a tensor of hidden states and an index `i` as input. The method should allocate the hidden states to a CUDA device b... | ```python
class DeviceManager:
def __init__(self, device_map, last_device):
self.device_map = device_map
self.last_device = last_device
def allocate_to_device(self, hidden_states, i):
for k, v in self.device_map.items():
if i == v[-1] and "cuda:" + str(k) != self.last_device... | magicoder | python |
You are tasked with identifying and resolving a data race in a multi-threaded program. The given code snippet is part of a larger program that uses multiple threads to manipulate shared data. Your goal is to analyze the code, identify the potential data race, and propose a solution to resolve it.
The code snippet prov... | Identifying and resolving a data race in a multi-threaded program requires careful synchronization of shared data to prevent concurrent access issues. Here's a general approach to resolving a data race:
1. Identify the shared data: Look for variables or resources that are accessed by multiple threads concurrently.
2.... | magicoder | python |
You are tasked with implementing a function that validates a list of decimal numbers based on a specific pattern. The pattern is defined as follows: each decimal number in the list must have exactly 3 digits after the decimal point and must be within the range of -100.0 to 100.0 (inclusive). Your task is to write a fun... | ```python
from typing import List
def validate_decimal_list(decimal_list: List[float]) -> bool:
for num in decimal_list:
if not (-100.0 <= num <= 100.0):
return False
if not "{:.3f}".format(num).endswith('.000'):
return False
return True
```
The `validate_decimal_list` ... | magicoder | python |
You are tasked with implementing a Rust module for controlling a PCA9685 servo driver using the `i2cdev` crate. The PCA9685 is a 16-channel, 12-bit PWM controller suitable for driving servos and LEDs. The `servo_driver` module contains the necessary code for interfacing with the PCA9685 and the `i2cdev` crate provides ... | ```rust
use i2cdev::linux::LinuxI2CError;
pub struct PCA9685 {
// Fields for PCA9685
}
impl PCA9685 {
pub fn new() -> Result<PCA9685, LinuxI2CError> {
// Initialize PCA9685 and return a new instance
unimplemented!()
}
pub fn set_pwm_frequency(&mut self, frequency: f64) -> Result<(), L... | magicoder | rust |
You are tasked with creating a Python program that logs messages from a Discord bot to a file using the `logging` module. The program should set up a logger to handle and format the log messages, and then write these messages to a file with a specified maximum size and no backup count. Your task is to complete the prog... | ```python
import logging
from logging.handlers import RotatingFileHandler
# Import the necessary module to work with Discord
import discord
LOG_FILENAME = "errs"
# Create a logger object for the program
logger = logging.getLogger(__name__)
# Configure a rotating file handler for the logger with a maximum file size ... | magicoder | python |
You are working on a project that involves interfacing with a low-level library using Python's Foreign Function Interface (FFI). The library in question is LLVM, a collection of modular and reusable compiler and toolchain technologies. Your task is to create a Python wrapper for certain functions in the LLVM library us... | ```python
import cffi
# Define the CFFI interface
ffi = cffi.FFI()
ffi.cdef("""
typedef struct LLVMOpaquePassManagerBuilder *LLVMPassManagerBuilderRef;
LLVMPassManagerBuilderRef LLVMPY_PassManagerBuilderCreate();
void LLVMPY_PassManagerBuilderDispose(LLVMPassManagerBuilderRef);
""")
# Load the LLVM librar... | magicoder | python |
You are tasked with implementing a function to evaluate a postfix expression. A postfix expression is an arithmetic expression in which the operators follow their operands. For example, the infix expression "2 + 3" would be written as "2 3 +". The operators supported are addition (+), subtraction (-), multiplication (*... | ```python
def evaluate_postfix(expression):
stack = []
for token in expression:
if token.isdigit():
stack.append(int(token))
else:
operand2 = stack.pop()
operand1 = stack.pop()
if token == '+':
stack.append(operand1 + operand2)
... | magicoder | python |
You are tasked with implementing a function that calculates the total number of occurrences of a given word in a list of strings. The function should be case-insensitive and should count partial matches as well. For example, if the word is "cat", it should count occurrences of "cat", "cats", "category", etc. The functi... | ```java
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WordCounter {
public static void main(String[] args) {
List<String> strings = Arrays.asList("The cat is on the mat.", "Cats are cute!", "category");
String word = "ca... | magicoder | java |
You are tasked with implementing a custom exception handling mechanism for an API. The API has two specific error types that need to be handled: `WrongToken` and `PermissionError`. Your task is to create a Python class that represents the custom API error and implement a function to handle these errors.
You need to cr... | ```python
class ApiError(Exception):
pass
class WrongToken(ApiError):
pass
class PermissionError(ApiError):
pass
def handle_api_error(error):
if isinstance(error, WrongToken):
# Handle WrongToken error
print("Handling WrongToken error")
elif isinstance(error, PermissionError):
... | magicoder | python |
You are tasked with implementing a class that manages shared memory for storing arrays. The class should support creating a shared memory array, accessing and modifying its elements, and providing a contextual wrapper for the shared memory.
You are given a partial implementation of the class as a starting point. The c... | ```python
import mmap
import numpy as np
class SharedMemoryArray:
def __init__(self, shape, dtype):
"""
Initializes the shared memory array with the given shape and data type.
:param shape: the shape of the array
:param dtype: the data type of the array
"""
... | magicoder | python |
You are tasked with developing a custom migration operation for a Django application. The goal is to create a new migration operation that will add a new field to an existing model in the database. The new field should be a CharField with a maximum length of 100 characters. Your task is to implement the custom migratio... | ```python
from django.db import migrations, models
class AddNewField(migrations.Migration):
dependencies = [
('users', '0002_auto_20170613_2124'),
]
operations = [
migrations.AddField(
model_name='your_model_name',
name='new_field_name',
field=models.Cha... | magicoder | python |
You are tasked with implementing a function that validates a given JavaScript object against a specified interface. The interface is defined using TypeScript's interface syntax, and the validation function should ensure that the object adheres to the structure defined by the interface.
You are provided with the follow... | ```typescript
function validateObject(obj: any, interfaceDef: any): boolean {
for (const key in interfaceDef) {
if (typeof interfaceDef[key] === "object") {
if (!validateObject(obj[key], interfaceDef[key])) {
return false;
}
} else if (Array.isArray(interfaceDef[key])) {
if (!Array.i... | magicoder | typescript |
You are tasked with creating a Python program that can decode a Lua table into a Python class. The Lua table will be represented as a string, and the Python class should be able to store the key-value pairs from the Lua table. Your program should be able to handle nested Lua tables and convert them into nested Python c... | ```python
import re
class LuaTable:
pass
def decode_lua_table(lua_table_str):
lua_table_str = lua_table_str.replace('{', '').replace('}', '') # Remove curly braces
lua_table_str = re.sub(r'\s*=\s*', ':', lua_table_str) # Replace '=' with ':'
lua_table_str = re.sub(r'(\w+)', r'"\1"', lua_table_str) ... | magicoder | python |
You are working on a project to analyze molecular structures represented as graphs. Each graph represents a molecule, with nodes representing atoms and edges representing bonds between atoms. Your task is to write a function to find all possible fragment combinations of the molecule graphs, i.e., all connected induced ... | ```python
class MoleculeGraph:
# Other methods and properties of the class
def build_unique_fragments(self):
"""
Find all possible fragment combinations of the MoleculeGraphs (i.e., all connected induced subgraphs)
:return: List of all possible fragment combinations
"""
... | magicoder | python |
You are tasked with creating a script to automate the generation and cleanup of hex files for a microcontroller project. The script should take in specific parameters and execute the necessary commands to generate the hex file, move it to a designated directory, and then clean up the build.
Write a bash script named `... | ```bash
#!/bin/bash
# Check if all required parameters are provided
if [ "$#" -ne 5 ]; then
echo "Usage: generate.sh TARGET MCU F_CPU I2C_ADDRESS I2C_PULLUPS"
exit 1
fi
# Assign parameters to variables
TARGET=$1
MCU=$2
F_CPU=$3
I2C_ADDRESS=$4
I2C_PULLUPS=$5
DIR="build" # Assuming the build directory is named 'bu... | magicoder | shell |
You are tasked with creating a Python function that processes a list of spans and performs various assertions on the attributes of these spans. Each span represents a request in a web application and contains attributes such as service, name, resource, span type, and error status. Your function should validate these at... | ```python
class Span:
def __init__(self, service, name, resource, span_type, error):
self.service = service
self.name = name
self.resource = resource
self.span_type = span_type
self.error = error
def validate_spans(spans):
for span in spans:
assert span.service =... | magicoder | python |
You are tasked with creating a program to analyze a given text and count the occurrences of each word. For the purpose of this problem, a word is defined as a sequence of alphanumeric characters separated by any non-alphanumeric character. The program should ignore the case of the letters and consider words with the sa... | ```python
from typing import List, Tuple
import re
from collections import Counter
def word_count_analysis(text: str) -> List[Tuple[str, int]]:
# Convert the text to lowercase and split it into words using regex
words = re.findall(r'\b\w+\b', text.lower())
# Define common English stop words
stop_w... | magicoder | python |
You are tasked with creating a Python program that simulates a simple student database using a hash data structure. The program should allow users to add, retrieve, and display student information using the hash data structure.
Your task is to implement the `StudentDatabase` class with the following functionalities:
1... | ```python
class StudentDatabase:
def __init__(self):
self.students = {}
def add_student(self, name, age):
self.students[name] = age
def get_student_age(self, name):
return self.students.get(name, "Student not found")
def display_all_students(self):
print("Students in t... | magicoder | python |
You are tasked with implementing a custom memory management system for a game engine. The system should efficiently manage memory for various resources, such as meshes, textures, and shaders, in a Vulkan-based rendering engine. Your task is to design and implement a class called `MemoryManager` that provides functional... | ```cpp
#include <mutex>
#include <unordered_map>
#include <vulkan/vulkan.h>
namespace inexor::vulkan_renderer::wrapper {
// Define a custom memory block structure to track allocated memory regions.
struct MemoryBlock {
VkDeviceMemory memory; // Vulkan device memory handle.
VkDeviceSize offset; // Offset w... | magicoder | cpp |
You are working on a financial transaction system that involves transferring funds between users. You need to implement a function to create a transfer request with a signature for authentication. The transfer request includes various details such as user UUIDs, unique IDs, price, currency name, ordinal, and timestamp.... | ```swift
import CryptoKit
func createTransferRequestWithSignature(userUUID: String, sourceUserUUID: String, destinationUserUUID: String, nineumUniqueIds: [String], price: Int, currencyName: String, ordinal: Int, timestamp: String) -> TransferRequestWithSignature {
let transferRequest = TransferRequestWithSignature... | magicoder | swift |
You are tasked with creating a program to crack a password using a brute-force attack. The program will read a wordlist file containing potential passwords and attempt to log in using each password until the correct one is found. If the correct password is found, the program will print a success message and terminate. ... | ```python
import sys
BRIGHT_YELLOW = '\033[93m'
BRIGHT_RED = '\033[91m'
def crack_password(wordlist_file, content):
try:
with open(wordlist_file, 'r') as file:
passwords = file.read().splitlines()
for password in passwords:
# Simulate login attempt
i... | magicoder | python |
You are tasked with implementing a simplified version of a scene renderer in C++. The scene renderer is responsible for submitting meshes to be rendered and retrieving the handle for the final framebuffer's color attachment.
You are provided with the following code snippet as a starting point:
```cpp
void SceneRender... | ```cpp
#include <vector>
// Define the Mesh class
class Mesh {
// Implementation details for the Mesh class
};
// Define the Transform class
class Transform {
// Implementation details for the Transform class
};
// Define the Framebuffer class
class Framebuffer {
public:
void* GetColorAttachmentHandle() ... | magicoder | cpp |
You are tasked with creating a Python class that manages a list of dares for a dare game. The class should have methods to add new dares, remove existing dares, and display all the dares in the list. Additionally, the class should be implemented as a Discord bot cog using the `discord.py` library.
Your task is to comp... | ```python
import discord
from discord.ext import commands
class Dare(commands.Cog):
def __init__(self, client):
self.client = client
self.dares = []
@commands.command(name="add_dare")
async def add_dare(self, ctx, new_dare: str):
self.dares.append(new_dare)
await ctx.send(f... | magicoder | python |
You are tasked with implementing a Java program that simulates a simple game of dice. The game involves two players taking turns to roll a standard six-sided die. The player who reaches a predefined target score first wins the game. Your task is to write a Java program that models this game and determines the winner ba... | ```java
import java.util.Random;
import java.util.Scanner;
public class DiceGame {
public static void main(String[] args) {
int targetScore = 50;
int player1Score = 0;
int player2Score = 0;
Random random = new Random();
Scanner scanner = new Scanner(System.in);
whil... | magicoder | java |
You are tasked with creating a custom view in SwiftUI that displays a list of items with alternating background colors. Your task is to implement a `ZebraListView` struct that conforms to the `View` protocol and displays a list of items with alternating background colors. The `ZebraListView` should take an array of ite... | ```swift
import SwiftUI
struct ZebraListView<Item, Content>: View where Content: View {
let items: [Item]
let content: (Item) -> Content
let color1: Color
let color2: Color
init(items: [Item], color1: Color, color2: Color, @ViewBuilder content: @escaping (Item) -> Content) {
self.items = i... | magicoder | swift |
You are tasked with implementing a Python class for performing Hill cipher encryption and decryption. The Hill cipher is a polygraphic substitution cipher based on linear algebra. It operates on blocks of plaintext and replaces them with ciphertext using matrix multiplication. The key for the Hill cipher is a square ma... | ```python
from typing import List
class Hill:
def __init__(self, key: List[List[int]], alphabet: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
self.key = key
self.alphabet = alphabet
self.mod = len(alphabet)
if len(key) != len(key[0]):
raise ValueError("Key matrix must be square... | magicoder | python |
You are tasked with creating a Python class that manages a simple inventory system for a small business. The class should allow for adding, removing, and updating items in the inventory, as well as providing functionality to check the quantity of a specific item and to generate a report of all items in the inventory.
... | ```python
class Inventory:
def __init__(self):
self.inventory = {}
def add_item(self, item_name, quantity):
if item_name in self.inventory:
self.inventory[item_name] += quantity
else:
self.inventory[item_name] = quantity
def remove_item(self, item_name, quan... | magicoder | python |
You are tasked with implementing a logistic regression model using PyTorch. Logistic regression is a fundamental machine learning algorithm used for binary classification tasks. In this problem, you will create a Python class that represents a logistic regression model using PyTorch's neural network module.
Your task ... | ```python
import torch
import torch.nn as nn
import torch.nn.functional as F
class LogisticRegression(nn.Module):
def __init__(self, n_input_features):
super(LogisticRegression, self).__init__()
self.linear = nn.Linear(n_input_features, 1)
def forward(self, x):
# Apply linear transfor... | magicoder | python |
You are tasked with implementing a rate limiting algorithm for a web service. Rate limiting is a technique used to control the rate of incoming requests to a server in order to prevent overwhelming the server and to ensure fair usage of resources. In this problem, you are required to implement a simple token bucket rat... | ```python
class TokenBucketRateLimiter:
def __init__(self, maxTokens: int, tokensPerSecond: int):
self.maxTokens = maxTokens
self.tokensPerSecond = tokensPerSecond
self.tokens = maxTokens
self.lastRefillTime = time.time()
def refillTokens(self, currentTime: float):
timeE... | magicoder | python |
You are given a code snippet that represents a part of a program. Your task is to complete the program by implementing a function that takes a string as input and returns the string with each character shifted by a specific number of positions in the alphabet. For example, if the input string is "abc" and the shift is ... | ```python
def shift_string(input_string, shift):
shifted_string = ""
for char in input_string:
if char.isalpha():
shift_amount = (ord(char) - ord('a') + shift) % 26
shifted_char = chr(ord('a') + shift_amount) if char.islower() else chr(ord('A') + shift_amount)
shifted... | magicoder | python |
You are tasked with implementing a simple DOM manipulation library in TypeScript. The library should provide two functions: `find` and `attr`.
The `find` function takes a CSS selector as input and returns a function that can be used to query for elements matching the selector within a given parent element. The returne... | ```typescript
// Define the find function
const find = (selector: string) => (selection: Element) =>
selection.querySelectorAll(selector);
// Define the attr function
const attr = (name: string, value?: string) => (selection: Element) => {
if (value === undefined) {
// Get the value of the attribute
return... | magicoder | typescript |
You are tasked with implementing a version control system for a software project. The version control system should be able to handle different versions of the project and provide functionalities to manage and retrieve specific versions of the project.
You need to create a class `VersionControl` with the following met... | ```python
class VersionControl:
def __init__(self, initial_version: str):
self.versions = [initial_version]
def commit(self, new_version: str):
self.versions.append(new_version)
def get_version(self, version_number: int) -> str:
if 1 <= version_number <= len(self.versions):
... | magicoder | python |
You are tasked with implementing a logging system for a software library. The logging system should be able to handle different levels of log messages and output them to various destinations. The code snippet provided includes the inclusion of a logging header file and a test data header file.
Your task is to design a... | ```cpp
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
// Define log levels
enum class LogLevel { DEBUG, INFO, WARNING, ERROR };
// Abstract base class for log output destinations
class LogOutput {
public:
virtual void write(const std::string& message) = 0;
virtual ~LogOutput() {}
};... | magicoder | cpp |
You are tasked with creating a Swift class that manages user information and provides methods to validate and check user status. Your task is to implement the `User` class with the following requirements:
1. The `User` class should have the following properties:
- `fname`: A string representing the user's first nam... | ```swift
enum UserType {
case channel
case user
}
class User {
var fname: String
var name: String
var rid: String
var auth: String?
var type: UserType
init(fname: String, name: String, rid: String, auth: String?, type: UserType) {
self.fname = fname
self.name = name
... | magicoder | swift |
You are tasked with implementing a function that performs an asynchronous operation and provides a completion handler with a result. Your goal is to create a function that takes in a closure as a parameter and calls it with a result of type `Result<Void, Error>`. The closure should be called with `.success(())` if the ... | ```swift
func performOperation(completion: @escaping (Result<Void, Error>) -> Void) {
// Simulate an asynchronous operation
DispatchQueue.global().async {
// Replace this with the actual asynchronous operation
let operationSuccessful = true // Replace with the actual condition for operation succ... | magicoder | swift |
You are tasked with implementing a multi-threaded program to process a list of tasks concurrently. Each task is represented by a function that takes no arguments and returns no value. Your goal is to create a program that can efficiently execute these tasks using multiple threads.
You are given a list of task function... | ```python
import threading
def execute_tasks_concurrently(task_functions, num_threads):
threads = []
for i in range(num_threads):
threads.append(threading.Thread(target=execute_task, args=(task_functions[i::num_threads],)))
threads[i].start()
for thread in threads:
thread.join()
de... | magicoder | python |
You are tasked with implementing a simple key-value store using Rust. The key-value store should support the following operations:
1. `put(key, value)`: Insert a new key-value pair into the store. If the key already exists, update the value.
2. `get(key)`: Retrieve the value associated with the given key. If the key d... | ```rust
pub const TOMBSTONE: &[u8] = &[];
pub struct KeyValueStore {
store: std::collections::HashMap<String, String>,
}
impl KeyValueStore {
pub fn new() -> Self {
KeyValueStore {
store: std::collections::HashMap::new(),
}
}
pub fn put(&mut self, key: String, value: Strin... | magicoder | rust |
You are tasked with creating a program that converts a phone number from alphanumeric format to numeric format. The input phone number will be a string containing alphanumeric characters and dashes. The program should convert any alphabetic characters to their corresponding numeric representation based on a standard ph... | ```python
def convert_to_numeric(phone_number):
numeric_phone = ''
for ch in phone_number:
if ch.islower():
ch = ch.upper()
if ch.isdigit():
numeric_phone += ch
elif ch == '-':
numeric_phone += '-'
elif ch in ['A', 'B', 'C']:
numeri... | magicoder | python |
You are tasked with creating a Python function that simulates a simple text-based game. The game involves a player navigating through a grid-based world, collecting treasures, and avoiding obstacles. The player's movements are controlled by a series of commands, and the game state is displayed after each move.
The gam... | ```python
def play_game(grid, start, commands):
def update_grid(grid, position):
new_grid = [list(row) for row in grid]
x, y = position
new_grid[y][x] = 'P'
return ["".join(row) for row in new_grid]
def collect_treasure(grid, position):
x, y = position
if grid[y]... | magicoder | python |
You are tasked with implementing a bijector class for a custom power transformation in TensorFlow Probability. The bijector should raise a given input to the power specified by an odd integer. Your task is to create a Python class that inherits from `tfp.bijectors.Bijector` and implements the power transformation logic... | ```python
import tensorflow as tf
import tensorflow_probability as tfp
import numpy as np
class PowerBijector(tfp.bijectors.Bijector):
def __init__(self, power, validate_args=False):
self._power = power
super(PowerBijector, self).__init__(
validate_args=validate_args,
forwar... | magicoder | python |
You are working for an advertising agency that uses an API to manage ad campaigns for various clients. The agency has a system that interacts with the ad platform through an adwords client and manages ad groups for different campaigns. Your task is to implement a function that will update the ad groups for a given clie... | ```python
def main(adwords_client, adgroups):
for ad_group in adgroups:
ad_group_id = ad_group['ad_group_id']
status = ad_group['status']
max_cpc = ad_group['max_cpc']
ad_group_service = adwords_client.GetService('AdGroupService', version='v201809')
ad_group_operatio... | magicoder | python |
You are tasked with implementing a simple neural network training loop for a sequence classification task. The provided code snippet outlines the beginning of the training loop, where the model is trained using a given dataloader. Your task is to complete the training loop by implementing the forward pass, backward pas... | ```python
import torch
import torch.nn as nn
import torch.optim as optim
# Define the neural network model
class SimpleClassifier(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(SimpleClassifier, self).__init__()
self.hidden = nn.Linear(input_size, hidden_size)
s... | magicoder | python |
You are given a Python code snippet that is intended to validate a specific input format. The code snippet is responsible for checking the validity of a given input string based on certain conditions. Your task is to understand the conditions and implement a function that performs the same validation as the given code ... | ```python
def validate_input(input_string: str) -> bool:
if len(input_string) != 10:
return False
if input_string.count('A') != 2 or input_string.count('N') != 3:
return False
for char in input_string:
if input_string.count(char) > 1:
return False
return True
```
... | magicoder | python |
You are given a Java method that is intended to return the maximum value from an array of integers. However, the method contains some extraneous code and is not functioning as expected. Your task is to fix the method so that it correctly returns the maximum value from the given array.
```java
public class MaxValueFind... | ```java
public class MaxValueFinder {
public static int findMaxValue(int[] arr) {
int v = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {
if (arr[i] > v) {
v = arr[i];
}
}
return v;
}
}
```
The solution simply removes the extraneo... | magicoder | java |
You are tasked with implementing a Python class for managing and validating poetic meter patterns. The class, named `Poet`, should provide methods for inserting and retrieving meter patterns, as well as for validating the existence of a given meter pattern. The meter pattern is a fundamental aspect of poetry, represent... | ```python
class Poet:
meter_patterns = set()
@classmethod
def insert_samples(cls):
cls.meter_patterns.update(["Iambic Pentameter", "Trochaic Tetrameter", "Anapestic Trimeter"])
@classmethod
def validate_meter_pattern(cls, pattern):
if pattern in cls.meter_patterns:
retu... | magicoder | python |
You are tasked with creating a Python script that processes a given text file to extract specific information. The text file contains copyright information for various software components. Each copyright notice is preceded by a comment symbol (#) and includes the copyright year and the name of the copyright holder. You... | ```python
from typing import List, Dict, Union
def extract_copyright_info(file_path: str) -> List[Dict[str, Union[str, int]]]:
copyright_info = []
with open(file_path, 'r') as file:
lines = file.readlines()
for line in lines:
if line.startswith("# This file is Copyright"):
... | magicoder | python |
You are working on a Pokémon data manipulation program. The code snippet provided is part of a class method that creates a new Pokémon instance based on an existing one. The new Pokémon's nature, nickname, and original trainer's name are set based on the existing Pokémon's attributes. Additionally, the location where t... | ```python
def calculate_exp_required(level):
exp_required = int(4 * (level ** 3) / 5)
return exp_required
```
The `calculate_exp_required` function takes the level of the Pokémon as input and calculates the experience points required using the provided formula. The result is then returned after rounding down to... | magicoder | python |
You are tasked with implementing a function that processes a given array of integers and returns the count of pairs of elements that sum up to a specific target value. The function should efficiently handle large input arrays and be optimized for time complexity.
Write a function `countPairsWithSum` that takes in the ... | ```swift
func countPairsWithSum(_ nums: [Int], _ target: Int) -> Int {
var count = 0
var numSet = Set<Int>()
for num in nums {
let complement = target - num
if numSet.contains(complement) {
count += 1
}
numSet.insert(num)
}
return count
}
// Test the fu... | magicoder | swift |
You are tasked with creating a program to find the nth ugly number. An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. For example, the first 10 ugly numbers are 1, 2, 3, 4, 5, 6, 8, 9, 10, and 12. Your program should take an integer n as input and return the nth ugly number.
Write a ... | ```python
def nthUglyNumber(n: int) -> int:
ugly = [1]
i2, i3, i5 = 0, 0, 0
while len(ugly) < n:
next_ugly = min(ugly[i2] * 2, ugly[i3] * 3, ugly[i5] * 5)
ugly.append(next_ugly)
if next_ugly == ugly[i2] * 2:
i2 += 1
if next_ugly == ugly[i3] * 3:
i3 += ... | magicoder | python |
You are tasked with implementing a Python class for handling I/O operations from/to a pickled file on disk. The class should inherit from a parent class `FileComm` and accept a file name as an argument. Additionally, any additional keyword arguments should be passed to the parent class.
Your task is to complete the im... | ```python
import pickle
import FileComm
class PickleFileComm(FileComm.FileComm):
r"""Class for handling I/O from/to a pickled file on disk.
Args:
name (str): The environment variable where file path is stored.
**kwargs: Additional keywords arguments are passed to parent class.
"""
def... | magicoder | python |
You are tasked with creating a Rust function that processes incoming messages from a TCP stream. The function should parse the incoming messages and extract specific information from them. The messages are formatted using color codes and contain transaction details. Your task is to implement a function that extracts th... | ```rust
use regex::Regex;
fn process_message(message: &str) -> Option<(u32, String)> {
let re = Regex::new(r"\u{1b}\[34mRECEIVE \u{1b}\[38;5;216m(\d+)\u{1b}\[38;5;208m'(.+)'").unwrap();
if let Some(captures) = re.captures(message) {
let amount = captures.get(1).unwrap().as_str().parse::<u32>().unwrap... | magicoder | rust |
You are tasked with implementing a generic response handler for a web service. The `Response` class is a generic class that contains the data and metadata of a response from the web service. Your goal is to implement the `SetResponse` method, which takes a `Response` object and performs certain operations based on the ... | ```csharp
void SetResponse<TData>(Response<TData> response)
{
if (response.IsSuccess)
{
Console.WriteLine("Success: " + response.Data);
}
else
{
Console.WriteLine("Failure: " + response.Message);
}
}
```
The `SetResponse` method takes a generic `Response` object as a parameter. I... | magicoder | csharp |
You are tasked with creating a command-line utility for managing a PostgreSQL database. The utility, `pg_proc.sh`, should support various operations such as displaying the process list, showing locks, canceling backend queries, and terminating backends. Your goal is to implement the logic for parsing the command-line a... | ```bash
#!/bin/bash
# Function to display the process list
show_process_list() {
# Logic to display the process list
echo "Displaying process list..."
# Your implementation here
}
# Function to show locks
show_locks() {
# Logic to show locks
echo "Showing locks..."
# Your implementation here
}... | magicoder | shell |
You are tasked with creating a program that reads a text file containing the content of a software license and extracts the license name and the URL to the license text. The license content is structured in a specific format, and your program needs to parse the file and extract the required information.
The license co... | ```python
import re
def extract_licenses(file_path):
with open(file_path, 'r') as file:
content = file.read()
licenses = re.findall(r'\* (.+?)\n \* (http.+?)\n', content)
for license in licenses:
print(f"License: {license[0]}")
print(f"URL: {license[1]}\n")
# Exam... | magicoder | python |
You are tasked with creating a Java method that generates a list of end-of-week dates for the last three months from the current weekend date. The end-of-week date is defined as the Sunday of each week. You are given a code snippet that demonstrates the use of Java 8's Stream API to iterate over the weeks and calculate... | ```java
import java.util.Date;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class EndOfWeekDateGenerator {
public List<Date> generateEndOfWeekDates(Date currentWeekendDate) {
LocalDate lastSunday = cu... | magicoder | java |
You are working on a computer vision project and need to implement a neural network model using PyTorch for optical flow analysis. The goal is to create a Python function that takes in a batch of flow vectors, calculates their magnitude, and then trains a neural network model using the calculated magnitudes as input da... | ```python
import torch
from torch import Tensor
from torch.autograd import Variable
from torch.optim import Adam
from visionutils import flowbatch2mag
from netmodels import classname
from torch.utils.tensorboard import SummaryWriter
def train_optical_flow_model(flow_vectors_batch: Tensor, labels: Tensor, num_epochs: i... | magicoder | python |
You are tasked with implementing a method to generate a unique identifier for a component and construct a client builder for OpenTSDB in a Java application. The OpenTSDB client builder is to be created using the provided code snippet as a reference.
Your task is to complete the implementation of the `addOpenTsdbClient... | ```java
import org.apache.storm.opentsdb.client.OpenTsdbClient;
public class OpenTsdbComponentManager {
private static final String UUID_FOR_COMPONENTS = "12345"; // Example unique identifier
public String addOpenTsdbClientBuilderComponent() {
String clientBuilderId = "openTsdbClientBuilder" + UUID_FO... | magicoder | java |
You are tasked with implementing a function that processes an array of strings representing PHP class names and returns a new array containing only the class names that belong to a specific namespace. The namespace will be provided as a parameter to the function. If no classes from the specified namespace are found, th... | ```php
function filterByNamespace(array $classNames, string $namespace): array {
$filteredClasses = array_filter($classNames, function($className) use ($namespace) {
return strpos($className, $namespace . '\\') === 0;
});
return array_values($filteredClasses);
}
```
The `filterByNamespace` function... | magicoder | php |
You are tasked with implementing a function that processes and generates HTML output for a pricing plan. The function takes in several parameters and constructs the HTML output based on the provided inputs. Your task is to complete the function by implementing the missing parts.
The function `generate_pricing_plan_htm... | ```php
function generate_pricing_plan_html($title_html, $price_html, $css_class, $align, $most, $col_elements, $el_color) {
$output = '<div class="uncode-wrapper ' . esc_attr($css_class) . '">';
$output .= '<div class="plan' . (($align === '') ? ' plan-centered' : '') . (($most === 'yes') ? ' plan-most-popular'... | magicoder | php |
You are tasked with creating a Python class for managing exams in a school management system. The class should have attributes for the exam topic, details, and the author (teacher), as well as a method for string representation and a meta ordering rule.
Your task is to implement the Exam class with the given requireme... | ```python
from django.db import models
class Teacher(models.Model):
# Define the Teacher class attributes and methods here
pass
class Exam(models.Model):
topic = models.CharField(max_length=60)
details = models.TextField(max_length=10000, blank=True)
author = models.ForeignKey(Teacher, null=True, ... | magicoder | python |
You are tasked with implementing a Python class that simulates a simple credit card system. The class should have methods for making purchases, checking the balance, and making payments. Additionally, the class should keep track of the total number of credit cards created.
Your task is to complete the implementation o... | ```python
class CreditCard:
total_cards_created = 0 # Class attribute to keep track of the total number of credit cards created
def __init__(self, card_number, initial_balance):
self.card_number = card_number
self.balance = initial_balance
CreditCard.total_cards_created += 1 # Increme... | magicoder | python |
You are tasked with creating a Python program to request coordinates of various building types in a specific city area from OpenStreetMap and save the results into a CSV file. The program should utilize the Overpass API to achieve this.
Your task is to implement the `request_coords_to_csv` function, which takes three ... | ```python
import overpy
import csv
import time
building_types = ["apartment", "residential", "semidetached_house", "static_caravan", "terrace"]
def request_coords_to_csv(csvfilename, city_area, seconds_sleep):
"""
Request coordinates of each building type defined in building_types[] in the specified city area... | magicoder | python |
You are working on a content management system for a web application. Your task is to create a Python function that registers image scales and packages image scales for the application's widgets.
You are provided with two Python modules: `ade25.base.utils` and `ade25.widgets.utils`. The `ade25.base.utils` module conta... | ```python
from ade25.base.utils import register_image_scales, package_image_scales
from ade25.widgets.utils import register_content_widgets
def register_and_package(image_scales):
register_image_scales(image_scales)
packaged_scales = package_image_scales()
register_content_widgets(packaged_scales)
```
In t... | magicoder | python |
You are working on a computer vision project that involves processing facial images. You are given a code snippet that performs some operations on facial landmarks and bounding boxes. Your task is to implement a function that calculates the area of the bounding box after a random mirroring operation is applied to the f... | ```python
import numpy as np
import random
import cv2
def flip(image, landmarks):
# Implement the logic to flip the image and adjust the landmarks accordingly
# Return the flipped image and landmarks
def BBox(coordinates):
# Implement the BBox class to construct a bounding box object
# Return the boun... | magicoder | python |
You are tasked with creating a custom widget for a text editor application that displays error messages for syntax errors in the user's code. The widget should be able to show the error message, the row and column where the error occurred, and an icon representing the error type. You need to implement a class `ErrorWid... | ```python
from PyQt5 import QtWidgets, QtGui
class ErrorWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.model = QtGui.QStandardItemModel()
self.setModel(self.model)
self.clicked.connect(self.itemSelected)
self.errorIcon = QtGui.QIcon... | magicoder | python |
You are tasked with creating a Python function that processes data from a neural network training experiment and visualizes the mean and standard deviation of maximum mean discrepancy (MMD) values for different hidden layer configurations. The provided code snippet is a part of a larger program that generates an error ... | ```python
import matplotlib.pyplot as plt
def plot_mmd_errorbar(hidden_layer_numbers, hidden_unit_numbers, mean_mmds, std_mmds):
fig, ax = plt.subplots()
for index, hidden_layer_number in enumerate(hidden_layer_numbers):
if hidden_layer_number == 1:
layer_string = ' hidden layer'
el... | magicoder | python |
You are tasked with implementing a Python function that processes a configuration file for a deep learning model training script. The configuration file contains settings for the device to be used (CPU or CUDA), the number of classes in the dataset, the path to the pre-trained model, and the directories containing the ... | ```python
import torch
import yaml
def process_config_file(config_file_path):
with open(config_file_path, 'r') as file:
config = yaml.safe_load(file)
device = config['device']
num_classes = config['num_classes']
pth = config['pth']
infer_data_dirs = config['infer_data_dirs']
if device... | magicoder | python |
You are tasked with creating a Python function that processes and filters chat messages based on certain criteria. The function will be used in a chat application and will be responsible for handling different types of chat events, such as channel messages, private messages, and actions. The chat application uses the H... | ```python
def on_msg(word, word_eol, userdata):
# Process and filter chat messages based on specific conditions
event = word[0] # Extract the chat event type
message = word[1] # Extract the chat message content
# Add your message processing and filtering logic here
if event in ['Channel Message',... | magicoder | python |
You are tasked with creating a program that can analyze the structure of HTML code and determine the depth of nested tags within the code. The depth of a tag is defined as the number of levels it is nested within other tags. For example, a tag directly within the `<body>` tag has a depth of 1, while a tag within a tag ... | ```java
public class MaxNestedDepth {
public static int maxNestedDepth(String htmlCode) {
int maxDepth = 0;
int currentDepth = 0;
for (int i = 0; i < htmlCode.length(); i++) {
if (htmlCode.charAt(i) == '<') {
if (htmlCode.charAt(i + 1) != '/') {
... | magicoder | java |
You are tasked with implementing a multithreading problem in Python. Your goal is to create a program that manages a set of threads, ensuring that they start and finish in a controlled manner. The provided code snippet is a part of the program that starts a batch of threads and waits for them to finish before resetting... | ```python
import threading
def thread_worker(thread_id):
print(f"Thread {thread_id} is doing some work")
def main():
toLock = True # Set to True if the lock needs to be released and acquired
imp = threading.Lock() # Initialize a lock
# Create a list of threads
threads = [threading.Thread(target... | magicoder | python |
You are tasked with creating a custom Unity editor tool that allows game developers to visualize and manipulate GPU skinning data for character animations. The GPU skinning system is provided by the GPUSkinning package, and the tool should integrate with the DCL (Decentraland) game engine. The tool will be used to adju... | ```csharp
using DCL.Helpers;
using GPUSkinning;
using UnityEngine;
using UnityEditor;
using static WearableLiterals;
public class WearableEditorWindow : EditorWindow
{
private GameObject characterModel;
private WearableItem[] wearableItems;
private int selectedWearableIndex = -1;
[MenuItem("Window/Wea... | magicoder | csharp |
You are tasked with creating a Python function to validate and process energy price data retrieved from a third-party API. The function should perform several checks on the retrieved data to ensure its integrity and correctness.
The function should take the following inputs:
- `data_first_hour`: A dictionary containin... | ```python
from pytz import timezone
def validate_energy_prices(data_first_hour, ESIOS_TARIFFS, prices, first_price, last_price, timezone):
# Check full PVPC data is retrieved
if len(data_first_hour) != 30:
return False
# Check if all tariff tags are present in the data
if not all(tag in data_f... | magicoder | python |
You are tasked with creating a function that emulates the behavior of a database query using a simplified version of Sequelize, a popular Node.js ORM. The function `findAllByConditions` takes in several parameters and is responsible for retrieving records from a database based on specified attributes and conditions.
T... | ```javascript
function findAllByConditions(attributes, conditions, include, order) {
// Assuming this is a class method, 'this' refers to the class instance
return this.sequelizeModel.findAll(
this.sequelizeQueryBuilder(attributes, conditions, include, order)
);
}
```
In the solution, the `findAllByConditions... | magicoder | javascript |
You are working on a web application that generates a status table for various controllers. The code snippet provided is a part of the code responsible for generating the table rows. The code uses a custom output stream `out` to construct the HTML table rows for each controller. The `g_controller` array holds instances... | The `generateStatusTableRows` function takes a vector of `Controller` objects and iterates through each controller to construct the HTML table rows based on the specified rules. It uses a stringstream `out` to build the HTML content and returns the concatenated string of table rows. The function handles the conditions ... | magicoder | html |
You are tasked with implementing a function that can parse and extract specific information from HTML code. Your function should be able to extract the text content of an HTML element with a specific class attribute.
Write a function `extractElementText(html, className)` that takes in two parameters:
- `html`: a strin... | ```javascript
function extractElementText(html, className) {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const elements = doc.getElementsByClassName(className);
if (elements.length > 0) {
return elements[0].textContent.trim();
}
return null; // Return null if n... | magicoder | javascript |
You are tasked with implementing a function that processes satellite image data. The function takes in a dataset, time index, and coordinates, and returns a processed image using the specified bands. The function also needs to handle the minimum and maximum valid values for the selected bands based on the platform used... | ```python
import numpy as np
def process_image(dataset_in, at_index, x_coord, y_coord, time_coord, bands, min_possible, max_possible, use_data_min):
# Extract the specified bands from the dataset
red_band = dataset_in[bands[0]].isel({time_coord: at_index})
green_band = dataset_in[bands[1]].isel({time_coord... | magicoder | python |
You are tasked with creating a script that processes a list of authors and their respective publications. The script should read the input from a file named `authors.txt` and produce an output in the format of `author: publication_count`. Each author may have multiple publications listed in the file. The script should ... | ```bash
#!/bin/bash
# Read the input from authors.txt
while IFS= read -r line; do
author=$(echo "$line" | cut -d ':' -f 1)
publications=$(echo "$line" | cut -d ':' -f 2 | tr -d ' ')
publication_count=$(echo "$publications" | tr ',' '\n' | wc -l)
echo "$author: $publication_count"
done < authors.txt
```... | magicoder | shell |
You are tasked with implementing a function that takes in an array of strings representing flags and returns an object containing the count of each unique flag.
The function should be named `countFlags` and should take in a single parameter:
- `flagArray`: an array of strings representing flags, where each string is a... | ```javascript
function countFlags(flagArray) {
const flagCounts = {};
for (let i = 0; i < flagArray.length; i++) {
const flag = flagArray[i].trim().toUpperCase(); // Convert to uppercase and remove leading/trailing whitespaces
flagCounts[flag] = (flagCounts[flag] || 0) + 1; // Increment count for the flag
... | magicoder | javascript |
You are tasked with creating a program that simulates a simplified version of a package manager. The program should be able to handle commands for installing, removing, and listing packages. Each package can have dependencies, and when a package is removed, its dependencies should also be removed if they are not requir... | ```python
class PackageManager:
def __init__(self):
self.packages = {}
self.dependencies = {}
def install(self, package):
if package in self.packages:
return
if package in self.dependencies:
for dependency in self.dependencies[package]:
se... | magicoder | python |
You are tasked with creating a notification system for a web application using Laravel. The application has a controller called `LoaihangController` with a method `edit($id)` that is responsible for editing a specific item. Your task is to implement the notification feature such that when an item is edited, a notificat... | To implement the notification feature in the `LoaihangController`, you can use the `Notification` facade to send a notification using the `thongbao` notification class. Here's how you can modify the `edit` method to trigger the notification:
```php
use App\Notifications\thongbao;
use Illuminate\Support\Facades\Notific... | magicoder | php |
You are tasked with implementing a program that processes a list of students and their corresponding grades. The program should calculate the average grade for each student and then determine the student with the highest average grade.
You are given a class `Student` with the following attributes:
- `name` (string): ... | ```python
from typing import List
class Student:
def __init__(self, name: str, grades: List[int]):
self.name = name
self.grades = grades
def highest_average_grade(students: List[Student]) -> str:
max_average = 0
top_student = ""
for student in students:
average_grade = sum... | magicoder | python |
You are tasked with implementing a transaction validation system for a digital artifact management platform. The system should handle various actions performed on artifacts and ensure that the artifact ID is provided for all actions that require it. If an invalid action is specified or if the artifact ID is missing, th... | ```python
class InvalidAction(Exception):
pass
class InvalidTransaction(Exception):
pass
def validate_transaction(action, artifact_id):
valid_actions = ["create", "update", "delete"]
if action not in valid_actions:
raise InvalidAction(f"Invalid action '{action}' is not a valid action.")
... | magicoder | python |
You are tasked with creating a Python program that reads a file and counts the occurrences of each word in the file. Your program should ignore case sensitivity and punctuation, and only consider alphanumeric characters as part of a word. Additionally, the program should exclude common English stop words such as "the",... | ```python
import re
from collections import Counter
from nltk.corpus import stopwords
def count_word_occurrences(file_path):
with open(file_path, 'r') as file:
text = file.read().lower()
words = re.findall(r'\b\w+\b', text)
filtered_words = [word for word in words if word not in stopwords.w... | magicoder | python |
You are given a vector of intervals `intervals`, each represented as a pair of integers `[start, end]`. Additionally, you are given a sorted vector `v` of pairs `[value, index]`. Your task is to create a new vector `answer` of size `N`, where `N` is the number of intervals. For each interval `intervals[i]`, you need to... | ```cpp
#include <vector>
#include <algorithm>
using namespace std;
bool lb_comp(const pair<int, int>& p, int val) {
return p.first < val;
}
vector<int> findValues(vector<pair<int, int>> intervals, vector<pair<int, int>> v, int N) {
vector<int> answer(N);
for (int i = 0; i < N; ++i) {
int pos = lo... | magicoder | cpp |
You are tasked with implementing a class that manages permissions for a user interface in a software application. The class should handle the availability of different types of UI elements based on the user's permissions. The permissions are represented by a flags enum called `UserInterfacePermission` with the followin... | ```csharp
public enum UserInterfacePermission {
None = 0x0000,
View = 0x0001,
Edit = 0x0002,
Delete = 0x0004,
All = View | Edit | Delete
}
public class UserInterfacePermissionManager {
public bool CheckPermission(UserInterfacePermission userPermission, UserInterfacePermission requiredPermission... | magicoder | csharp |
You are tasked with creating a function that processes the output of a Git command and extracts relevant information. The function should parse the output of the `git diff --cached` command and identify the staged files for commit. The staged files are those that have been added to the staging area but not yet committe... | ```python
def find_staged_files():
status, output = sct.run("git diff --cached")
output_list = output.split("\n")
staged_files = []
for line in output_list:
if line.startswith("diff --git"):
file = line.split(" b/")[1]
staged_files.append(file)
return staged_files... | magicoder | python |
You are tasked with creating a function to process checkout data received from an API response. The checkout data is in the form of a payload within the response body. Your task is to implement a function that takes the response data as input, extracts and processes the payload, and returns the processed checkout data.... | ```typescript
function processCheckoutData(responseData: TApiResponseData): ProcessedCheckoutData {
if (responseData.ok) {
const payloadData = parseCheckoutData(responseData.data);
// Process the payloadData as per the requirements
// Example: Extract necessary information and format it into... | magicoder | typescript |
You are working on a project for a financial services company that involves managing agents and their registration process. The project has a class called `AgentService` with several methods related to agent registration and data validation. Your task is to implement a new method in the `AgentService` class to check if... | ```java
public boolean isUserIdAvailable(String userId) {
// Check if the user ID is available for registration
Agent existingAgent = getAgentByUserName(userId);
return existingAgent == null;
}
```
In the solution, the `isUserIdAvailable` method uses the `getAgentByUserName` method to retrieve an agent base... | magicoder | java |
You are tasked with implementing a Python function that processes training metrics for a machine learning model. The function takes in several parameters and generates a log string based on the provided inputs. Your task is to complete the function by implementing the logic to construct the log string based on the give... | ```python
def generate_log_string(epoch: int, epochs: int, train_loss: float, verbose: bool, metrics: dict) -> str:
if not verbose:
return "" # Return empty string if verbose logging is disabled
log_str = f"epoch: {epoch}/{epochs} - train_loss: {train_loss:.8f}" # Construct initial log string
if... | magicoder | python |
You are tasked with implementing a stochastic Mealy machine, a type of finite state machine where the output is determined by the current state and input, and the transition between states is probabilistic. The stochastic Mealy machine has the following characteristics:
- It is a subclass of the `Automaton` class, whi... | ```python
from random import choices
class StochasticMealyMachine(Automaton):
def __init__(self, initial_state: StochasticMealyState, states: list):
super().__init__(initial_state, states)
self.transitions = defaultdict(list)
def reset_to_initial(self):
self.current_state = self.initi... | magicoder | python |
You are tasked with creating a Python web application that handles routing and serves static files. Your application should have two main functionalities: URL routing and serving static files. You need to implement the following two functions in your web application:
1. `url_for`: This function should take the name of... | ```python
from flask import Flask, url_for
app = Flask(__name__)
@app.route('/')
def index():
return 'Welcome to the homepage'
@app.route('/about')
def about():
return 'This is the about page'
@app.route('/static/<path:filename>')
def static(filename):
return f'Serving static file: {filename}'
def test... | magicoder | python |
You are tasked with creating a Python class that represents an AI for a game. The AI's objective is to navigate a game environment without causing harm to itself. Your task is to implement the `NotKillingItselfAI` class, which will be responsible for making decisions based on the game state and its internal logic.
The... | ```python
from enum import Enum
class Direction(Enum):
up = 0
down = 1
left = 2
right = 3
class Action(Enum):
speed_up = 0
change_nothing = 1
turn_right = 2
class Player:
def __init__(self, x, y, speed, direction, health, alive, name):
self.x = x
self.y = y
sel... | magicoder | python |
You are tasked with creating a Python class that generates deployment commands for package managers. The class should have methods to generate deployment commands for both APT (Advanced Package Tool) and Pacman package managers. The APT deployment command should include a list of architectures, sources, keys, and an op... | ```python
class PackageDeployGenerator:
def __init__(self, apt_archs, sources, keys):
self.apt_archs = apt_archs
self.sources = sources
self.keys = keys
def _generate_apt_deploy_command(self, allow_unauthenticated):
command = f"apt-get deploy -a {' '.join(self.apt_archs)} -s {' ... | magicoder | python |
You are given a list of integers `numbers`. Your task is to write a function that returns the count of distinct prime factors for each number in the list. A distinct prime factor is a prime number that divides the given number exactly, without leaving a remainder.
Create a function `distinct_prime_factors_count(number... | ```python
def distinct_prime_factors_count(numbers):
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
def prime_factors_count(n):
count = 0
for i in range(2, n + ... | magicoder | python |
You are tasked with creating a text classification model using scikit-learn in Python. Your goal is to build a pipeline that includes a TfidfVectorizer for feature extraction and an SGDClassifier for multi-label classification. Additionally, you need to perform hyperparameter tuning using GridSearchCV to find the best ... | ```python
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.multioutput import MultiOutputClassifier
from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import GridSearchCV
class Text_clean:
@staticmethod
def tokenize(text):
... | magicoder | python |
You are tasked with implementing a Siamese network for image similarity comparison using PyTorch. The Siamese network architecture consists of two identical subnetworks (twins) that share the same weights and architecture. Given a pair of images, the Siamese network should learn to output a similarity score indicating ... | ```python
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader, Dataset
import torchvision.datasets as dset
import torchvision.transforms as transforms
# Step 1: Define a custom dataset class
class SiameseDataset(Dataset):
def __init__(self, image_folder_datase... | magicoder | python |
You are tasked with creating a script to process a configuration file and replace a specific line based on a given pattern. Your script should be able to handle the replacement of the line with a default value if the pattern is not found in the file.
You are given a code snippet from a script that performs a line repl... | ```bash
#!/bin/bash
config_file=$1
replacement_value=$2
# Check if the pattern exists in the configuration file
if grep -q "^#\ use-incoming-edns-subnet=" "$config_file"; then
# Replace the line with the provided value
sed -i "s/^#\ use-incoming-edns-subnet=.*/use-incoming-edns-subnet=$replacement_value/g" "$... | magicoder | shell |
You are given a partially implemented function in Swift that is intended to search for a specific value in a binary search tree (BST). However, the function is incomplete and needs to be filled in to properly search the BST for the target value. Your task is to complete the implementation of the `search` function to co... | ```swift
func search(_ target: Int) -> TreeNode? {
var current: TreeNode? = self
while let node = current {
if target < node.value {
current = node.left
} else if target > node.value {
current = node.right
} else {
return node
}
}
retur... | magicoder | swift |
You are tasked with implementing a Python class method that processes financial data using the Wind API. The method is responsible for retrieving sector constituent data for a given date range and initializing a progress tracker to monitor the processing status. Your task is to complete the implementation of the method... | ```python
from WindPy import w # Assuming the Wind API is imported from WindPy
class FinancialDataProcessor:
def __init__(self, info, sectorCodeWindMap):
self._info = info
self.sectorCodeWindMap = sectorCodeWindMap
def processFinancialData(self, startDate, endDate, sectorCode):
dates ... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.