query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with writing a Python function to process and extract specific data from a nested JSON structure. The JSON data represents records with various fields, including nested structures. Your function should extract and return specific information based on the given criteria.
Write a Python function `extract_... | ```python
from typing import List, Tuple, Union
import json
def extract_nested_data(json_data: List[str]) -> List[Tuple[str, Union[int, bool, str]]]:
result = []
for data in json_data:
json_obj = json.loads(data)
for key, value in json_obj.items():
if isinstance(value, (bool, int)):... | magicoder | python |
You are tasked with creating a Python decorator that restricts access to certain views based on a user's group membership. Your goal is to implement the missing parts of the `user_in_group` decorator function.
The `user_in_group` decorator takes the following parameters:
- `function`: The view function to be decorated... | ```python
from django.contrib.auth.decorators import user_passes_test
from django.shortcuts import redirect
def user_in_group(function=None, group=None, redirect_field_name="", login_url="/403"):
def user_in_the_group(user):
if user:
return user.groups.filter(name=group).count() > 0
ret... | magicoder | python |
You are tasked with implementing a function to determine the number of closing curly braces (`}`) that are not preceded by any opening curly brace (`{`) within a given string. Your function should take a string as input and return the count of such "lonely" closing curly braces.
For example, given the input string:
``... | ```python
def countLonelyClosingBraces(input_string):
lonely_count = 0
open_brace = False
for char in input_string:
if char == '{':
open_brace = True
elif char == '}':
if not open_brace:
lonely_count += 1
else:
open_brace = ... | magicoder | python |
You are tasked with creating a command for a Discord bot that prunes messages in a channel based on a specified number of messages to delete. The bot is programmed in Rust using the Serenity library, and the command is implemented as an asynchronous function `prune` that takes in the context `ctx`, the message `msg`, a... | ```rust
async fn prune(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult {
let channel = msg.channel_id;
let total = args.find::<u64>()?;
// Retrieve the messages from the channel
let messages = channel.messages(ctx, |retriever| {
retriever.limit(total + 1) // Include the command m... | magicoder | rust |
You are tasked with implementing a function that processes a list of dependencies and returns a dictionary representing the dependency graph. Each dependency is represented as a tuple containing two elements: the dependent module and the module it depends on. The function should handle circular dependencies by raising ... | ```python
class CircularDependencyError(Exception):
pass
def build_dependency_graph(dependencies):
graph = {}
for dependent, dependency in dependencies:
if dependent not in graph:
graph[dependent] = []
if dependency not in graph:
graph[dependency] = [dependent]
... | magicoder | python |
You are given a binary image represented as a 2D array `bImg` containing boolean values. The code snippet provided is a part of a Python script that processes this binary image using the `label` and `regionprops` functions from the `skimage.measure` module. The `label` function assigns a unique label to connected regio... | ```python
from typing import List
import numpy as np
from skimage.measure import label, regionprops
def count_regions(bImg: List[List[bool]]) -> int:
labelImg = label(np.array(bImg)) # Convert the 2D list to a numpy array and label the connected regions
numLabel = labelImg.max() # Get the maximum label value... | magicoder | python |
You are tasked with implementing a class that represents a simple shopping cart. The class should have the following functionalities:
1. Add items to the cart with a specified quantity.
2. Remove items from the cart.
3. Calculate the total cost of all items in the cart.
4. Implement a destructor method to handle the c... | ```python
class ShoppingCart:
def __init__(self):
self.cart = {}
def add_item(self, item_name, quantity, price):
if item_name in self.cart:
self.cart[item_name] += quantity
else:
self.cart[item_name] = quantity
self.cart[item_name] = price
def remove... | magicoder | python |
You are tasked with creating a Python class that inherits from a given parent class and defines a specific attribute. Your task is to complete the implementation of the child class by adding a new method and overriding an existing method.
Given the following code snippet:
```python
from iptv_proxy.providers.iptv_prov... | ```python
from iptv_proxy.providers.iptv_provider.json_api import ProviderConfigurationJSONAPI
import logging
logger = logging.getLogger(__name__)
class BeastConfigurationJSONAPI(ProviderConfigurationJSONAPI):
__slots__ = []
_provider_name = BeastConstants.PROVIDER_NAME.lower()
def get_provider_name(sel... | magicoder | python |
You are tasked with creating a program that can extract and display the text content within HTML tags. Your program should be able to handle multiple HTML tags and extract the text content within them. For this problem, you will focus on extracting the text content within the `<div>` tags from the given HTML snippet.
... | ```python
import re
def extractDivContent(html: str) -> str:
# Using regular expression to extract text content within <div> tags
match = re.search(r'<div class="section-title[^>]*>(.*?)</div>', html)
if match:
return match.group(1)
else:
return "No <div> tag with class 'section-title' ... | magicoder | python |
You are tasked with creating a notification system for a forum application. The system should send an email to all users who are following a specific forum thread whenever a new post is made in that thread. The code snippet provided is a part of the function responsible for creating a new post in the forum. It includes... | ```php
function sendForumNotifications($threadId, $postContent, $author) {
// Get all followers of the forum thread
$followers = \Model\Game\Forum\Follow::GetFollowers($threadId);
// Compose the email message
$subject = "New post in forum thread";
$message = "A new post has been added to the fo... | magicoder | php |
You are working on a data pipeline project that involves loading data from staging tables into the final production tables in a database. You have been provided with two functions, `load_staging_tables` and `insert_tables`, which are responsible for executing the necessary SQL queries to achieve this. The `load_staging... | ```python
def load_and_insert_data(cur, conn, copy_table_queries, insert_table_queries):
try:
# Load data from staging tables to database
for query in copy_table_queries:
cur.execute(query)
conn.commit()
# Insert data into production tables
for query in inser... | magicoder | python |
You are given a dictionary `codon_protein` that maps RNA codons to the corresponding amino acids. Each codon is a sequence of three nucleotides, and each amino acid is represented by a string. Your task is to write a function that translates a given RNA sequence into a sequence of amino acids until a stop codon is enco... | ```python
def translate_rna(rna_sequence):
codon_protein = {
"AUG": "Methionine",
"UUU": "Phenylalanine",
"UUC": "Phenylalanine",
"UUA": "Leucine",
"UUG": "Leucine",
"UCU": "Serine",
"UCG": "Serine",
"UCC": "Serine",
"UCA": "Serine",
"U... | magicoder | python |
You are tasked with creating a Python program that simulates an Intcode computer. The Intcode computer processes a list of integers and performs various operations based on the opcode provided. Your task is to implement the Intcode computer with the ability to handle different opcodes and parameter modes.
Your program... | ```python
class Intcode:
def __init__(self, program):
self.program = program
self.pointer = 0
def get_value(self, parameter, mode):
return parameter if mode == 1 else self.program[parameter]
def execute(self):
while True:
opcode = str(self.program[self.pointer])... | magicoder | python |
You are tasked with implementing a function that processes a list of dictionaries representing configuration options for a software application. Each dictionary contains key-value pairs representing a specific configuration option. Your task is to write a function that takes this list of dictionaries and returns a new ... | ```python
from typing import List, Dict, Union
def preserve_default_values(config_options: List[Dict[str, Union[str, bool]]]) -> List[Dict[str, Union[str, bool]]]:
output = []
for option in config_options:
if "preserve_default" in option and option["preserve_default"]:
output.append({key: v... | magicoder | python |
You are tasked with creating a web application using Laravel framework to manage a database of members. The code snippet provided includes some Laravel framework classes and a model for the Member entity. Your task is to implement a feature that allows users to add new members to the database and display the list of me... | ```php
// Route for adding new members
Route::get('/members/create', 'MemberController@create');
Route::post('/members', 'MemberController@store');
// MemberController.php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Redirect;
use RealRashid\SweetAlert\Facades\A... | magicoder | php |
You are tasked with implementing a function that processes a nested object to extract a specific value based on a given key. The object may contain nested objects and arrays, and the key may or may not exist within the object structure. If the key exists, the function should return the corresponding value; otherwise, i... | ```javascript
function extractValue(obj, targetKey, defaultValue) {
const keys = targetKey.split('.');
let value = obj;
for (const key of keys) {
if (value && typeof value === 'object' && key in value) {
value = value[key];
} else {
return defaultValue;
}
}
return value !== undefined... | magicoder | javascript |
You are tasked with creating a Python function that processes proposals for a project management system. The function should take in a proposal name, description, and options, and then save the proposal to the database. Additionally, the function should verify that the proposal has been successfully saved and that its ... | ```python
from datetime import datetime, timedelta
from django.utils import timezone
from .models import Proposal
def process_proposal(proposal_name, proposal_description, options):
# Create and save the proposal
new_proposal = Proposal(proposal_name=proposal_name, proposal_description=proposal_description, op... | magicoder | python |
You are tasked with creating a simple Python program to simulate a basic text-based user interface. Your program should display a grid of characters and allow the user to move a cursor within this grid. The cursor movement should be controlled by the arrow keys on the keyboard. When the user presses an arrow key, the c... | ```python
class TextUI:
def __init__(self, width, height):
self.width = width
self.height = height
def move_cursor(self, x, y):
print(f"\033[{y};{x}H", end='')
def print_text(self, x, y, text):
print(f"\033[{y};{x}H{text}", end='')
# Example usage
ui = TextUI(10, 5)
ui.mo... | magicoder | python |
You are tasked with implementing a Python class that simulates a simple counter. The class should have the following functionalities:
1. Create an instance of the class with an initial value.
2. Increment the value by a specified amount.
3. Decrement the value by a specified amount.
4. Output the current value in a sp... | ```python
class Counter:
def __init__(self, initial_value):
self.v = initial_value
def increment(self, amount):
self.v += amount
def decrement(self, amount):
self.v -= amount
def output(self):
print("value= {0:d}".format(self.v))
# Demonstration
c = Counter(3) # Crea... | magicoder | python |
You are tasked with implementing a Python function to calculate the inter-rater reliability using Krippendorff's alpha coefficient. Krippendorff's alpha is a statistical measure of inter-rater agreement for categorical items. It is widely used in fields such as social sciences, communication studies, and information sc... | ```python
import krippendorff
def calculate_krippendorff_alpha(data, level_of_measurement):
return krippendorff.alpha(reliability_data=data, level_of_measurement=level_of_measurement)
```
The solution provides a Python function `calculate_krippendorff_alpha` that utilizes the `krippendorff` library to calculate K... | magicoder | python |
You are tasked with simulating a distributed system where multiple users and servers interact. The system is prone to Byzantine failures, where nodes may exhibit arbitrary and potentially malicious behavior. Your goal is to implement a program that can detect Byzantine behavior in the system.
You are given a code snip... | ```python
import subprocess
def detect_byzantine_behavior():
# Execute the script and capture its output
process = subprocess.Popen(['./start_user_script.sh'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
output, _ = process.communicate()
# Check the output for signs of Byzantine behavi... | magicoder | python |
You are tasked with creating a Guitar class that represents a musical instrument. The class should have attributes such as serial number, price, guitar specification, and availability. The guitar specification should include details such as builder, model, type, back wood, top wood, and number of strings. Additionally,... | ```python
from enum import Enum
class GuitarType(Enum):
ACOUSTIC = 1
ELECTRIC = 2
class Wood(Enum):
MAHOGANY = 1
ROSEWOOD = 2
MAPLE = 3
CEDAR = 4
class Builder(Enum):
FENDER = 1
GIBSON = 2
MARTIN = 3
class GuitarSpec:
def __init__(self, builder, model, guitar_type, back_wood,... | magicoder | python |
You are given a list of integers representing the velocities of particles in a one-dimensional space. Each particle has a unique identifier and a corresponding velocity. Your task is to find the pair of particles that will collide first, i.e., the pair of particles that will have the smallest time gap before colliding.... | ```python
def find_first_collision(particles):
min_time = float('inf')
collision_pair = None
for i in range(len(particles)):
for j in range(i + 1, len(particles)):
time_to_collision = (particles[j][0] - particles[i][0]) / (particles[i][1] - particles[j][1])
if time_to_collis... | magicoder | python |
You are tasked with creating a Python function that generates a Spack package specification based on the given code snippet. Spack is a package manager for supercomputers, Linux, and macOS. The package specification should include the version, SHA256 hash, and variants specified in the code snippet.
Your task is to im... | ```python
def generate_spack_package_spec(code_snippet):
package_spec = ""
versions = []
sha256_hashes = {}
variants = []
# Parse the code snippet to extract version, sha256, and variant information
for line in code_snippet.split('\n'):
if line.startswith("version"):
version... | magicoder | python |
You are tasked with creating a function that parses a given HTML snippet and extracts the names of all the classes used within the "div" elements. The function should return a list of unique class names found within the "div" elements of the HTML snippet.
Write a function called `extractDivClasses` that takes a string... | ```python
from bs4 import BeautifulSoup
def extractDivClasses(htmlSnippet):
class_names = []
soup = BeautifulSoup(htmlSnippet, 'html.parser')
div_elements = soup.find_all('div')
for div in div_elements:
if 'class' in div.attrs:
classes = div['class']
class_names.extend(c... | magicoder | python |
You are tasked with implementing a file processing system that can handle large files efficiently. The system should be able to read and process files in chunks, and it should also have the capability to detect if subprocesses are needed for processing.
You are given the following configuration parameters:
- `chunk_si... | ```python
import os
def process_file(file_path, config):
chunk_size = config.get('chunk_size')
detect_subprocess_need = config.get('detect_subprocess_need')
if chunk_size is None:
with open(file_path, 'r') as file:
data = file.read()
return process_data(data)
else:
... | magicoder | python |
You are tasked with implementing a string matching algorithm to find occurrences of multiple patterns within a given text. The code snippet provided is a part of the string matching algorithm, where the text is divided into chunks and each chunk is compared with the patterns to find matches.
Your task is to complete t... | ```cpp
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
std::vector<std::vector<size_t>> findPatternOccurrences(const std::string& text, const std::vector<std::string>& patterns, size_t chunkSize) {
size_t strLen = text.length();
size_t pattCnt = patterns.size();
std::vector<std... | magicoder | cpp |
You are tasked with creating a task scheduler that can manage and execute various tasks. Each task is represented as a function, and the scheduler should be able to add tasks and execute them in a specified order.
You need to implement a TaskScheduler class with the following functionalities:
1. `add_task(task)`: A me... | ```python
class TaskScheduler:
def __init__(self):
self.tasks = []
def add_task(self, task):
self.tasks.append(task)
def run_tasks(self):
for task in self.tasks:
task()
# Example usage
def run_migrations():
print("Running database migrations...")
def backup_data()... | magicoder | python |
You are tasked with creating a script that processes genetic data to identify specific gene sequences. The script should take a DNA sequence as input and output the locations of a given gene within the sequence. The gene sequence is provided as a command-line argument when running the script.
Your task is to implement... | ```bash
#!/bin/bash
if [ -z "$1" ]; then
echo "Usage: gene <gene_sequence>"
exit 1
fi
# Process the DNA sequence
dna_sequence="ATGCGTACGCGTACGCGTACGCGTACGCGTACGCGTACGCGTACGCGTACGCGTACGCGTACGCGTACGCGTACGCGTACGCGTACGCGTACGCGTACGCGTACGCGTACGCGTACGCGTACGCGTACGCGTACGCGTACGCGTACGCGTACG"
# Find the gene sequence
ge... | magicoder | shell |
You are tasked with creating a program to determine the winning ticket in a lottery. Each ticket is represented by a string of characters, and the winning ticket is the one with the longest consecutive sequence of identical characters. If there are multiple tickets with the same longest consecutive sequence length, the... | ```csharp
using System;
using System.Collections.Generic;
using System.Linq;
namespace WinningTicket
{
class WinningTicket
{
static void Main(string[] args)
{
var tickets = Console.ReadLine().Split(',').ToList();
string winningTicket = FindWinningTicket(tickets);
... | magicoder | csharp |
You are tasked with implementing a simple linear regression model using Python and Numpy. The given code snippet initializes the weights `w` and bias `b` to 0 and sets the number of training epochs to 1000 with a learning rate of 1e-3. Your task is to complete the implementation of the linear regression model by updati... | ```python
import numpy as np
def linear_regression_train(features, targets, num_epoch, learning_rate):
# Initialize weights and bias
w, b = np.zeros(features.shape[1]), 0
# Gradient descent
for e in range(num_epoch):
# Forward pass
predictions = np.dot(features, w) + b
... | magicoder | python |
You are tasked with implementing a text processing function that handles URL encoding and decoding. Your function should take a string as input and perform the following operations in sequence:
1. If the input string starts with '%', decode the URL-encoded characters using the `urllib.parse.unquote` function from the ... | ```python
import urllib.parse
import re
def process_text(input_string: str) -> str:
temp = ""
words = input_string.split()
for word in words:
if word.startswith('%'):
word = urllib.parse.unquote(word)
temp = temp + " " + word
value = temp
value = re.sub(r"[%][a-zA-Z0-9]+... | magicoder | python |
You are tasked with creating a program that can parse and analyze a given SCSS (Sassy CSS) file to extract and count the number of unique CSS classes used in the file. SCSS is a preprocessor scripting language that is interpreted or compiled into CSS. Each CSS class is defined by a selector followed by a block of prope... | ```python
import re
def extract_unique_css_classes(file_path):
css_classes = set()
with open(file_path, 'r') as file:
scss_content = file.read()
matches = re.findall(r'\.([a-zA-Z][\w-]*)', scss_content)
for match in matches:
css_classes.add('.' + match)
return css_c... | magicoder | python |
You are tasked with creating a reinforcement learning agent to play the "SC2MoveToBeacon" game using the OpenAI Gym environment. The environment provides an observation space and an action space, which are essential for training the agent. Your goal is to implement a function that initializes the environment, prints th... | ```python
import gym
from gym.spaces import Box, Discrete
from absl import app
def initialize_and_train_agent(num_episodes):
env = gym.make('SC2MoveToBeacon-bbueno5000-v0')
print("Observation Space:", env.observation_space)
print("Action Space:", env.action_space)
# Run the main training loop for ... | magicoder | python |
You are tasked with creating a program that reads a file containing software licenses and categorizes them based on their type. The software licenses are represented as strings, and the program should identify whether each license is released under the Apache License 2.0, the MIT License, or is of an unknown type. The ... | ```python
def categorize_licenses(file_path):
license_counts = {"Apache License 2.0": 0, "MIT License": 0, "Unknown License": 0}
with open(file_path, 'r') as file:
for line in file:
if "Apache License 2.0" in line:
license_counts["Apache License 2.0"] += 1
elif "... | magicoder | python |
You are tasked with creating a simple iOS app that allows users to track their daily water intake. The app should have a button to add a glass of water to the daily total and display the current count of glasses consumed. Additionally, the app should have a reset button to clear the daily total.
Your task is to comple... | ```swift
import UIKit
class WaterTracker {
private var totalIntake: Int = 0
func addWater() {
totalIntake += 1
}
func reset() {
totalIntake = 0
}
func getTotalIntake() -> Int {
return totalIntake
}
}
class ViewController: UIViewController {
let wa... | magicoder | swift |
You are tasked with implementing a password hashing function in JavaScript. The function should take a plaintext password as input and return the hashed password. The hashing algorithm to be used is a simple custom algorithm that involves reversing the characters of the plaintext password and then applying a shift oper... | ```javascript
function hashPassword(plaintext) {
let reversed = plaintext.split('').reverse().join('');
let hashed = '';
for (let i = 0; i < reversed.length; i++) {
let shiftedCharCode = reversed.charCodeAt(i) + (i + 1);
hashed += String.fromCharCode(shiftedCharCode);
}
return hashed;
}
// Test the h... | magicoder | javascript |
You are tasked with implementing a function that processes data from multiple sources and organizes it into a specific data structure. The function takes in a list of summary iterators, each of which provides access to time-series data for various tags. The goal is to create a dictionary that groups the data by tag and... | ```python
from collections import defaultdict
def process_data(summary_iterators, tags):
out = defaultdict(list)
for tag in tags:
for events in zip(*[acc.Scalars(tag) for acc in summary_iterators]):
steps = [e.step for e in events]
wall_times = [e.wall_time for e in events]
... | magicoder | python |
You are tasked with implementing a message routing system for a chat application. The system should be able to route messages from one client to another through a server. The server maintains a list of connected peers and their corresponding clients.
You are given a code snippet that represents part of the message rou... | ```rust
use std::collections::{HashMap, HashSet};
#[derive(Clone)]
struct Message {
to_peer: String,
from_peer: String,
to_client: u32,
from_client: u32,
service: u16,
content: String,
}
#[derive(Clone, Copy)]
enum Service {
Chat = 1,
// Add other service types as needed
}
struct Mess... | magicoder | rust |
You are tasked with implementing a Python class that generates synthetic datasets for clustering algorithms. The class should have an `__init__` method that takes in parameters for the number of clusters, device type, feature dimension, and standard deviation of the clusters. Additionally, the class should have a metho... | ```python
# Sample usage of the DatasetFactory class
factory = DatasetFactory(n_clusters=3, device='cpu', feature=5, sigma=1)
synthetic_data = factory.generate_data(n_samples=100)
print(synthetic_data.shape) # Output: torch.Size([300, 5])
```
The `generate_data` method first initializes an empty list `data` to store ... | magicoder | python |
You are tasked with implementing a function `multiply(x, y)` that takes in two integers `x` and `y` and returns their product without using the multiplication operator or any built-in multiplication functions.
For example, if the input is `x = 5` and `y = 4`, the function should return `20`.
Your task is to implement... | ```python
def multiply(x, y):
# Initialize the result to 0
result = 0
# Iterate through the bits of y
while y > 0:
# If the least significant bit of y is 1, add x to the result
if y & 1:
result = result + x
# Left shift x and right shift y
x = x ... | magicoder | python |
You are tasked with creating a Python script to automate the process of setting up a local socks proxy using SSH. The script should take user input for the destination port and execute the necessary commands to establish the proxy connection.
Your Python script should perform the following steps:
1. Prompt the user to... | ```python
import subprocess
def create_socks_proxy():
destination_port = input("Enter the destination port for the SSH connection: ")
try:
subprocess.run(["echo", "Creating local socks proxy to *:8181"], check=True)
subprocess.run(["echo", ""], check=True)
subprocess.run(["sshpass", "-... | magicoder | python |
You are tasked with creating a program to analyze the frequency distribution of words in a given text file. The program should read the text file, tokenize the words, and then calculate the frequency of each word. Finally, it should display the frequency distribution of the words using a bar chart.
Write a Python prog... | ```python
import nltk
from nltk.corpus import PlaintextCorpusReader
from nltk import FreqDist
from matplotlib import pyplot as plt
# Define the path to the text file
corpus_root = 'C:/Users/IBM/Desktop/FYP Codes/untitled2'
wordlists = PlaintextCorpusReader(corpus_root, '.*')
# Read the content of the text file and to... | magicoder | python |
You are tasked with implementing a function that calculates the average of an array of numbers, rounded to a specified number of decimal places. You are provided with a code snippet that extends the `Double` type with a method for rounding to a specified number of decimal places.
You need to implement a function `roun... | ```swift
func roundedAverage(_ numbers: [Double], toPlaces places: Int) -> Double {
guard !numbers.isEmpty else { return 0.0 } // Return 0 if the array is empty
let sum = numbers.reduce(0.0, +) // Calculate the sum of the numbers
let average = sum / Double(numbers.count) // Calculate the average
... | magicoder | swift |
You are tasked with implementing a function to run a command with a timeout and handle the output. The function `runCmdTimeout` takes three parameters: `cmd` (the command to be executed), `sol` (the solution to be used), and `size` (the size of the command). Additionally, there is a helper function `runCNF` that takes ... | ```python
import subprocess
import signal
import os
def runCmdTimeout(cmd, sol, size):
try:
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, _ = process.communicate(timeout=size)
return output.decode('utf-8')
except subprocess.TimeoutExpired:
... | magicoder | python |
You are tasked with creating a Django view that takes latitude and longitude as input parameters and returns the corresponding geographical information. Your task is to implement the `geoView` function in the `views.py` file.
The `geoView` function should take two string parameters, `lat` and `lng`, representing latit... | ```python
# views.py
import requests
from django.http import JsonResponse
def geoView(request, lat, lng):
# Assuming the use of a geocoding API (e.g., OpenCage Geocoding API)
api_key = 'your_api_key_here' # Replace with your actual API key
url = f'https://api.opencagedata.com/geocode/v1/json?q={lat}+{lng... | magicoder | python |
You are tasked with creating a Python function that utilizes the `compas_rrc` library to move a robotic arm to a specified set of joint positions. The `compas_rrc` library provides functionalities for controlling robotic arms using the Robotic Remote Control (RRC) protocol. Your function should take in the desired join... | ```python
import compas_rrc as rrc
def move_to_joints(joint_positions):
"""
Move the robotic arm to the specified joint positions.
Parameters:
joint_positions (list): A list of joint positions to move the robotic arm to.
Returns:
bool: True if the movement was successful, False otherwise.
... | magicoder | python |
You are tasked with implementing a function that processes a list of items based on their types and performs specific operations on each type. The function should handle three specific types: `spectrum::Nested`, `spectrum::Group`, and `spectrum::BoxedDoc`. For the `spectrum::BoxedDoc` type, the function should import t... | ```rust
enum EnumType {
Nested,
Group(String),
BoxedDoc,
}
fn process_items(items: Vec<EnumType>) -> Vec<String> {
let mut result = Vec::new();
for item in items {
match item {
EnumType::Nested => continue,
EnumType::Group(processed_group) => result.push(processed_gr... | magicoder | rust |
You are tasked with implementing a simple data structure to manage a set of unique integers. The data structure should support adding elements, removing elements, and checking if a specific element is present in the set. Additionally, you need to implement a method to return the number of elements in the set.
You are ... | ```python
class Set:
def __init__(self):
self._SIGSET_H_types = 1 # Using the provided constant as the internal representation
# Using a dictionary to store the elements as keys for efficient lookup
self.elements = {}
def add(self, element: int):
self.elements[element] = True ... | magicoder | python |
You are working on a project that involves processing images using a set of predefined operations. One of the operations is a random perspective transformation applied to an image. The transformation is defined by four control points, and the transformation is randomly applied with a certain probability.
You need to i... | ```python
from PIL import Image
import numpy as np
import random
import math
def apply_random_perspective_transformation(image, cfgs):
# Extracting the configuration for random perspective transformation
perspective_cfg = cfgs["scratch"][0][0]
# Applying the transformation with the given probability
i... | magicoder | python |
You are tasked with implementing a program that can efficiently determine the frequency of each word in a given text. A word is defined as a sequence of characters separated by spaces, and punctuation should be disregarded. The program should be case-insensitive, meaning that "Word" and "word" should be considered the ... | ```swift
func wordFrequency(text: String, stopWords: [String]) -> [String: Int] {
var wordCounts: [String: Int] = [:]
let words = text.lowercased().components(separatedBy: CharacterSet.alphanumerics.inverted)
for word in words {
if !stopWords.contains(word) && !word.isEmpty {
w... | magicoder | swift |
You are working on a messaging system for a game, and you need to implement a message handling system for various actions. The given code snippet defines an enum `MapleDueyActions` with several message types and their corresponding codes. Your task is to create a Java program that processes incoming messages and perfor... | ```java
public class MessageHandler {
public enum MapleDueyActions {
C_CLAIM_RECEIVED_PACKAGE(0x04),
S_SUCCESSFULLY_RECEIVED(0x17),
S_SUCCESSFULLY_SENT(0x18),
S_ERROR_SENDING(0x12),
S_OPEN_DUEY(0x08);
final byte code;
private MapleDueyActions(int code) {
... | magicoder | java |
You are tasked with creating a program that parses a given text to extract the licensing information. The licensing information is typically found at the beginning of a file and follows a specific format. The license text begins with the copyright year and the name of the company, followed by the licensing details. The... | ```python
import re
def extract_license_info(text):
license_info = {
"copyright": "",
"company": "",
"license_type": "",
"license_version": "",
"permissions": "",
"restrictions": ""
}
copyright_match = re.search(r'Copyright (\d{4}) (.+)', text)
if copyri... | magicoder | python |
You are tasked with implementing a function to process a list of plate IDs. Each plate ID consists of a string representing a combination of letters and numbers. The function should partition the list of plate IDs into two separate lists based on a specific criterion. The criterion is that the plate ID should be added ... | ```python
def partition_plate_ids(plate_ids):
letters_only = []
letters_and_numbers = []
for plate_id in plate_ids:
if plate_id.isalpha(): # Check if the plate ID contains only letters
letters_only.append(plate_id)
elif plate_id.isalnum(): # Check if the plate ID contains ... | magicoder | python |
You are working on a FastCGI (Fast Common Gateway Interface) implementation in Swift. FastCGI is a protocol for interfacing external applications with web servers. In this scenario, you need to define a Swift enumeration to represent the different types of FastCGI records.
You are given a code snippet that defines som... | ```swift
enum FastCGIRecordType: UInt8 {
case FCGI_NO_TYPE = 0
case FCGI_BEGIN_REQUEST = 1
case FCGI_END_REQUEST = 3
case FCGI_PARAMS = 4
case FCGI_STDIN = 5
case FCGI_STDOUT = 6
}
``` | magicoder | swift |
You are tasked with implementing a rating system for a web application. The system should allow users to save or update their ratings for various items. The ratings are represented by an interface `RatingInterface`, and you need to create a method to save or update the ratings.
You are provided with the following code... | ```php
/**
* Save or update rating
*
* @param \DCS\RatingBundle\Model\RatingInterface $rating
* @return RatingInterface
* @throws \InvalidArgumentException if the rating object is invalid
*/
public function saveRating(RatingInterface $rating) {
// Validate the input rating object
if (!$this->isValidRating... | magicoder | php |
You are given an array of length `n` initialized to all 0's and a list of queries. Each query is represented by a triplet of integers `(a, b, k)`. Your task is to apply each query to the array and finally return the maximum value in the array after all the queries have been applied.
The `arrayManipulation` function ta... | ```python
from typing import List, Tuple
def arrayManipulation(n: int, queries: List[Tuple[int, int, int]]) -> int:
arr = [0] * (n + 1) # Initialize the array with an extra element for 1-based indexing
for a, b, k in queries:
arr[a - 1] += k # Add k to the element at index a-1
arr[b] -= k # ... | magicoder | python |
You are tasked with creating a Python program that captures frames from a video file, compresses them using JPEG encoding, and sends the compressed frames over a network connection to a server. Your program should establish a TCP connection with the server, capture frames from the video file, compress them using JPEG e... | ```python
import cv2
import socket
import struct
import pickle
import zlib
# Create a TCP client socket and connect to the server
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('127.0.0.1', 8485))
# Set up video capture from the specified file
cam = cv2.VideoCapture("E:/songs... | magicoder | python |
You are tasked with implementing a caching mechanism for view models in a mobile application framework. The provided code snippet outlines the interface for the caching system, which includes the following methods:
```csharp
int Cache(IMvxViewModel viewModel);
IMvxViewModel Get(int index);
IMvxViewModel Get(Type viewM... | ```csharp
using System;
using System.Collections.Generic;
public class ViewModelCache
{
private Dictionary<int, IMvxViewModel> cache;
private Dictionary<Type, int> typeIndexMap;
private int currentIndex;
public ViewModelCache()
{
cache = new Dictionary<int, IMvxViewModel>();
typeIn... | magicoder | csharp |
You are tasked with implementing a parallel vector update operation using OpenCL and the ViennaCL library. The provided code snippet initializes an OpenCL kernel and retrieves the size of a vector for the update operation. Your task is to complete the implementation of the vector update operation using the ViennaCL and... | ```cpp
// Create an OpenCL buffer for the vector to be updated
viennacl::ocl::context & ctx = viennacl::ocl::get_context(0);
viennacl::vector<NumericT> result(vec_size);
viennacl::ocl::handle<cl_mem> result_mem = viennacl::ocl::current_context().create_memory(CL_MEM_READ_WRITE, vec_size * sizeof(NumericT));
// Set the... | magicoder | cpp |
You are tasked with implementing a Python function that calculates the total size of all files within a given directory. The function should consider the sizes of all files within the directory and its subdirectories. You are provided with a code snippet that defines a dictionary containing file information, including ... | ```python
def total_directory_size(directory_info):
total_size = 0
for item, info in directory_info.items():
if info['dir']:
total_size += total_directory_size(info) # Recursively calculate size for subdirectories
else:
total_size += info['size'] # Add size of the file
... | magicoder | python |
You are tasked with implementing a TypeScript function that determines whether a given identifier name requires quoting. In TypeScript, certain identifier names may require quoting if they are reserved keywords or contain special characters. The function `requiresQuoting` takes two parameters: `name` (the identifier na... | ```typescript
import * as ts from 'typescript';
function requiresQuoting(name: string, target?: ts.ScriptTarget): boolean {
// List of reserved keywords in TypeScript
const reservedKeywords: Set<string> = new Set([
"abstract", "as", "any", "boolean", "break", "case", "catch", "class",
"const", "continue", ... | magicoder | typescript |
You are tasked with creating a caching mechanism for a web application that retrieves and stores recommendations for users. The recommendations are fetched from an external API and need to be cached to improve performance and reduce the number of API calls. Your task is to implement a caching system using the `System.R... | ```csharp
using System;
using System.Collections.Generic;
using System.Runtime.Caching;
using System.Threading.Tasks;
using Recommendations.Common.Api;
public class RecommendationCache
{
private MemoryCache _cache;
public RecommendationCache()
{
_cache = MemoryCache.Default;
}
public asyn... | magicoder | csharp |
You are tasked with implementing a Python function that simulates a simple text-based adventure game. The game will involve navigating through different rooms, encountering obstacles, and making decisions that affect the outcome of the game.
Your function should take in a list of dictionaries, where each dictionary re... | ```python
def explore_game(rooms):
current_room = rooms[0]
while True:
print(current_room["description"])
if current_room["outcome"]:
return current_room["outcome"]
print("Exits:", ", ".join(current_room["exits"].keys()))
direction = input("Choose a direction: ").lowe... | magicoder | python |
You are given a list of strings and an integer `n`. Your task is to write a function `remove_short_words` that removes all the words from the list that have a length less than `n`. The function should return the modified list of strings.
Function signature:
```python
def remove_short_words(words: List[str], n: int) -... | ```python
from typing import List
def remove_short_words(words: List[str], n: int) -> List[str]:
return [word for word in words if len(word) >= n]
``` | magicoder | python |
You are tasked with creating a program to compute the average temperature of various regions under different treatments and scenarios. The temperature data is stored in a list of dataframes, `temp_veg_dfs`, and the spatial information is provided in a spatial prefix map, `luts.spatial_prefix_map`. The treatments and sc... | ```python
import pandas as pd
from typing import List, Dict
def compute_averages(temp_veg_dfs: List[pd.DataFrame], spatial_prefix_map: Dict[str, List[str]], treatment_options: List[str], scenarios: List[str]) -> Dict[str, Dict[str, Dict[str, float]]]:
result = {}
for spatial_prefix, regions in spatial_prefix_m... | magicoder | python |
You are tasked with creating a program to generate a word search puzzle and save it as a PDF file. The program should take input parameters for the number of words, the length of each word, the number of words per line, and the dimensions of the puzzle grid. The word search puzzle should be generated with random words ... | ```python
from random import randint, shuffle, sample, choice
from math import floor
from reportlab.lib.pagesizes import A4
from reportlab.lib.units import cm
from reportlab.pdfgen.canvas import Canvas
def generate_word_search_pdf(word_count, word_length, words_per_line, dimensions):
words = [''.join([chr(randint(... | magicoder | python |
You are tasked with creating a custom filter for a trading card game (TCG) using Java and the Mage library. The goal is to implement a filter that selects all creature cards with a specific subtype for a game effect.
Your task is to complete the implementation of the custom filter by defining the necessary parameters ... | ```java
import mage.constants.SubType;
import mage.filter.FilterCard;
import mage.filter.common.FilterCreatureCard;
import mage.filter.predicate.mageobject.SubtypePredicate;
import mage.target.common.TargetCreaturePermanent;
import java.util.UUID;
public class CustomSubtypeFilter extends FilterCreatureCard {
priv... | magicoder | java |
You are tasked with implementing a Python package for object detection using the YOLOv5 model. The package should provide two different implementations of the YOLOv5 model: one using PyTorch and another using ONNX. The code snippet provided is from the `__init__.py` file of the package, which is responsible for importi... | ```python
# yolo_v5_torch.py
import torch
import torchvision.transforms as T
from PIL import Image
from yolov5.models import YOLOv5 # Assuming the YOLOv5 model is implemented in the yolov5 package
class YOLOv5Torch:
def __init__(self, model_path):
self.model = YOLOv5(model_path)
def load_model(self):... | magicoder | python |
You are tasked with creating a Python program that processes files in a given directory and its subdirectories. Your program should recursively traverse the directory structure, identify all Python files, and count the total number of lines of code in each file. Additionally, you need to calculate the total number of P... | ```python
import os
def count_lines_of_code(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
return sum(1 for line in file if line.strip())
def process_directory(directory):
total_files = 0
total_lines_of_code = 0
for root, _, files in os.walk(directory):
for file in fi... | magicoder | python |
You are tasked with implementing a DNA sequence processing system. The system needs to calculate the MD5 checksum for each reference sequence and construct a list of reference sequences with their corresponding MD5 checksums.
You are given a code snippet that demonstrates part of the process. The snippet shows the add... | ```rust
use md5::{Md5, Digest};
fn process_reference_sequences(reference_sequence_records: Vec<ReferenceSequenceRecord>) -> Vec<(String, String)> {
let mut result = Vec::new();
for record in reference_sequence_records {
let sequence = record.sequence();
let mut hasher = Md5::new();
ha... | magicoder | rust |
You are tasked with implementing a user authentication and authorization system for a web application. The system should use the `sentry_sdk` library to set user information and enforce certain access control rules.
You are provided with a code snippet that sets the user information using `sentry_sdk` and an asynchron... | ```python
import sentry_sdk
# Set user information using sentry_sdk
sentry_sdk.set_user({"id": request.uid})
# Complete the access control check in the get_user_info() function
async def get_user_info():
if method == "bearer" and (god is not None or request.god_id is not None):
# Access control check pass... | magicoder | python |
You are working on a data analysis project that involves processing and visualizing spectral data from a scientific instrument. The code snippet provided is a part of a larger script that processes and plots spectral data. The snippet uses the `matplotlib` library to create plots and save them as image files. Additiona... | ```python
import matplotlib.pyplot as plt
def generate_spectral_report(slit_profile, low, high, edge_cut, i, data):
# Plot the slit_profile and add vertical lines
plt.plot(slit_profile)
plt.axvline(low - edge_cut, color="black", lw=4, label=low, alpha=0.4)
plt.axvline(high - edge_cut, color="red", lw=4... | magicoder | python |
You are tasked with implementing a middleware system for a web application framework. The middleware system is responsible for processing incoming requests and outgoing responses. Each middleware component can perform specific tasks such as authentication, logging, error handling, etc. The middleware components are exe... | ```python
class MiddlewareManager:
def __init__(self):
self.middlewares = []
def add_middleware(self, middleware):
self.middlewares.append(middleware)
def setup_middleware(self):
for middleware in self.middlewares:
if hasattr(middleware, 'setup_middleware'):
... | magicoder | python |
You are given a binary search tree (BST) implemented using the following Node class:
```typescript
class Node {
value: number;
left?: this;
right?: this;
}
```
You need to implement a function `lca` (lowest common ancestor) that finds the lowest common ancestor of two nodes `a` and `b` in the given BST. T... | ```typescript
function lca(root: Node, a: Node, b: Node): Node {
let current = root;
while (true) {
if (a.value < current.value && b.value < current.value) {
current = current.left!;
} else if (a.value > current.value && b.value > current.value) {
current = current.right... | magicoder | typescript |
You are tasked with implementing a Python class method that checks the validity of a YAML configuration file. The class `ConfigChecker` has an `__init__` method that takes a `location` parameter, representing the path to the YAML file. You need to implement the `config_file_ok` method that checks whether the YAML file ... | ```python
import os
import yaml
class ConfigChecker:
def __init__(self, location):
self.loc = location # path to yaml file
def config_file_ok(self):
if not os.path.exists(self.loc):
return False # File does not exist
try:
with open(self.loc, 'r') as file:
... | magicoder | python |
You are tasked with creating a Python function that processes football match data from different sources and returns a pandas DataFrame containing the relevant information. The function should handle data from both a local file and a web API response.
You are provided with a code snippet that includes part of the logi... | ```python
import pandas as pd
import warnings
STATSBOMB_WARNING = "StatsBomb Warning"
def process_match_data(path_or_buf, warn=False):
if warn:
warnings.warn(STATSBOMB_WARNING)
if type(path_or_buf).__name__ == 'Response':
df_competition = pd.read_json(path_or_buf.content, convert_dates=['matc... | magicoder | python |
You are tasked with implementing a retry mechanism for a specific method in a Python class. The method, `test_control_x`, is part of the `TestPathControlXInterface` class and is decorated with the `@retry` decorator. The `@retry` decorator is used to automatically retry the method in case of failure, with a maximum num... | ```python
from functools import wraps
import time
from random import randint
class Retry:
def __init__(self, stop_max_attempt_number, wait_fixed):
self.stop_max_attempt_number = stop_max_attempt_number
self.wait_fixed = wait_fixed
def __call__(self, func):
@wraps(func)
def wrap... | magicoder | python |
You are tasked with implementing a class that coordinates among different parts of a chart to manage their dimensions and layout specifications. The class should facilitate the registration of participants and the execution of the coordination process.
Your task is to implement the `IPartCoordinator` interface with th... | ```java
import java.util.ArrayList;
import java.util.List;
public class ChartPartCoordinator<T> implements IPartCoordinator<T> {
private List<T> participants;
public ChartPartCoordinator() {
this.participants = new ArrayList<>();
}
@Override
public void register(T participant) {
p... | magicoder | java |
You are tasked with creating a Python function that simulates a database connection retry mechanism. The function should attempt to connect to a database using a given URL and retry a specified number of times if the connection fails. If the maximum number of attempts is reached without a successful connection, the fun... | ```python
def connect_to_database(database_url: str, max_attempts: int) -> str:
attempts = 1
while attempts <= max_attempts:
try:
# Attempt to connect to the database
# Replace the following line with actual database connection logic
if database_connection_successful(... | magicoder | python |
You are working on a project that involves building and training a deep learning model using a Python library such as TensorFlow or Keras. As part of the project, you need to understand and manipulate the model's architecture, weights, and predictions. Your task is to create a Python function that performs specific ope... | ```python
import copy
import numpy as np
from tensorflow.keras.models import Model
from tensorflow.keras.layers import wrappers, Input
from tensorflow.python.keras.utils import CustomObjectScope
from numpy.testing import assert_allclose
def manipulate_model(model, x_np, s_fw_np, s_bk_np, c_np):
# Make predictions ... | magicoder | python |
You are tasked with implementing a utility function to convert a given date and time string from one format to another. The function should be able to handle both standard and fractional date-time formats. The date and time string will be in the format specified by the `DATE_TIME_FORMAT` or `DATE_TIME_FORMAT_FRACTIONAL... | ```python
from datetime import datetime
BINDINGS_HTTP_POST = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
DATE_TIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
DATE_TIME_FORMAT_FRACTIONAL = "%Y-%m-%dT%H:%M:%S.%fZ"
def convert_date_time_format(input_datetime: str) -> str:
if DATE_TIME_FORMAT in input_datetime:
input... | magicoder | python |
You are given a task to implement a function to match a string against a pattern that includes '.' and '*'. In this context, the character '.' represents any single character, while '*' represents zero or more occurrences of the preceding character. Your goal is to write a function that determines whether a given strin... | ```java
public class Match {
public boolean match(char[] str, char[] pattern) {
int m = str.length, n = pattern.length;
boolean[][] dp = new boolean[m + 1][n + 1];
dp[0][0] = true;
for (int i = 0; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (pattern[... | magicoder | java |
You are tasked with creating a Python class that generates a form with multiple fields for a web application. The form should include a multiple select field and a checkbox field. The multiple select field should use a CheckboxSelectMultiple widget and have choices ranging from 0 to 4, with corresponding labels. The ch... | ```python
from django import forms
class CustomForm:
@staticmethod
def generate_multiple_select_field():
choices = ((x, f'choice {x}') for x in range(5))
multiple_select_field = forms.ChoiceField(
widget=forms.CheckboxSelectMultiple,
label='CheckboxSelectMultiple',
... | magicoder | python |
You are tasked with implementing a memory-mapped I/O system for a simple computer emulator. The emulator has a bus structure that connects various components such as the CPU, RAM, PPU (Picture Processing Unit), and controllers. The bus is responsible for managing memory access and I/O operations.
The provided code sni... | ```rust
use std::cell::RefCell;
use std::rc::Rc;
pub const RAM_SIZE: usize = 0x800;
pub struct Bus {
controller: Controller,
mapper: Rc<RefCell<Box<dyn Mapper + Send>>>,
ppu: Ricoh2C02,
ram: Box<[u8]>,
}
impl Bus {
fn read(&self, address: u16) -> u8 {
match address {
0x0000..=... | magicoder | rust |
You are tasked with implementing a data splitting algorithm for a machine learning project. The given code snippet is part of a data preprocessing step, where the dataset is divided into training and testing sets. The variable `train_frac` represents the fraction of the data to be used for training, and `Num_Each_Class... | ```python
import math
import numpy as np
def data_splitting(train_frac, Num_Each_Class):
Num_Train_Each_Class = [math.ceil(train_frac * x) for x in Num_Each_Class]
Num_Train_Each_Class = [int(x) for x in Num_Train_Each_Class]
Num_Test_Each_Class = list(np.array(Num_Each_Class) - np.array(Num_Train_Eac... | magicoder | python |
You are tasked with implementing a module resolution algorithm for a JavaScript module system. The module system uses the `export * from "module"` syntax to re-export all the exports from another module. Your goal is to write a function that resolves the exports of a given module, taking into account the re-export synt... | ```javascript
function resolveModuleImports(moduleImports) {
const resolvedExports = {};
for (const importStatement of moduleImports) {
const match = importStatement.match(/export \* from "(.*?)";/);
if (match) {
const moduleName = match[1];
const moduleExports = resolveModuleImports([`export *... | magicoder | javascript |
You are tasked with implementing a key validation system for a contact tracing application. The system should validate a set of temporary exposure keys based on a given configuration.
You are provided with the following interface definition:
```csharp
namespace DIGNDB.App.SmitteStop.Core.Contracts
{
public interf... | ```csharp
using System;
namespace DIGNDB.App.SmitteStop.Core.Contracts
{
public class ExposureKeyValidator : IExposureKeyValidator
{
public void ValidateParameterAndThrowIfIncorrect(TemporaryExposureKeyBatchDto parameter, KeyValidationConfiguration config)
{
// Check if the paramete... | magicoder | csharp |
You are tasked with implementing a PID (Proportional-Integral-Derivative) controller class in C++. The PID controller is a widely used control loop feedback mechanism that calculates an error value as the difference between a desired setpoint (SP) and a measured process variable (PV). The controller attempts to minimiz... | ```cpp
#include <iostream>
class PID {
private:
double Kp_;
double Ki_;
double Kd_;
double prev_error_;
double integral_;
public:
PID() : Kp_(0.0), Ki_(0.0), Kd_(0.0), prev_error_(0.0), integral_(0.0) {}
~PID() {}
void Init(double Kp, double Ki, double Kd) {
Kp_ = Kp;
... | magicoder | cpp |
You are tasked with creating a function that takes a string as input and returns a new string with the characters reversed. You must implement the function in Rust.
Function Signature:
```rust
fn reverse_string(name: &str) -> String {
// Your code here
}
```
Example:
```rust
assert_eq!(reverse_string("hello"), "o... | ```rust
fn reverse_string(name: &str) -> String {
name.chars().rev().collect()
}
``` | magicoder | rust |
You are tasked with implementing a function to find the closest point on a polygon to a given point in a 2D space. The polygon is represented by a set of points, and the function should return the closest point on the polygon, along with the minimum translation vector and the normal of the resulting collision.
You are... | ```csharp
public class Polygon
{
public static Vector2 GetClosestPointOnPolygonToPoint(List<Vector2> polygonPoints, Vector2 relativePoint,
out float distanceSquared, out Vector2 normal)
{
Vector2 closestPoint = Vector2.zero;
distanceSquared = float.MaxValue;
normal = Vector2.zero... | magicoder | csharp |
You are given a Python code snippet that imports the `pseudopol` library and the `numpy` library. The code snippet takes an integer input from the command line, generates a list of 5000 random integers between 1 and 500000 using `numpy`, and then calls the `find_max_subsum` function from the `pseudopol` library with th... | ```python
from typing import List
def find_max_subsum(max_val: int, vals: List[int]) -> int:
n = len(vals)
dp = [0] * (max_val + 1)
for val in vals:
for j in range(max_val, val - 1, -1):
dp[j] = max(dp[j], dp[j - val] + val)
return dp[max_val]
```
The `find_max_subsum` fu... | magicoder | python |
You are working on a system monitoring and maintenance application that tracks the performance and maintenance activities of various components. The system stores results in dictionaries: `system_obs`, `system_action`, `yearly_costs_breakdown`, and `cost_breakdown`. Your task is to analyze the data and extract relevant... | ```python
import numpy as np
def average_pf_change_during_repairs(system_model):
t, pf = np.vstack(system_model.system_pf).T
unique_mask = np.diff(t) == 1
delta_pf = np.diff(pf)[unique_mask]
average_change = np.mean(delta_pf)
return average_change
```
The `average_pf_change_during_repairs` functio... | magicoder | python |
You are working on a version control system and need to create a set of aliases for common CVS (Concurrent Versions System) commands. The provided code snippet contains a set of alias commands for various CVS operations. Your task is to write a Bash script that incorporates these aliases and performs specific CVS opera... | ```bash
#!/bin/bash
case "$1" in
"cvsun")
cvsun
;;
"cvsmod")
cvsmod
;;
"update")
update
;;
"cvsstat")
cvsstat
;;
"cvsstatx")
cvsstatx
;;
"cvsst_long")
cvsst_long
;;
*)
echo "Unsupported operation"
;;
esac
```
Save the above script in a file named `... | magicoder | shell |
You are tasked with creating a program to process and analyze data from a transportation system. The program will read in a JSON data structure containing information about traffic recognition and location links. For each recognition, the program will calculate the average speed and output the result in a specific form... | ```python
import json
def process_traffic_data(locationdata, recognition, data):
for item in locationdata['links']:
if item['id'] == recognition['id']:
link_data = item
average_speed = (link_data['dist'] / recognition['tt']) * 3.6
hour_of_day = data['date'][11:13]
... | magicoder | python |
You are tasked with implementing a business management system using Python's Django framework. The system should allow users to create and delete businesses, with each business having a unique email associated with it. You need to create a Django model for the business, along with the necessary methods for creating and... | ```python
from django.db import models
class Business(models.Model):
email = models.EmailField(max_length=60)
def __str__(self):
return self.name # Assuming the name field exists in the Business model
def create_business(self):
self.save()
def delete_business(self):
self.del... | magicoder | python |
You are tasked with creating a custom auto-complete feature for a text input field in a PyQt application. The application allows users to select a deck from a list of available decks. The code snippet provided initializes the auto-complete functionality for the text input field.
Your task is to implement the `Complete... | ```python
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QCompleter, QLineEdit
class Completer:
def __init__(self, line_edit, deck_names):
self.line_edit = line_edit
self.deck_names = deck_names
self.completer = QCompleter(self.deck_names, line_edit)
self.completer.setCaseS... | magicoder | python |
You are working on a computer vision project and are tasked with implementing a custom neural network architecture for image processing. The given code snippet is a part of the network's forward pass, where certain operations are performed on feature maps. Your task is to understand the code and design a problem relate... | To solve this problem, you can create a scenario where the students are given a custom neural network architecture and are asked to perform specific operations on the feature maps at different layers of the network. The problem can involve tasks such as implementing custom layers, applying batch normalization, or modif... | magicoder | python |
You are tasked with implementing a neural network class in Python for image classification. The given code snippet is a part of the initialization method of the neural network class. Your task is to complete the implementation of the `create_net` method, which will define the architecture of the neural network using th... | ```python
import torch
import torch.nn as nn
class NeuralNetwork(nn.Module):
def __init__(self, lr, cuda, channels_in, classes, batch_size, Nbatches, nhid, side_in, alpha_shape, bias):
super(NeuralNetwork, self).__init__()
self.lr = lr
self.schedule = None # [] #[50,200,400,600]
se... | magicoder | python |
You are tasked with implementing a Python class that performs segmentation on a set of data using the BBBSeg algorithm. The BBBSeg algorithm is a proprietary segmentation algorithm designed to partition data into distinct segments based on certain criteria. Your task is to complete the implementation of the `BBBSeg` cl... | ```python
from typing import List
class BBBSeg:
def __init__(self, data: List[float]):
self.data = data
def segment(self) -> List[List[float]]:
segments = []
current_segment = [self.data[0]]
for i in range(1, len(self.data)):
if abs(self.data[i] - current_segment[-... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.