query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a function to handle configuration changes in a distributed system. The function is responsible for calling a Node actor to propose configuration changes. However, the provided code snippet contains an incomplete implementation of this function. Your task is to complete the implementati... | ```rust
use std::sync::Arc;
use tokio::task::JoinHandle;
// Define the configuration change type
struct ConfigChange {
// Define the structure of a configuration change
// (e.g., change_type, affected_nodes, etc.)
// ...
}
// Define the Node actor type
struct NodeActor {
// Define the structure and be... | magicoder | rust |
You are working on a computer vision project and need to implement a function that filters and returns the largest contours based on their relative areas. The function takes in two arrays: `relative_areas` containing the relative areas of contours and `top_contours` containing the contours themselves. Additionally, the... | ```python
import numpy as np
def filter_largest_contours(relative_areas, top_contours, min_perc_area, max_perc_area):
# Convert input arrays to numpy arrays for efficient computation
relative_areas = np.array(relative_areas)
top_contours = np.array(top_contours)
# Condition to check if area is within ... | magicoder | python |
You are working on a web application for managing insurance policies and user information. The application uses Laravel framework and interacts with a database. Your task is to implement a feature for editing user information. The relevant code snippet from the controller is provided below:
```php
public function edit... | ```php
public function edituser() {
$userId = $this->request->user_id; // Assuming user_id is passed in the request
$data = array(
'name' => $this->request->name,
'surname' => $this->request->surname,
'affiliate_no' => $this->request->affiliate_no,
'nss' => $this->request->nss,
... | magicoder | php |
You are tasked with implementing a Dropdown widget for a user interface library. The Dropdown widget should allow users to select a single option from a list of options. Your task is to design and implement the Dropdown widget class in Rust, ensuring that it can be properly integrated into the existing UI framework.
Y... | ```rust
// Define the Dropdown struct to hold the list of options and the selected option
pub struct Dropdown {
options: Vec<String>,
selected_option: Option<String>,
}
impl Dropdown {
// Create a new instance of Dropdown with the provided list of options
pub fn new(options: Vec<String>) -> Self {
... | magicoder | rust |
You are tasked with implementing a function to handle database connections and data loading. The function should be able to load data from a CSV file into a SQLite database and add meta columns to the database table. Additionally, it should handle the download of data dumps if the source is not a local file.
You are g... | ```python
import sqlite3
class DataHandler:
def __init__(self, csv_template, db_filename, delimiter, roadata, local_file, retries):
self.dbh = self.sql3load(csv_template, db_filename, delimiter, roadata)
self.local_file = local_file
self._retries = retries
self._add_columns() # add... | magicoder | python |
You are tasked with implementing a simple JSON-RPC (Remote Procedure Call) request class in TypeScript. The provided code snippet is a starting point for the `JsonRpcRequest` class, which is used to create JSON-RPC requests. Your task is to complete the implementation of the `JsonRpcRequest` class by adding a method to... | ```typescript
import { UUID } from 'angular2-uuid';
export class JsonRpcRequest {
id: string = UUID.UUID();
method: string;
params: Array<any> = new Array();
constructor(_method: string, _params: any) {
this.method = _method;
this.params.push(_params);
}
toJsonString(): string {
const jsonRpc... | magicoder | typescript |
You are tasked with creating a web application form that allows users to update their profile information. The form is designed to be submitted to the server using the POST method and includes fields for the user's name and an image upload. The form is populated with the user's existing information, and the user's ID i... | ```python
from flask import Flask, request, url_for, redirect, render_template
import os
from werkzeug.utils import secure_filename
app = Flask(__name__)
# Define the allowed image extensions
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
# Function to check if the file extension is allowed
def allowed_file(file... | magicoder | python |
You are tasked with creating a Python program that processes image files based on certain conditions. The program should traverse a directory structure, locate image files, and perform specific operations based on a selected case. The code snippet provided gives a glimpse of the program's functionality. The `get_locati... | ```python
import os
from PIL import Image
def get_location_for_code():
# Implementation of get_location_for_code() function
return "/path/to/home/address"
def select_case():
# Implementation of select_case() function
return 1 # Example: Assume case 1 is selected
def resize_images(directory, dimensio... | magicoder | python |
You are tasked with creating a class hierarchy for a simple game. The game involves players who can have different roles, such as "Attacker" and "Defender". Each player has a name and a level. The "Attacker" players also have an attack power, while the "Defender" players have a defense power. Your task is to create a s... | ```php
// Define the Player class
class Player {
protected $name;
protected $level;
public function __construct($name, $level) {
$this->name = $name;
$this->level = $level;
}
public function getName() {
return $this->name;
}
public function getLevel() {
ret... | magicoder | php |
You are tasked with implementing a reinforcement learning agent that can handle both continuous and discrete action spaces. The agent needs to determine the type of action space and then construct the appropriate neural network architecture based on this determination.
You are provided with a code snippet from the age... | ```python
def _build_network(self):
if self.action_type == "continuous":
actor_encoder = build_actor_encoder(self.arch)
critic_encoder = build_critic_encoder(self.arch)
action_decoder = build_action_decoder(self.arch)
value_decoder = build_value_decoder(self.arch)
return acto... | magicoder | python |
You are tasked with implementing a genetic algorithm to solve a combinatorial optimization problem. In a genetic algorithm, a population of candidate solutions evolves over generations through processes such as selection, crossover, and mutation. The given code snippet represents the crossover operation in the genetic ... | ```python
# Solution for the Traveling Salesman Problem (TSP)
class City:
def __init__(self, x, y):
self.x = x
self.y = y
def distance_to(self, other_city):
return ((self.x - other_city.x) ** 2 + (self.y - other_city.y) ** 2) ** 0.5
class Route:
def __init__(self, cities):
... | magicoder | python |
You are tasked with creating a PHP class to handle the formatting of messages and timestamps for a messaging system. Your class should include methods to set the message content, retrieve the formatted message with timestamp, and retrieve the name of the message poster. The message should be formatted as follows: "Mess... | ```php
class MessageFormatter {
private $message;
private $dateCreated;
private $posterName;
public function setMessage($message) {
$this->message = $message;
}
public function setDateCreated($dateCreated) {
$this->dateCreated = $dateCreated;
}
public function setPoste... | magicoder | php |
You are tasked with implementing a packet routing system for a network communication library. The system should support adding and deleting packet sources, as well as routing packets to the appropriate sources based on their destination IDs.
You are given a partial code snippet for the packet routing system:
```cpp
#... | ```cpp
#include <string>
#include <string_view>
#include <unordered_map>
#include <tl/expected.hpp>
class packet {
public:
struct generic_source {
// Implementation details not shown
};
tl::expected<void, int> add_source(std::string_view src_id, packet::generic_source source) {
if (sources... | magicoder | cpp |
You are tasked with implementing a text processing function that takes a list of strings as input and performs several transformations to clean and format the text. The input data contains paragraphs with sentences separated by " . " and may include unwanted characters such as " @.@ ", " @-@ ", " ,", " '", " )", "( ", ... | ```python
def process_text(data):
data = [x.split(" . ") for x in data if x.strip() and x.strip()[0] != "="] # Step 1
sentences = []
for para in data:
for sent in para:
sentences.append(sent + ".") # Step 2
data = "\n".join(sentences)
data = data.replace(" @.@ ", ".").replace("... | magicoder | python |
You are given a set of data points represented by floating-point numbers. Your task is to implement a class `DataAnalyzer` in C++ that can efficiently process these data points and provide the maximum and minimum values encountered so far.
The class should have the following methods:
1. `DataAnalyzer()`: A constructor... | ```cpp
#include <cfloat>
class DataAnalyzer {
double maxdata;
double mindata;
public:
DataAnalyzer() : maxdata(-DBL_MAX), mindata(DBL_MAX) {}
void addDataPoint(double data) {
if (data > maxdata) {
maxdata = data;
}
if (data < mindata) {
mindata = data;
... | magicoder | cpp |
You are tasked with creating a Python function that interacts with an API endpoint to exchange a default data token. The API endpoint is used for obtaining a new data token by providing the `data_token_bk_app_code` as a parameter. Your function should make a POST request to the specified endpoint and handle the respons... | ```python
import requests
def exchange_data_token(data_token_bk_app_code: str) -> str:
url = "https://api.example.com/auth/tokens/exchange_default_data_token/"
payload = {"data_token_bk_app_code": data_token_bk_app_code}
headers = {"Content-Type": "application/json"}
response = requests.post(url, json... | magicoder | python |
You are tasked with creating a C# program to manage the movement of a virtual mouse within a 2D coordinate system. The program should allow the user to set the position of the mouse and then retrieve its coordinates. To achieve this, you need to define a `Coord` structure and use the `FieldOffset` attribute to ensure t... | ```csharp
using System;
using System.Runtime.InteropServices;
public struct Coord
{
public int X;
public int Y;
}
public class VirtualMouse
{
[FieldOffset(0)]
public Coord MousePosition;
public void SetMousePosition(int x, int y)
{
MousePosition.X = x;
MousePosition.Y = y;
... | magicoder | csharp |
You are tasked with implementing a simplified version of the Apriori algorithm, a popular algorithm for frequent item set mining and association rule learning in data mining. The Apriori algorithm is used to identify frequent item sets in a transaction database and generate association rules based on these item sets.
... | ```python
class Apriori:
@staticmethod
def run(inputFile, minSupport, minConfidence):
# Read transaction data from inputFile and initialize variables
transactions = []
with open(inputFile, 'r') as file:
for line in file:
if line.strip(): # Skip empty lines
... | magicoder | python |
You are tasked with creating a Python function that processes media properties and a coroutine that reads a stream into a buffer. Your task is to implement the function `process_media_properties` and the coroutine `read_stream_into_buffer` based on the given code snippet.
The `process_media_properties` function takes ... | ```python
import asyncio
from typing import Any
from Windows.Storage.Streams import InputStreamOptions, Buffer
async def process_media_properties(current_session: Any) -> dict:
if current_session:
media_props = await current_session.try_get_media_properties_async()
return {
song_attr: m... | magicoder | python |
You are tasked with creating a script to automate a series of mouse and keyboard actions based on input coordinates and values. The script will read input from a file and perform the specified actions using the `xte` command, a utility for simulating keyboard and mouse input.
The input file contains lines in the follo... | ```bash
#!/bin/bash
input_file="input.txt"
temp_file="temp.txt"
# Read input file line by line
while IFS= read -r line || [[ -n "$line" ]]; do
# Extract coordinates from the line
read x1 y1 x2 y2 <<< "$line"
# Calculate the new y coordinate
y=$(expr $y1 + $y2 + 5)
# Simulate keyboard and mouse a... | magicoder | shell |
You are tasked with creating a program that can analyze a given text file and count the occurrences of each unique word. For the purpose of this problem, a word is defined as a sequence of alphanumeric characters, excluding any punctuation or whitespace. The program should be case-insensitive, meaning that "Hello" and ... | ```python
import re
from collections import Counter
from typing import Dict
def count_unique_words(file_path: str) -> Dict[str, int]:
with open(file_path, 'r', encoding='utf-8') as file:
text = file.read().lower() # Read the file and convert the text to lowercase
words = re.findall(r'\b\w+\b', tex... | magicoder | python |
You are tasked with creating a Python function that checks the versions of various libraries and returns a dictionary containing the library names and their corresponding minor version tuples. The function should handle cases where the libraries are not installed or have incompatible versions.
Write a Python function ... | ```python
import cloudpickle
import json_tricks
import yaml
import nni
import sys
import numpy
def version_check() -> dict[str, tuple[int, int] | None]:
def _minor_version_tuple(version: str) -> tuple[int, int] | None:
try:
major, minor, _ = map(int, version.split('.'))
return major... | magicoder | python |
You are tasked with parsing and extracting data from an HTML table. The table contains rows of student information, and each row is represented by a set of `<tr>` and `<td>` tags. The data within the `<td>` tags represents different attributes of the students, such as their ID, name, course, tenant, date, percentage, a... | ```python
from bs4 import BeautifulSoup
html_data = """
</tr>
<tr>
<td data-label="Name">177402120</td>
<td data-label="Age">Course User 100</td>
<td data-label="Age">Sunbird QA Tenant</td>
<td data-label="Age">30/07/19... | magicoder | python |
You are given a list of non-negative integers representing the amount of money of each house. The houses are arranged in a circle, meaning the first house is adjacent to the last house. You are not allowed to rob adjacent houses. The goal is to determine the maximum amount of money you can rob without alerting the poli... | ```python
from typing import List
def maxRobbery(nums: List[int]) -> int:
def rob(nums: List[int], start: int, end: int) -> int:
if start == end:
return nums[start]
prev, curr = 0, 0
for i in range(start, end):
prev, curr = curr, max(curr, prev + nums[i])
ret... | magicoder | python |
You are tasked with implementing a function that processes a given style object and returns a new object containing only the properties that have numerical values. The style object is represented as a JavaScript object, where each key represents a CSS property and its value represents the corresponding style value. The... | ```javascript
function filterNumericStyles(style) {
const numericStyles = {};
for (const key in style) {
if (typeof style[key] === 'number') {
numericStyles[key] = style[key];
} else if (!isNaN(parseFloat(style[key]))) {
numericStyles[key] = parseFloat(style[key]);
... | magicoder | javascript |
You are tasked with implementing a password reset feature for a web application. The application has a `ForgotPasswordViewModel` class that is responsible for handling the data related to the password reset process. The `ForgotPasswordViewModel` class has a method `SendPasswordResetEmail` that sends a password reset em... | ```csharp
using System;
using System.Net;
using System.Net.Mail;
using System.Text;
public class ForgotPasswordViewModel
{
private const int TokenLength = 10;
public void SendPasswordResetEmail(string userEmail)
{
string token = GenerateRandomToken(TokenLength);
string resetLink = $"https:... | magicoder | csharp |
You are tasked with creating a function that parses a GraphQL query string and extracts the names of all the fields present in the query. The GraphQL query string will be provided as input to your function. You need to implement a function `extractFields` that takes a GraphQL query string as input and returns a list of... | ```javascript
import gql from 'graphql-tag';
function extractFields(queryString) {
const document = gql(queryString);
const fieldNames = [];
function extractFieldsFromSelectionSet(selectionSet) {
for (const selection of selectionSet.selections) {
if (selection.kind === 'Field') {
fieldNames.pu... | magicoder | javascript |
You are tasked with creating a program that analyzes a given text file to count the occurrences of each unique word. The program should ignore punctuation and consider words regardless of their case (i.e., "Word" and "word" should be considered the same). Additionally, the program should exclude common stop words such ... | ```python
import re
from collections import Counter
# Read the input text file
with open('input.txt', 'r') as file:
text = file.read().lower() # Convert text to lowercase
# Read the stop words file
with open('stopwords.txt', 'r') as file:
stop_words = file.read().split()
# Remove punctuation and split the t... | magicoder | python |
You are tasked with implementing a Python class that handles search results and supplied data from different datamarts. The class should have an initializer method that takes in several parameters and initializes instance variables accordingly.
You are given the following code snippet as a starting point:
```python
"... | ```python
import logging
import typing
from d3m import DataFrame as d3m_DataFrame, Dataset as d3m_Dataset
class DatamartHandler:
def __init__(self, search_result: dict,
supplied_data: typing.Union[d3m_DataFrame, d3m_Dataset, None],
query_json: dict, search_type: str, connection_ur... | magicoder | python |
You are working on a natural language processing (NLP) project and need to implement a convolutional neural network (CNN) for text classification. You have a code snippet that sets up the convolutional layer using TensorFlow, but you need to understand and manipulate the parameters to achieve the desired output.
Given... | ```python
import tensorflow as tf
def calculate_output_shape(input_shape, desired_output_shape):
batch_size, sequence_length, embedding_size, _ = input_shape
output_height, output_width, num_filters = desired_output_shape[1:]
# Calculate the value of n based on the input sequence length and desired output... | magicoder | python |
You are tasked with creating a program that utilizes TensorFlow to build a simple neural network for image classification. The program should load a pre-defined hyperparameters configuration from the `hparams_config` module and use it to construct the neural network model. The model should then be trained on a given da... | ```python
import tensorflow.compat.v1 as tf
import hparams_config
import numpy as np
# Step 1: Load hyperparameters configuration
hyperparams = hparams_config.load_hyperparameters()
# Step 2: Define input placeholders
input_shape = (None, hyperparams['input_size'])
output_shape = (None, hyperparams['output_classes'])... | magicoder | python |
You are given a code snippet that performs matrix multiplication using nested loops. Your task is to implement a parallel version of matrix multiplication using the concept of message passing interface (MPI) in C++.
You need to write a program that distributes the matrix multiplication task among multiple processes us... | ```cpp
#include <iostream>
#include <fstream>
#include <vector>
#include <mpi.h>
#define SZ 100 // Define the size of the matrices
int main(int argc, char *argv[]) {
int rank, size;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
if (argc != 2) ... | magicoder | cpp |
You are tasked with creating a Python class that interacts with an external API to perform various operations. The class should inherit from the `App` class and implement specific functionality using the `requests` library for making HTTP requests, `json` for handling JSON data, and other relevant modules.
Your task i... | ```python
from app import App
import requests
import json
import polling2
from behave import step
from openshift import Openshift
from util import substitute_scenario_id
from string import Template
class GenericTestApp(App):
def get_request(self, url):
try:
response = requests.get(url)
... | magicoder | python |
You are tasked with implementing a Gaussian Mixture Model (GMM) using the `viDKL` algorithm to fit and predict on a given dataset. The `viDKL` function takes in the dimensionality of the input data and returns a GMM model. The `fit_predict` method of the GMM model fits the model to the training data and predicts the cl... | ```python
from sklearn.mixture import GaussianMixture
import numpy as np
def viDKL(dim):
# Define and return a Gaussian Mixture Model with 3 components
return GaussianMixture(n_components=3, covariance_type='full', random_state=42)
def get_dummy_vector_data():
# Generate and return dummy vector data for t... | magicoder | python |
You are tasked with implementing a two-factor authentication (2FA) system for a web application. The code snippet provided is a part of the implementation. The `create2FA` method is called on a user object, passing the private key stored in the `$_SESSION` superglobal. Additionally, a check is performed to start a sess... | ```php
class User {
public function create2FA($privateKey) {
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
// Generate a unique one-time code using the private key and a secure hashing algorithm
$oneTimeCode = hash('sha256', $privateKey . uniqid());
... | magicoder | php |
You are given a 2D array representing a grid of cells. Each cell can be either alive (denoted by 1) or dead (denoted by 0). Your task is to write a function that takes this grid as input and returns a new grid representing the next state of the cells according to the following rules:
1. Any live cell with fewer than tw... | ```python
def nextGeneration(grid):
rows = len(grid)
cols = len(grid[0])
new_grid = [[0 for _ in range(cols)] for _ in range(rows)]
for i in range(rows):
for j in range(cols):
live_neighbors = 0
for x in range(max(0, i-1), min(rows, i+2)):
for y in range(... | magicoder | python |
You are working on a software project that involves handling a large number of configuration parameters. These parameters are used to control various aspects of the software's behavior. To manage these parameters effectively, you decide to implement a configuration parser that can read and process the parameters from a... | ```python
def parse_config_file(config_file: str, prefix: str) -> dict:
parameter_values = {}
with open(config_file, 'r') as file:
for line in file:
key, value = line.strip().split()
if key.startswith(prefix):
parameter_number = key[len(prefix):]
p... | magicoder | python |
You are tasked with creating a custom DataTableComponent using the Rappasoft\LaravelLivewireTables package in a Laravel application. Your DataTableComponent should display a list of products with their names, prices, and categories. Additionally, you need to implement sorting and searching functionality for the DataTab... | ```php
use Rappasoft\LaravelLivewireTables\DataTableComponent;
use Rappasoft\LaravelLivewireTables\Views\Column;
use App\Models\Product;
class ProductDataTable extends DataTableComponent
{
public $sortField = 'name'; // Default sorting field
public function columns(): array
{
return [
... | magicoder | php |
You are working for a company that is integrating the Braintree payment gateway into its e-commerce platform. Your task is to create a script that securely loads the necessary configuration settings from a `.env` file and sets up the Braintree SDK with the appropriate credentials. The `.env` file contains sensitive inf... | ```php
<?php
require_once 'vendor/autoload.php'; // Include the Composer autoloader
use Dotenv\Dotenv;
use Braintree\Configuration as Braintree_Configuration;
// Load environment variables from the .env file
$dotenv = new Dotenv(__DIR__);
$dotenv->load();
// Set up the Braintree SDK with the environment, merchant ID... | magicoder | php |
You are given a JSON file containing geographical data for various locations. Each location entry consists of the following fields: "longitude", "latitude", "county", and "stateCode". Your task is to write a Python function that takes this JSON data as input and returns a list of dictionaries containing only the "count... | ```python
def filter_locations(json_data: dict, threshold: float) -> list:
filtered_locations = []
for location in json_data["locations"]:
abs_diff = abs(location["longitude"] - location["latitude"])
if abs_diff > threshold:
filtered_locations.append({"county": location["county"], "s... | magicoder | python |
You are tasked with implementing a custom extension for the UIButton class in Swift. The extension should add a method that allows the button to display a pulsating animation when tapped.
Your task is to create the `addPulsatingAnimation` method within the `UIButton` extension. The method should animate the button by ... | ```swift
public extension UIButton {
func addPulsatingAnimation() {
let pulseAnimation = CABasicAnimation(keyPath: "transform.scale")
pulseAnimation.duration = 0.5
pulseAnimation.fromValue = 1.0
pulseAnimation.toValue = 1.2
pulseAnimation.timingFunction = CAMediaTimingFunctio... | magicoder | swift |
You are tasked with implementing a file transfer protocol using Python's socket library. Your goal is to create a server-side program that can receive a file sent from a client over a UDP connection and save it to a specified path on the server. The server should handle potential timeouts during the file transfer proce... | ```python
import socket
class FileTransferServer:
def __init__(self, host, port, save_path):
self.host = host
self.port = port
self.save_path = save_path
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.bind((self.host, self.port))
self.receive_... | magicoder | python |
You are tasked with creating a Python function that processes a list of strings and returns a dictionary containing the frequency of each unique word in the list. The function should ignore case sensitivity and consider only alphanumeric characters when identifying words. Additionally, the function should exclude any c... | ```python
import re
from collections import Counter
def word_frequency(input_list):
stop_words = set(["the", "and", "in", "of", "a", "an", "is", "are", "to", "for", "on", "at", "by", "with", "from"])
word_count = Counter()
for sentence in input_list:
words = re.findall(r'\b\w+\b', sentence.low... | magicoder | python |
You are tasked with implementing a compression algorithm for a custom data structure. The algorithm operates on a state and an input block, and it involves several steps of XOR operations and function calls. Your goal is to understand the given code snippet and implement the `compress` method for the data structure.
T... | ```rust
impl YourDataStructure {
pub fn compress(&mut self, input_block: &GenericArray<u8, BlockSize>) {
// Step 1: XOR the state with the input_block
let step1_result = xor_generic_array(&self.state, input_block);
// Step 2: Call the function p with the result of step 1 and XOR the result ... | magicoder | rust |
You are tasked with creating a Python class to manage and export entity data in the DXF (Drawing Exchange Format) file format. The provided code snippet is a part of a larger class that handles the export of entity data. Your task is to complete the implementation of the `export_entity` method and ensure that it correc... | ```python
def export_entity(self, tagwriter: 'TagWriter') -> None:
super().export_entity(tagwriter)
# AcDbEntity export is done by parent class
if tagwriter.dxfversion > DXF12:
tagwriter.write_tag2(SUBCLASS_MARKER, acdb_symbol_table_record.name)
tagwriter.write_tag2(SUBCLASS_MARKER, acdb_sty... | magicoder | python |
You are tasked with implementing a gRPC server for a machine learning model using Python. The server will receive requests containing features, and it should use a pre-trained KMeans model to predict the cluster index for the given features. Your task is to complete the implementation of the `Predict` method and the `s... | ```python
# Import necessary libraries
import grpc
import numpy as np
from concurrent import futures
from sklearn.cluster import KMeans
from generated_code import prediction_pb2_grpc
from generated_code.prediction_pb2 import PredictResponse
class PredictionService(prediction_pb2_grpc.PredictionServicer):
def __ini... | magicoder | python |
You are tasked with designing a system to manage compute resources for a stamp processing application. The system should be able to allocate resources to different tasks and track the usage of these resources. To achieve this, you need to implement a class structure in TypeScript that represents the compute resources a... | ```typescript
// Define the StampComputeResources class
class StampComputeResources {
// Define properties
// ...
// Define the one-to-many relationship with StampTask
@OneToMany(() => StampTask, stampTask => stampTask.resourceType2)
stampTasks: StampTask[];
}
// Define the StampTask class
class StampTask {... | magicoder | typescript |
You are tasked with implementing a network discovery system that utilizes Python's `yield` keyword and socket communication. The system consists of a function that yields discovery sources and a receiver function that processes these sources.
The `yield` keyword is used to produce a series of DiscoverySource objects, ... | ```python
import socket
import queue
from typing import NamedTuple
class DiscoverySource(NamedTuple):
interface_name: str
src_address: str
dst_address: str
dst_is_broadcast: bool
def receiver(sock: socket.socket, max_discovery_secs: float,
response_queue: queue.Queue) -> None:
start_t... | magicoder | python |
You are given a list of integers. Your task is to write a Python program that takes the input list, raises each integer to the power of 5, multiplies all the results together, and then prints the final product.
Your program should follow these steps:
1. Accept a space-separated list of integers as input.
2. Raise each... | ```python
from functools import reduce
# Step 1: Accept a space-separated list of integers as input
input_list = list(map(int, input().split()))
# Step 2: Raise each integer to the power of 5
powered_list = list(map(lambda x: x**5, input_list))
# Step 3: Multiply all the results together
final_product = reduce(lambd... | magicoder | python |
You are tasked with creating a program to validate user passwords based on certain criteria. The program should prompt the user to enter a password and then determine if it meets the specified requirements. If the password does not meet the criteria, the program should display an error message. The password validation ... | ```python
def validate_password(password):
if len(password) < 8:
return False
has_uppercase = any(char.isupper() for char in password)
has_lowercase = any(char.islower() for char in password)
has_digit = any(char.isdigit() for char in password)
return has_uppercase and has_lowercase and has_... | magicoder | python |
You are given a snippet of code that represents the iterative process of solving a linear system of equations using the Conjugate Gradient method. The code snippet uses NumPy for array operations and assumes the existence of variables `p`, `r`, `rsold`, `T`, `A`, `x`, and `alpha`. The variables `A`, `p`, `r`, and `x` a... | ```python
import numpy as np
def conjugate_gradient(A, b, T):
x = np.zeros_like(b) # Initialize the solution vector
r = b - A @ x # Calculate the initial residual
p = r # Set the initial search direction
rsold = np.sum(r * r) # Calculate the squared norm of the residual
for i in range(T):
... | magicoder | python |
You are working on a reinforcement learning framework that involves multiple agents interacting with an environment. The code snippet provided is a part of the training process for these agents. The `multi_agent` and `multi_agent_other` objects are used to handle the learning and training of the agents. The `to_tensor`... | ```python
import numpy as np
from typing import List, Tuple
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import OneHotEncoder
def preprocess_data(states: List[List[float]], actions: List[int]) -> Tuple[np.ndarray, np.ndarray]:
# Normalize the states
scaler = StandardScaler()
... | magicoder | python |
You are tasked with implementing a social media platform's user follow/unfollow functionality. The platform has a `User` class with a property `isFollowed` indicating whether the current user is following the user in question. The `UserService` class provides methods to follow and unfollow users. When a user is followe... | ```swift
class UserService {
static let shared = UserService()
func followUser(uid: String, completion: @escaping (Error?, DatabaseReference) -> Void) {
// Assume userExists method checks if the user with given uid exists
if userExists(uid: uid) {
// Perform follow operation
... | magicoder | swift |
You are tasked with implementing a function that assembles an elliptic matrix for a finite element method. The function takes in various input parameters and constructs the matrix based on the provided data. Your goal is to write a function that correctly assembles the elliptic matrix based on the given input.
The fun... | ```rust
fn assemble_elliptic_matrix(
element_matrix: &mut DMatrix<f64>,
element: &Element,
operator: &Operator,
u_element: &DVector<f64>,
weights: &DVector<f64>,
points: &DMatrix<f64>,
parameters: &Parameters,
gradient_buffer: &mut DMatrix<f64>,
) {
// Implement the assembly of the e... | magicoder | rust |
You are tasked with implementing a function that reads text from a file and returns a set of unique characters present in the text. However, the function should handle Unicode decoding errors gracefully. If a Unicode decoding error occurs, the function should retry decoding the text using the 'latin1' encoding. If the ... | ```python
def read_and_return_unique_chars(filename):
try:
with open(filename, 'r') as infile:
text = ''.join(infile)
except UnicodeDecodeError:
try:
with open(filename, 'r', encoding='latin1') as infile:
text = ''.join(infile)
except Exception as ... | magicoder | python |
You are tasked with implementing a function that converts a given icon name into its corresponding Unicode representation. The function should take a string representing the icon name and return the Unicode representation of the icon.
For example, given the icon name "arrow_back", the function should return the Unicod... | ```python
def iconToUnicode(iconName):
icon_map = {
"arrow_back": "\u2190",
"check_circle": "\u2713",
# Add more icon mappings as needed
}
return icon_map.get(iconName, "Icon not found")
```
The `iconToUnicode` function uses a dictionary `icon_map` to store the icon names as keys an... | magicoder | python |
You are tasked with implementing a `rational_cast` function that converts a floating-point number to a rational number represented as a pair of integers (numerator and denominator). The `rational_cast` function should take a floating-point number as input and return a pair of integers representing the equivalent ration... | ```cpp
#include <iostream>
#include <utility>
int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
std::pair<int, int> rational_cast(double value) {
const double EPSILON = 1e-9; // Small value to compare floating-point numbers
int sign... | magicoder | cpp |
You are tasked with implementing a task management system that involves creating, deleting, and reviving tasks. The system uses a caching mechanism to store task information. The code snippet provided is a part of the test suite for this task management system. The snippet includes assertions and operations related to ... | To handle the revival of a task in the task management system, you can create a method named `revive_task` within the task management class. This method should perform the following steps:
```python
def revive_task(self, task_id):
# Revive the task
shotgun.revive('Task', task_id) # Assuming there is a revive ... | magicoder | python |
You are given a bash script that contains a snippet of code. Your task is to analyze the code and identify the missing parts to make it functional. The code snippet is as follows:
```bash
fi
done
echo
echo "done"
fi
```
Your task is to complete the missing parts of the bash script to ensure that it executes cor... | ```bash
#!/bin/bash
# Define a list of items
items=("item1" "item2" "item3")
# Iterate through the list of items
for item in "${items[@]}"; do
# Check a condition for each item and execute a block of code if the condition is met
if [ condition ]; then
# Add the code to be executed if the condition is ... | magicoder | shell |
You are tasked with implementing a simple event handling system for a mobile application. The application has two events, `applicationDidEnterBackground` and `applicationWillEnterForeground`, which are triggered when the application enters the background and when it enters the foreground, respectively. Your goal is to ... | ```swift
class ApplicationEventManager {
var backgroundHandlers: [() -> Void] = []
var foregroundHandlers: [() -> Void] = []
func registerHandler(eventType: String, handler: @escaping () -> Void) {
switch eventType {
case "background":
backgroundHandlers.append(handler)
... | magicoder | swift |
You are tasked with implementing a custom neural network layer and loss function in PyTorch for a specific use case. The provided code snippet contains a simplified version of a PyTorch model with a custom layer and loss function. Your task is to extend this code to create a custom neural network module and loss functi... | ```python
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.transforms as transforms
import torchvision.datasets as datasets
# Define the custom neural network module
class CustomLayer(nn.Module):
def __init__(self, input_dim, output_dim):
super(CustomLayer, self).__init... | magicoder | python |
You are tasked with implementing a function that calculates a range proof for a confidential transaction. A range proof is a cryptographic proof that a value lies within a specified range without revealing the exact value. The function `confidential.rangeProofWithNonceHash` takes several parameters and returns the rang... | ```javascript
const confidential = require('confidential-library'); // Assuming the library for range proof calculation is imported
async function calculateRangeProof(f) {
const rangeProof = await confidential.rangeProofWithNonceHash(
f.value,
Buffer.from(f.blindingPubkey, 'hex'),
Buffer.from(f.ephemeral... | magicoder | javascript |
You are tasked with implementing a custom transformation function for a data processing framework. The function takes a key-value pair as input and performs a transformation on the values associated with the key. The input key-value pair consists of a key of type `REDUCE_KEY` and an iterator of tagged writable values o... | ```java
public void transform(KeyValue<REDUCE_KEY, Iterator<TaggedWritable<REDUCE_VALUE>>> input,
Emitter<OUT> emitter) throws Exception {
JOIN_KEY joinKey = keyConversion.fromWritable(input.getKey()); // Convert input key to JOIN_KEY
Iterator<JoinElement<INPUT_RECORD>> inputIterator = Iterato... | magicoder | java |
You are working on a program that processes 3D triangles represented by their vertices in the form of `glm::vec3` objects. Each triangle is defined by three vertices: `a`, `b`, and `c`. Your task is to implement a function that calculates the centroid of each triangle.
You are given the following code snippet as a ref... | ```cpp
#include <glm/glm.hpp>
glm::vec3 calculateCentroid(const glm::vec3& a, const glm::vec3& b, const glm::vec3& c) {
float x = (a.x + b.x + c.x) / 3.0f;
float y = (a.y + b.y + c.y) / 3.0f;
float z = (a.z + b.z + c.z) / 3.0f;
return glm::vec3(x, y, z);
}
// Usage
glm::vec3 centroid1 = calculateCentr... | magicoder | cpp |
You are tasked with implementing a function to perform a binary operation on two matrices and then compare the result with another matrix. The matrices are represented using the `fcppt::math::matrix` data structure, and the binary operation is performed using the `fcppt::math::matrix::binary_map` function.
You are giv... | ```cpp
#include <fcppt/math/matrix/make.hpp>
#include <fcppt/math/matrix/object_impl.hpp>
#include <fcppt/math/matrix/static.hpp>
#include <fcppt/math/matrix/structure_cast.hpp>
#include <fcppt/math/matrix/dim.hpp>
#include <fcppt/math/matrix/at_c.hpp>
#include <fcppt/math/matrix/binary_map.hpp>
#include <fcppt/math/ma... | magicoder | cpp |
You are tasked with implementing a custom node class for a comparison operation in a programming language that supports object-oriented programming. The provided code snippet is a constructor for the custom node class, which takes an array of context as a parameter. Your task is to complete the implementation of the cu... | ```php
/**
* Custom node class for comparison operation.
*/
class CompareNode extends Node
{
const COMPARE_TYPE = 'compare';
/**
* New Compare node instance.
*
* @param array $context
*/
public function __construct(array $context = [])
{
parent::__construct(self::COMPARE_T... | magicoder | php |
You are tasked with creating a Python script that generates a `setup.py` file for a Django package based on the given code snippet. The `setup.py` file is used to package and distribute Python projects. Your script should use the provided variables to construct the necessary metadata for the package, including the pack... | ```python
def generate_setup_py(PACKAGE_NAME, INSTALL_REQUIRES, KEYWORDS, CLASSIFIERS):
setup_content = f"""
from setuptools import setup
GITHUB_URL = "https://github.com/alexseitsinger/{PACKAGE_NAME}"
HOMEPAGE_URL = GITHUB_URL
README_NAME = "README.md"
setup(
name="{PACKAGE_NAME}",
version="1.0.0",
u... | magicoder | python |
You are tasked with implementing a program that processes HTML table data to calculate the total number of items in a specific column. The input will be a string representing an HTML table, and the output should be the total count of items in the specified column.
You are given the following HTML table snippet as an e... | ```python
from bs4 import BeautifulSoup
def calculateColumnTotal(htmlTable, columnName):
soup = BeautifulSoup(htmlTable, 'html.parser')
column_values = [td.text for td in soup.find_all('td', string=True)]
column_index = [th.text for th in soup.find_all('th')].index(columnName)
column_values = column_va... | magicoder | python |
You are tasked with implementing a function that applies an OData query to a Django QuerySet. OData is a protocol for querying and updating data, and it uses a specific syntax for filtering, sorting, and selecting data. Your function should take a Django QuerySet and an OData query string as input, and return the filte... | ```python
from django.db.models import Q
def apply_odata_query(queryset, odata_query):
filters = {}
order_by = []
# Parsing the OData query string
query_options = odata_query.split('&')
for option in query_options:
key, value = option.split('=')
if key == '$filter':
# P... | magicoder | python |
You are tasked with creating a Python program that simulates a simple file system. The file system will consist of files and directories, and you need to implement the necessary classes and methods to manage and manipulate these entities.
Your task is to create a Python class called `FileSystem` that represents the fi... | ```python
class FileObject:
def __init__(self, name, content):
self.name = name
self.content = content
class DirectoryObject:
def __init__(self, name):
self.name = name
self.contents = []
class FileSystem:
def __init__(self):
self.root = DirectoryObject('root')
... | magicoder | python |
You are tasked with implementing a class hierarchy for a simple web page header system. The system should support different types of page headers, each with its own specific behavior. Your task is to define the necessary classes and methods to achieve this functionality.
You are provided with a code snippet that initi... | ```csharp
// Define the base class PageHeaderBase
public class PageHeaderBase
{
public virtual string GetPageType(string page)
{
// Default implementation returns "Unknown" type
return "Unknown";
}
}
// Define a derived class for specific type of page header - HeaderType1
public class Heade... | magicoder | csharp |
You are tasked with implementing a function to upsample or point-sample audio data based on certain conditions. The provided code snippet is part of a larger audio processing system and contains a conditional block that determines whether to use a high-quality upsampling function or a point-sampling function based on t... | ```cpp
// Function for high-quality upsampling
void* upsampleRout(void* buffer, void* cbuffer, void* accum, float samp_frac, int dstSamples) {
// Implement high-quality upsampling logic here
// Example:
// Perform high-quality upsampling using interpolation or filtering techniques
// Update the accum va... | magicoder | cpp |
You are tasked with creating a Python function that extracts and returns the names of all the test files present in a given GitHub repository. The function should take the repository name as input and return a list of test file names.
You are provided with a code snippet from a GitHub repository as an example:
```
<re... | ```python
import requests
from typing import List
def extract_test_files(repo_name: str) -> List[str]:
url = f"https://api.github.com/repos/{repo_name}/contents"
response = requests.get(url)
if response.status_code == 200:
test_files = [file["name"] for file in response.json() if file["name"].start... | magicoder | python |
You are tasked with implementing a simple locking mechanism using Python's multiprocessing and threading modules. The provided code snippet is a part of a class method that is responsible for acquiring a lock. The class has an attribute `is_locked` which indicates whether the lock is currently acquired or not. Your tas... | ```python
import os
import time
import threading
class LockManager:
def __init__(self, id):
self.id = id
self.is_locked = False
self.lock = threading.Lock()
def acquire_lock(self):
start_time = time.time()
pid = os.getpid()
checkString = "<" + str(pid) + "." + s... | magicoder | python |
You are tasked with creating a filtering mechanism for a web application that displays investment opportunities. The code snippet provided is a part of a Django view that handles the filtering of investment opportunities based on query parameters. The view receives query parameters for "ville" (city), "etat_d_avancemen... | ```python
from typing import List
class InvestmentOpportunity:
def __init__(self, ville, etat_d_avancement):
self.ville = ville
self.etat_d_avancement = etat_d_avancement
def filter_investment_opportunities(query_params: dict, queryset: List[InvestmentOpportunity]) -> List[InvestmentOpportunity]:
... | magicoder | python |
You are tasked with creating a Python class that manages conference configurations and entities within a home automation system. The class should handle processing configuration settings, creating and updating entities, and retrieving entity states. Your task is to implement the missing methods of the `ConferenceManage... | ```python
class Entity:
def __init__(self):
self.entity_id = ''
self.hass = None
def update_ha_state(self):
# Implementation to update the state of the entity in the home automation system
pass
class ConferenceManager:
def __init__(self, longitude, name):
self.long... | magicoder | python |
You are tasked with implementing a function that retrieves the topmost view controller from a given view controller hierarchy. The view controller hierarchy can consist of UINavigationController and UITabBarController instances, and the function should handle these cases appropriately.
You are to write a Swift functi... | ```swift
func topViewController(_ vc: UIViewController?) -> UIViewController? {
if let navController = vc as? UINavigationController {
return topViewController(navController.topViewController)
} else if let tabController = vc as? UITabBarController {
return topViewController(tabController.select... | magicoder | swift |
You are tasked with creating a Python class to interface with an Analog-to-Digital Converter (ADC) using the Industrial I/O (IIO) interface on a Linux-based system. The provided code snippet is a part of the class method that attempts to open a file representing the raw analog voltage value for a specific ADC channel. ... | ```python
class ADCInterface:
def __init__(self, adc_iio_device):
self.adc_iio_device = adc_iio_device
self.gpio_handlers = {}
def open_adc_channel(self, adc, linux_pin):
try:
file_path = '/sys/bus/iio/devices/iio:device%d/in_voltage%d_raw' % (self.adc_iio_device, adc)
... | magicoder | python |
You are tasked with implementing a function that can read a GUID (Globally Unique Identifier) from a given input string. A GUID is a 128-bit identifier often used in software development for uniquely identifying information. The input string may contain multiple GUIDs, and your function should be able to extract and re... | ```csharp
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
public class GuidExtractor
{
public List<string> ReadGuids(string input)
{
List<string> extractedGuids = new List<string>();
// Define the pattern for matching a GUID
string pattern = @"\b[a... | magicoder | csharp |
You are given a 2D grid representing a game board. Each cell in the grid can be either an open space (denoted by 1) or an obstacle (denoted by 0). The objective is to find the shortest path from the top-left corner of the grid to the bottom-right corner, moving only through open spaces. You can move in four directions:... | ```python
from typing import List
from collections import deque
def shortestPath(grid: List[List[int]]) -> int:
rows, cols = len(grid), len(grid[0])
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
queue = deque([(0, 0, 1)]) # (row, col, path_length)
while queue:
row, col, path_length = queue.... | magicoder | python |
You are tasked with implementing a macro expansion system for a C++ codebase. The given code snippet demonstrates a series of macro definitions that are used to generate member variables within a class. Each `BOOST_MOVE_MREF` macro is used to define a member variable with a specific name, and the number at the end of t... | ```cpp
#define BOOST_MOVE_MREF(name) int name;
#define EXPAND_CLASS(classname, num_members) \
struct classname { \
BOOST_MOVE_MREF##num_members \
};
// Usage example
EXPAND_CLASS(MyClass, 4)
```
When the `EXPAND_CLASS` macro is used with the desired class name and the number of member variables, it e... | magicoder | cpp |
You are tasked with designing a URL routing system for a social networking platform. The platform has user profiles and a review feature. The given code snippet represents a part of the URL configuration for the platform using Django's URL patterns.
The URL patterns are as follows:
1. A URL pattern for viewing a user'... | The missing URL patterns can be added as follows:
```python
# Delete profile URL
url(r'^profile/(?P<slug>[-\w]+)/delete/$', SocialProfileDeleteView.as_view(), name='delete'),
# List all reviews for a profile
url(r'^reviews/(?P<slug>[-\w]+)/all/$', ReviewListView.as_view(), name='all_reviews'),
```
In... | magicoder | python |
You are tasked with implementing a function that calculates the distance between two points in a hexagonal grid. The hexagonal grid is represented using the axial coordinate system, and the distance between two points is defined as the minimum number of steps required to move from one point to the other, considering on... | ```rust
pub fn hex_distance(q1: i32, r1: i32, q2: i32, r2: i32) -> i32 {
((q2 - q1).abs() + (q2 + r2 - q1 - r1).abs() + (r2 - r1).abs()) / 2
}
``` | magicoder | rust |
You are tasked with creating a Python function that generates a command for synchronizing files and directories using the `rsync` utility. The function should take in the source path, destination path, and an optional flag for relative synchronization. The generated command should include options for deleting extraneou... | ```python
def generate_rsync_command(from_path: str, to_path: str, relative: bool = False) -> str:
cmd = [
"rsync",
"--delete",
"--info=progress2",
"--times",
from_path,
to_path
]
if relative:
cmd.append("--relative")
return " ".join(cmd)
```
... | magicoder | python |
You are tasked with implementing a quantum circuit simulator in Python. Quantum circuits are composed of quantum registers, which are collections of qubits. Each qubit can be in a superposition of states and can be entangled with other qubits. Your task is to create a class `QuantumRegister` that represents a quantum r... | ```python
import numpy as np
class Qubit:
def __init__(self):
self.state = np.array([1, 0]) # Initialize qubit in |0> state
def apply_gate(self, gate_matrix):
self.state = np.dot(gate_matrix, self.state) # Apply gate to the qubit
def measure(self):
probabilities = np.abs(self.st... | magicoder | python |
You are tasked with implementing a class that represents a user's location data. The class should include properties for the user ID, location ID, data version, creation and modification timestamps, and the creator's name. Additionally, you need to create a method that calculates the time difference between the creatio... | ```csharp
using System;
public class UsersLocation
{
public string UserId { get; set; }
public string LocationId { get; set; }
public int DataVersion { get; set; }
public DateTime CreatedUtcDate { get; set; }
public string CreatedBy { get; set; }
public DateTime ModifiedUtcDate { get; set; }
... | magicoder | csharp |
You are tasked with developing a configuration file parser for a static site generator tool. The configuration file contains various settings that dictate the behavior and appearance of the generated website. Your task is to implement a function that parses the configuration file and extracts specific settings based on... | ```python
def parse_config_file(file_path):
settings = {}
try:
with open(file_path, 'r') as file:
for line in file:
key_value = line.strip().split('=')
if len(key_value) == 2:
key = key_value[0].strip()
value = key_value... | magicoder | python |
You are tasked with implementing a simple arithmetic expression parser in Java. Your task is to create a class `Add` that represents an addition operation and parse a given string input to evaluate the addition expression.
The `Add` class has two instance variables `left` and `right` representing the left and right op... | ```java
public class Add {
public String left;
public String right;
public static Add parse(String input) {
String[] parts = input.split("\\s*\\+\\s*");
if (parts.length != 2) {
throw new IllegalArgumentException("Invalid input format");
}
Add a = new Add();
... | magicoder | java |
You are tasked with implementing a Python class that simulates a simple banking system. The class should have methods to deposit funds, withdraw funds, and check the account balance. Additionally, the class should support the concept of an overdraft limit, which allows the account to temporarily have a negative balance... | ```python
class BankAccount:
def __init__(self, account_holder, initial_balance=0, overdraft_limit=0):
self.account_holder = account_holder
self.balance = initial_balance
self.overdraft_limit = overdraft_limit
def deposit(self, amount):
self.balance += amount
def withdraw(s... | magicoder | python |
You are tasked with implementing a function that calculates the distance between two points in a multi-dimensional space. The points are represented as arrays of numbers, where each element in the array corresponds to the coordinate along a specific axis. For example, in a 3-dimensional space, a point would be represen... | ```typescript
export type Addr = number[];
function calculateDistance(point1: Addr, point2: Addr): number {
if (point1.length !== point2.length) {
throw new Error("Points must have the same number of dimensions");
}
let sumOfSquares = 0;
for (let i = 0; i < point1.length; i++) {
sumOfSquares += Math.p... | magicoder | typescript |
You are working on a bioinformatics pipeline that processes RNA-seq data using the Biowdl framework. The provided code snippet is a shell command that runs the pipeline using Cromwell, a workflow management system. The command uses a configuration file, a Cromwell JAR file, input JSON file, pipeline script, and a log f... | ```python
import re
def parse_cromwell_command(command):
file_paths = {}
pattern = r'(-Dconfig\.file=|jar )([^ ]+)'
matches = re.findall(pattern, command)
for match in matches:
if match[0] == '-Dconfig.file=':
file_paths["CONFIG"] = match[1]
else:
file_paths["JAR... | magicoder | python |
You are working on a Python project that involves importing custom classes from a module. The project structure includes a package with the following layout:
```
project/
│
├── package/
│ ├── __init__.py
│ ├── auto_class.py
│ └── custom/
│ ├── __init__.py
│ └── my_classes.py
```
The `auto_class.py` ... | ```python
# auto_class.py
from package.custom.my_classes import MyClass, MultiContainer
def get_class(class_name):
# Dynamically load the specified class
if class_name == 'MyClass':
return MyClass()
else:
raise ValueError(f"Class '{class_name}' not found")
def get_multi_container():
#... | magicoder | python |
You are tasked with implementing a custom `FileObjectHolder` class that encapsulates a file object and provides methods for hashing and string representation. The class should override the `hashCode` method to return the hash code of the encapsulated file object and the `toString` method to return a string representati... | ```java
import java.io.File;
public class FileObjectHolder {
private File file;
public FileObjectHolder(File file) {
this.file = file;
}
@Override
public int hashCode() {
return file.hashCode();
}
@Override
public String toString() {
return "FileObjectHolder("... | magicoder | java |
You are tasked with designing a system for scheduling and executing periodic tasks using a thread pool in Rust. The system should allow for the execution of a specific task at fixed intervals, and it should be able to handle concurrent execution of multiple tasks.
Your task is to implement a function `schedule_periodi... | ```rust
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
struct ScheduledTask {
handle: thread::JoinHandle<()>,
}
struct ThreadPool {
// Assume the implementation of a thread pool with necessary methods
}
impl ThreadPool {
fn execute_with_fixed_delay<F>(&self, initial_delay: Duratio... | magicoder | rust |
You are tasked with writing a script to process a file containing a list of file paths and perform a series of operations on each path. The script should read the file, remove unwanted lines, extract and manipulate the paths, and then update another file with the modified paths. Your task is to implement the necessary ... | ```bash
#!/bin/bash
cut_no=10 # Example value for cut_no
SOURCE="input_file.txt" # Example input file
DEST="output_file.txt" # Example output file
head -n $cut_no "$SOURCE" | grep -v "Allocating common symbols" | tail -n +2 | sed 's/^[ ]*//' | sed 's/[ ]*$//' | sed 's/\([^(]*\)(.*/\1/' | grep -v '^$' | sort... | magicoder | shell |
You are tasked with implementing a Python function that refreshes a list of proxies using asynchronous programming. The function `refresh_proxy` is responsible for calling an asynchronous function `valid_proxies` using the `asyncio` library. The `valid_proxies` function is expected to return a boolean value indicating ... | ```python
import asyncio
async def check_proxy_validity(proxy):
# Assume this function checks the validity of the given proxy asynchronously
# and returns True if the proxy is valid, False otherwise
pass
async def valid_proxies():
proxies = [...] # List of proxy servers to be checked
tasks = [che... | magicoder | python |
You are tasked with creating a Bash script to merge log files for a set of samples in a genomics analysis pipeline. The script should take a tissue type as input and merge the log files for that tissue type.
The provided code snippet is a function `get_stm_log` that takes a tissue type as an argument and sets up the f... | ```bash
# Function to merge log files for a given tissue type
merge_logs () {
local tissue="$1"
local data_dir="$(get_data_dir $tissue)"
local filestem="vdr-chip_${tissue}_merged_ngm_bt2"
# Check if data directory exists
if [ ! -d "$data_dir" ]; then
echo "Error: Data directory for tissue '$tissue' not... | magicoder | shell |
You are tasked with creating a program that simulates a train station management system. The system should be able to handle the addition of new train stations, retrieval of nearby stations based on geographical proximity, and sorting of station names.
You are given a class `TrainStation` with the following attributes... | ```python
from math import radians, sin, cos, sqrt, atan2
class TrainStation:
def __init__(self, name, latitude, longitude):
self.name = name
self.latitude = latitude
self.longitude = longitude
self.nearby_stations = []
def distance_to(self, other):
# Haversine formula ... | magicoder | python |
You are tasked with creating a Python program that simulates a file management system. The program should accept command-line arguments to perform various file operations such as creating directories, listing files, and removing files or directories.
Your program should accept the following command-line arguments:
1. ... | ```python
import argparse
import os
import shutil
def create_directory(directory_name):
try:
os.mkdir(directory_name)
print(f"Directory '{directory_name}' created successfully.")
except FileExistsError:
print(f"Directory '{directory_name}' already exists.")
def list_files(directory_pat... | magicoder | python |
You are tasked with implementing a parser for a simple markup language that supports parsing numbers and percentages. The language allows for numbers and percentages to be represented in various formats, such as "50%", "0.75", "100", etc. Your task is to create a parser for this markup language using the Rust programmi... | ```rust
use nom::{IResult, character::complete::char, combinator::map_res, sequence::preceded};
#[derive(Debug)]
enum NumberOrPercentage {
Number(f64),
Percentage(f64),
}
#[derive(Debug)]
struct ParseError<'i> {
message: &'i str,
}
fn parse_number(input: &str) -> IResult<&str, NumberOrPercentage> {
m... | magicoder | rust |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.