query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with creating a custom attribute class in C# to provide localizable descriptions for an enum type. The attribute should allow developers to specify localized descriptions for each enum value, making it easier to internationalize the application.
Your task is to create a custom attribute class called `Lo... | ```csharp
using System;
using System.ComponentModel;
// Custom attribute class for localizable enum
[AttributeUsage(AttributeTargets.Enum)]
public class LocalisableEnumAttribute : Attribute
{
public Type MapperType { get; }
public LocalisableEnumAttribute(Type mapperType)
{
MapperType = mapperType... | magicoder | csharp |
You are tasked with implementing a data calibration algorithm for a 3D color space. The provided code snippet includes a class `Grads` and a class `polyCalibration`, which are used to store and calibrate polynomial tables from a data pack. Your task is to create a function that takes the data pack file path as input, c... | ```python
import numpy as np
from typing import Tuple
class Grads:
"""each grad contains the N*N*params table for one (normal_mag, normal_dir) pair"""
grad_r = None
grad_g = None
grad_b = None
countmap = None
class polyCalibration:
"""
Calibrate the polynomial table from the data pack
... | magicoder | python |
You are tasked with implementing a function to smooth the coordinates of the vertices of a polygon using a moving average algorithm. The function takes as input an instance of `shapely.geometry.Polygon`, the number of vertices in the smoothing half-window, the number of iterations, and a boolean flag for input argument... | ```python
import numpy as np
from shapely.geometry import Polygon
def smooth_polygon_vertices(polygon_object, num_vertices_in_half_window, num_iterations, check_input_args):
if check_input_args:
if not isinstance(polygon_object, Polygon):
raise ValueError("Input polygon_object must be an instan... | magicoder | python |
You are given an array of integers `a`. Your task is to implement a function that converts the given array into a min-heap and returns the resulting min-heap array.
A min-heap is a complete binary tree where the value of each node is less than or equal to the values of its children. The root is the minimum element in ... | ```python
def build_min_heap(a):
def heapify(arr, n, i):
smallest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[i] > arr[left]:
smallest = left
if right < n and arr[smallest] > arr[right]:
smallest = right
if smallest != i:
... | magicoder | python |
You are tasked with creating a Python program that utilizes the `System.Management` and `System.Management.Instrumentation` namespaces to retrieve system information and perform management tasks. Your program should be able to retrieve the CPU usage, total physical memory, and list all running processes on a Windows sy... | ```python
import psutil
def get_cpu_usage():
return psutil.cpu_percent(interval=1)
def get_total_physical_memory():
return psutil.virtual_memory().total
def list_running_processes():
processes = []
for proc in psutil.process_iter(['pid', 'name']):
processes.append((proc.info['pid'], proc.info... | magicoder | python |
You are tasked with creating a Java program that interacts with a database to retrieve and display a list of items. The program uses MyBatis, a persistence framework that maps Java methods to SQL statements. Your goal is to implement a method that retrieves a list of items from the database and returns it as a JSON res... | ```java
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import java.util.List;
public class ItemService {
private SqlSessionFactory factory;
// Constructor to initialize the SqlSessionFactory
public ItemService(SqlSessionFactory factory) {
this.fact... | magicoder | java |
You are tasked with creating a program to perform bi-gram analysis on a given input phrase. A bi-gram is a pair of consecutive words within a string of text. Your program should take a phrase as input and output the frequency of each unique bi-gram in the phrase.
For example, given the input phrase "the quick brown fo... | ```csharp
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
string phrase = "the quick brown fox jumps over the lazy dog";
Dictionary<string, int> biGramFrequency = GetBiGramFrequency(phrase);
PrintBiGramFrequency(biGramFrequency);
... | magicoder | csharp |
You are tasked with implementing a custom macro in Rust that emulates the behavior of a `select` statement in Go. The `select` statement in Go allows for concurrent communication among goroutines, enabling them to wait on multiple communication operations. Your task is to create a Rust macro, `loop_select!`, that mimic... | ```rust
#[macro_export]
macro_rules! loop_select {
($($expr:expr),*) => {{
loop {
$(
if let Some(val) = $expr {
break Some(val);
}
)*
}
}};
}
fn main() {
let result = loop_select! {
Some(5),
None,
... | magicoder | rust |
You are tasked with implementing a Python class for managing runs of a scientific experiment. The class, named `ExperimentManager`, should have the following functionalities:
1. `is_finished()`: A method that returns `True` if all runs are finished, and `False` otherwise.
2. `create_runs_upto(n)`: A method that create... | ```python
class Run:
def __init__(self):
self.results = []
self.start_time = 0
self.end_time = 0
self.start_temp = 0
self.end_temp = 0
self.finished = False
def store_result(self, results, start_time, end_time, start_temp, end_temp):
self.results = result... | magicoder | python |
You are given a set of instructions represented as a list of strings. Each instruction can be one of the following:
1. "acc x": Increase the global variable `acc` by the value of `x`.
2. "jmp x": Jump to a new instruction relative to the current one. The value of `x` can be positive or negative, indicating the number ... | ```python
from typing import List
def find_accumulator_value(instructions: List[str]) -> int:
acc = 0
done = [False] * len(instructions)
i = 0
while i < len(instructions):
if done[i]:
break # Terminate if the instruction is about to be executed a second time
done[i] = True... | magicoder | python |
You are tasked with implementing a version bumping function in a shell script. The function should take two arguments: the bump type and the current version. The bump type can be one of the following: 0 (for no change), 1 (for a patch update), 2 (for a minor update), or 3 (for a major update). The current version is a ... | ```bash
bump() {
bump_type=$1
current_version=$2
IFS='.' read -r -a version_parts <<< "$current_version"
major=${version_parts[0]}
minor=${version_parts[1]}
patch=${version_parts[2]}
if [ "$bump_type" == "3" ]; then
major=$((major + 1))
minor=0
patch=0
elif [ "... | magicoder | shell |
You are tasked with creating a versioning system for a software project. The versioning system should automatically generate a new version number based on the current date and the number of revisions made on that date. The version number should follow the format `YYYY.R.D.R`, where:
- `YYYY` represents the current year... | ```python
import datetime
def generateVersionNumber():
today = datetime.date.today()
year = today.year
day_of_year = today.timetuple().tm_yday
revision_number = getRevisionNumber(today)
return f"{year}.{revision_number}.{day_of_year}.{revision_number}"
def getRevisionNumber(date):
# Logic to r... | magicoder | python |
You are tasked with implementing a notification system for a blogging platform. The platform uses Django, and the code snippet provided is a part of the URL configuration for the notifications feature. When a user visits the URL `/remainder/`, the `notification` view function in the `views` module is called to handle t... | ```python
# views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from .models import Notification
@login_required
def notification(request):
user = request.user
notifications = Notification.objects.filter(user=user)
context = {
'user': user,
... | magicoder | python |
You are working on a Laravel application that involves seeding a database with sample data. The code snippet provided is from a Laravel migration file that seeds the database using the `call` method to execute various seeder classes. Each seeder class populates a specific table in the database with sample data. Your ta... | ```python
from collections import defaultdict
class SeederGraph:
def __init__(self):
self.graph = defaultdict(list)
def add_dependency(self, seeder, dependency):
self.graph[seeder].append(dependency)
def topological_sort_util(self, seeder, visited, stack):
visited[seeder] = True
... | magicoder | python |
You are tasked with implementing a function that processes an array of vouchers and returns a new array containing only the unique vouchers. A voucher is represented as a string and is considered unique if it does not appear more than once in the input array. You need to write a function `getUniqueVouchers` that takes ... | ```python
from typing import List
def getUniqueVouchers(vouchers: List[str]) -> List[str]:
unique_vouchers = []
seen_vouchers = set()
for voucher in vouchers:
if voucher not in seen_vouchers:
unique_vouchers.append(voucher)
seen_vouchers.add(voucher)
return uni... | magicoder | python |
You are working on a project that involves interfacing with a shared library written in C using Python's ctypes module. The shared library, named librmath, contains functions for mathematical operations and manipulation of geometric points. You need to create a Python wrapper for the library to perform certain operatio... | ```python
import ctypes
class Point(ctypes.Structure):
_fields_ = [('x', ctypes.c_double), ('y', ctypes.c_double)]
def __str__(self):
return 'Point(%f,%f)' % (self.x, self.y)
class MathOperations:
def __init__(self, lib_path: str):
self.librmath = ctypes.CDLL(lib_path)
self.librma... | magicoder | python |
You are tasked with creating a build automation tool that can execute a series of commands based on a given configuration file. The configuration file will contain a list of commands to be executed in sequential order. Each command may have dependencies on other commands, and the tool should ensure that these dependenc... | ```python
from typing import List, Tuple
from collections import defaultdict
def executeCommands(commands: List[str], dependencies: List[Tuple[str, List[str]]]) -> List[str]:
graph = defaultdict(list)
indegree = defaultdict(int)
order = []
for command in commands:
indegree[command] = 0
fo... | magicoder | python |
You are tasked with creating a Rust module that handles parsing and processing intermediate representation (IR) code for a compiler. The provided code snippet includes the declaration of two modules: `ir` and `parser`. Your task is to implement the functionality for these modules to handle the parsing and processing of... | ```rust
// parser.rs
pub mod parser {
pub struct IRParser;
impl IRParser {
pub fn parse_ir_code(code: &str) -> Result<IRStructure, ParseError> {
// Implement code parsing logic here
// Return structured representation or error
}
}
}
// ir.rs
pub mod ir {
pub str... | magicoder | rust |
You are given a Java method that is intended to check whether a given string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). However, the given method contains some errors and is incompl... | ```java
public class PalindromeChecker {
public static boolean isPalindrome(String str) {
str = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase(); // Remove non-alphanumeric characters and convert to lowercase
int left = 0;
int right = str.length() - 1;
while (left < right) {
... | magicoder | java |
You are tasked with creating a program to manage and execute various command codes in a Trusted Platform Module (TPM) system. The command codes are represented as constants of the `CommandCodeStructure` type. Your goal is to implement a function that takes a list of command codes and executes them in a specific order. ... | ```rust
fn execute_command_codes(command_codes: Vec<CommandCodeStructure>) -> Vec<CommandCodeStructure> {
let mut priority_map: HashMap<CommandCodeStructure, usize> = HashMap::new();
priority_map.insert(POLICY_OR, 1);
priority_map.insert(POLICY_TICKET, 2);
priority_map.insert(READ_PUBLIC, 3);
priori... | magicoder | rust |
You are tasked with creating a function that generates CSS styles based on a given theme object. The theme object contains key-value pairs where the keys represent the CSS property names and the values represent the corresponding property values. Your task is to implement the `generate_style` function that takes the th... | ```javascript
const generate_style = (theme) => {
const sortedProperties = Object.keys(theme).sort();
let styleString = '';
for (const property of sortedProperties) {
styleString += `${property}: ${theme[property]};\n`;
}
return styleString;
};
// Test the function
const theme = {
color: 'red',
fontS... | magicoder | javascript |
You are given a Python function `sum_list_1` that takes a list of integers `dataset` as input. The function is intended to calculate the sum of numbers in the list `dataset` where the sum of their digits is divisible by 7. However, the given code snippet is incomplete and contains errors. Your task is to complete the f... | ```python
def sum_list_1(dataset: list) -> int:
"""Calculates the sum of numbers in the list dataset, where the sum of their digits is divisible by 7"""
total_sum = 0
for num in dataset:
digit_sum = 0
temp_num = abs(num) # Handle negative numbers
while temp_num > 0:
digi... | magicoder | python |
You are given a Python function `src_number` that takes in a list of integers as input. The function is intended to return the source number, which is defined as the number that appears only once in the input list, while all other numbers appear exactly twice. If the input list does not contain a source number, the fun... | ```python
from typing import List
def src_number(nums: List[int]) -> int:
num_count = {}
# Count the occurrences of each number in the input list
for num in nums:
if num in num_count:
num_count[num] += 1
else:
num_count[num] = 1
# Find the source number... | magicoder | python |
You are tasked with creating a Python script to automate the selection of test scripts based on certain conditions. The script should determine the appropriate test script to call based on the given arguments and configuration.
The script should take into account the following conditions:
1. If the command-line argume... | ```python
import sys
def select_test_script(sys_argv, config):
tocall = ""
if "msvc" in sys_argv[1]:
tocall = "alltests_msvc.bat"
else:
tocall = "alltests_gcc.bat"
if config[0] == "standalone_singleabi":
tocall = "standalone_" + tocall
else:
tocall = "test_all"
... | magicoder | python |
You are tasked with implementing a Python function to convert a given transfer function to a linear phase. The transfer function is represented as a NumPy array, and the conversion involves performing a Fourier transform on the transfer function.
Write a function `tf2linphase(h, normalize=True)` that takes in the orig... | ```python
import numpy as np
def tf2linphase(h, normalize=True):
"""Converts a transfer function to linear phase
Parameters
----------
h : ndarray
Numpy array containing the original transfer function
normalize : bool, optional
Flag to indicate whether to normalize the linear phase... | magicoder | python |
You are tasked with implementing a Python class to store and manipulate information about blockchain blocks. The class, `BlockInfo`, should have the following attributes:
- `block_hash`: A string representing the hash of the block.
- `short_ids`: A list of integers representing short IDs associated with the block.
- `d... | ```python
from datetime import datetime
class BlockInfo:
def __init__(self, block_hash, short_ids, decompress_start_datetime, decompress_end_datetime):
self.block_hash = block_hash
self.short_ids = short_ids
self.decompress_start_datetime = decompress_start_datetime
self.decompress_... | magicoder | python |
You are tasked with implementing a module dependency resolution system for a software project. The system should allow different scheduling strategies for handling module dependencies. The provided code snippet is a part of a Rust project and shows the module structure and the public re-exports of different scheduling ... | ```rust
// Define a module struct to represent a module and its dependencies
struct Module {
name: String,
dependencies: Vec<String>,
}
// Define the trait for a scheduler
trait Scheduler {
fn schedule(&self, modules: &[Module]) -> Vec<String>;
}
// Implement the AdaptiveScheduler
mod adaptive {
use s... | magicoder | rust |
You are given a Python class `Count` with the following attributes and method:
```python
@attr.s
class Count(object):
"""Count class with monochromatic and bichromatic counts"""
n = attr.ib()
monochromatic = attr.ib(default=0)
bichromatic = attr.ib(default=0)
def count_edge(self, u, v):
pa... | ```python
from typing import List, Tuple
@attr.s
class Count(object):
"""Count class with monochromatic and bichromatic counts"""
n = attr.ib()
monochromatic = attr.ib(default=0)
bichromatic = attr.ib(default=0)
def count_edge(self, u, v):
if colors[u-1] == colors[v-1]:
self.mo... | magicoder | python |
You are working on a robotics project and need to implement a configuration manager for a robotic arm. The configuration manager is responsible for storing and managing different joint configurations for the robotic arm. Each joint configuration is represented as a 6-dimensional array of joint angles.
Your task is to ... | ```python
import numpy as np
class RobotConfigurationManager:
def __init__(self):
self.configurations = {
"qs": np.array([0, 0, -np.pi / 2, 0, 0, 0]),
"qn": np.array([0, np.pi / 4, np.pi, 0, np.pi / 4, 0])
}
def add_configuration(self, config_name, joint_angles):
... | magicoder | python |
You are tasked with creating a script to automate the cleanup of a specific file in a given directory. The script should remove a file named `server.pid` located in the `/myapp/tmp/pids/` directory. Additionally, the script should handle the case where the file does not exist and should not raise an error in that scena... | ```bash
#!/bin/bash
set -e
pid_file="/myapp/tmp/pids/server.pid"
if [ -f "$pid_file" ]; then
rm -f "$pid_file"
echo "File $pid_file removed successfully"
else
echo "File $pid_file does not exist"
fi
```
The provided shell script begins by setting the `-e` option to ensure that the script exits immediately if ... | magicoder | shell |
You are tasked with implementing a Python class that manages a dictionary with additional functionality for publishing and retrieving values. The class, named `PublisherDict`, has the following methods:
1. `__getitem__(self, key)`: This method should return the value associated with the given key. If the key is associ... | ```python
class PublisherDict(dict):
def __init__(self):
self._proxies = {}
self._publishers = {}
def __getitem__(self, key):
if self._proxies.get(key) is not None:
(p, newkey) = self._proxies[key]
return p[newkey]
elif self._publishers.get(key) is not No... | magicoder | python |
You are tasked with implementing a validation system for a web application that allows users to create posts. The system should check if the user is a bot before allowing the post creation. You are given a code snippet from the backend controller that handles the post creation process. The snippet includes a check for ... | ```php
// BotDetectionMiddleware.php
namespace App\Http\Middleware;
use Closure;
class BotDetectionMiddleware
{
public function handle($request, Closure $next)
{
// Perform bot detection logic here
$isBot = $this->detectBot($request);
if ($isBot) {
return redirect()->back... | magicoder | php |
You are tasked with simulating the energy production and storage of a power plant based on the given generation mapping and raw data. The raw data contains the energy values produced by different sources, and the generation mapping specifies how these values should be aggregated into the production data. Your task is t... | ```python
def update_production_data(raw_data, GENERATION_MAPPING, initial_production):
production_data = initial_production.copy()
for from_key, to_key in GENERATION_MAPPING.items():
production_data[to_key] += max(0, raw_data.get(from_key, {"value": 0})["value"])
return production_data
```
The `up... | magicoder | python |
You are tasked with creating a Python script that processes a long description of a software package and extracts specific information from it. The long description is stored in a file and is formatted in Markdown. The script should extract the name, version, description, and URL of the software package and print them ... | ```python
import re
# Read the long description from the file
with open("long_description.md", "r") as file:
long_description = file.read()
# Extract name, version, description, and URL using regular expressions
name_match = re.search(r'# (.+)', long_description)
version_match = re.search(r'version="(.+)"', long_... | magicoder | python |
You are tasked with implementing a Python class to manage and analyze time-series data. The class, named `Data`, should have a method `add_data` to add new data points to the time-series dataset. Each data point consists of a timestamp and multiple numerical values. The `add_data` method should take a timestamp and a v... | ```python
from datetime import datetime
class Data:
dataset = []
@classmethod
def add_data(cls, timestamp, *values):
if not isinstance(timestamp, datetime):
raise ValueError("Not datetime object")
expected_num_values = 6 # Assuming each data point has 6 numerical values
... | magicoder | python |
You are tasked with creating a gRPC web service for a merchant client application. The application needs to support invoice functionality, and you are required to define the protocol buffer message types and gRPC service methods for handling invoices.
You have been provided with a code snippet that includes a command ... | ```protobuf
// invoice.proto
syntax = "proto3";
package merchantclient;
message Invoice {
string id = 1;
string customer_id = 2;
repeated Item items = 3;
float total_amount = 4;
string status = 5;
// Add any other required fields for the invoice
}
message Item {
string name = 1;
float price = 2;
i... | magicoder | protobuf |
You are given a Rust code snippet that implements a graph data structure using depth-first search (DFS) to compute the depth of nodes and their adjacent nodes. Your task is to implement a function that finds the maximum depth of the graph and returns the node with that depth.
You need to implement a function `max_dept... | ```rust
impl Graph {
// Other existing functions are omitted for brevity
pub fn max_depth_node(&self) -> usize {
let mut max_depth = 0;
let mut max_depth_node = 0;
for (index, node) in self.nodes.iter().enumerate() {
if node.depth > max_depth {
max_depth = n... | magicoder | rust |
You are tasked with implementing a function that parses a given `slugReference` string and extracts the relevant information based on the provided conditions. The `slugReference` string contains a conditional statement that selects a specific slug based on the type of content and the language. Your task is to write a f... | ```javascript
function parseSlugReference(slugReference, lang, type) {
const conditionRegex = /_type == '(.+?)'/;
const slugRegex = /slug\[(.+?)\]\.current/;
const matchCondition = slugReference.match(conditionRegex);
const matchSlug = slugReference.match(slugRegex);
if (matchCondition && matchSlug) {
c... | magicoder | javascript |
You are tasked with implementing a password validation function for a user registration system. The function should validate the password based on a set of rules and return a boolean value indicating whether the password meets the criteria.
You are given a code snippet representing the rules for password validation:
... | ```php
function validatePassword($password, $rules) {
$minLength = 8;
$uppercaseRegex = '/[A-Z]/';
$lowercaseRegex = '/[a-z]/';
$digitRegex = '/\d/';
$specialCharRegex = '/[!@#$%^&*()-_+=]/';
if (strlen($password) < $minLength) {
return false;
}
if (!preg_match($uppercaseRegex,... | magicoder | php |
You are tasked with creating a web application that utilizes the EligereVS library to manage and display voting data. The EligereVS library provides functionality for handling voting processes and displaying voting results. Your task is to implement a feature that allows users to view and interact with voting data usin... | To solve this problem, you would need to create an ASP.NET Core web application and integrate the EligereVS library to manage and display the voting data. Here's a high-level overview of the steps involved in the solution:
1. Set up an ASP.NET Core web application project.
2. Install the EligereVS library as a depende... | magicoder | csharp |
You are tasked with implementing a material mapping system for a 3D model loading library. The code snippet provided is a part of the material mapping process. The `MaterialMapper` class is responsible for mapping materials from various sources to a unified format. The `RegisteredMappers` property contains the names of... | ```csharp
// MaterialMapper class for mapping materials
public abstract class MaterialMapper : ScriptableObject
{
public static List<string> RegisteredMappers { get; } = new List<string>();
public abstract void MapMaterial(); // Method for mapping materials
// Method for registering material mappers
p... | magicoder | csharp |
You are tasked with implementing a simplified version of the `transform_reduce` function, which applies a transformation and reduction operation to two arrays of the same size. The transformation and reduction operations are provided as function objects. The goal is to calculate the result of applying the transformatio... | ```cpp
#include <array>
namespace intern {
template <class T, size_t size, size_t index>
struct TransformReduce_ {
static constexpr auto call(const std::array<T, size> &lhs,
const std::array<T, size> &rhs,
const Transformer &transforme... | magicoder | cpp |
You are tasked with implementing a mnemonic seed generator for different types of wallets. Mnemonic seeds are used to generate deterministic wallets, allowing users to easily back up and restore their wallets using a series of words. Each type of wallet has a specific prefix that must be included in the hash of the mne... | ```python
import hashlib
from bip_utils import Mnemonic
def generate_random_mnemonic_seed() -> str:
# Function to generate a random BIP39-compliant mnemonic seed
# Implementation not provided for brevity
pass
def generate_mnemonic_seed(wallet_type: str) -> str:
prefixes = {
'standard': '01',
... | magicoder | python |
You are tasked with implementing a data structure to efficiently store and retrieve snapshot values. The data structure should support the following operations:
1. `take_snapshot()`: Take a snapshot of the current state of the data structure and return a unique snapshot index.
2. `get_value(snapshot_index, value_node)... | ```python
class SnapshotDataStructure:
def __init__(self):
self.snapshots = {}
self.current_snapshot_index = 0
def take_snapshot(self, snapshot_values):
snapshot_index = self.current_snapshot_index
snapshot = dict(self.snapshots[snapshot_index - 1]) if snapshot_index > 0 else {}... | magicoder | python |
You are tasked with implementing a thread-safe scheduler class in C++ that manages a schedule of tasks. The class should provide methods to set and clear tasks at specific indices in the schedule, as well as a method to check if all tasks are completed.
You are given a code snippet that includes a `std::mutex` and a `... | ```cpp
#include <mutex>
#include <vector>
class Scheduler {
private:
std::mutex scheduleMutex;
std::vector<bool> schedule;
public:
Scheduler(uint32_t size, bool initializer = true) : schedule(size, initializer) {}
~Scheduler() {}
void setTask(uint32_t index) {
std::lock_guard<std::mutex>... | magicoder | cpp |
You are given a Python function that takes a list of integers as input and is intended to return a new list containing only the unique elements from the input list, preserving their original order. However, the given code snippet is incomplete and contains a logical error. Your task is to identify the error in the code... | The logical error in the given code snippet is that the condition `if i not in ans` is not sufficient to identify unique elements when the input list contains mutable objects like lists or dictionaries. To fix this, we need to use a different approach to check for uniqueness.
Here's the corrected code for the `unique_... | magicoder | python |
You are tasked with creating a TypeScript interface for managing effects in a functional programming environment. The interface, `Effect<R, E, A>`, is defined with a method `runMain` that is annotated with a rewrite method directive. Your goal is to implement the `runMain` method in a way that adheres to the provided a... | ```typescript
// Define the Effect interface
export interface Effect<R, E, A> {
/**
* @ets_rewrite_method runMain from "@effect-ts/node/Runtime"
*/
runMain<EX, AX>(this: T.Effect<T.DefaultEnv, EX, AX>): void {
// Implement the runMain method according to the rewrite method directive
// The implementat... | magicoder | typescript |
You are tasked with implementing a Serial Number Diagnostic system for a manufacturing company. The system should be able to validate the serial numbers of the products being produced. The serial numbers are expected to follow a specific format and should be checked for validity based on certain criteria.
The format o... | ```python
class SerialNumberDiagnostic:
def validate_serial_number(self, serial_number: str) -> bool:
if len(serial_number) != 10:
return False
product_code = serial_number[:3]
production_date = serial_number[3:7]
batch_number = serial_number[7:]
if not (product_c... | magicoder | python |
You are given a Python function `d` that takes eight arguments representing the coordinates of four points in a 2D plane. The function is intended to calculate the perimeter of the quadrilateral formed by these points. However, the function has some issues that need to be fixed.
The function `d` has the following sign... | ```python
from math import sqrt
def d(p1x, p1y, p2x, p2y, p3x, p3y, p4x, p4y):
if len(set([(p1x, p1y), (p2x, p2y), (p3x, p3y), (p4x, p4y)]) != 4:
return (0, 0) # Return (0, 0) if at least two points are the same
side1 = sqrt((p2x - p1x) ** 2 + (p2y - p1y) ** 2)
side2 = sqrt((p3x - p2x) ** 2 + (p3y... | magicoder | python |
You are tasked with implementing a Python function that takes a list of integers as input and returns the frequency of each unique integer in the list as a dictionary. You are also required to handle the scenario where the input list is empty. The frequency of each integer should be calculated using the Counter class f... | ```python
from typing import List, Dict
from collections import Counter
def calculate_frequency(input_list: List[int]) -> Dict[int, int]:
# If the input list is empty, return an empty dictionary
if not input_list:
return {}
# Use Counter to calculate the frequency of each unique integer
freque... | magicoder | python |
You are tasked with creating a TypeScript function that generates CSS styles for responsive border radii in a web application. The function should take in an object of properties and return an array of CSS objects representing the responsive border radius styles.
The function signature is as follows:
```typescript
exp... | ```typescript
export function responsiveRadiusStyle(props: ResponsiveRadiusStyleProps & ThemeProps): import("styled-components").CSSObject[] {
const { borderRadius, theme: { breakpoints } } = props;
const responsiveStyles: import("styled-components").CSSObject[] = [];
for (let i = 0; i < breakpoints.length; i++)... | magicoder | typescript |
You are tasked with creating a Python script to automate the migration of collections from a MongoDB database to a PostgreSQL database. The script should utilize the `mongo_to_sql` library, which provides functionality for interacting with both MongoDB and PostgreSQL databases. The script should be able to handle the m... | ```python
import os
from mongo_to_sql.databases import mongo, postgres
from environ import Env, Path
directory = '/Users/wgarlock/Documents/all_collections'
root = Path(__file__) - 4
BASE_DIR = root()
env = Env(DEBUG=(bool, False))
env.read_env(os.path.join(BASE_DIR, '.migrate_config'))
mongo_database = mongo.MongoDa... | magicoder | python |
You are tasked with creating a Python function that simulates a rocket takeoff sequence. The function should handle potential errors that may occur during the takeoff process.
Your task is to implement the `rocket_takeoff` function, which takes two parameters:
1. `countdown` (integer): The countdown value in seconds ... | ```python
import time
def rocket_takeoff(countdown, error_occurred):
try:
for i in range(countdown, 0, -1):
print(i)
if error_occurred and i == 3:
raise TimeoutError("Simulated timeout error")
time.sleep(1)
print("Rocket has taken off successfully... | magicoder | python |
You are tasked with creating a Python class that represents a task in a to-do list application. The task should have a title, a description, a due date, and a priority level. Additionally, you need to implement a method that allows for the comparison of two tasks based on their priority levels.
Create a Python class `... | ```python
from __future__ import annotations
from typing import TypedDict
class DueDate(TypedDict):
"""Dict representing a due date in a todoist api response."""
date: str
is_recurring: bool
lang: str
string: str
timezone: str | None
class Task:
def __init__(self, title: str, description: ... | magicoder | python |
You are tasked with implementing a Swift class for managing cryptocurrency data. The class should have properties for storing various attributes of a cryptocurrency, and a designated initializer to populate these properties from a given database row.
Your task is to complete the implementation of the `CryptoCurrency` ... | ```swift
// Define the CryptoCurrency class
class CryptoCurrency {
var uid: String
var name: String
var code: String
var marketCapRank: String
var coinGeckoId: String
// Designated initializer to populate the properties from the given row
required init(row: Row) {
uid = row[Columns.... | magicoder | swift |
You are tasked with implementing a simple blockchain system using Python. A blockchain is a distributed ledger that records transactions across multiple computers in a secure and tamper-proof manner. The provided code snippet is a function to initialize the blockchain by setting up the necessary database table and ensu... | ```python
def initBlockchain(mydb):
print("Initializing Blockchain...")
if existsAudittrailsTable(mydb):
print("Resetting existing Table...")
try:
mydb.cursor().execute("TRUNCATE TABLE `audittrails`")
mydb.commit()
print("Done!")
except Exception as e:... | magicoder | python |
You are given a 2D grid representing a map with cells containing either 0 or 9. The map is represented as a list of lists, where each inner list represents a row of the map. The value 0 represents an empty cell, and 9 represents an obstacle. You need to find the largest product of the sizes of three connected regions o... | ```python
def largest_product_of_three_regions(grid):
rlen, clen = len(grid), len(grid[0])
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
checked = set()
ans = []
def dfs(r, c):
size = 0
s = [(r, c)]
while s:
nr, nc = s.pop()
size += 1
fo... | magicoder | python |
You are tasked with implementing a Queue data structure using a linked list. The Queue class has a destructor and a method to make the queue empty. The linked list is implemented using a separate List class, which has a method to make the list empty. Your task is to complete the implementation of the Queue class by pro... | ```cpp
//Destructor
Queue::~Queue()
{
delete this->list;
this->list = nullptr;
}
//Makes an empty Queue
void Queue::MakeEmpty()
{
this->list->makeEmpty();
}
// Other methods to be implemented
```
In the solution, the destructor of the Queue class is implemented to delete the linked list and set the point... | magicoder | cpp |
You are working on a project that involves image processing and machine learning. Your task is to create a program that uses the K-Nearest Neighbors (KNN) algorithm to classify colors in images based on their HSV (Hue, Saturation, Value) values. You will need to load a pre-trained KNN model, process an input image, and... | ```python
# Import necessary libraries
import cv2
from joblib import load
from flask import Flask, request
import numpy as np
# Load the pre-trained KNN model for color classification
hsv_knn = load('static/ds_h_knn_3.joblib')
# Function to process an input image and classify colors using the KNN model
def classify_c... | magicoder | python |
You are tasked with creating a Python function that simulates a database management system's command execution. The function should take in a database name, port number, and a SQL command as input, and then construct and log the corresponding command to be executed. The SQL command should include dropping existing tabl... | ```python
import logging
def execute_database_command(db_name, db_port, sql_cmd):
logger = logging.getLogger(__name__)
logger.info('----------------------------Creating a MySQL-compatible database. Expectation: Successful creation-----------------------------')
excute_cmd = f'source $DB_ENV_PATH ; gsq... | magicoder | python |
You are tasked with implementing a function that calculates the total number of unique paths from the top-left corner to the bottom-right corner of a grid. You can only move either down or to the right at any point in time. The grid is represented as a 2D array of integers, where each element represents the cost of mov... | ```swift
func minMaxPathSum(grid: [[Int]]) -> Int {
let m = grid.count
let n = grid[0].count
var dpMin = Array(repeating: Array(repeating: 0, count: n), count: m)
var dpMax = Array(repeating: Array(repeating: 0, count: n), count: m)
dpMin[0][0] = grid[0][0]
dpMax[0][0] = grid[0][0]
... | magicoder | swift |
You are tasked with implementing a simplified version of a command-line interface (CLI) navigation system. The CLI supports two commands: "cd" to change the current directory and "exit" to terminate the program. The "cd" command takes a single argument representing the directory to change to. Directories are represente... | ```python
from typing import List
def final_directory(commands: List[str]) -> str:
current_directory = "/"
for command in commands:
if command == "exit":
return current_directory
elif command == "cd" and commands.index(command) + 1 < len(commands):
next_directory = comma... | magicoder | python |
You are tasked with implementing a caching system using Python. The provided code snippet imports a module named `caches`, which contains various caching implementations. Your goal is to create a new caching class that utilizes a specific caching strategy and implements the necessary methods to interact with the cache.... | ```python
from .caches import Cache
class LRUCache(Cache):
def __init__(self, capacity):
super().__init__(capacity)
self.cache = {}
self.order = []
def get(self, key):
if key in self.cache:
self.order.remove(key)
self.order.append(key)
return... | magicoder | python |
You are tasked with implementing a particle simulation system that includes the behavior of particles interacting with boundaries. The system should support both rectangular and circular boundaries, with specific interactions defined for each type of boundary.
For rectangular boundaries, newly generated particles are ... | To address the issue with the rectangular boundary collision causing particles to explode, the problem likely lies in the calculation of the boundary weight or the handling of particle collisions. By reviewing the collision detection and handling code, and potentially adjusting the boundary weight calculation, the issu... | magicoder | python |
You are tasked with implementing a bytecode emitter for a custom programming language. The emitter takes floating-point numbers and converts them into a series of opcodes to be executed by a virtual machine. Your task is to complete the implementation of the `emit_value` method, which takes a `value` of type `f64` and ... | ```rust
impl BytecodeEmitter {
// ... other methods ...
fn emit_value(&mut self, value: f64) {
// Check if the value is negative infinity and emit PushNegativeInfinity if true
if value.is_infinite() && value.is_sign_negative() {
self.emit_opcode(Opcode::PushNegativeInfinity);
... | magicoder | rust |
You are tasked with creating a script to automate the setup of a Venafi-PKI backend in HashiCorp Vault. The script should include the necessary environment variable configurations and Vault commands to enable the secrets engine, create a PKI role, and configure specific settings for the Venafi-PKI backend.
Given the c... | ```bash
#!/bin/bash
# Set environment variables
export TPP_PASS=<PASSWORD>
export TPP_ZONE="Certificates\\\\HashiCorp Vault\\\\Internal PKI"
export VAULT_ADDR=http://127.0.0.1:8200
# Enable the secrets engine for the venafi-pki-backend plugin
vault secrets enable -path=venafi-pki -plugin-name=venafi-pki-backend plugi... | magicoder | shell |
You are tasked with implementing a class that manages the rendering of shadow maps in a 3D graphics application. The class contains a method `onReceiveShadowMap` that is called after activating a shader and before validation. The method takes three parameters: an OpenGL interface `g`, a texture unit context `tc`, and a... | ```java
public class ShadowMapRenderer {
// Other class members and methods
/**
* This method will be called after a call to {@link
* com.io7m.r2.shaders.api.R2ShaderUsableType#onActivate(JCGLInterfaceGL33Type)}
* and before a call to {@link #onValidate()}.
*
* @param g An OpenGL int... | magicoder | java |
You are tasked with creating a script to automate the generation of PDF files from LaTeX (.tex) documents. Your script should handle the compilation of the LaTeX document using pdflatex and optionally display the resulting PDF file using the evince viewer. Additionally, the script should reset a configuration using the... | ```bash
#!/bin/bash
# Compile the LaTeX document using pdflatex
echo "Generating PDF from .tex"
pdflatex example.tex
# Check if "--no_plots" argument is provided
if [[ ! $* == *--no_plots* ]]; then
# Display the resulting PDF file using the evince viewer
evince example.pdf
fi
# Reset the configuration using ... | magicoder | shell |
You are tasked with implementing a data serialization and deserialization process for a messaging system. The provided code snippet is a part of the serialization process, using a binary writer (`bw`) to write specific data types to a stream. Your task is to complete the serialization process and then implement the cor... | ```csharp
using System;
using System.IO;
public class Message
{
public int m_activateEventId;
public uint m_attachmentLength;
public string m_attachment;
public void Serialize(BinaryWriter bw)
{
bw.Write(m_activateEventId);
bw.Write(m_attachmentLength);
bw.Write(Encoding.UT... | magicoder | csharp |
You are tasked with creating a Python function that interacts with a network management system to retrieve information about networks to be added. The network management system is accessed through an API, and the function needs to make a request to the system to fetch the required data.
You are provided with a code sn... | ```python
import requests
mri_url = "http://192.168.0.201" # Assuming the URL should include the protocol
mri_user = "admin"
mri_pwd = "<PASSWORD>"
def get_networks_to_add():
querystring = {"_return_fields+": "extattrs", "*NetMRI:": "Add"}
headers = {
'Content-Type': "application/json",
'Acce... | magicoder | python |
You are given a dataset containing information about passengers on the Titanic. The dataset includes a column "Name" which contains the names of the passengers. You are required to write a Python function that assigns a numerical "Title" to each passenger based on their name. The titles are assigned according to the fo... | ```python
import pandas as pd
def assign_titles(data):
data["Title"] = None # Create a new column "Title" and initialize with None
data.loc[data["Name"].str.contains("Mrs"), "Title"] = 1.0
data.loc[data["Name"].str.contains("Miss"), "Title"] = 2.0
data.loc[data["Name"].str.contains("Master"), "Title"]... | magicoder | python |
You are tasked with implementing a function to process audio data and extract mel spectrogram features. The function should take in audio data, along with various parameters for spectrogram computation, and return the mel spectrogram features.
You are given a code snippet that partially implements the feature extracti... | ```python
import numpy as np
import librosa
def extract_mel_spectrogram(audio, pextract):
# Function to compute the mel spectrogram features
# audio: Input audio data (shape: channels x samples)
# pextract: Parameters for feature extraction
# Compute mel basis
mel_basis = librosa.filters.mel(sr=pe... | magicoder | python |
You are tasked with implementing a support vector machine (SVM) classifier using Python's scikit-learn library. Your goal is to build a program that performs hyperparameter tuning for the SVM classifier using cross-validation and selects the best parameters for the model.
You are given a code snippet that initializes ... | ```python
from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVC
# Initialize the SVM classifier
svm_classifier = SVC()
# Define the hyperparameters to be tuned
tuned_params = [
{'kernel': ['rbf'], 'gamma': [1e-1, 1e-2, 1e-3, 1e-4], 'C': [1, 10, 100, 1000]}
]
# Perform grid search with cros... | magicoder | python |
You are tasked with implementing a class called `SyncHandlerManager` that manages different types of handlers for a messaging system. The class should have a method called `stop()` which stops all the running handlers. The handlers can be of two types: receiver handlers and client event handlers. The `SyncHandlerManage... | ```python
class SyncHandlerManager:
def __init__(self, inbox_manager):
self.inbox_manager = inbox_manager
self._client_event_runner = None
self.receiver_handlers_running = False
self.client_event_handlers_running = False
def start_receiver_handlers(self):
# Logic to star... | magicoder | python |
You are tasked with creating a Python function that validates the configuration of Docker Swarm nodes based on the information provided by the `docker_info` command output. The function should take the hostname of the node and the `docker_info` output as input and perform the necessary assertions to ensure the correctn... | ```python
def validate_docker_swarm_config(hostname: str, docker_info: str) -> bool:
MANAGER_HOSTS = ['manager1', 'manager2'] # Replace with actual manager hostnames
WORKER_HOSTS = ['worker1', 'worker2'] # Replace with actual worker hostnames
if hostname in MANAGER_HOSTS:
if 'Is Manager: true' in... | magicoder | python |
You are tasked with creating a Django migration to add a new field to an existing model. The model is part of an application named "saef" and the migration should be based on the existing migration "0025_auto_20210809_1555". The new field to be added is not specified in the given code snippet.
Your task is to write th... | ```python
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('saef', '0025_auto_20210809_1555'),
]
operations = [
migrations.AddField(
model_name='your_model_name', # Replace 'your_model_name' with the actual model name
... | magicoder | python |
You are tasked with designing a digital circuit that performs a specific operation on a set of input bits and produces the corresponding output bits. The circuit will have a set of input and output ports, and it needs to be interfaced with a clock signal. Your task is to implement the logic for this digital circuit usi... | To solve this problem, you can implement the digital circuit using a hardware description language such as Verilog or VHDL. Below is an example Verilog solution that demonstrates the implementation of a digital circuit based on the provided input and output interfaces.
```verilog
module DigitalCircuit (
input wire... | magicoder | verilog |
You are tasked with implementing a function to perform a specific operation on a complex vector. The complex vector is represented by two arrays: one for the real part and one for the imaginary part. The operation involves calculating the magnitude of each complex number in the vector and then finding the maximum magni... | ```cpp
#include <array>
#include <cmath>
template <std::size_t N>
double maxMagnitude(const std::array<double, N>& realPart, const std::array<double, N>& imagPart) {
double maxMag = 0.0;
for (std::size_t i = 0; i < N; ++i) {
double mag = std::sqrt(realPart[i] * realPart[i] + imagPart[i] * imagPart[i]);... | magicoder | cpp |
You are tasked with implementing a function to process an image and identify the number of objects present in it. The function takes an input image in YUV color space and two threshold values, `lower` and `upper`, to create a mask for object detection. After creating the mask, the function uses OpenCV to find contours ... | ```python
import cv2
import numpy as np
from typing import Tuple
def count_objects(yuv_image: np.ndarray, lower: Tuple[int, int, int], upper: Tuple[int, int, int]) -> int:
mask = cv2.inRange(yuv_image.copy(), lower, upper)
# Find contours.
_, contours, _ = cv2.findContours(
image=mask, mode=cv2.RET... | magicoder | python |
You are tasked with implementing a DialogEnhancer utility for a web application. The utility should provide methods for opening, destroying, and displaying different types of dialogs, such as success, info, error, warning, and confirmation dialogs. You need to create a JavaScript class that encapsulates this functional... | ```javascript
class DialogEnhancer {
static open(dialogType, message) {
if (this.currentDialog) {
this.currentDialog.destroy();
}
this.currentDialog = Dialog.open(dialogType, message);
}
static destroyAll() {
Dialog.destroyAll();
this.currentDialog = null;
}
static success(message)... | magicoder | javascript |
You are tasked with implementing a class that can perform nested dictionary substitutions in a given template string. The template string may contain placeholders in the form of `${...}` or `{...}` for nested dictionary keys. The class should be able to substitute these placeholders with the corresponding values from t... | ```python
import re
class NestedDictTemplate:
def __init__(self, dictionary):
self.dictionary = dictionary
def safe_substitute(self, template):
def substitute(match):
key = match.group(1)
value = self.dictionary
for k in key.split('.'):
if is... | magicoder | python |
You are tasked with implementing a function that processes a list of dependencies and returns a dictionary representing the dependency graph. Each dependency is a tuple containing two elements: the name of the module and the version number. The dependency graph should represent the relationships between modules and the... | ```python
def build_dependency_graph(dependencies):
dependency_graph = {}
for module, version in dependencies:
if module not in dependency_graph:
dependency_graph[module] = []
for key, value in dependency_graph.items():
if key != module:
for ... | magicoder | python |
You are given three integers, x, y, and bound. Your task is to find all the powerful integers that can be formed by adding the powers of x and y, where the result is less than or equal to the given bound. A powerful integer is a number that can be represented as a^i + b^j, where a and b are integers greater than 0, and... | ```python
from typing import List
def powerfulIntegers(x: int, y: int, bound: int) -> List[int]:
ans = set()
for i in range(bound):
if pow(x, i) > bound or (x == 1 and i > 0):
break
for j in range(bound):
if pow(y, j) > bound or (y == 1 and j > 0):
break
... | magicoder | python |
You are tasked with automating the release process for a Python library called "goopylib." The release process involves pushing files to GitHub, creating a GitHub release, updating the download URL in the setup.cfg file, building a source distribution, uploading the release to TestPyPi, installing and checking from Tes... | ```python
import os
import subprocess
# Push files to GitHub
subprocess.run(["git", "add", "."])
subprocess.run(["git", "commit", "-m", "Initial commit"])
subprocess.run(["git", "push"])
# Create GitHub Release
# Code to create GitHub release using GitHub API or library
# Update download_url in setup.cfg
with open('... | magicoder | python |
You are tasked with implementing a simple layer management system for a 2D game. The provided code snippet shows a part of the layer configuration for the game. Each layer is represented by a `LayerInfo` object, which contains information about the layer, such as its depth. The `Layers` object is used to store and mana... | ```javascript
class LayerInfo {
constructor(depth) {
this.depth = depth;
}
}
export const Layers = {
world_back: new LayerInfo(1),
world: new LayerInfo(1),
addLayer(layerName, depth) {
if (this[layerName]) {
this[layerName].depth = depth; // Update depth if layer already exists
} else {
... | magicoder | javascript |
You are tasked with creating a Python class that simulates a smart plug device. The smart plug should be able to turn on and off, as well as provide information about its current state. You should also implement a method to track the total usage time of the smart plug.
Your task is to complete the implementation of th... | ```python
class SmartPlug:
def __init__(self, name: str):
self.name = name
self.state = False # Initial state is off
self.total_usage_time = 0 # Total usage time in minutes
def turn_on(self):
if not self.state:
self.state = True
def turn_off(self):
if ... | magicoder | python |
You are tasked with creating a script that checks the version of the Autotools suite installed on a system. The Autotools suite includes tools like Autoconf, Automake, and Libtool, which are used for building and distributing software packages. Your script should determine the version of Autoconf and Automake installed... | ```bash
function error () {
echo "Error: $1" 1>&2
exit 1
}
function check_autotool_version () {
autoconf_version=$(autoconf --version | grep -oE '[0-9]+\.[0-9]+')
automake_version=$(automake --version | grep -oE '[0-9]+\.[0-9]+')
if [[ -z $autoconf_version ]]; then
error "Autoconf is not installed"
elif [[ $(... | magicoder | shell |
You are tasked with implementing a function that removes a library from a Blender file using the Blender Python API. The function takes in the path of the library to be removed and should return `True` if the removal was successful, and `False` otherwise. The code snippet provided gives a glimpse of the process, but yo... | ```python
import bpy
def remove_library(libpath: str) -> bool:
library = bpy.data.libraries.get(bpy.path.basename(libpath)) # Retrieve the library based on its name
if library is not None: # Check if the library exists
bpy.data.libraries.remove(library) # Remove the library
return True # Re... | magicoder | python |
You are tasked with implementing a Python class that handles API endpoints for managing schedules within a workforce management system. The class should inherit from the `Auth` class and provide functionality for interacting with three specific endpoints: "accounts", "workers/scripts", and "schedules". Your task is to ... | ```python
import requests
class Auth:
# Assume implementation of authentication and authorization methods
class Schedules(Auth):
_endpoint1 = "accounts"
_endpoint2 = "workers/scripts"
_endpoint3 = "schedules"
def __init__(self, base_url, auth_token):
self.base_url = base_url
self.... | magicoder | python |
You are tasked with implementing a Python class for a dataset called `CXR14Dataset` that is used for benchmarking in the context of medical image analysis. The `CXR14Dataset` class should be designed to work with a configuration object named `chexnet_config`. The `benchmark()` method of the `CXR14Dataset` class should ... | ```python
class CXR14Dataset:
def __init__(self, config):
self.config = config
# Initialize dataset attributes and configurations here
def benchmark(self):
# Implement the benchmarking process specific to CXR14Dataset
# This could involve tasks such as model evaluation, performa... | magicoder | python |
You are tasked with implementing a notification system for a chat application. The `Notification` struct contains the following fields:
- `read`: a boolean indicating whether the user has sent a read receipt indicating that they have read the message.
- `room_id`: the ID of the room in which the event was posted.
- `ts... | ```rust
use std::time::{SystemTime, Duration};
pub struct Notification {
pub read: bool,
pub room_id: RoomId,
pub ts: SystemTime,
}
impl Notification {
pub fn time_elapsed_since_notification(&self) -> String {
let now = SystemTime::now();
let elapsed = now.duration_since(self.ts).unwra... | magicoder | rust |
You are working as a system administrator for a company that manages a large number of servers. As part of your responsibilities, you need to create a script to automate the process of archiving and moving specific directories. Your task is to write a Python script that replicates the functionality of the given shell c... | ```python
import os
import sys
import subprocess
def archive_and_move(directory, destination):
# Create the archive file
archive_name = os.path.basename(directory) + ".tar.gz"
subprocess.run(["tar", "cvfz", archive_name, directory])
# Move the archive to the destination directory
subprocess.run(["... | magicoder | python |
You are tasked with debugging a multi-threaded Java program that is intended to calculate the total of an array of integers. The given code snippet is a part of the program and contains logging statements and synchronization blocks. Your goal is to identify and fix the issues in the code to ensure that the program func... | The issues in the given code snippet are related to synchronization and thread interruption. Here's the corrected code snippet with explanations:
```java
// Assuming the code snippet is part of a method in a class that calculates the total of an array of integers
// Incorrect synchronization block, should be synchron... | magicoder | java |
You are tasked with creating a script to automate the testing of a software system. The system consists of three components: a PostgreSQL database, an HTTP server, and an AMQP (Advanced Message Queuing Protocol) service. Each component has its own set of tests that need to be run. Your task is to write a script that wi... | ```bash
#!/bin/bash
# Function to run tests and handle errors
run_tests() {
if [ -x "$1" ]; then
./"$1"
if [ $? -ne 0 ]; then
echo "Error: $1 failed"
fi
else
echo "Error: $1 not found or not executable"
fi
}
# Run PostgreSQL tests
run_tests "run-postgres-tests.s... | magicoder | shell |
You are working on a file management system for a company. The system has various entities such as Checklists, Uploads, Files, Notes, and Comments. Each entity has a relationship with the FileRequest entity, which represents a request for a file. The FileRequest entity has properties for the associated Checklist, Uploa... | ```php
class FileRequest
{
// ... other properties and methods
public function countAssociatedEntities()
{
$counts = [
'checklist' => $this->checklist->count(),
'uploads' => $this->uploads->count(),
'file' => 1, // Assuming each FileRequest has exactly one file a... | magicoder | php |
You are tasked with creating a script to automate the installation of software using a tool called Mason. Mason is a package manager that allows for the installation and management of software packages. Your goal is to write a Bash script that installs a specific version of the ccache software using Mason.
Your script... | ```bash
#!/bin/bash
function mason_prepare_compile {
${MASON_DIR}/mason install ccache 3.3.4
}
mason_prepare_compile
```
In the solution, we define a Bash script that includes the `mason_prepare_compile` function as required. Inside the function, we use the `${MASON_DIR}` environment variable to reference the Mas... | magicoder | shell |
You are tasked with creating a script that monitors the response status of an application and takes appropriate action based on the status code. Your script should handle the following scenarios:
1. If the status code is 200, the script should echo "PASS: App is responding with 200" and exit with a status code of 0.
2... | ```bash
#!/bin/bash
# Check if the status code is provided as an argument
if [ -z "$1" ]; then
echo "Usage: $0 <status_code>"
exit 1
fi
status_code=$1
if [ $status_code -eq 200 ]; then
echo "PASS: App is responding with $status_code"
exit 0
else
echo "FAIL: App is not responding with 200"
exit 1
fi
```
I... | magicoder | shell |
You are tasked with implementing a function that initializes the weights for a neural network using a custom module called `clustre`. The `init_params` function from the `clustre.helpers._weights` module is responsible for initializing the weights based on the specified configuration.
The `init_params` function takes ... | ```python
import clustre.helpers._weights as weights
def initialize_weights(layers, init_type, seed=None):
if seed is not None:
weights.set_seed(seed)
if init_type == "random":
return weights.init_params(layers, "random")
elif init_type == "xavier":
return weights.init_params(layer... | magicoder | python |
You are tasked with creating a Python class that can compare the directory structures of two given paths and report the differences. Your class should be able to identify added, removed, and modified files and directories between the two paths.
Your task is to implement the `CompareCommand` class with the following re... | ```python
import os
import filecmp
class CompareCommand(CLICommand):
def compare_directories(self, dir1, dir2):
differences = {'added': [], 'removed': [], 'modified': []}
if not os.path.exists(dir1) or not os.path.exists(dir2):
raise FileNotFoundError("One or both directories do not ex... | magicoder | python |
You are tasked with creating a command-line utility that parses and converts human-readable time durations into seconds. The utility should accept time durations in the format of hours, minutes, and seconds, and convert them into the equivalent duration in seconds. For example, the input '1h 30m 15s' should be converte... | ```rust
fn parse_duration(input: &str) -> Result<u64, String> {
let mut total_seconds = 0;
let mut current_value = 0;
let mut current_unit = "s"; // Default unit is seconds
for c in input.chars() {
if c.is_digit(10) {
current_value = current_value * 10 + c.to_digit(10).unwrap() as u... | magicoder | rust |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.