query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a custom attribute system in C#. The goal is to create a system that allows developers to mark their classes and methods with custom attributes and then retrieve and use this metadata at runtime.
Your task is to create a `CustomAttribute` class that can be used to mark classes and met... | ```csharp
using System;
using System.Collections.Generic;
// CustomAttribute class to store and retrieve metadata
public class CustomAttribute
{
private Dictionary<string, object> attributeData;
public CustomAttribute()
{
attributeData = new Dictionary<string, object>();
}
public void Add... | magicoder | csharp |
You are tasked with creating a custom JUnit Runner for a Java project. The custom runner should be able to handle the execution of test classes that reference GWT (Google Web Toolkit) components, either directly or indirectly. The custom runner should be annotated with `@RunWith(GwtRunner.class)` to enable its usage in... | ```java
import com.googlecode.gwt.test.internal.junit.AbstractGwtRunner;
import com.googlecode.gwt.test.internal.junit.AbstractGwtRunnerFactory;
import org.junit.runners.model.InitializationError;
public class GwtRunner extends AbstractGwtRunner {
public GwtRunner(Class<?> clazz) throws InitializationError {
... | magicoder | java |
You are tasked with creating a Python function that parses a given text file to extract the copyright information. The copyright information is typically found within comments at the beginning of the file and follows a specific format. The function should return the name of the copyright holder and the license under wh... | ```python
import re
def extract_copyright_info(file_path):
with open(file_path, 'r') as file:
content = file.read()
pattern = r'# Copyright (\d{4}) (.+)\n# Licensed under the (.+);\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# ... | magicoder | python |
You are working on a project that involves modeling count data using a probabilistic programming framework. The code snippet provided is a part of a Python class that defines a probabilistic model using TensorFlow Probability (TFP) library. The model is a Poisson distribution with a time-varying rate parameter. Your ta... | ```python
import tensorflow as tf
import tensorflow_probability as tfp
import numpy as np
class PoissonModel:
def __init__(self, timeperiod_length):
self.timeperiod_length = timeperiod_length
def get_model(self, count_data):
return tfp.distributions.JointDistributionNamed(dict(
s=t... | magicoder | python |
You are tasked with creating a program that monitors a set of URLs for changes and stores the updated content in a Redis database. Your program should periodically make HTTP requests to the specified URLs, compare the retrieved content with the previously stored content in Redis, and update the Redis database if any ch... | ```python
import requests
import redis
import json
import time
# Define the list of URLs to monitor
urls_to_monitor = ['https://example.com/page1', 'https://example.com/page2']
# Connect to the Redis database
redis_db = redis.StrictRedis(host='localhost', port=6379, db=0)
def monitor_urls():
while True:
... | magicoder | python |
You are tasked with implementing a custom modal component in a React application. The modal should provide a confirmation dialog with customizable buttons and behavior. Your task is to create a TypeScript interface for the props of the modal component and then implement the modal component itself.
You are given the fo... | ```typescript
// Define the interface for ConfirmModalProps
interface ConfirmModalProps {
open: boolean;
onRequestClose: () => void;
onConfirm?: () => void;
onCancel?: () => void;
confirmButton?: boolean;
cancelButton?: boolean;
cancelOnBackgroundPress?: boolean;
}
// Implement the modal component
const ... | magicoder | typescript |
You are tasked with implementing a DAG (Directed Acyclic Graph) traversal algorithm to process a series of passes on a simulation top object. Each pass represents a specific operation that needs to be executed in a particular order. Your goal is to design a program that can efficiently execute these passes in the corre... | ```python
class SimulationTop:
def __init__(self):
self.locked = False
def lock_in_simulation(self):
self.locked = True
def execute_passes(top):
GenDAGPass()(top)
WrapGreenletPass()(top)
HeuristicTopoPass()(top)
UnrollTickPass()(top)
top.lock_in_simulation()
# Example usag... | magicoder | python |
You are tasked with creating a Python function that processes a given dataset to perform graph analysis. The function should take a dataset as input, perform necessary preprocessing, and then apply graph analysis techniques to extract relevant information.
Your task is to implement the `graph_analysis` function, whic... | ```python
import scipy.io
import networkx as nx
from grakel import datasets
from scipy import sparse
from sklearn.utils import shuffle
from scipy import linalg
import time
import csv
def graph_analysis(dataset_path, output_csv):
# Load the dataset
dataset = scipy.io.loadmat(dataset_path)
# Convert dataset... | magicoder | python |
You are tasked with creating a Bash script that validates versioning information for a software release. The script should check if the environment variables `VERSION` and `SNAPSHOT` are set, and if the `SNAPSHOT` version follows a specific format.
The script should perform the following checks:
1. If the `VERSION` en... | ```bash
#!/bin/bash
# Check if VERSION is set
if [ -z "${VERSION}" ] ; then
echo "VERSION is not set. Usage: <script_name> -v <version> -s <snapshot_version>"
exit 1
fi
# Check if SNAPSHOT is set
if [ -z "${SNAPSHOT}" ] ; then
echo "SNAPSHOT is not set. Usage: <script_name> -v <version> -s <snapshot_ve... | magicoder | shell |
You are tasked with creating a Django REST framework API endpoint for managing contacts. Your task is to implement a view that allows users to create a new contact, retrieve a list of all contacts, and retrieve a specific contact by its ID. You will need to define the necessary serializer and view to achieve this funct... | ```python
# serializers.py
from rest_framework import serializers
from .models import Contact
class ContactSerializer(serializers.ModelSerializer):
class Meta:
model = Contact
fields = ['id', 'name', 'email', 'mobile', 'message']
# views.py
from rest_framework import generics
from .models import C... | magicoder | python |
You are tasked with implementing a function that checks the validity of a given package graph. A package graph is a collection of interconnected packages, where each package has dependencies on other packages. The function should take the package graph as input and return whether the graph is valid or not. A valid pack... | ```swift
func validatePackageGraph(roots: [String], completion: @escaping (PackageGraph, [Diagnostic]) -> Void) -> Bool {
var visited: Set<String> = []
var visiting: Set<String> = []
func hasCycle(_ package: String, graph: [String: [String]]) -> Bool {
if visiting.contains(package) {
re... | magicoder | swift |
You are tasked with creating a program that simulates a simple banking system. The system should be able to create accounts, deposit and withdraw funds, and provide the account balance. Additionally, the program should be able to transfer funds between accounts.
Your task is to implement a class `Bank` that provides t... | ```swift
class Account {
let accountNumber: Int
let name: String
var balance: Double
init(accountNumber: Int, name: String, initialBalance: Double) {
self.accountNumber = accountNumber
self.name = name
self.balance = initialBalance
}
}
class Bank {
var accounts: [Int: A... | magicoder | swift |
You are working on a system that integrates with various APIs to retrieve information about land titles. The system needs to make authenticated requests to a search API and retrieve geographic and historical data about specific land titles. The environment variables for the API endpoints and URLs are provided as follow... | ```javascript
function constructAPIUrls(titleNumber) {
const {
AUTHENTICATED_SEARCH_API_ENDPOINT,
GEO_API_URL,
GEO_API_ENDPOINT,
HISTORIAN_API_URL,
HISTORIAN_API_ENDPOINT
} = process.env;
const geoApiUrl = `${GEO_API_URL}${GEO_API_ENDPOINT.replace('<title_number>', titleNumber)}`;
const his... | magicoder | javascript |
You are tasked with creating a program to parse and analyze a series of job experiences stored in a list of dictionaries. Each dictionary represents a job experience and contains the following keys: 'name' (job title), 'company' (company name), 'location' (job location), 'working_period' (period of employment), and 'jo... | ```python
from datetime import datetime
def calculate_employment_duration(working_period):
start_date, end_date = working_period.split(' - ')
start_date = datetime.strptime(start_date, '%B %Y')
end_date = datetime.strptime(end_date, '%B %Y')
return (end_date - start_date).days
def find_longest_job_exp... | magicoder | python |
You are given a list of strings, where each string is a word. Your task is to find the length of the longest string chain that can be formed by deleting a single character from any of the words. A string chain is a sequence of words [w1, w2, ..., wn] where each word is formed by deleting a single character from the pre... | ```python
from typing import List
class Solution:
def longestStrChain(self, words: List[str]) -> int:
words.sort(key=len) # Sort the words by length
dp = {}
for word in words:
dp[word] = 1 # Initialize the chain length for each word as 1
for i in range(len(word)):
... | magicoder | python |
You are tasked with implementing a Java class that represents a basic geometric shape. The class should have methods to set and retrieve the color of the shape. Additionally, the class should have a constructor that initializes the color of the shape to a default value if no color is provided. Your task is to complete ... | ```java
public void setCor(String cor) {
if (cor != null && !cor.isEmpty()) {
this.cor = cor;
}
}
```
The `setCor` method checks if the input color `cor` is not null and not an empty string. If the input is valid, it updates the color of the geometric shape. Otherwise, it does not modify the color. Thi... | magicoder | java |
You are tasked with creating a Python class that manages a music library. The class should be able to handle albums, students, modules, and tracks, and provide serialization functionality for each of these entities. Your task is to implement the `MusicLibrary` class with the following requirements:
1. The class should... | ```python
from .serializers import AlbumSerializer, StudentSerializer, ModuleSerializer, TrackSerializer
from rest_framework.response import Response
class MusicLibrary:
def __init__(self):
self.albums = []
self.students = []
self.modules = []
self.tracks = []
def add_album(sel... | magicoder | python |
You are tasked with implementing a binomial tree option pricing model to calculate the price of a European put option. The binomial tree model is a discrete-time, discrete-state model used for valuing options. The option has the following parameters:
- Option type: Put
- Current stock price: $50
- Strike price: $52
- R... | ```python
import math
class Option:
def __init__(self, option_type, current_price, strike_price, risk_free_rate, time_to_expiration, volatility):
self.option_type = option_type
self.current_price = current_price
self.strike_price = strike_price
self.risk_free_rate = risk_free_rate
... | magicoder | python |
You are tasked with creating a Python program that involves defining a data model for a REST API using the Flask-RESTPlus library. The code snippet provided is a part of this process and demonstrates the usage of the `api.model` method to define a data model for a specific resource.
Your task is to complete the progra... | ```python
from flask_restplus import Api, Resource, fields
# Create an instance of the Flask-RESTPlus API
api = Api()
# Define the data model for the _groups_fields_put using the api.model method
_groups_fields_put = api.model('GroupsPut', {
'name': fields.String(required=True, description='The group name'),
... | magicoder | python |
You are tasked with creating a Python class that represents a simple bank account. The class should have methods to deposit funds, withdraw funds, and check the current balance. Additionally, the class should handle currency conversion for deposits and withdrawals in different currencies.
Your task is to implement the... | ```python
class BankAccount:
def __init__(self, account_number, account_holder, initial_balance_usd):
self.account_number = account_number
self.account_holder = account_holder
self.balance_usd = initial_balance_usd
def deposit(self, amount, currency):
if currency == "USD":
... | magicoder | python |
You are tasked with implementing a class that manages system configurations and snapshots. The class should provide methods for retrieving configurations, snapshots, and setting the current configuration. The class should also establish connections to the Snapper and Systemd services.
You are given a code snippet that... | ```python
from typing import Dict, List, Optional
class ConfigurationManager:
def __init__(self):
self.__snapper_connection = SnapperConnection(Snapshot)
self.__systemd_connection = SystemdConnection()
self.__configs: Dict[str, Config] = {}
self.__current_config_snapshots: Dict[int,... | magicoder | python |
You are tasked with implementing a feature in an Android application that allows the user to exit the app by pressing the back button twice within a short time frame. You need to create a class that manages this behavior and integrate it into the existing codebase.
You are provided with a partial code snippet from an ... | ```java
// ManageActivityUtils.java
public class ManageActivityUtils {
private static List<Activity> activityList = new ArrayList<>();
public static void addActivity(Activity activity) {
activityList.add(activity);
}
public static void removeActivity(Activity activity) {
activityList.r... | magicoder | java |
You are tasked with creating a script to automate the process of checking for Go import errors in a given set of files and fixing them if necessary. The script should utilize the `goimports` tool to identify any import errors and provide instructions for resolving them.
Your script should perform the following steps:
... | ```bash
#!/bin/bash
# Step 1: Use goimports to check for import errors
FILES=$(goimports -e -l -local=github.com/openshift/backup pkg cmd)
# Step 2: Display errors and provide fix command if errors are found
if [ -n "$FILES" ]; then
echo "You have go import errors in the below files, please run 'goimports -e -w -... | magicoder | shell |
You are tasked with implementing a ControllerLoader class that dynamically loads and instantiates controller classes from a specified directory in a Python web application. The ControllerLoader class should provide a method to load a controller by its name and execute a method on the loaded controller.
The ControllerL... | ```python
import os
import importlib
import inspect
class ControllerLoader:
def __init__(self, controllers_dir: str):
self.controllers_dir = controllers_dir
def load_controller(self, controller_name: str) -> object:
controller_module = importlib.import_module(f"{self.controllers_dir}.{control... | magicoder | python |
You are tasked with creating a script to automate the testing of different compiler optimization options for C and C++ source files. The script should iterate through a directory containing C and C++ source files, compile each file with different optimization options, and then run a test script to evaluate the compiled... | ```bash
#!/bin/bash
cd compile-only # Navigate to the directory containing source files
for options in -O0 -O2 "-O2 -flto"; do # Iterate through optimization options
echo "===== Testing compile-only with $options ====="
for file in *.c; do # Compile C source files
echo "Testing compile-only $file...... | magicoder | shell |
You are tasked with creating a Python function that processes a list of paths and generates a JSON file containing Docker build instructions for each path. The function should take in the following parameters:
- `paths`: A list of strings representing paths to different services.
- `registry`: A string representing the... | ```python
import json
def generate_docker_json(paths, registry, app, tag):
def write_json(data):
with open("docker-bake.json", mode='a', encoding='utf-8') as feeds_json:
json.dump(data, feeds_json)
feeds_json.write('\n')
with open("docker-bake.json", mode='w', encoding='utf-8')... | magicoder | python |
You are tasked with implementing a cancellation and commit mechanism for a series of events in a JavaScript application. The application uses the `esp-js` library for managing event streams and the `ImmutableModel` class for maintaining the application state.
The `TestEvent` interface defines the structure of events t... | ```javascript
import {ObservationStage} from 'esp-js';
import {ImmutableModel} from '../../src';
function processEvent(event, currentState, currentStage) {
if (event.shouldCancel) {
if (
(event.cancelAtStage && event.cancelAtStage === currentStage) ||
(event.cancelAtState && event.c... | magicoder | javascript |
You are tasked with creating a program that generates ASCII art of animals using the `cowpy` library and saves the output to a JSON file. The program should prompt the user to enter the name of an animal and the text to be displayed in the ASCII art. The program should then use the `cowpy` library to generate the ASCII... | ```python
from textwrap import dedent
from cowpy import cow
import json
def generate_ascii_art():
animal_name = input("Enter the name of the animal: ")
text = input("Enter the text to be displayed in the ASCII art: ")
try:
ascii_art = cow.Cowacter().milk(dedent(text))
with open('ascii_... | magicoder | python |
You are tasked with implementing a function that extracts and formats data from a given array of objects. The objects represent products, and each object contains information about the product's name, category, and price. Your function should filter the products based on a specified category and format the price of eac... | ```javascript
function filterAndFormatProducts(products, selectedCategory, formatPrice) {
const filteredProducts = products.filter(product => product.category === selectedCategory);
const formattedProducts = filteredProducts.map(product => ({
name: product.name,
category: product.category,
price: format... | magicoder | javascript |
You are tasked with implementing a generic class for handling interpolation of values. The class should support different types of interpolation methods and provide the flexibility to specify the interpolation method when creating an instance of the class.
You are provided with a TypeScript code snippet that defines a... | ```typescript
class InterpolatedValue<T> {
constructor(public value: T, public interpolation: Interpolation = Interpolation.None) { }
interpolate(targetValue: T): T {
if (this.interpolation === Interpolation.Linear) {
if (typeof this.value === 'number' && typeof targetValue === 'number') {
return... | magicoder | typescript |
You are tasked with creating a program to visualize the intersection and union of two sets using a Venn diagram. The Venn diagram should display the sets A and B, along with their intersection and union. The program should allow for customization of the subset sizes and set labels.
Write a Python function `create_venn... | ```python
from matplotlib_venn import venn2, venn2_circles
def create_venn_diagram(set_A, set_B, label_A, label_B, subset_sizes):
venn_diagram = venn2(subsets=subset_sizes, set_labels=(label_A, label_B))
c = venn2_circles(subsets=(len(set_A - set_B), len(set_B - set_A), len(set_A & set_B)), linestyle='dashed')... | magicoder | python |
You are tasked with creating a program that simulates a simple address book. The address book should allow users to add, delete, and search for contacts. Each contact will have a name, phone number, and email address. The program should provide a menu-based interface for users to interact with the address book.
Your t... | ```python
class Contact:
def __init__(self, name, phone_number, email):
self.name = name
self.phone_number = phone_number
self.email = email
class AddressBook:
def __init__(self):
self.contacts = []
def add_contact(self, contact):
self.contacts.append(contact)
... | magicoder | python |
You are tasked with creating a Python function that interacts with a virtualization library to manage virtual machines. The function should connect to the virtualization platform, retrieve a list of running virtual machines, and return the names of these virtual machines as a list. You are provided with a code snippet ... | ```python
def get_running_virtual_machines():
try:
# Establish connection to the virtualization platform
virt_connection = KaresansuiVirtConnection()
# Retrieve a list of running virtual machines
running_vms = virt_connection.list_running_virtual_machines()
# Extract and re... | magicoder | python |
You are tasked with implementing a class that handles the serialization and deserialization of data using the Apache Arrow library. The class should support loading data and potentially offsetting the buffer based on the provided metadata.
You are given a partial code snippet for the class:
```java
public class Arrow... | ```java
@Override
public void loadDataAndPossiblyOffsetBuffer(SerializedField metadata, ArrowBuf buffer) {
// Extract relevant information from the metadata
int offset = metadata.getOffset(); // Assuming getOffset() returns the offset value
// If offsetting is required, adjust the buffer
if (offset > 0) {
... | magicoder | java |
You are tasked with implementing a function to convert data from a Lua configuration table into a custom data structure. The provided code snippet is a part of a C++ program that defines a method `convert` within the `GodDB` class. The `convert` method takes a Lua `ConfigTable` object named `data` and a `std::string` n... | ```cpp
GodData GodDB::convert(const lua::ConfigTable& data, const std::string& id)
{
// Retrieve the "legacy_id" from the Lua ConfigTable
auto legacy_id = data.required<int>("legacy_id");
// Create a GodData object using the provided id and the extracted legacy_id
return GodData{SharedId{id}, legacy_id... | magicoder | cpp |
You are tasked with implementing a message broker system that handles message payloads and subscriptions. The system should allow subscribers to register callback methods for specific topics and receive messages when those topics are published.
You are given a partial code snippet from the message broker system, which... | ```python
class MessageBroker:
def __init__(self):
self.callback_dictionary = {}
def subscribe(self, topic, callback):
if topic in self.callback_dictionary:
self.callback_dictionary[topic].append(callback)
else:
self.callback_dictionary[topic] = [callback]
d... | magicoder | python |
You are tasked with creating a function that searches for images based on a user-provided query and returns a random image result. You are given a code snippet that partially implements this functionality using an `images` object and various utility functions. Your task is to complete the implementation of the `searchI... | ```javascript
function searchImages(query) {
if (!query) query = "anime"; // Default to "anime" if query is not provided
const imageResult = images.search(query); // Assuming images.search returns an array of image objects
const rand = Math.floor(Math.random() * imageResult.length);
const randPin = imag... | magicoder | javascript |
You are tasked with implementing a simplified version of a virtual machine for a custom programming language. The virtual machine operates on a set of instructions and data types, and your goal is to create a function that executes these instructions.
You are given the following code snippet as a reference for the typ... | ```rust
fn execute_instructions(instructions: Vec<Instruction>) -> Option<Constant> {
let mut stack: Vec<Constant> = Vec::new();
for instruction in instructions {
match instruction {
Instruction::LoadConstant(constant) => {
stack.push(constant);
}
Ins... | magicoder | rust |
You are tasked with creating a program that reads a text file and counts the occurrences of each word in the file. Your program should then write the word counts to a new file in the format "word: count". Additionally, the program should be able to handle different file encodings and should ignore punctuation and case ... | ```python
import string
def count_word_occurrences(input_file, output_file):
word_counts = {}
with open(input_file, "r", encoding="utf-8") as file:
text = file.read().lower()
text = text.translate(str.maketrans('', '', string.punctuation))
words = text.split()
for ... | magicoder | python |
You are tasked with implementing a Rust trait and its associated functions for managing the versioning of a pallet in a blockchain runtime. The trait `GetPalletVersion` has two associated functions: `current_version` and `storage_version`. The `current_version` function returns the current version of the pallet, while ... | ```rust
// Define a struct to represent the version of the pallet
struct PalletVersion {
// Define the fields of the version, e.g., major, minor, patch
// ...
}
// Implement the GetPalletVersion trait for a specific pallet
pub trait GetPalletVersion {
// Returns the current version of the pallet.
fn cu... | magicoder | rust |
You are tasked with implementing a Python module that provides a custom hexdump function for displaying the hexadecimal content of a file. The module should also include a helper function for abbreviated usage and a constant for enabling colored output.
Your task is to create a Python module that fulfills the followin... | ```python
# hexdump2.py
# Import required modules
import binascii
import os
# Define constant for colored output
color_always = False
# Custom hexdump function
def hexdump(file_path):
with open(file_path, 'rb') as file:
data = file.read()
offset = 0
while data:
line = data[:16... | magicoder | python |
You are tasked with creating a program that analyzes a given text file to count the occurrences of specific license-related terms. The program should read the text file and identify the number of times the following terms appear: "license", "License", "LICENSE", "Apache", "apache", "APACHE". The program should be case-... | ```python
def count_license_terms(file_path: str) -> dict:
terms_count = {
"license": 0,
"License": 0,
"LICENSE": 0,
"Apache": 0,
"apache": 0,
"APACHE": 0
}
with open(file_path, 'r') as file:
text = file.read()
for term in terms_count.keys():
... | magicoder | python |
You are tasked with implementing a logging system for a software application. The application has a `Logger` interface with a method `getLogInfo()` that should be implemented by various logging classes. The `getLogInfo()` method should return a string containing the log information specific to the logging class. Your t... | ```java
import java.io.FileWriter;
import java.io.IOException;
interface Logger {
String getLogInfo();
}
class FileLogger implements Logger {
private String filePath;
public FileLogger(String filePath) {
this.filePath = filePath;
}
@Override
public String getLogInfo() {
try {... | magicoder | java |
You are given a Python class `A` with an attribute `a`, a subclass `C` of `A` with an attribute `c`, and a test case `TestKeys` that checks the keys of an object using a function `R.keys(obj)`. Your task is to implement the `R.keys(obj)` function that returns an array of the given object's own keys.
Write a function `... | ```python
def keys(obj):
return [key for key in obj.__dict__ if not key.startswith('__')]
```
The `keys` function uses a list comprehension to iterate through the keys of the object's `__dict__` attribute and filters out keys that start with double underscores, which are considered private attributes. This ensures... | magicoder | python |
You are tasked with creating a web application that manages products. The application uses the Laravel framework, and the code snippet provided is from a Blade template file used to display product information in a table. The `{{$producto->activo}}` and `{{$producto->sliderprincipal}}` are variables representing the "a... | ```php
function countActiveAndSliderProducts(array $products): array {
$activeCount = 0;
$sliderCount = 0;
foreach ($products as $product) {
if ($product->activo) {
$activeCount++;
}
if ($product->sliderprincipal) {
$sliderCount++;
}
}
return... | magicoder | php |
You are tasked with implementing a Python program that performs feature selection and evaluation for a machine learning model. The program takes command-line arguments for training and test data files, as well as an optional argument for the feature size. The feature size must be at least 2, and if not provided, it def... | ```python
import sys
import numpy as np
import pandas as pd
# Assuming the machine learning model and feature selection logic are implemented elsewhere
if len(sys.argv) < 3:
print("Usage: python program.py <training_csv> <test_csv> [feature_size]")
sys.exit(1)
training_csv = sys.argv[1]
test_csv = sys.argv[2]... | magicoder | python |
You are tasked with creating a program that simulates a simplified version of a message passing interface (MPI) communication pattern. In this problem, you will be focusing on the "uniband" communication benchmark, which measures the bandwidth of point-to-point communication between MPI processes.
The benchmark is typ... | ```python
import time
import random
def simulate_uniband(num_processes):
# Simulate sending a large amount of data between processes
data_size_mb = 1000 # Size of data to be sent in megabytes
start_time = time.time()
# Simulate point-to-point communication between processes
for _ in range(num_pro... | magicoder | python |
You are given a Python code snippet that defines a dictionary of locations on a map. Each location is represented by a key and a corresponding `map_funcs.Point` object, which contains the x and y coordinates of the location. However, some of the locations are commented out, and it's unclear why. Your task is to write a... | ```python
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
locations = {
'red_building': Point(914, 2827),
'helicopter': Point(2630, 1236),
'camera_B': Point(2890, 1103),
'buildings_apron_edge': Point(2213, 1780),
'right_dark_grass': Point(2742, 1137),
'right_lig... | magicoder | python |
You are tasked with implementing a file management system that involves deleting files and directories. Your goal is to write a function that takes in an array of file system objects and deletes them according to the following rules:
1. If the object is a file, it should be deleted directly.
2. If the object is a direc... | The issue with the given code snippet is that it attempts to delete the directory before deleting its contents. This can lead to an error if the directory is not empty. To resolve this issue, the code should first delete the contents of the directory before deleting the directory itself. Here's the corrected code snipp... | magicoder | java |
You are tasked with implementing a custom deep copy function in Python. The deep copy function should create a new object and recursively copy all nested objects within the original object, ensuring that the copied object is completely independent of the original. You should not use the built-in `copy.deepcopy()` funct... | ```python
def custom_deep_copy(obj):
if isinstance(obj, dict):
copied_obj = {}
for key, value in obj.items():
copied_obj[key] = custom_deep_copy(value)
return copied_obj
elif isinstance(obj, list):
copied_obj = []
for item in obj:
copied_obj.append... | magicoder | python |
You are tasked with creating a script to automate the process of updating a package in an Arch Linux repository. The script should clone the upstream repository, copy modified files to it, grant write permission to the nobody user, and then run a command to check if the package works.
Your task is to write a Bash scri... | ```bash
#!/bin/bash
# Define the package name
PACKAGE="your_package_name"
# Clone the upstream repository
git clone "ssh://aur@aur.archlinux.org/${PACKAGE}.git" "${PACKAGE}-upstream"
# Copy modified files to the upstream repository
cp -R "${PACKAGE}/." "${PACKAGE}-upstream"
# Grant write permission to the nobody us... | magicoder | shell |
You are tasked with creating a Python script to automate the deletion of Google Cloud Platform (GCP) service accounts using the `google-cloud-sdk` library. Your script should take a service account name as input and delete the specified service account from the GCP project. You should handle any potential errors that m... | ```python
from google.cloud import iam
def delete_gcp_service_account(service_account_name):
client = iam.ServiceAccountManagerClient()
parent = "projects/my-project-id"
service_account = f"{parent}/serviceAccounts/{service_account_name}@my-project-id.iam.gserviceaccount.com"
try:
client.delet... | magicoder | python |
You are tasked with implementing a Python function that processes a list of tasks in parallel using a specified number of workers. Each task is represented by a string and needs to be processed by a worker function. The function should distribute the tasks among the workers and return the results in the same order as t... | ```python
from typing import List, Callable, Any
from concurrent.futures import ThreadPoolExecutor
def process_tasks(tasks: List[str], worker_function: Callable[[str], Any], num_workers: int) -> List[Any]:
results = []
with ThreadPoolExecutor(max_workers=num_workers) as executor:
# Submit tasks to work... | magicoder | python |
You are working on a software project that heavily utilizes design by contract (DbC) principles to ensure the correctness of the code. The project uses a library called "contracts" to implement these contracts. The library provides two functions: `disable_all` and `enable_all`, which respectively disable and enable all... | ```python
from functools import wraps
from contracts import disable_all as disable_contracts, enable_all as enable_contracts
def contracted(enabled):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
if enabled:
enable_contracts()
else:
... | magicoder | python |
You are tasked with implementing a function to update the means of clusters in a K-means clustering algorithm. The function `CalcMeans` takes three parameters: `X`, `oldmeans`, and `clusters`.
- `X` is a 2D array representing the data points, where each row corresponds to a data point and each column corresponds to a... | The `CalcMeans` function is implemented as follows:
```python
import numpy as np
def CalcMeans(X, oldmeans, clusters, boxl):
k = len(oldmeans)
means = np.zeros((k, X.shape[1]))
keys = sorted(clusters.keys())
for key in keys:
for i in clusters[key]:
means[key] += X[i] - boxl * np.ar... | magicoder | python |
You are tasked with implementing a doubly linked list in Python. The provided code snippet is a part of a `Node` class that represents a node in the doubly linked list. The `Next` property returns the data of the next node in the list, and the `Prev` property returns the data of the previous node. If the current node i... | ```python
class Node:
def __init__(self, data, prev=None, next=None):
self.Data = data
self.PrevNode = prev
self.NextNode = next
def Next(self):
if self.NextNode is None:
return 'At end of the list!'
return self.NextNode.Data
@property
def Prev(self)... | magicoder | python |
You are tasked with implementing a Python class that interacts with the Electrum blockchain API to retrieve unspent transaction outputs (UTXOs) for a given Bitcoin address. Your task is to complete the implementation of the `ElectrumAPI` class by adding a method to parse the response from the API and return the list of... | ```python
import requests
DEFAULT_TIMEOUT = 10 # seconds
class ElectrumAPI:
UNSPENT_API = 'https://api.mbc.wiki/?method=blockchain.address.allutxo¶ms[]={}'
@classmethod
def get_unspent(cls, address):
r = requests.get(cls.UNSPENT_API.format(address), timeout=DEFAULT_TIMEOUT)
return cl... | magicoder | python |
You are tasked with implementing a function to check for the installation of a specific software patch. The function will take in a version number as an argument and should return 1 if a newer 100 series patch is already installed, and 0 otherwise. The function will be part of a larger script that iterates through inst... | ```bash
checkPatch() {
local version=$1
local newerPatch=0
while IFS= read -r patch; do
if [[ $patch -gt 100 && $patch -gt $version ]]; then
echo "Newer 100 series patch already installed"
return 1
fi
done < installed_patches.txt
return 0
}
```
The `checkPat... | magicoder | shell |
You are given a string containing a series of hexadecimal escape sequences. Each escape sequence represents a character in the string. Your task is to decode the string and convert it into its corresponding ASCII representation.
Write a function `decode_hex_string` that takes a string `hex_string` as input and returns... | ```python
def decode_hex_string(hex_string: str) -> str:
decoded_string = ""
hex_list = hex_string.split("\\x")[1:] # Split the string and remove the empty first element
for hex_char in hex_list:
decoded_string += chr(int(hex_char, 16)) # Convert each hexadecimal escape sequence to its correspondi... | magicoder | python |
You are tasked with creating a Python program to classify handwritten digits using a pre-trained neural network model. The model has three hidden layers (l1, l2, and l3) and uses the softmax function to output the probabilities for each digit (0-9). Your program should load the pre-trained model from a file, process an... | ```python
import pickle
import torch
import torch.nn.functional as F
# Load the pre-trained model from the file
model = pickle.load(open('trained-mnist-model', 'rb'))
# Assuming h0 is the input image data
h0 = torch.tensor(...) # Replace ... with the input image data
# Process the input image through the model
h1 =... | magicoder | python |
You are tasked with implementing a simple pressure field simulation in a 2D grid. The pressure field is represented by a 2D array of floating-point numbers. You need to create a `PressureField` struct and implement methods to manipulate and visualize the pressure field.
You are provided with a partial code snippet for... | ```rust
pub struct PressureField {
buf: Vec<f64>,
width: usize,
height: usize,
}
impl PressureField {
pub fn new(width: usize, height: usize) -> Self {
Self {
buf: vec![0.0; width * height],
width,
height,
}
}
pub fn add_point_pressure(&mut s... | magicoder | rust |
You are tasked with implementing a function that simulates a text-to-speech system. The function should take a string of text and a host as input, and return the time it takes to "say" the text using the specified host. Additionally, the function should print the text and the time it took to say the text, followed by a... | ```python
import time
def say_text(host, text):
# Simulate the text-to-speech process
# Here, you can implement the actual text-to-speech functionality using the specified host
# For the purpose of this problem, we will simulate the process by returning a random time
# Replace this with actual text-to-... | magicoder | python |
You are tasked with implementing a function to plot scatter pie plots. A scatter pie plot is a type of scatter plot where the markers are replaced by pie charts. Each pie chart represents the distribution of a categorical variable at a specific point in the scatter plot.
You need to implement a Python function `plot_s... | ```python
import matplotlib.pyplot as plt
import numpy as np
def plot_scatter_pie(x, y, ratios, ax=None, size=100, edgecolor="none", **kwargs):
"""
Plot scatter pie plots.
Parameters:
x: list/array of x values
y: list/array of y values
ratios: List of lists of ratios that add up to ... | magicoder | python |
You are tasked with creating a program that simulates a simple banking system. The system should be able to create and manage bank accounts, allowing users to deposit, withdraw, and check their balance. Each bank account should have a unique account number and be associated with the account holder's name. The program s... | ```python
class BankAccount:
total_accounts = 0
def __init__(self, account_holder_name):
BankAccount.total_accounts += 1
self.account_number = BankAccount.total_accounts
self.account_holder_name = account_holder_name
self.account_balance = 0
def deposit(self, amount):
... | magicoder | python |
You are tasked with implementing a parallelized random search algorithm using Python's `multiprocessing` module. The goal is to parallelize the random search process to efficiently explore a large search space for finding optimal solutions.
Your task is to complete the implementation of the `parallel_random_search` fu... | ```python
import random
import multiprocessing
def parallel_random_search(search_space, objective_function, num_iterations, num_processes):
manager = multiprocessing.Manager()
ransearch_probe_set = manager.list([None] * num_processes)
ransearch_count = manager.list([None] * num_processes)
ransearch_see... | magicoder | python |
You are tasked with implementing a generic function that calculates the total distance of a route in a transportation network. The transportation network is represented by a graph, where nodes are locations and edges are roads connecting the locations. Each edge has a weight representing the distance between the connec... | ```rust
// Define the NetworkHandler trait representing the transportation network
trait NetworkHandler {
// Define the method to retrieve the distance between two locations
fn get_distance(&self, start: &str, end: &str) -> f64;
}
// Define the Path trait representing the route
trait Path {
// Define the m... | magicoder | rust |
You are tasked with implementing a Python module for iterative linear solvers used in numerical methods for solving linear systems of equations. The given code snippet is a part of the module, which contains various iterative solvers such as GMRES, FGMRES, CG, CR, CGNR, CGNE, BiCGSTAB, steepest descent, and minimal res... | ```python
from typing import List
def is_solver_available(solver_name: str) -> bool:
available_solvers = ['GMRES', 'FGMRES', 'CG', 'CR', 'CGNR', 'CGNE', 'BiCGSTAB', 'Steepest Descent', 'Minimal Residual']
return solver_name in available_solvers
```
The `is_solver_available` function checks if the given `solver... | magicoder | python |
You are tasked with creating a Python class to process and analyze Twitter data. The class should have methods to perform various operations on tweets, such as calculating the average score, finding the most frequent Twitter handle, and updating the tweet counter. The class should also maintain a list of tweets and the... | ```python
from datetime import datetime
class TwitterDataProcessor:
def __init__(self):
self.tweet_data = []
def add_tweet(self, twitter_handle, tweet_id, tweet_data, tweet_date, is_notification, score, sum_score, counter):
tweet = {
'twitter_handle': twitter_handle,
't... | magicoder | python |
You are tasked with creating a program that simulates a mood mirror. The mood mirror program should take input from the user and reflect it back in a modified form based on certain rules. The rules for modifying the input are as follows:
1. If the input is a single word, the program should reverse the word and display ... | ```python
def mood_mirror(input_str):
if input_str.endswith('?'):
response = "I'm not sure, but let's find out! "
else:
response = ""
words = input_str.strip('?').split()
if len(words) == 1:
modified_output = response + words[0][::-1]
else:
modified_output = resp... | magicoder | python |
You are tasked with implementing a program to manage a warehouse inventory system. The inventory consists of various items, each with a unique name. Your program should support adding new items to the inventory, removing items, and displaying the current inventory list in alphabetical order.
You are given a list of it... | ```python
class InventoryManager:
def __init__(self):
self.inventory = set()
def add_item(self, item_name):
item_name = item_name.lower()
self.inventory.add(item_name)
def remove_item(self, item_name):
item_name = item_name.lower()
if item_name in self.inventory:
... | magicoder | python |
You are tasked with creating a Python program that efficiently calculates the memory size of a given object. The program should prompt the user to enter a value for the object and then display the memory size of the object in bytes. You should implement a function that takes the object as input and returns its memory s... | ```python
import sys
def get_memory_size(obj):
return sys.getsizeof(obj)
def main():
var1 = input("Enter a value of the object: ")
size = get_memory_size(var1)
print(size, "bytes")
if __name__ == "__main__":
main()
```
The `get_memory_size` function uses the `sys.getsizeof` method to obtain the ... | magicoder | python |
You are tasked with creating a Python class that manages schema migrations for different databases. Your task is to implement the `MigrationController` class, which should handle listing and tracking the status of migrations for various database groups.
The `MigrationController` class should have the following methods... | ```python
from typing import List, Dict, Any
STATUS_PENDING = 'pending'
STATUS_COMPLETED = 'completed'
class MigrationController:
def __init__(self, databases: List[str], groups: Dict[str, str]):
self.databases = databases
self.groups = groups
self.migration_status = {group: {db: [] for db... | magicoder | python |
You are tasked with implementing a Python class that interacts with an API using a user token for authentication. Your task is to complete the implementation of the `Client` class, which inherits from `AbstractClient` and is responsible for making requests to the specified API host using the provided user token.
Your ... | ```python
# The solution provides a complete implementation of the Client class, fulfilling the requirements specified in the problem description.
# The Client class inherits from AbstractClient and has attributes api_host and user_token.
# The __init__ method initializes the api_host and user_token attributes.
# The... | magicoder | python |
You are working on a geographic information system (GIS) project and need to implement a function to calculate the bathymetric gradient within a given workspace. The function `bathymetricGradient` takes several input parameters: `workspace`, `snapGrid`, `hucPoly`, `hydrographyArea`, `hydrographyFlowline`, `hydrographyW... | ```python
def bathymetricGradient(workspace, snapGrid, hucPoly, hydrographyArea, hydrographyFlowline, hydrographyWaterbody, cellsize):
# Implement the bathymetric gradient calculation here
# Use the input parameters to perform the necessary GIS analysis
# Calculate the gradient based on the bathymetric data... | magicoder | python |
You are tasked with creating a function that processes a given script and extracts the variables used within it. The script is written in JavaScript and may contain variable assignments, function calls, and other JavaScript statements. Your task is to write a function that identifies and returns all the unique variable... | ```javascript
function extractVariables(script) {
// Regular expression to match variable declarations and function calls
const regex = /(?:var|let|const)\s+([a-zA-Z_]\w*)|([a-zA-Z_]\w*)\s*\(/g;
let matches;
const variables = new Set();
// Loop through all matches and add them to the set
while ((matches = ... | magicoder | javascript |
You are tasked with creating a Swift application that manages multiple view controllers using storyboards. Your goal is to implement a function that instantiates a view controller from a specified storyboard. You are provided with a code snippet that includes an extension to the UIViewController class, which contains a... | ```swift
import UIKit
extension UIViewController {
class func instantiateViewController(fromStoryboard name: String, withIdentifier identifier: String) -> UIViewController {
let storyboard = UIStoryboard(name: name, bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifi... | magicoder | swift |
You are tasked with implementing a simple observer pattern in Swift. You need to create a class that allows other objects to observe changes to a specific property and be notified when the property's value changes.
Your task is to create a `PropertyObserver` class that allows observers to register themselves and recei... | ```swift
class PropertyObserver {
private var observers: [ObjectIdentifier: Selector] = [:]
private var value: String = ""
func addObserver(_ observer: AnyObject, selector: Selector) {
observers[ObjectIdentifier(observer)] = selector
}
func removeObserver(_ observer: AnyObject) {
o... | magicoder | swift |
You are tasked with creating a program that simulates a space mission to the moon. The program will calculate the number of trips required to transport a given number of people from Earth to the moon, based on the capacity of a spacecraft and the average distance from Earth to the moon.
You are given the following inf... | ```java
public class SpaceMission {
public static int calculateTripsToMoon(int spacecraftCapacity, int totalPeople) {
if (spacecraftCapacity <= 0 || totalPeople <= 0) {
throw new IllegalArgumentException("Capacity and total people must be positive integers");
}
int trips = totalP... | magicoder | java |
You are tasked with implementing a simple text-based user interface (TUI) library in C#. The library should support the creation of various widgets such as paragraphs, headers, buttons, panels, and checkboxes. Your goal is to create a class hierarchy for these widgets and implement the necessary functionality to add th... | ```csharp
using System;
using System.Collections.Generic;
// Base class for all widgets
public class Widget
{
public virtual void Draw()
{
// Base implementation for drawing a widget
}
}
// Class representing a paragraph widget
public class Paragraph : Widget
{
private string _text;
publi... | magicoder | csharp |
You are tasked with creating a program that simulates a simple banking system. The program should allow users to create accounts, deposit and withdraw funds, and check their balance. The program should also be able to handle multiple accounts and perform basic error checking.
Your task is to implement the `BankAccount... | ```cpp
#include <iostream>
#include <string>
#include <vector>
class BankAccount {
private:
int accountNumber;
std::string accountHolderName;
double balance;
public:
BankAccount(int accNum, const std::string& accHolder) : accountNumber(accNum), accountHolderName(accHolder), balance(0.0) {}
void d... | magicoder | cpp |
You are tasked with creating a script to automate the build and deployment process for a web application. The script should handle building the application using Bazel and then copying the output to a specified destination. Additionally, the script should include a function to build a WebAssembly module using npm and h... | ```bash
#!/bin/bash
# Function to build the web application using Bazel
build_and_copy() {
bazel build ${TARGET}
cp -r bazel-bin/${BAZEL_OUTPUT} ${DESTFILE}
}
# Function to build a WebAssembly module using npm
npm_build() {
# Set default value for NPM_OUTPUT if not already set
NPM_OUTPUT=${NPM_OUTPUT:-build/o... | magicoder | shell |
You are tasked with implementing a simple module system for a programming language. The module system should allow users to define and import modules, and resolve dependencies between modules. Each module can have dependencies on other modules, and the module system should ensure that all dependencies are resolved befo... | ```rust
mod core {
use std::collections::{HashMap, HashSet};
pub struct Module {
name: String,
dependencies: Vec<String>,
}
pub struct ModuleSystem {
modules: HashMap<String, Module>,
}
impl ModuleSystem {
pub fn new() -> ModuleSystem {
ModuleSystem... | magicoder | rust |
You are tasked with creating a Python function that processes a list of tasks in parallel using the `multiprocessing` module. Each task is a dictionary containing arguments to be passed to a specified function. The function should execute the specified function for each task and return a list of success flags indicatin... | ```python
import multiprocessing
def execute_task(task):
"""Execute the specified task and return success flag"""
try:
func = globals()[task["func"]] # Get the function from the global scope
func(**task["args"]) # Call the function with the specified arguments
return True # Task exec... | magicoder | python |
You are tasked with creating a Python program to analyze and visualize shot lengths in a movie. Shot length refers to the duration of a single continuous shot in a film. The program should read a list of shot lengths from a file, calculate the frequency of each shot length, and then create a histogram to visualize the ... | ```python
import argparse
import matplotlib.pyplot as plt
import os
def read_shot_lengths(input_file):
with open(input_file, 'r') as file:
shot_lengths = [int(line.strip()) for line in file]
return shot_lengths
def generate_shot_length_histogram(shot_lengths, output_file, output_format):
plt.hist(... | magicoder | python |
You are tasked with implementing a C++ template meta-programming problem related to operator lifting. The goal is to create a meta-function that determines the result type and value type of a lifted operator.
You are provided with a partial code snippet that defines a `lift_traits` meta-function within the `operators:... | ```cpp
namespace operators {
namespace detail {
template<class ResultType, class SourceOperator, class Operator>
struct lift_traits
{
typedef rxu::decay_t<ResultType> result_value_type;
typedef rxu::decay_t<SourceOperator> source_operator_type;
typedef rxu::decay_t<Operator> operator_type;
typedef ty... | magicoder | cpp |
You are working on a project that involves parsing and analyzing PHP code. As part of this task, you need to write a function that extracts the names of all the constants defined in a given PHP file. A constant in PHP is defined using the `const` keyword and is case-sensitive.
Write a function `extractConstants` that ... | ```php
function extractConstants(string $phpCode): array {
$constants = [];
$tokens = token_get_all($phpCode);
$inConstantDefinition = false;
$constantName = '';
foreach ($tokens as $token) {
if (is_array($token)) {
if ($token[0] === T_CONST) {
$inConsta... | magicoder | php |
You are tasked with implementing a function to decompress data using the ZLIB compression algorithm. ZLIB is a widely used data compression library that uses the DEFLATE algorithm, which combines the LZ77 algorithm and Huffman coding. Your goal is to write a function that takes compressed data as input and returns the ... | ```rust
use std::io::prelude::*;
use flate2::read::ZlibDecoder;
fn decompress_zlib(compressed_data: &[u8], uncompressed_size: usize) -> Result<Vec<u8>, String> {
let mut decompressed_data = Vec::new();
let mut decoder = ZlibDecoder::new(compressed_data);
match decoder.read_to_end(&mut decompressed_data) {
... | magicoder | rust |
You are given a list of flights, where each flight is represented as a tuple (source, destination, price). You are also given three integers, src, dst, and k, representing the source city, destination city, and the maximum number of stops allowed in a flight path. You need to find the cheapest price from src to dst wit... | ```python
import collections
import heapq
def findCheapestPrice(n, flights, src, dst, k):
graph = collections.defaultdict(list)
for s, d, p in flights:
graph[s].append((d, p))
heap = [(0, src, k + 1)]
while heap:
price, city, stops = heapq.heappop(heap)
if city == dst:
... | magicoder | python |
You are tasked with creating a Python package that provides a simplified interface for working with JSON data. Your package, named "lazyjson", should offer lazy loading of JSON files and provide a method for accessing specific keys within the JSON data.
Your task is to implement the `LazyJSON` class within the "lazyjs... | ```python
# File: lazyjson.py
import json
class LazyJSON:
def __init__(self, file_path):
self.file_path = file_path
self._data = None
def _load_data(self):
with open(self.file_path, "r") as fh:
self._data = json.load(fh)
def get(self, key):
if self._data is No... | magicoder | python |
You are tasked with creating a Python function that processes financial data to calculate the polynomial regression of stock prices over time. The function should take in a list of polynomial coefficients and a list of dates, and return the polynomial regression function and the first date in the list.
The function si... | ```python
import numpy as np
def calculate_polynomial_regression(p_coeff, dates):
poly = np.poly1d(p_coeff) # Create a polynomial regression function using the coefficients
return poly, dates[0] # Return the polynomial regression function and the first date in the list
``` | magicoder | python |
You are tasked with implementing a Python function that calculates the total number of ways to reach the top of a staircase. You can climb the staircase by either taking one step or two steps at a time. The function should take the number of steps in the staircase as input and return the total number of distinct ways t... | ```python
def count_ways_to_climb(n):
if n <= 0:
return 0
elif n == 1:
return 1
elif n == 2:
return 2
else:
first = 1
second = 2
for _ in range(3, n + 1):
current = first + second
first = second
second = current
... | magicoder | python |
You are tasked with implementing a SQL query parser for a custom SQL dialect. The parser is responsible for handling various SQL operations and expressions. One of the functionalities of the parser is to modify the structure of a SQL expression based on certain conditions. Your task is to implement a method that modifi... | ```python
class SQLExpressionParser:
def __init__(self, join_expr):
self.join_expr = join_expr
def modify_sql_expression(self, alias):
expr = self.join_expr
while True:
if expr.sql_op == '=':
left = expr.left
names = left.names
... | magicoder | python |
You are given a directed graph with weighted edges. Your task is to implement a bidirectional Dijkstra algorithm to find the shortest path between two given nodes. The bidirectional Dijkstra algorithm simultaneously runs Dijkstra's algorithm from the source node and the target node, meeting in the middle when their sea... | ```rust
use std::collections::{BinaryHeap, HashMap};
use std::cmp::Ordering;
type NodeId = usize;
type Weight = i32;
#[derive(Clone, Copy, Eq, PartialEq)]
struct State {
node: NodeId,
cost: Weight,
}
impl Ord for State {
fn cmp(&self, other: &Self) -> Ordering {
other.cost.cmp(&self.cost)
}
}... | magicoder | rust |
You are tasked with analyzing CPU utilization data from a set of servers. The data is represented in a Pandas DataFrame with the following structure:
| server_name | cpu_utilization |
|-------------|-----------------|
| server1 | 80 |
| server2 | 60 |
| server3 | 90 |... | ```python
import plotly.express as px
def create_cpu_utilization_violin_plot(data):
fig = px.violin(data, y='cpu_utilization', box=True, points="all", title="CPU Utilization Distribution")
fig.update_traces(meanline_visible=True, box_visible=True, opacity=0.6, scalemode='count')
fig.update_layout(viol... | magicoder | python |
You are tasked with creating a unit test for a Python class method. The class, `Store`, is responsible for managing settings from a file. The method to be tested is `get` which is expected to read settings from a file and store them in the `settings` attribute of the `Store` instance. The code snippet provided is a par... | ```python
from unittest import mock
from krux.settings import Store
def test_store_get(mocker):
# Arrange
settings_file_content = "key1=value1\nkey2=value2\nkey3=value3\n"
mo = mock.mock_open(read_data=settings_file_content)
mocker.patch("builtins.open", mo)
# Act
s = Store()
s.get("settin... | magicoder | python |
You are working on a project that involves defining and using generic types and extensions in Swift. As part of this project, you need to create a custom type and extension to measure the size of internal nodes in a tree structure. The provided code snippet is a starting point for this task.
Your task is to define a g... | ```swift
// Define the InternalNode type
struct InternalNode {}
// Define the Number type
typealias Number = Int
// Define the Size type
struct Size<T> {
var width: T
var height: T
}
// Define the Measuring type with associated types
struct Measuring<T, In, Out> {
let target: T
let function: (In) -> ... | magicoder | swift |
You are tasked with implementing a Python function that performs eigenvalue decomposition on a given matrix using the appropriate solver based on certain conditions. The function should take into account the number of eigenpairs to compute, the symmetry of the matrix, and specific solver settings.
You are provided wit... | ```python
import numpy as np
from typing import Tuple, Dict
import scipy.linalg
def eigen_solver(matrix: np.ndarray, n_eigenpairs: int, is_symmetric: bool) -> Tuple[np.ndarray, np.ndarray]:
if n_eigenpairs == matrix.shape[1]:
if is_symmetric:
scipy_eigvec_solver = scipy.linalg.eigh
else... | magicoder | python |
You are tasked with implementing a custom error type for a Rust networking library. The library needs to handle errors related to socket addresses and provide a way to log these errors. Your task is to define the custom error type and implement the necessary functionality to log socket address errors.
Your custom erro... | ```rust
use log::warn;
use std::io::Error as IoError;
// Custom error type for socket address errors
pub struct SocketAddressError {
error: IoError,
}
impl SocketAddressError {
// Constructor function to create a new instance of SocketAddressError
pub fn new(error: IoError) -> Self {
SocketAddress... | magicoder | rust |
You are tasked with implementing a protein sequence modification algorithm. Given a protein sequence and a set of fixed modifications, the algorithm should apply the fixed modifications to the N-terminus of the protein sequence. Each fixed modification is represented by a description enclosed in square brackets, and th... | ```python
class Modification:
def __init__(self, description):
self.Description = description
def apply_fixed_modifications(protein_sequence, fixed_modifications):
modified_sequence = protein_sequence
if 0 in fixed_modifications:
prot_n_term_fixed_mods = fixed_modifications[0]
for f... | magicoder | python |
You are tasked with implementing a non-recursive version of Huffman coding algorithm. Huffman coding is a widely used algorithm for lossless data compression. In this problem, you are required to write a Python function to generate Huffman codes for characters in a given text using a non-recursive approach.
You are gi... | ```python
class HuffmanNode:
def __init__(self, value, frequency):
self.value = value
self.frequency = frequency
self.left = None
self.right = None
def generate_huffman_code_non_recursive(self, word_dict):
# Create Huffman nodes for each character and their frequency
... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.