query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are given a Python class `Visualization` that represents a visualization tool for skeletal structures. The class has several methods for interacting with the visualization, such as setting the color, getting the file path, and obtaining the number of joints in the skeleton being visualized. Your task is to implemen... | ```python
class Visualization:
def __init__(self, filePath, visualization):
self.filePath = filePath
self._visualization = visualization
def isLoadedCorrectly(self):
# Implementation not shown
pass
def getFilePath(self):
if self.isLoadedCorrectly():
retu... | magicoder | python |
You are tasked with implementing a BitTorrent protocol handler in Python. The given code snippet is a part of the protocol handler's message processing logic. The handler receives messages from different types of BitTorrent clients and processes them accordingly.
The code snippet shows a part of the message processing... | ```python
def process_bittorrent_message(self, message, t, noisy):
if t == UTORRENT_MSG:
if noisy:
log("UTORRENT_MSG: %r:%r" % (msg_type, d))
self._got_utorrent_msg(msg_type, bdecode(message))
return
if t == AZUREUS_SUCKS and self.uses_azureus_extension:
magic_intro =... | magicoder | python |
You are given a Python module `mod` containing two classes `Foo` and `Bar`. The code snippet provided tests the hash value of the classes and accesses the method resolution order (MRO) of the `Foo` class.
Your task is to implement a Python class `Baz` that inherits from both `Foo` and `Bar` and overrides the `__hash__... | ```python
class Foo:
pass
class Bar:
pass
class Baz(Foo, Bar):
def __hash__(self):
return 8765
def get_mro(self):
return [cls.__name__ for cls in type(self).__mro__]
```
The `Baz` class inherits from both `Foo` and `Bar`, overrides the `__hash__` method to return 8765, and implements... | magicoder | python |
You are tasked with creating a Python function that simulates a simplified version of a web API client. The function should send a GET request to a specified endpoint with given parameters and validate the response status code. Your task is to implement the function and write test cases to ensure its correctness.
Writ... | ```python
import requests
def api_get_request(endpoint, params):
"""Send a GET request to the specified endpoint with given parameters and return the status code."""
req = requests.get(endpoint, params=params)
return req.status_code
def test_basic():
"""Test that we can walk."""
# Define the endpo... | magicoder | python |
You are given a Java code snippet that processes a collection of SAMRecords, which represent aligned sequencing reads in the Sequence Alignment/Map (SAM) format. The code iterates through the SAMRecords and updates a map called `refCounts` based on certain conditions. Your task is to implement a method that takes a lis... | ```java
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Solution {
public String findMostFrequentReference(List<SAMRecord> records, boolean unique) {
Map<String, Integer> refCounts = new HashMap<>();
for (SAMRecord read : IterUtils.wrap(records.iterator())) {
... | magicoder | java |
You are tasked with implementing a data processing pipeline for a machine learning project. The pipeline involves generating samples, organizing them into files, and shuffling the dataset. The code snippet provided is a part of this pipeline and uses a function `generate_samples` to create samples for a given dataset s... | ```python
import os
import random
import problem # Assuming problem.DatasetSplit.TRAIN is defined in a separate module
def generate_samples(data_dir, tmp_dir, split):
# Read dataset based on the specified split
dataset = read_dataset(data_dir, split)
# Process the data and generate samples
generated_... | magicoder | python |
You are tasked with implementing a function to parse and process MySQL packets in a Rust application. The provided code snippet includes imports and declarations related to MySQL packet parsing and handling.
Your task is to create a Rust function that takes a raw MySQL packet payload as input and returns a parsed repr... | ```rust
use mysql_common::{
named_params::parse_named_params,
packets::{column_from_payload, parse_stmt_packet, ComStmtClose, StmtPacket},
};
use std::{borrow::Cow, sync::Arc};
use crate::{
conn::routines::{ExecRoutine, PrepareRoutine},
consts::CapabilityFlags,
error::*,
};
// Define a custom enu... | magicoder | rust |
You are given a C++ code snippet that includes a function for calculating the total cost and a template function for finding the Steiner tree in a graph. Your task is to implement the missing parts of the code, specifically the `GrafoP` class and the `setMandatory` function, and then use these functions to find the Ste... | ```cpp
// Definition of GrafoP class representing a weighted graph
template <typename tCoste>
class GrafoP {
public:
// Define necessary data structures and methods to represent a weighted graph
// For example, you can use an adjacency matrix or adjacency list to store the graph structure
// Include methods... | magicoder | cpp |
You are tasked with implementing a Python class that manages a collection of words and their associated tags. The class should provide methods for adding words with tags, retrieving all words with a specific tag, and removing words from the collection.
You are given a partial implementation of the `WordTagManager` cla... | ```python
class WordTagManager:
def __init__(self):
self.words = []
self.tags = []
def add_word(self, word, tag):
self.words.append((word, tag))
if tag not in self.tags:
self.tags.append(tag)
def get_words_with_tag(self, tag):
return [word for word, t in... | magicoder | python |
You are tasked with creating a test case for a Python application that involves activating and deactivating a demo extension and testing a proxy backend. The code snippet provided includes the necessary imports and a test case class with a method for running the application. Your task is to complete the test case by im... | ```python
from demo_extension import activate_demo_extension, deactivate_demo_extension
from proxytest import backend, proxytest
import unittest
from typing import List
class RunnerTestCase(unittest.TestCase):
def _run_runner(self, args: List[str]):
# Implement the method for running the application
... | magicoder | python |
You are tasked with creating a program that processes data from an Excel spreadsheet and performs matrix addition using the PHP programming language. The program should read data from a specific sheet in the spreadsheet, perform matrix addition on the data, and then return the result as a downloadable Excel file.
You ... | ```php
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
// Read data from a specific sheet in the Excel spreadsheet
$spreadsheet = new Spreadsheet();
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$spreadsheet = $reader->load('input.xlsx');
$worksheet = $spreadsheet->getActiv... | magicoder | php |
You are tasked with implementing a batch action system for enabling and disabling comments on a website. The system should support multiple actions, each with a label and an option to ask for confirmation before execution.
You are given a code snippet that defines two batch actions, 'enabled' and 'disabled', each with... | ```python
class BatchActionManager:
def __init__(self):
self.actions = {}
def add_action(self, name, label, ask_confirmation):
self.actions[name] = {'label': label, 'ask_confirmation': ask_confirmation}
def get_action_details(self, name):
return self.actions.get(name)
def exec... | magicoder | python |
You are tasked with creating a chat application using the Orleans framework, which is a distributed actor framework for building distributed systems. In this problem, you will implement the `IChat` interface to create a chat application that allows users to send and receive messages.
The `IChat` interface has the foll... | ```csharp
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Orleans;
namespace HelloGrains
{
public class Chat : Orleans.Grain, IChat
{
private List<string> chatHistory;
private string chatName;
public override Task OnActivateAsync()
{
... | magicoder | csharp |
You are tasked with creating a program that simulates a simple file system. Your program should be able to handle basic file operations such as creating, deleting, and listing files and directories. For this problem, you need to implement the functionality to list all files and directories in a given directory.
You ar... | ```python
def list_files_and_directories(directory_path):
import os
items = []
for item in os.listdir(directory_path):
if os.path.isfile(os.path.join(directory_path, item)):
items.append(item)
else:
items.append(item + "/")
return items
```
The `list_files_and_d... | magicoder | python |
You are tasked with implementing a simple file decompression algorithm. The provided code snippet is a part of the decompression process. The `_decompress` object is an input stream for the compressed file, and the `_dest` object is an output stream for the decompressed file. The `ch` variable represents the character ... | ```cpp
#include <iostream>
void decompressFile(std::istream& _decompress, std::ostream& _dest) {
char ch = _decompress.get(); // Read the first character from the input stream
while (!_decompress.eof() && !_decompress.fail()) {
_dest.put(ch); // Write the character to the output stream
ch = ... | magicoder | cpp |
You are tasked with creating a script to manage user entries in the `/etc/passwd` file. The script should check if a user with a specific `USER_ID` exists in the `/etc/passwd` file. If the user does not exist, the script should create a new entry for the user using the provided `USER_ID`, `USER`, and `GROUP_ID`. The ne... | ```bash
#!/bin/bash
USER_ID=1001
USER="newuser"
GROUP_ID=1001
# Check if user exists in passwd file
if ! grep -q ":${USER_ID}:" /etc/passwd; then
NSS_WRAPPER_PASSWD=/tmp/passwd.nss_wrapper
NSS_WRAPPER_GROUP=/etc/group
# Create new entry for the user and append to passwd.nss_wrapper
echo "${USER}:x:${... | magicoder | shell |
You are tasked with creating a program that manipulates and prints a given set of words based on a specific pattern. The program should take input words and a pattern, then output the manipulated string according to the given pattern.
Write a program that takes in a set of words and a pattern as input. The pattern con... | ```python
def manipulate_words(words, pattern):
words = words.split()
pattern = list(map(int, pattern.split()))
manipulated_string = ' '.join(words[i-1] for i in pattern)
return manipulated_string + "?!?"
# Example usage
input_words = "How are you"
input_pattern = "2 3 2 1"
output = manipulate_words(in... | magicoder | python |
You are tasked with implementing a user authentication system for a web application. The system should allow users to sign up with a unique username and password. To achieve this, you need to create a class that handles the signup process and ensures the uniqueness of usernames.
You are provided with a code snippet f... | ```java
import java.util.Scanner;
import java.util.HashMap;
import java.util.Map;
public class Signup {
private static Map<String, String> userCredentials = new HashMap<>();
/**
* Shows the signup menus
*/
public static void signUpUI() {
Scanner sc = new Scanner(System.in);
int s... | magicoder | java |
You are tasked with creating a Minecraft mod that introduces a new item called "Enderfuge" into the game. The Enderfuge is a special crafting item that players can use to combine different materials and create unique items. To implement this, you need to define the Enderfuge class and its associated functionalities wit... | ```java
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.ItemStack;
import com.themastergeneral.ctdcore.item.CTDItem;
import com.themastergeneral.enderfuge.Enderfuge;
public class EnderfugeItem extends CTDItem {
public EnderfugeItem() {
super("enderfuge_item");
this.se... | magicoder | java |
You are given a Python code snippet that prints the shapes of two arrays, `dominance_cropped_val` and `x_entire_test`. Your task is to write a function that takes in these shapes as input and determines whether the shapes are compatible for matrix multiplication.
The function should return `True` if the shapes are com... | ```python
def check_matrix_multiplication_compatibility(m, n, p, q):
return n == p
```
The function `check_matrix_multiplication_compatibility` simply checks if the number of columns in the first matrix is equal to the number of rows in the second matrix. If they are equal, it returns `True`, indicating that the s... | magicoder | python |
You are tasked with implementing a custom error handling mechanism in JavaScript. Your goal is to create a class that extends the built-in `Error` class and captures the stack trace when an error is thrown. You should also include a property to store the error code. Your task is to complete the implementation of the `C... | ```javascript
class CustomError extends Error {
constructor(message, code) {
super(message);
this.name = this.constructor.name;
this.code = code;
Error.captureStackTrace(this, this.constructor);
}
}
// Example usage
try {
throw new CustomError('Custom error message', 500);
} catch (error) {
con... | magicoder | javascript |
You are working on a multilingual application that needs to support translations for various terms and phrases. Your task is to write a function that takes a dictionary of key-value pairs, where the keys are in English and the values are in French, and returns a new dictionary with the keys and values swapped. Addition... | ```python
def swap_translations(translations):
swapped_translations = {}
french_to_english = {}
for english, french in translations.items():
if french in french_to_english:
french_to_english[french].append(english)
else:
french_to_english[french] = [english]
... | magicoder | python |
You are tasked with implementing a function to process Pokémon mega evolution data. The given code snippet contains information about a specific mega evolution in the Pokémon universe. The `megaStone` property holds the name of the mega stone required for evolution, the `megaEvolves` property specifies the Pokémon that... | ```javascript
function canMegaEvolve(pokemon, stone, userArray) {
return stone.includes("-Mega-") && userArray.includes(pokemon);
}
// Test cases
console.log(canMegaEvolve("Exploud", "Exploud-Mega-Ausma", ["Exploud"])); // Output: true
console.log(canMegaEvolve("Blaziken", "Blaziken-Mega", ["Blaziken", "Sceptile"]))... | magicoder | javascript |
You are tasked with implementing a custom loss function and training procedure for a neural network model. The provided code snippet is a part of a larger deep learning framework and includes components for loss calculation, model training, and feature extraction.
Your task is to complete the implementation by definin... | ```python
import torch
import torch.nn as nn
import torch.optim as optim
class CustomModel(nn.Module):
def __init__(self):
super(CustomModel, self).__init__()
self.F = nn.Sequential(
# Define layers for feature extraction (e.g., convolutional, pooling layers)
)
self.C1 =... | magicoder | python |
You are tasked with creating a custom attribute class in C# that will be used to enforce a specific naming convention for properties within a class. The naming convention requires that all property names should start with a specified prefix. Your task is to implement the custom attribute and apply it to a sample class,... | ```csharp
// Custom attribute class to enforce property naming convention
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class PropertyNamePrefixAttribute : Attribute
{
public string Prefix { get; }
public PropertyNamePrefixAttribute(string prefix)
{
Prefix = prefix;
... | magicoder | csharp |
You are tasked with creating a Python function that captures a screenshot of a selected area of the screen using the `maim` command-line tool and saves it to a file with a timestamp in the filename. Your function should take no input and return the filename of the saved screenshot.
The code snippet provided demonstrat... | ```python
import os
from datetime import datetime
from subprocess import run, DEVNULL
from os import path
def capture_and_save_screenshot():
directory = path.dirname(vim.current.buffer.name) # Assuming vim.current.buffer.name is accessible
timestamp = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
filename ... | magicoder | python |
You are tasked with implementing a Python function that performs polynomial operations. The function should take two polynomials as input and return the result of adding and multiplying these polynomials. Each polynomial is represented as a list of coefficients, where the index of the coefficient corresponds to the pow... | ```python
def polynomial_operations(poly1, poly2):
add_result = []
mul_result = [0] * (len(poly1) + len(poly2) - 1)
for i in range(max(len(poly1), len(poly2))):
coeff1 = poly1[i] if i < len(poly1) else 0
coeff2 = poly2[i] if i < len(poly2) else 0
add_result.append(coeff1 + coeff2)
... | magicoder | python |
You are tasked with implementing a message passing algorithm for a graphical model. The given code snippet is a part of the algorithm and involves initializing and updating message passing for a specific time step.
Your task is to complete the implementation of the message passing algorithm by writing the `init_messag... | ```python
class GraphicalModel:
def __init__(self, N):
self.N = N
# Other initialization code
def init_message(self, node, message):
# Initialize message for the first time step
# Implement initialization logic here
pass
def multiply_CPT(self, node, evidence, messag... | magicoder | python |
You are tasked with creating a GUI application for a sports management system. The application has three buttons for different functionalities: offense, defense, and miscellaneous actions. Each button is created using the `Button` class and is placed within a specific grid layout.
Your task is to write a Python functi... | ```python
def generate_button_code(button_labels, bg_colors, text_colors, fonts, grid_positions, command_functions):
code = "from tkinter import Button\n\n"
for label, bg, text_color, font, position, command in zip(button_labels, bg_colors, text_colors, fonts, grid_positions, command_functions):
code +=... | magicoder | python |
You are tasked with creating a program that simulates a simplified version of the `system` function in C. The `system` function is used to pass a command to the operating system for execution. Your program should take a command as input and execute it, then return the exit status of the command.
Your program should fo... | ```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int execute_command(const char *command) {
pid_t pid;
int status;
pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork failed\n");
exit(1);
} else if (pid == 0) {
// ... | magicoder | c |
You are tasked with simulating an interstellar war between two alien species, the Zorgons and the Xelars. The war is fought in a 2D grid representing the battlefield. Each species has a fleet of spaceships, and the goal is to determine the outcome of the war based on their strategic movements.
The battlefield is repre... | ```java
public char[][] simulateWar(char[][] battlefield, String zorgonMoves, String xelarMoves) {
int n = battlefield.length;
char[][] newBattlefield = new char[n][n];
for (int i = 0; i < n; i++) {
System.arraycopy(battlefield[i], 0, newBattlefield[i], 0, n);
}
moveSpaceships(newBattlefiel... | magicoder | java |
You are tasked with implementing a Python class that can dynamically generate OpenAPI specifications in both Swagger 2.0 and OpenAPI 3.0 formats. The class should provide methods for defining paths, operations, parameters, and responses, and should be able to output the generated specifications in the respective format... | ```python
import json
class OpenAPISpecGenerator:
def __init__(self, version):
self.spec = {
"openapi": version,
"info": {
"title": "API Specification",
"version": "1.0.0"
},
"paths": {}
}
@classmethod
def swag... | magicoder | python |
You are tasked with implementing a custom event handling system in JavaScript using the EventEmitter class from the 'events' module. Additionally, you need to work with 64-bit integers using the Long library.
Your task is to create a class, CustomEventEmitter, that extends the EventEmitter class and adds the functiona... | ```javascript
import { EventEmitter } from 'events';
import * as Long from 'long';
class CustomEventEmitter extends EventEmitter {
emitLongEvent(eventName, longValue) {
if (!Long.isLong(longValue)) {
throw new Error('Invalid argument: longValue must be a Long');
}
this.emit(eventName, longValue);
... | magicoder | javascript |
You are tasked with implementing a feature for a running app that allows users to add more options to their favorite active runs by performing a long hold gesture on the table view cells. The app uses a `UITableView` to display a list of favorite active runs, and each cell contains information about a specific run. The... | ```swift
@objc func showOptions(gesture: UILongPressGestureRecognizer) {
guard gesture.state == .began else {
return
}
if let cell = gesture.view as? ActiveRunTableViewCell,
let indexPath = tableView.indexPath(for: cell),
let selectedRun = profile?.favoriteActiveRuns[indexPath.row... | magicoder | swift |
You are tasked with creating a script to automate the process of building and deploying a documentation website for a project. The project uses npm for package management and Git for version control. The provided code snippet demonstrates a part of the build and deployment process. Your task is to write a script that e... | ```bash
#!/bin/bash
# Step 1: Install project dependencies using npm
npm install
# Step 2: Rebuild the node-sass package
npm rebuild node-sass
# Step 3: Clean the project build directory
npm run clean
# Step 4: Build the project library
npm run build:lib
# Step 5: Build the project documentation
npm run build:docs... | magicoder | shell |
You are tasked with implementing a custom logging system for a software application. The logging system should support different log levels (e.g., INFO, WARNING, ERROR) and be able to write log messages to different output destinations (e.g., console, file, database). Additionally, the logging system should be extensib... | ```csharp
using System;
using System.Collections.Generic;
namespace Integrator.Common
{
// Define an enum for log levels
public enum LogLevel
{
INFO,
WARNING,
ERROR
}
// Define an interface for log output destinations
public interface ILogOutput
{
void Write... | magicoder | csharp |
You are tasked with implementing a rolling hash function for a given string using a polynomial hash function. The polynomial hash function is defined as follows:
\[ H(S) = \sum_{i=0}^{n-1} (S[i] \times p^i) \mod m \]
Where:
- \( S \) is the input string of length \( n \)
- \( p \) is a prime number
- \( m \) is the mod... | ```python
def rolling_hash(s, p, m):
n = len(s)
hash_value = 0
x = 0
for i in range(n):
hash_value = (hash_value + ord(s[i]) * pow(p, i, m)) % m
return hash_value
```
The `rolling_hash` function computes the hash value of the input string using the polynomial rolling hash function. It iterat... | magicoder | python |
You are tasked with implementing a pattern generator function that takes an integer `i` as input and yields a specific pattern based on a predefined `BASE_PATTERN`. The `BASE_PATTERN` is a sequence of values that the generator will iterate through. The generator should repeat each value in the `BASE_PATTERN` `i + 1` ti... | ```python
BASE_PATTERN = [1, 2, 3]
def pattern_generator(i):
first = True
while True:
for v in BASE_PATTERN:
for _ in range(i + 1):
if first:
first = False
continue
yield v
```
The solution completes the `pattern_genera... | magicoder | python |
You are tasked with creating a Python script to automate the process of backing up data from a PostgreSQL database to a specified directory. The script should utilize the provided PostgreSQL connection parameters and data directory path to perform the backup operation.
You need to write a Python function `backup_postg... | ```python
import subprocess
def backup_postgres_data(connection_params: dict, data_dir: str) -> str:
# Construct the pg_dump command using the provided connection parameters
pg_dump_command = [
'pg_dump',
f"--dbname={connection_params['dbname']}",
f"--username={connection_params['user']... | magicoder | python |
You are tasked with creating a function that processes a given HTML template and extracts information from it. The HTML template contains a div element with a nested small element, and the function needs to extract the text content of the small element if it exists. The function should take the HTML template as input a... | ```python
from bs4 import BeautifulSoup
def extract_info(html_template: str) -> str:
soup = BeautifulSoup(html_template, 'html.parser')
small_tag = soup.find('small', class_='form-text text-muted')
if small_tag:
return small_tag.get_text()
else:
return ""
```
The solution uses the Beau... | magicoder | python |
You are tasked with creating a program that simulates a simple text-based drawing tool. The program should be able to handle a set of basic commands to manipulate an "canvas" and draw on it.
The canvas is represented as a 2D grid of characters, where each cell is initially filled with a space character. The program sh... | ```python
class DrawingTool:
def __init__(self, width, height):
self.width = width
self.height = height
self.canvas = [[' ' for _ in range(width)] for _ in range(height)]
def draw_line(self, x1, y1, x2, y2):
if x1 == x2: # Vertical line
for y in range(min(y1, y2), m... | magicoder | python |
You are working on a deployment script for a web application, and you need to ensure that the correct version of PHP is included in the system's `PATH` environment variable. The deployment script is written in Bash and needs to handle the inclusion of the PHP binary path based on the specified version.
The code snippe... | ```bash
update_php_path() {
local version=${1:-latest}
local php_bin_path="/usr/local/php/${version}/bin"
if [[ -z $PATH ]]; then
export PATH="$php_bin_path"
else
if [[ ":$PATH:" != *":$php_bin_path:"* ]]; then
export PATH="$php_bin_path:$PATH"
fi
fi
}
```
T... | magicoder | shell |
You are tasked with creating a program that analyzes a given text file to count the occurrences of specific words. Your program should read the text file and then count the occurrences of each word in the file. The words should be case-insensitive, meaning "Word" and "word" should be considered the same. Additionally, ... | ```python
import string
from typing import List, Dict
def count_word_occurrences(file_path: str, words: List[str]) -> Dict[str, int]:
word_counts = {}
with open(file_path, 'r') as file:
text = file.read().lower()
text = ''.join(char for char in text if char not in string.punctuation)
wo... | magicoder | python |
You are tasked with creating a C++ function that utilizes the `getdns` library to perform a DNS lookup and return the IP address of a given domain name. The `getdns` library provides a modern asynchronous DNS API for C and C++.
Your task is to implement a function that takes a domain name as input and returns its corr... | ```cpp
#include <getdns/getdns.h>
#include <getdns/getdns_extra.h>
#include <arpa/inet.h>
#include <iostream>
std::string getIPAddress(const std::string& domain) {
getdns_context *context = NULL;
getdns_return_t ret;
getdns_dict *response = NULL;
getdns_list *replies_tree = NULL;
getdns_list *just_... | magicoder | cpp |
You are given a code snippet that calculates the cosine and sine of an angle, and then uses these values to compute a rotation matrix and translation vector. Your task is to implement a function that takes a set of 2D point pairs, performs the calculations described in the code snippet, and returns the resulting rotati... | ```cpp
#include <vector>
#include <cmath>
struct Point2 {
double x, y;
// Constructor and other methods are not shown for brevity
};
struct Point2Pair {
Point2 first, second;
};
struct Rot2 {
double angle;
// Other methods are not shown for brevity
static Rot2 fromAngle(double theta) {
Rot2 r;
r... | magicoder | cpp |
You are tasked with creating a Python program to parse XML files containing object detection annotations and generate a report on the distribution of detected objects within the dataset. The program should read the XML files, extract the object labels, and then produce a summary report showing the frequency of each obj... | ```python
import os
import xml.dom.minidom as xmldom
def parse_xml_files(directory):
object_counts = {}
for root, _, files in os.walk(directory):
for file in files:
if file.endswith('.xml'):
xml_path = os.path.join(root, file)
with open(xml_path, 'r') as f:
... | magicoder | python |
You are tasked with creating a Python script to automate the process of distributing training jobs for a machine learning model across multiple GPUs using CUDA. The script should take into account the number of available GPUs and evenly distribute the training tasks among them.
Your script should accept the following ... | ```python
import os
def distribute_training_jobs(num_jobs, available_gpus):
for i in range(1, num_jobs + 1):
gpu_id = (i - 1) % available_gpus
os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_id)
command = f"python train.py --dataset fashion_mnist --model VAE --split {i} &"
os.system(co... | magicoder | python |
You are working with a Python script that utilizes the `load_dotenv` function to load environment variables from a specified file. Additionally, there is a test function `test_find_common_set_of_column_names` that takes a Spark session as an argument and is expected to perform a specific test. The test function initial... | ```python
from typing import List, Tuple, Set
def find_common_set_of_column_names(vals: List[Tuple[int, ...]]) -> Set[int]:
if not vals:
return set()
common_columns = set(range(len(vals[0]))) # Initialize with all column indices
for tuple_vals in vals[1:]:
common_columns = common_columns... | magicoder | python |
You are given a Rust code snippet that involves a `Faces` struct and its associated methods. The `extract_boundaries1` function initializes a `Faces` instance and then calls its `extract_boundaries` method. Your task is to understand the behavior of the `Faces` and `extract_boundaries` methods and implement the logic f... | ```rust
#[derive(Debug, PartialEq)]
struct Faces(Vec<[usize; 4]>);
impl Faces {
fn from_iter(arrays: &[&[usize; 4]]) -> Faces {
let faces = arrays.iter().map(|&arr| arr.clone()).collect();
Faces(faces)
}
fn extract_boundaries(&self) -> Vec<[usize; 2]> {
let mut edge_count = std::co... | magicoder | rust |
You are tasked with creating a script to automate the compilation of Qt style plugins for different architectures. The script should determine the architecture and then compile the plugins accordingly. Your task is to complete the script by adding the necessary code to handle the compilation for the "win32" architectur... | ```bash
set -ev
ARCH=${QT_ARCH%%_*}
# Compile Qt style plugins
case $ARCH in
win32)
# Add code to compile Qt style plugins for win32 architecture
# Example:
# Assuming qmake and make are available for compilation
qmake
make
;;
*)
echo "Unsupported architecture: $ARCH"
exit 1
;;
esa... | magicoder | shell |
You are working on a web development project and need to create a component for displaying project items. The component should include various elements such as project item header, image wrapper, overlay, technology pills, and a "See More" link. You have been provided with the code snippet for the styled components use... | ```jsx
import React from "react";
import {
ProjectItemWrapper,
ProjectItemHeaderWrapper,
ProjectItemHeader,
ProjectItemImageWrapper,
ProjectItemOverlay,
ProjectItemTechPillsWrapper,
ProjectItemTechPill,
ProjectItemSeeMore,
ProjectItemOverlayWrapper,
} from "./ProjectItem.styles";
const ProjectItem = ... | magicoder | jsx |
You are given a Python code snippet that imports the `lru_cache` function from the `functools` module and the `FunctionTool` class from the `foxylib.tools.function.function_tool` module. Your task is to create a function that utilizes the `lru_cache` decorator to implement memoization for a recursive function.
Write a... | ```python
from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci_memoized(n):
if n <= 1:
return n
else:
return fibonacci_memoized(n-1) + fibonacci_memoized(n-2)
```
The `fibonacci_memoized` function uses the `@lru_cache` decorator to cache the results of previous function calls.... | magicoder | python |
You are tasked with implementing a Python class that performs reflection on a given function definition. Reflection in this context refers to the ability of a program to examine and modify its structure and behavior at runtime. Your task is to create a class called `FunctionLint` with a method `reflection_at_line` that... | ```python
import inspect
class FunctionLint:
def __init__(self, definition):
self.definition = definition
def reflection_at_line(self):
# Use the inspect module to retrieve the line number of the function definition
line_number = inspect.getsourcelines(self.definition)[1]
retur... | magicoder | python |
You are working on a speech recognition project and need to create a script to sort and report results for different models. The script is expected to run from a specific directory structure and will generate a results file in a designated location. Your task is to write a Python script that accomplishes this task.
Yo... | ```python
import os
def sort_and_report_results(results_file="results/results.txt"):
exp_dir = "exp"
results_dir = "results"
results_path = os.path.join(results_dir, results_file)
if not os.path.exists(results_dir):
os.makedirs(results_dir)
if os.path.exists(results_path):
os.remo... | magicoder | python |
You are given a list of integers representing the population growth rates of different regions. Your task is to write a function to categorize these growth rates into three groups: positive growth rates, negative growth rates, and zero growth rates.
Write a function `categorize_growth_rates` that takes a list of inte... | ```python
def categorize_growth_rates(population_growth):
positive_growth = [rate for rate in population_growth if rate > 0]
negative_growth = [rate for rate in population_growth if rate < 0]
zero_growth = [rate for rate in population_growth if rate == 0]
return (positive_growth, negative_growth, zero_g... | magicoder | python |
You are given a function `reverseFraction` that takes in two parameters: `x` (a floating-point number) and `n` (an integer). The function is intended to reverse the fraction `x` and then multiply the result by `-n`. However, the given code snippet is incorrect and needs to be fixed.
Your task is to correct the code sn... | ```python
def reverseFraction(x: float, n: int) -> float:
reversed_fraction = 1 / x # Reverse the fraction
result = reversed_fraction * -n # Multiply the reversed fraction by -n
return result
```
The `reverseFraction` function first reverses the fraction `x` by taking the reciprocal (1/x). Then, it multi... | magicoder | python |
You are tasked with creating a class for image manipulation. Your goal is to implement a method that resizes an image to a specified width while maintaining its aspect ratio. You should also handle exceptions that may occur during the image manipulation process.
Your task is to create a PHP class `Image` with the foll... | ```php
<?php
namespace Image\Exception;
class NotFoundException extends \Exception {}
class Image
{
private $imageContent;
public function load($path)
{
if (!file_exists($path)) {
throw new NotFoundException("Image file not found at path: $path");
}
$this->imageConten... | magicoder | php |
You are tasked with creating a lighting system for a 3D rendering engine using MetalKit, a framework for building GPU-accelerated apps on iOS and macOS. The lighting system will support both directional (sun) lighting and point lighting. You are provided with a code snippet that initializes a `LightingRenderPass` struc... | ```swift
import MetalKit
struct LightingRenderPass: RenderPass {
let label = "Lighting Render Pass"
var descriptor: MTLRenderPassDescriptor?
var sunLightPSO: MTLRenderPipelineState
var pointLightPSO: MTLRenderPipelineState
init(device: MTLDevice, colorPixelFormat: MTLPixelFormat, depthPixelFormat: MTLPixelF... | magicoder | swift |
You are tasked with creating a script to automate the tagging and pushing of Docker images to a registry based on the Travis CI build environment. The script should set the appropriate Docker image names and tags based on the Travis CI environment variables.
The following environment variables are available:
- `DOCKER... | ```bash
#!/bin/bash
export DOCKER_KIBANA=$DOCKER_USERNAME/vento-kibana
export DOCKER_LOGSTASH=$DOCKER_USERNAME/vento-logstash
export DOCKER_MATCH=$DOCKER_USERNAME/vento-match
export DOCKER_MONITORING=$DOCKER_USERNAME/vento-monitoring
export DOCKER_PROFILE=$DOCKER_USERNAME/vento-profile
export DOCKER_REGISTRY=$DOCKER_U... | magicoder | shell |
You are tasked with implementing a function to calculate the GC content of a DNA polymer. The GC content is the percentage of guanine (G) and cytosine (C) nucleotides in a DNA sequence. Given a DNA polymer as a string, your task is to write a function to calculate the GC content and return it as a floating-point number... | ```rust
pub fn polymer(&self, polymer: &String) -> Option<f32> {
let seq = polymer.to_ascii_uppercase();
let len = seq.len();
if len < 3 {
return None;
}
let nuc = ['A', 'G', 'C', 'T'];
if !seq.chars().all(|c| nuc.contains(&c)) {
return None;
}
let gc_count = seq.chars... | magicoder | rust |
You are tasked with creating a program that can parse and extract information from C function declarations. The function declarations are written in a specific format and may span multiple lines. Your program should be able to identify the function name, its arguments, and the return type.
The function declarations fo... | ```python
import re
def parse_function_declaration(declaration):
pattern = r"""
^(?P<ws>[ \t]*) # Capture leading whitespace
(?P<decl>.*\(\n # Capture the opening line, ending with (\n
(?:.*,\n)* # Lines with arguments, all ending with ,\n
... | magicoder | python |
You are tasked with implementing a Python function that performs a specific image processing operation using the OpenCV library. The function should take an input image, apply dilation and erosion operations to it, and then return the resulting processed image. The dilation and erosion operations should be performed wi... | ```python
import cv2
import numpy as np
def image_processing(input_image: np.ndarray) -> np.ndarray:
# Apply dilation to the input image using a kernel of size (5,5)
dilation_kernel = np.ones((5, 5), np.uint8)
dilation = cv2.dilate(input_image, dilation_kernel, iterations=1)
# Apply erosion to the... | magicoder | python |
You are tasked with creating a program that simulates a simple assembly language interpreter. The assembly language, called "REDASM," has a limited set of instructions and operates on a stack-based architecture. Each instruction is represented by a string and may have zero or more arguments. The stack is initially empt... | ```python
from typing import List
def redasm_interpreter(instructions: List[str]) -> int:
stack = []
for instruction in instructions:
if instruction.startswith("PUSH"):
value = int(instruction.split()[1])
stack.append(value)
elif instruction == "POP":
if stac... | magicoder | python |
You are tasked with implementing a pipeline system for executing operations in a specific order. The pipeline system should allow contributors to register their operations and specify the order in which they should be executed. Your task is to create a class that manages the pipeline and ensures that contributors' oper... | ```csharp
using System;
using System.Collections.Generic;
// Define an interface for pipeline contributors
public interface IPipelineContributor
{
void Execute();
}
// Define a class to represent the pipeline
public class Pipeline
{
private readonly List<IPipelineContributor> contributors = new List<IPipeline... | magicoder | csharp |
You are tasked with implementing a function that performs a specific operation on input data using the TensorRT (NVIDIA's deep learning inference library) API. The given code snippet is a part of this function and demonstrates the process of adding a bias to the input data using TensorRT operations. Your task is to com... | ```python
import tensorrt as trt
def add_bias_using_trt(input, bias, ctx, output):
result_trt = trt_(ctx.network, input) # Convert input to TensorRT format
while bias.ndim < input.ndim:
bias = bias.unsqueeze(0)
bias_trt = trt_(ctx.network, bias) # Convert bias to TensorRT format
layer = ctx... | magicoder | python |
You are tasked with creating a Python program that simulates a simple game of dice. The game should allow two players to take turns rolling a six-sided die and keep track of their scores. The game should continue until one of the players reaches a specified winning score.
Your task is to implement the `DiceGame` class... | ```python
import random
class DiceGame:
def __init__(self, winning_score):
self.winning_score = winning_score
self.scores = [0, 0]
self.current_player = 1
def roll_dice(self):
roll_result = random.randint(1, 6)
self.scores[self.current_player - 1] += roll_result
... | magicoder | python |
You are tasked with implementing a Python module that provides a network class for a binary logistic regression model. The module should include a class named `bLVNet_TAM` that encapsulates the functionality for training and making predictions using the binary logistic regression model. The model should be trained usin... | ```python
import numpy as np
class bLVNet_TAM:
def __init__(self, learning_rate, threshold):
self.learning_rate = learning_rate
self.threshold = threshold
self.weights = None
self.bias = None
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def train(self, X, y, m... | magicoder | python |
You are tasked with implementing a function to perform 2D convolution using Fast Fourier Transform (FFT) in Python. The function should take an input image and a kernel, and return the convolved image. You are provided with the following code snippet as a reference for using FFT functions and handling the case when the... | ```python
import numpy as np
import warnings
def convolve_fft(img, kernel):
try:
import pyfftw
use_fftn = pyfftw.interfaces.numpy_fft.fftn
use_ifftn = pyfftw.interfaces.numpy_fft.ifftn
except ImportError:
warnings.warn("pyfftw not installed. Using numpy.fft functions.")
... | magicoder | python |
You are tasked with implementing a function that extracts data from a nested object structure. The object represents a provider hierarchy in a blockchain application. Each provider has a `name` and an optional `children` array, which contains nested provider objects. Your goal is to write a function that extracts the n... | ```javascript
function extractProviderNames(provider) {
const names = [provider.name];
if (provider.children) {
provider.children.forEach(child => {
names.push(...extractProviderNames(child));
});
}
return names;
}
const providers = {
name: "EthereumProvider",
children: [
{
name: "M... | magicoder | javascript |
You are tasked with implementing a Python class method that creates a JSON Web Token (JWT) for authentication. The method should accept various parameters and generate a JWT based on the input. Your task is to complete the implementation of the `create` method in the `JWTGenerator` class.
The `create` method has the f... | ```python
import jwt
from typing import Optional, List, Text
class JWTGenerator:
@classmethod
def create(cls,
*,
type_header: Optional[Text] = None,
issuer: Optional[Text] = None,
subject: Optional[Text] = None,
audiences: Optional[List... | magicoder | python |
You are tasked with creating a Python package management system that can handle dependencies and installation of packages. Your system should be able to parse a given list of packages and their dependencies, resolve the dependencies, and generate a valid installation order for the packages.
You are given a list of pac... | ```python
def resolve_dependencies(packages):
installation_order = []
def dfs(package):
if package not in installation_order:
for dependency in packages[package]:
dfs(dependency)
installation_order.append(package)
for package in packages:
dfs(package... | magicoder | python |
You are tasked with implementing a secure version of the `app-unsecure` component in an Angular application. The `app-unsecure` component is currently vulnerable to Cross-Site Scripting (XSS) attacks due to improper handling of user input. Your goal is to modify the component to ensure that user input is properly sanit... | To secure the `app-unsecure` component and mitigate the XSS vulnerability, we can utilize Angular's built-in DomSanitizer to sanitize the user input before rendering it in the template. Here's the modified implementation of the `UnsecureComponent`:
```typescript
import { Component, SecurityContext } from '@angular/cor... | magicoder | typescript |
You are tasked with creating a Python program that simulates a file copying process. Your program should take a source file path and a destination file path as input and then create a copy of the source file at the specified destination. Additionally, the program should display the progress of the copying process by pr... | ```python
import shutil
import os
def copy_file_with_progress(source_path, destination_path):
print("Copying CSS")
try:
shutil.copyfile(source_path, destination_path)
file_size = os.path.getsize(source_path)
copied_size = 0
with open(source_path, 'rb') as src_file, open(destinat... | magicoder | python |
You are working on a natural language processing (NLP) project and need to implement a custom attention mechanism using TensorFlow. The attention mechanism is a key component in many NLP tasks, such as machine translation and text summarization. In this problem, you are tasked with implementing a specific part of the a... | ```python
import tensorflow as tf
# Given code snippet
# ...
else:
news_field_embed = tf.expand_dims(news_field_embed, 1)
news_field_embed_repeat = tf.add(
tf.zeros_like(click_field_embed), news_field_embed
)
attention_x = tf.concat(
[click_field_embed, news_field_embed_repeat], axis=1
... | magicoder | python |
You are working for a company that needs to manage its data storage on Amazon Web Services (AWS) S3. Your task is to write a Python script that interacts with the AWS S3 service to perform various operations such as uploading, downloading, and listing files. You need to implement functions for each of these operations ... | ```python
import boto3
import botocore
# AWS credentials and configuration
aws_access_key = 'YOUR_AWS_ACCESS_KEY'
aws_secret_key = 'YOUR_AWS_SECRET_KEY'
region_name = 'YOUR_AWS_REGION'
# Create an S3 client
s3 = boto3.client('s3', aws_access_key_id=aws_access_key, aws_secret_access_key=aws_secret_key, region_name=reg... | magicoder | python |
You are tasked with implementing a Python class method that decodes a binary input using the `bincode` library. The `from_binary` method should take a `PyBytes` object as input and return the decoded result as an instance of the class. However, the provided code snippet is incomplete and contains errors. Your task is t... | ```python
class YourClass:
@staticmethod
def from_binary(input: PyBytes) -> PyResult:
try:
# Complete the implementation to decode the input using the bincode library
decoded_result = bincode.deserialize(input.as_bytes())
return PyResult(decoded_result)
except... | magicoder | python |
You are tasked with creating a Python function that validates and decodes JSON Web Tokens (JWT) using the `PyJWT` library. Your function should handle different scenarios such as expired signatures and invalid tokens.
Write a function `validate_and_decode_jwt(auth_token: str) -> Union[Dict[str, Any], str]` that takes... | ```python
import jwt
from typing import Union, Dict, Any
def validate_and_decode_jwt(auth_token: str) -> Union[Dict[str, Any], str]:
try:
payload = jwt.decode(auth_token, 'key', algorithm='HS256')
return payload
except jwt.ExpiredSignatureError:
return 'Signature expired. Please log in ... | magicoder | python |
You are tasked with creating a Python function that interacts with a PostgreSQL database using SQLAlchemy. Your function should establish a connection to the database, retrieve data from a specific table, and perform some data manipulation before returning the results.
You are provided with the following code snippet ... | ```python
from sqlalchemy import create_engine, MetaData, Table
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql import select
DATABASE_URL = "postgresql://username:password@localhost/database_name"
def get_data_from_table(table_name):
engine = create_engine(DATABASE_URL)
Session = sessionmaker(bin... | magicoder | python |
You are tasked with implementing a matrix library in Rust to perform various matrix operations. The library should support operations such as matrix addition, matrix multiplication, and scalar multiplication.
Your task is to implement the `rs_matrix` module, which should contain the following functionalities:
1. Defin... | ```rust
// Example usage of the rs_matrix module
mod rs_matrix;
fn main() {
let mat1 = rs_matrix::Matrix {
rows: 2,
cols: 2,
data: vec![vec![1.0, 2.0], vec![3.0, 4.0]],
};
let mat2 = rs_matrix::Matrix {
rows: 2,
cols: 2,
data: vec![vec![5.0, 6.0], vec![7.0, ... | magicoder | rust |
You are tasked with implementing a custom feature-gating system for a software library. The library is designed to work in both standard and no-std environments, and certain features are conditionally enabled based on the presence of the "std" feature. Your task is to create a macro that conditionally enables features ... | ```rust
macro_rules! feature_gate {
(std => { $($std_code:tt)* }, no_std => { $($no_std_code:tt)* }) => {
#[cfg(feature = "std")]
{
$($std_code)*
}
#[cfg(not(feature = "std"))]
{
$($no_std_code)*
}
};
}
// Example usage
fn main() {
fea... | magicoder | rust |
You are tasked with creating a program to manage a list of tasks. Each task has a title, a description, and a status (either "pending" or "completed"). You need to implement a Task class with the following requirements:
1. The Task class should have properties for title, description, and status.
2. The status property... | ```swift
// Task class definition
class Task {
var title: String
var description: String
private var status: Status
// Status enum definition
private enum Status {
case pending
case completed
}
// Initialize Task with title, description, and initial status
init(... | magicoder | swift |
You are tasked with creating a program that can analyze a given text file and count the occurrences of each unique word. Your program should be able to handle large text files efficiently and accurately.
Your program should read in a text file and output a list of unique words along with their respective counts, sort... | ```python
import re
from collections import Counter
def count_word_occurrences(file_path):
try:
with open(file_path, 'r') as file:
text = file.read().lower() # Read the file and convert text to lowercase
words = re.findall(r'\b\w+\b', text) # Extract words ignoring punctuation
... | magicoder | python |
You are tasked with simulating a simplified secure messaging system. The system involves clients registering, exchanging encryption keys, and sending/receiving messages. Your goal is to implement a Python class that models this system and verify its functionality through unit tests.
Your task is to complete the implem... | ```python
import hashlib
class SecureMessagingSystem:
def __init__(self):
self.clients = {} # Dictionary to store client information
self.key_exchange = {} # Dictionary to store exchanged keys
self.saved_messages = {} # Dictionary to store saved messages
def register_client(self, cl... | magicoder | python |
You are tasked with automating the deployment process for a web application using a combination of build tools and containerization. Your goal is to create a script that streamlines the deployment process by executing the necessary commands in the correct sequence. The deployment process involves installing dependencie... | ```bash
#!/bin/bash
# Install project dependencies
npm install
gulp install
bower update
bower install
# Build the application using Maven
./mvnw clean package -Dmaven.test.skip=true
# Copy the built WAR file to the Docker directory
cp target/bibal-denis-0.0.1-SNAPSHOT.war src/main/docker/app.war
cd src/main/docker
... | magicoder | shell |
You are tasked with implementing a function to convert a custom location object to a Protocol Buffers Format (PBF) representation. The custom location object, `PathLocation`, contains information about a geographical point and its associated edges. The edges represent connections to other points in the geographical net... | ```cpp
#include <valhalla/midgard/pointll.h>
#include <valhalla/sif/costconstants.h>
#include <valhalla/sif/edgelabel.h>
#include <valhalla/sif/pathlocation.h>
#include <valhalla/proto/api.pb.h>
#include <valhalla/proto/directions_options.pb.h>
#include <valhalla/proto/tripdirections.pb.h>
#include <valhalla/proto/trip... | magicoder | cpp |
You are tasked with implementing a Java class that represents a room detail in a symmetrical building. The class should have the following attributes:
- `roomNumber`: an integer representing the room number
- `roomType`: a string representing the type of the room (e.g., "bedroom", "kitchen", "bathroom")
- `roomArea`: a... | ```java
public class SymRoomDetail {
private int roomNumber;
private String roomType;
private double roomArea;
public SymRoomDetail(int roomNumber, String roomType, double roomArea) {
this.roomNumber = roomNumber;
this.roomType = roomType;
this.roomArea = roomArea;
}
pu... | magicoder | java |
You are tasked with implementing a simplified version of a radio button functionality in a C++ program. The radio button should allow users to select a single option from a group of options. Your task is to create a class representing a radio button and implement the necessary methods to handle user interactions.
You ... | ```cpp
#include <iostream>
#include <vector>
class UI_Radio {
private:
bool selected_;
static std::vector<UI_Radio*> radioGroup_;
public:
UI_Radio() : selected_(false) {
radioGroup_.push_back(this);
}
~UI_Radio() = default;
void OnClickBegin(const IntVector2& position, const IntVecto... | magicoder | cpp |
You are tasked with implementing a function to find all abundant numbers within a given range. An abundant number is a positive integer for which the sum of its proper divisors (excluding itself) exceeds the number itself. For example, the proper divisors of 12 are 1, 2, 3, 4, and 6, and their sum is 16, making 12 an a... | ```rust
fn abundant_numbers(upper_limit: u32) -> Vec<u32> {
let mut abundant_nums = Vec::new();
for num in 1..=upper_limit {
if is_abundant(num) {
abundant_nums.push(num);
}
}
abundant_nums
}
fn is_abundant(num: u32) -> bool {
let mut sum = 0;
for i in 1..num {
... | magicoder | rust |
You are tasked with creating a Python function that processes job and shipment data from a database using the provided code snippet as a reference. Your function should handle the splitting of job and shipment information and then retrieve relevant data from a database using a secure connection.
Your function should t... | ```python
import pyodbc
def process_job_shipment(job_shipment, server, use_win_auth):
if "-" in job_shipment:
job, shipment = job_shipment.split("-")
else:
job, shipment = job_shipment, None
data = list()
with pyodbc.connect('DRIVER={SQL Server};SERVER=' + server + ';Trusted_Connection... | magicoder | python |
You are tasked with implementing a class for managing Bluetooth Low Energy (BLE) devices. The class should support sending raw data and handling device disconnection. Your task is to complete the implementation of the given class by adding the missing method for handling device disconnection.
You are provided with a p... | ```python
class BLEDeviceManager:
def __init__(self, ble_driver_instance):
self.ble_driver_instance = ble_driver_instance
def send_raw_data(self):
self.ble_driver_instance.sendRawData(self.__make_iBeacon_message())
def down(self):
# Implementing the method to handle device disc... | magicoder | python |
You are tasked with creating a script to automate the creation of databases in a PostgreSQL server if they do not already exist. The script should connect to the PostgreSQL server, check for the existence of specific databases, and create them if they are not found.
Write a Python script that accomplishes the followin... | ```python
import psycopg2
# PostgreSQL server connection parameters
db_params = {
'host': 'localhost',
'database': 'postgres',
'user': 'postgres',
'password': 'your_password'
}
# Databases to be checked and created if missing
databases = ['hive', 'hue', 'schema_registry']
def create_missing_databases... | magicoder | python |
You are tasked with creating a script to monitor memory usage on a Linux system and automatically clear the cache at regular intervals. The script should use a while loop to continuously monitor memory usage, clear the cache, and then wait for a specified duration before repeating the process.
Your task is to write a ... | ```bash
#!/bin/bash
# Function to display memory usage
display_memory_usage() {
free -m
}
# Continuously monitor memory usage and clear cache
while true
do
echo "Memory usage before clearing cache:"
display_memory_usage
echo "Clearing cache..."
echo 1 > /proc/sys/vm/drop_caches
echo "Memory us... | magicoder | shell |
You are tasked with implementing a caching mechanism for a repository manager in a software application. The repository manager has a method `FetchDetails` that retrieves details from a cache and updates the cache if necessary. The method takes two boolean parameters: `fromCache` indicating whether to fetch details fro... | ```swift
func FetchDetails(fromCache: Bool, updatedCache: Bool) -> String {
if fromCache {
if updatedCache {
return "Details fetched from cache, Cache updated"
} else {
return "Details fetched from cache"
}
} else {
return "Details fetched from server"
... | magicoder | swift |
You are given a code snippet that initializes an array of 2D vectors representing the positions of various elements of a spaceship. Your task is to write a function that calculates the total area of the spaceship by using the positions of its vertices. The spaceship is composed of multiple polygons, and the total area ... | ```cpp
#include <array>
#include <glm/glm.hpp>
float calculateTriangleArea(const glm::vec2& p1, const glm::vec2& p2, const glm::vec2& p3) {
return 0.5f * std::abs((p1.x * (p2.y - p3.y) + p2.x * (p3.y - p1.y) + p3.x * (p1.y - p2.y)));
}
float calculateSpaceshipArea(const std::array<glm::vec2, 24>& positions) {
... | magicoder | cpp |
You are tasked with creating a Python middleware system for a web application. Middleware is a crucial component in web frameworks, allowing for the interception of incoming requests and outgoing responses. The provided code snippet is a part of the middleware setup for the application.
Your task is to implement a Pyt... | ```python
class MiddlewareSystem:
def __init__(self):
self.middlewares = []
def register_middleware(self, middleware):
self.middlewares.append(middleware)
def process_request(self, request):
for middleware in self.middlewares:
request = middleware.process_request(reques... | magicoder | python |
You are tasked with implementing a simple photo gallery application using the RxSwift framework. The application should display a list of photos and allow the user to select and view individual photos in a detail view.
You are provided with a `PhotosViewModel` class that contains the necessary logic for fetching and m... | ```swift
import UIKit
import RxSwift
import RxCocoa
enum PhotosScene: Scene {
case photos(PhotosViewModel)
var viewController: UIViewController {
switch self {
case .photos(let viewModel):
let photosViewController = PhotosViewController(viewModel: viewModel)
re... | magicoder | swift |
You are tasked with implementing a statistics calculation function in Rust. The function `stats` takes two parameters: `vals`, a HashMap containing key-value pairs of data points, and `_opts`, a HashMap containing optional parameters for the statistics calculation. The function should calculate and return various stati... | ```rust
use std::collections::HashMap;
pub fn stats(vals: HashMap<String, String>, _opts: HashMap<String, String>) {
// Convert string values to numeric values for calculations
let numeric_vals: Vec<f64> = vals
.values()
.filter_map(|v| v.parse().ok())
.collect();
if numeric_vals.i... | magicoder | rust |
You are tasked with implementing a method for the `Sms` struct that will send a text message using the provided `Client` and message details. The `Sms` struct has several fields, including `to` (recipient phone number), `unicode` (whether the message contains unicode characters), `udh` (user data header for advanced me... | ```rust
impl Sms {
pub fn send_text_message(&self, message: &str) -> Result<(), Box<dyn Error>> {
if self.to.is_empty() {
return Err("Invalid recipient".into());
}
if message.trim().is_empty() {
return Err("Empty message".into());
}
self.client.send_m... | magicoder | rust |
You are tasked with creating a Python function that performs audio steganography, a technique of hiding secret data within an audio file. Your function should take in a cover audio file path, a stego (hidden) audio file path, and a boolean flag indicating whether to save the stego audio in the cover path. The function ... | ```python
import soundfile as sf
def embed_stego(cover_path: str, stego_path: str, inplace: bool) -> None:
# Read cover and stego audio files
cover, fs_cover = sf.read(cover_path)
stego, fs_stego = sf.read(stego_path)
# Ensure both audio files have the same sample rate
if fs_cover != fs_stego:
... | magicoder | python |
You are tasked with implementing a generic function that calculates the sum of elements in a vector of a specific type. The function should work for any type that implements the `Add` trait, allowing for flexibility in the types of elements that can be summed.
You are provided with a code snippet that imports the `Fq`... | ```rust
fn sum_elements<T: std::ops::Add<Output = T> + Default>(elements: Vec<T>) -> T {
elements.into_iter().fold(T::default(), |acc, x| acc + x)
}
```
In this solution, the `sum_elements` function takes a vector of elements of type T. It uses `into_iter()` to consume the vector and then applies `fold` to accumula... | magicoder | rust |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.