query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with creating a Python function that simulates the behavior of the `os.chdir` function. The `os.chdir` function is used to change the current working directory to the specified path. Your task is to create a function `change_directory` that takes a current working directory path and a relative path as in... | ```python
import os
def change_directory(current_directory: str, relative_path: str) -> str:
return os.path.normpath(os.path.join(current_directory, relative_path))
```
The `change_directory` function uses the `os.path.join` method to join the `current_directory` and `relative_path` and then normalizes the result... | magicoder | python |
You are tasked with implementing a function that filters and sorts a list of website history URLs based on a given search domain and sort order criteria. The function should take in the website history URLs, search domain, and sort order as input and return the filtered and sorted URLs.
You are given the following cod... | ```python
def filter_and_sort_urls(t_history_urls, _search, t_sort_order):
filtered_urls = [url for url in t_history_urls if _search in url]
if not t_sort_order:
return filtered_urls
def custom_sort_key(url):
for sort_criteria in t_sort_order:
if sort_criteria['sort'] == 'index... | magicoder | python |
You are tasked with creating a Java program that simulates a simple online shopping system. The system should have classes for products, customers, and a shopping cart. The shopping cart should be able to add and remove products, calculate the total price, and generate an invoice.
Your task is to implement the `Produc... | ```java
// Product class
class Product {
private int productId;
private String productName;
private double price;
public Product(int productId, String productName, double price) {
this.productId = productId;
this.productName = productName;
this.price = price;
}
public i... | magicoder | java |
You are tasked with creating a Python function that checks whether a given host and port are connectable. The function should attempt to establish a connection to the specified host and port and return a boolean value indicating whether the connection was successful.
The function signature should be:
```python
def is_... | ```python
import socket
def is_connectable(host, port):
try:
# Create a socket object
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Set a timeout for the connection attempt
sock.settimeout(5)
# Attempt to connect to the specified host and port
sock.conne... | magicoder | python |
You are tasked with creating a Python class that simulates a simple banking system. The class should have methods for depositing funds, withdrawing funds, and checking the current balance. Additionally, the class should keep track of the transaction history, including the date, type of transaction (deposit or withdrawa... | ```python
from datetime import datetime
class BankAccount:
def __init__(self):
self.balance = 0
self.transaction_history = []
def deposit(self, amount):
if amount > 0:
self.balance += amount
self.transaction_history.append({
'date': datetime.now(... | magicoder | python |
You are tasked with implementing a custom layout manager for a graphical user interface (GUI) library. The layout manager should be able to arrange GUI components in a specific manner based on the layout constraints provided. In this problem, you will focus on implementing a simplified version of a custom layout manage... | ```cpp
#include <vector>
#include "Component.h"
class CustomLayoutManager : public LayoutManager {
public:
void layoutComponents(std::vector<Component*>& components, int availableWidth, int availableHeight) override {
int componentWidth = availableWidth / components.size();
int maxHeight = 0;
... | magicoder | cpp |
You are tasked with implementing a translation function for a multilingual application. The function should support nested namespaces and return the translated string based on the provided namespace and key.
You are given a code snippet that tests the translation function using the `namespaceTranslation` method. The `... | ```javascript
// Implementation of namespaceTranslation method and translation function
function namespaceTranslation(namespace, parentTranslation) {
if (parentTranslation) {
return key => parentTranslation(`${namespace}.${key}`);
} else {
return key => key;
}
}
// Test cases for namespaceTranslation met... | magicoder | javascript |
You are tasked with implementing a hash function using the SHA-256 algorithm. The SHA-256 algorithm is a widely used cryptographic hash function that produces a 256-bit (32-byte) hash value. The algorithm operates on a message with a maximum length of 2^64-1 bits and produces a 256-bit hash value. The algorithm consist... | ```cpp
#include <iostream>
#include <string>
#include <bitset>
// SHA-256 logical functions
#define Ch(x, y, z) ((x & y) ^ (~x & z))
#define Maj(x, y, z) ((x & y) ^ (x & z) ^ (y & z))
#define Sigma0(x) (ROTRIGHT(x, 2) ^ ROTRIGHT(x, 13) ^ ROTRIGHT(x, 22))
#define Sigma1(x) (ROTRIGHT(x, 6) ^ ROTRIGHT(x, 11) ^ ROTRIGHT(x... | magicoder | cpp |
You are given a program that is intended to solve a specific problem. However, the program is incomplete and contains a code snippet that needs to be filled in. Your task is to complete the program by filling in the missing code snippet to achieve the desired functionality.
The program is intended to take an integer i... | ```c
#include <stdio.h>
void printSquarePattern(int n) {
for (int i = 0; i < n / 2; i++) {
for (int j = 0; j < n / 2; j++) {
printf("* ");
}
printf("\n");
}
}
int main() {
int n;
scanf("%d", &n);
if (n % 2 == 0) {
printSquarePattern(n);
} else {
puts("Impossible");
}
return 0... | magicoder | c |
You are tasked with implementing a generic tree data structure in Swift. The tree should support adding child nodes with optional z-order and name parameters. Additionally, the add method should be designed to allow for easy extension by subclasses.
Your task is to implement the add method for the Node class, ensurin... | ```swift
class Node {
var name: String?
var children: [Node] = []
func add(child: Node, z: Int? = nil, name: String? = nil) {
assert(child.parent == nil, "Child already added to another node. It can't be added again")
child.parent = self
if let zOrder = z {
// Handle z-... | magicoder | swift |
You are tasked with implementing a Python module that provides a unified interface for searching and accessing various deep learning models. The module should allow users to easily import and utilize different models without needing to know the specific details of each model's implementation. To achieve this, you need ... | ```python
class ModelLoader:
def load_model(self, model_name):
if model_name == 'MobileNet':
from .searchable_mobilenet import SearchableMobileNet
return SearchableMobileNet()
elif model_name == 'ShuffleNetV2':
from .searchable_shufflenet_v2 import SearchableShuff... | magicoder | python |
You are tasked with creating a script to compare the release information of a software package from two different sources. The release information is embedded in the HTML of the web pages. The script should extract the release information from the given URLs and compare them to determine if there is a newer release ava... | ```bash
#!/bin/bash
# Extract release information from the currentDRaw variable
currentD=$(grep -oP '(?<=ReleaseInfo" class="PageFooter">)[^<]+' <<< "$currentDRaw")
# Extract release information from the web page
latestDRaw=$(curl -Ls https://dcps.follettdestiny.com/)
latestD=$(grep -oP '(?<=ReleaseInfo" class="PageF... | magicoder | shell |
You are tasked with implementing a numerical integration algorithm for different profiles in a specific coordinate system. The code snippet provided is a part of a larger program that sets the integrands for numerical integration based on the problem type and coordinate system. Your task is to create a function that pe... | ```cpp
#include <iostream>
#include <cstring>
#include <functional>
// Define the integrand functions
double InitialGaussianProfile(double x) {
// Implement the InitialGaussianProfile integrand function
// ...
}
double FinalGaussianProfile(double x) {
// Implement the FinalGaussianProfile integrand functi... | magicoder | cpp |
You are given a chessboard represented as a 2D array `captured` of size `n x n`, where each cell `captured[i][j]` contains a non-negative integer representing the number of times that cell has been captured by a player. Additionally, you are given a starting position `(x, y)` on the chessboard, where `0 <= x, y < n`.
... | ```python
from typing import List
def updateCaptured(captured: List[List[int]], n: int, x: int, y: int) -> List[List[int]]:
moves = [(2, 1), (1, 2), (-2, 1), (-1, 2), (2, -1), (1, -2), (-2, -1), (-1, -2)]
for dx, dy in moves:
new_x, new_y = x + dx, y + dy
if 0 <= new_x < n and 0 <= new_y <... | magicoder | python |
You are tasked with creating a mock server for testing HTTP requests and responses. Your goal is to implement a function that verifies whether an incoming HTTP request matches an expected request and, if so, returns the corresponding HTTP response.
You are given the following structs representing an HTTP request and a... | ```rust
use std::collections::HashMap;
struct HttpRequest {
method: Option<HttpMethod>,
path: Option<String>,
body: Option<String>,
params: Vec<(String, String)>,
headers: HashMap<String, String>,
}
struct HttpResponse {
status_code: Option<u16>,
status_reason: Option<String>,
body: Op... | magicoder | rust |
You are tasked with implementing a function that calculates the area of a shadow cast by a given object. The shadow is cast on a flat surface, and the object is represented by a 2D shape. The shadow's properties are determined by the object's position, size, and the light source's position.
You are given the following... | ```python
from typing import List, Tuple
import math
def calculate_shadow_area(vertices: List[Tuple[float, float]], light_position: Tuple[float, float], object_position: Tuple[float, float], shadow_opacity: float, shadow_radius: float) -> float:
def distance(p1, p2):
return math.sqrt((p2[0] - p1[0])**2 + (... | magicoder | python |
You are tasked with creating a Rust library for neural network operations using the `tract_core` crate. Your goal is to implement a custom layer that performs a specific operation on input data. The layer should utilize the provided modules and traits: `global_pools`, `layer_max`, `reduce::{Reduce, Reducer}`, `softmax:... | ```rust
use global_pools::*;
use layer_max::*;
use reduce::{Reduce, Reducer};
use softmax::Softmax;
use tract_core::ops::nn::{sigmoid, DataFormat};
struct CustomLayer {
// Define the necessary fields here, if any
}
impl CustomLayer {
fn new() -> Self {
// Implement the constructor to initialize the la... | magicoder | rust |
You are tasked with creating a Python script to manage the installation of required packages for a data science project. The script should read a list of required packages from a file, check if each package is installed, and install any missing packages using the appropriate package manager.
You are given a sample cod... | ```python
import platform
import subprocess
def manage_packages(package_file_path: str):
with open(package_file_path, 'r') as file:
required_packages = [package.strip() for package in file.readlines()]
operating_system = platform.system()
if operating_system == 'Windows':
package_manager ... | magicoder | python |
You are given a Python class `Grafo` that represents a graph. The class has a method `insertAresta` to insert an edge (represented by `Aresta` objects) into the graph, and a method `ciclico` to determine whether the graph contains a cycle. An edge is represented by the `Aresta` class, which takes two vertices as its pa... | ```python
class Aresta:
def __init__(self, v1, v2):
self.v1 = v1
self.v2 = v2
class Grafo:
def __init__(self):
self.arestas = []
def insertAresta(self, aresta):
self.arestas.append(aresta)
def ciclico(self):
def is_cyclic_util(v, visited, rec_stack):
... | magicoder | python |
You are tasked with creating a password validation function for a user registration system. The function should use the Laravel framework's Hash facade to securely hash and store the user's password. Additionally, the function should enforce certain password requirements to ensure security.
Write a function `validateA... | ```php
use Illuminate\Support\Facades\Hash;
function validateAndHashPassword(string $password): ?string
{
// Check if the password meets the requirements
if (strlen($password) < 8 || !preg_match('/[A-Z]/', $password) || !preg_match('/[a-z]/', $password) || !preg_match('/[0-9]/', $password) || strpos($password,... | magicoder | php |
You are given a code snippet that contains a commented-out for loop. Your task is to write a program that will parse the given code snippet and extract the information about the for loop, including the loop variable, loop condition, and loop body.
Write a function or method called `parseForLoop` that takes the code s... | ```csharp
using System;
using System.Text.RegularExpressions;
public class ForLoopInfo
{
public string LoopVariable { get; set; }
public string LoopCondition { get; set; }
public string LoopBody { get; set; }
}
public class ForLoopParser
{
public static ForLoopInfo ParseForLoop(string codeSnippet)
... | magicoder | csharp |
You are tasked with implementing a testing function for a reinforcement learning agent. The agent is expected to train and then save its models. Your goal is to create a test function that verifies the correctness of the training process and the saved models.
You are provided with a code snippet that includes a call t... | ```python
def test_save_models():
# Create a mock agent and replay buffer for testing
agent = MockAgent()
agent.train() # Train the agent
# Sample an observation from the replay buffer
ob = agent.replay_buffer.sample(1)
# Save the agent's models
agent.save_models()
# Test the trainin... | magicoder | python |
You are tasked with implementing a method to fade out a main menu animation in a Windows Presentation Foundation (WPF) application. The provided code snippet contains a method called `FadeOutMMAnim_Completed` which is triggered when the fade-out animation is completed. Inside this method, there is a conditional check a... | ```csharp
using System;
using System.Windows;
using System.Windows.Media.Animation;
public class MainMenuAnimator
{
private static Grid gMain; // Assume gMain is the main container grid
public static void FadeOutMainMenuAnimation()
{
if (gMain != null)
{
DoubleAnimation fadeOut... | magicoder | csharp |
You are given a list of bounding box coordinates and a list of colors. Your task is to create a function that takes these inputs and visualizes the bounding boxes using the given colors.
The function should take the following inputs:
- `det_xmax`: A list of maximum x-coordinates of the bounding boxes.
- `det_ymax`: A ... | ```python
import numpy as np
import matplotlib.pyplot as plt
def visualize_bounding_boxes(det_xmax, det_ymax, top_indices, colors):
top_xmax = det_xmax[top_indices]
top_ymax = det_ymax[top_indices]
for i, (xmax, ymax) in enumerate(zip(top_xmax, top_ymax)):
color_index = i % len(colors) # Ensure c... | magicoder | python |
You are tasked with creating a program to parse and extract data from HTML code representing a website's footer. The footer contains lists of links categorized under different headings. Each link is represented by an anchor tag `<a>` with the `href` attribute specifying the link's URL and the `class` attribute indicati... | ```python
from typing import Dict, List, Tuple
from bs4 import BeautifulSoup
def parse_footer_links(html_code: str) -> Dict[str, List[Tuple[str, str]]]:
footer_links = {}
soup = BeautifulSoup(html_code, 'html.parser')
footer_sections = soup.find_all('div', class_='ft__list')
for section in footer_... | magicoder | python |
You are working on a material management system that interacts with an HTTP service to retrieve material counts of different types. The system has a method `count($type)` which takes a material type as input and returns the count of that material type. The method makes a GET request to the HTTP service endpoint 'materi... | ```php
class MaterialManager
{
private $httpService;
public function __construct($httpService)
{
$this->httpService = $httpService;
}
public function count($type)
{
try {
$resp = $this->httpService->request('GET', 'material/get_materialcount');
$key = $t... | magicoder | php |
You are tasked with implementing a simple HTTP header parser that extracts and organizes key-value pairs from a list of HTTP headers. Each header is represented as a string in the format "Key:Value". The input is a list of strings, each representing a single HTTP header. Your goal is to create a function that parses th... | ```python
from typing import List, Dict
def parse_http_headers(headers: List[str]) -> Dict[str, str]:
parsed_headers = {}
for header in headers:
key, value = header.split(":")
parsed_headers[key.strip()] = value.strip()
return parsed_headers
```
The `parse_http_headers` function iterates t... | magicoder | python |
You are tasked with implementing a text generation model using a recurrent neural network (RNN) with a specific sampling mechanism. The model uses a word embedding layer to represent input words and has a method for generating output text based on the hidden state of the RNN. The output sampling method incorporates sel... | ```python
def forward_output_sampling(self, h, y_type, selection_temperatures=None, selection_probability_tresholds=None):
# sample type
if selection_probability_tresholds is None:
# Implement sampling based on y_type and return the sampled word
sampled_word = sample_word_based_on_type(y_type)
... | magicoder | python |
You are tasked with implementing a job scheduling system using a priority queue. The system should be able to add jobs with a specified priority and retrieve the next job to be processed based on its priority.
You are provided with the following code snippet as a starting point:
```python
job = add.queue(5, 2)
```
In ... | ```python
import heapq
class JobScheduler:
def __init__(self):
self.job_queue = []
self.counter = 0 # To maintain FIFO order for jobs with the same priority
def add_job(self, job_id, priority):
heapq.heappush(self.job_queue, (priority, self.counter, job_id))
self.counter += 1
... | magicoder | python |
You are tasked with creating a program that processes a given HTML text and extracts specific information based on predefined patterns. The program should identify and extract all the quoted text within `<p>` tags and count the occurrences of specific words within those quotes.
For example, given the input HTML text:
... | ```python
import re
def extract_and_count(html_text, target_words):
quoted_text = re.findall(r"<p>(.*?)<\/p>", html_text) # Extract quoted text within <p> tags
word_counts = {word: 0 for word in target_words} # Initialize word count dictionary
for quote in quoted_text:
for word in target_words:
... | magicoder | python |
You are tasked with implementing a composite design pattern for managing employees in a construction site. The `IEmployee` interface is provided, which represents an employee in the construction site. The interface has three methods: `Work()`, `Break()`, and a property `Description` of type string. The `Work()` method ... | ```csharp
using System;
using System.Collections.Generic;
namespace StructuralDesignPatterns.Composite.ConstructionSite
{
public interface IEmployee
{
void Work();
void Break();
string Description { get; }
}
public class Employee : IEmployee
{
public string Descript... | magicoder | csharp |
You are tasked with creating a Django migration for a new column in a database table. The migration should add a new column called `related_dog` to the `dogs_testimonial` table. This new column should be a foreign key that references the `Dog` model in the `dogs` app. The related name for the foreign key should be set ... | ```python
# Assuming the app name is 'dogs' and the model name is 'Dog'
# Create a new migration file
python manage.py makemigrations your_app_name
# Open the newly created migration file and add the following operation inside the operations list
from django.db import migrations, models
# ...
migrations.AddField(
... | magicoder | python |
You are tasked with implementing a Proportional-Integral-Derivative (PID) controller for a two-axis gimbal system. The code snippet provided initializes two PID controllers, one for the pan axis and one for the tilt axis. The PID controller is a control loop feedback mechanism widely used in industrial control systems.... | ```python
class PIDController:
def __init__(self, p, i, d, imax):
self.Kp = p
self.Ki = i
self.Kd = d
self.imax = imax
self.prev_error = 0
self.integral = 0
def update_gains(self, p, i, d):
self.Kp = p
self.Ki = i
self.Kd = d
def upda... | magicoder | python |
You are tasked with creating a Python function that processes a file containing attribute data and extracts specific attributes based on predefined patterns. The function should read the file, identify the lines containing attribute data, and store the extracted attributes in a list.
You are given the following code s... | ```python
import re
from typing import List
def extract_attributes(file_path, formiRE, endingsRE) -> List[str]:
attrList = []
reading = False
with open(file_path, 'r') as fh:
for line in fh.readlines():
if formiRE.match(line) or endingsRE.match(line):
reading = True
... | magicoder | python |
You are tasked with implementing a periodic callback mechanism using the given code snippet as a reference. The provided code snippet outlines a class with methods to start and stop a timer that executes a callback at specified intervals on a thread pool thread.
Your task is to create a class `PeriodicCallbackManager`... | ```csharp
using System;
using System.Threading;
public class PeriodicCallbackManager
{
private Timer timer;
private Action? onThreadPoolTimerCallback;
public Action? OnThreadPoolTimerCallback
{
set => onThreadPoolTimerCallback = value;
get => onThreadPoolTimerCallback;
}
publi... | magicoder | csharp |
You are tasked with creating a program to manage squads of developers in a software development company. Each squad has a name, description, number of team members, backend programming language, and frontend framework. Your program should allow for the creation, modification, and retrieval of squad information.
Create... | ```python
class Squad:
def __init__(self, name, description, num_members, backend_language, frontend_framework):
self.name = name
self.description = description
self.num_members = num_members
self.backend_language = backend_language
self.frontend_framework = frontend_framewor... | magicoder | python |
You are tasked with implementing a simple task scheduler using Python's Celery library. Your goal is to create a Celery task that retrieves data from an external source and then returns a unique identifier associated with the result. Additionally, you need to configure the Celery application and set up a periodic task ... | ```python
# Import necessary libraries
from celery import Celery
from celery.schedules import crontab
from datetime import timedelta
# Define the Celery application
app = Celery('task_scheduler')
# Configure the Celery application
app.conf.update(
BROKER_URL='redis://localhost:6379/0', # Example broker URL, repl... | magicoder | python |
You are tasked with implementing a data loading and model building process for a machine learning project. The code snippet provided gives a glimpse of the process, but there are missing details and potential errors. Your task is to identify and rectify the issues in the code snippet and provide a complete implementati... | ```python
import help as hp
import torch
try:
# load the data
print('Loading data')
data_path = "path_to_data_directory"
train_loader, validation_loader, test_loader = hp.data_load(data_path)
# build model
architecture = "specified_architecture"
print(f'Loading weights from {architecture}'... | magicoder | python |
You are tasked with implementing a module resolution system for a JavaScript project. The system should be able to resolve and import modules based on the provided import statement.
You are given a code snippet from a JavaScript file that uses the ES6 module syntax to import a module. The snippet is as follows:
```ja... | ```javascript
function resolveModulePath(importStatement, currentFilePath) {
const importRegex = /from\s+['"]([^'"]+)['"]/;
const match = importStatement.match(importRegex);
if (match) {
const modulePath = match[1];
if (modulePath.startsWith('./') || modulePath.startsWith('../')) {
const path = requ... | magicoder | javascript |
You are tasked with creating a Python function to generate random hand information for a given batch size and number of components. The hand information includes vertices and joint positions. Your goal is to implement the function `generate_random_hand(batch_size, ncomps)` that returns a dictionary containing the verti... | ```python
import numpy as np
def generate_random_hand(batch_size, ncomps):
# Generate random vertices and joint positions for the specified batch size and number of components
verts = np.random.rand(batch_size, 778, 3) # Random vertices array of shape (batch_size, 778, 3)
joints = np.random.rand(batch_siz... | magicoder | python |
You are tasked with creating a messaging system for a social media platform. The system should allow users to send and receive messages, and also provide a feature to display the list of rooms (conversations) a user is a part of.
You are given a partial code snippet from the messaging system, which includes a method t... | ```csharp
public class RoomViewModel
{
public DateTime CreatedOn { get; set; }
public string Sender { get; set; }
public string Receiver { get; set; }
}
public class Message
{
public int Id { get; set; }
public User Sender { get; set; }
public User Receiver { get; set; }
public DateTime Cre... | magicoder | csharp |
You are tasked with developing a program to analyze palm images and enhance the visibility of palm lines. The program should read an input image, detect the palm lines, and then overlay the detected lines onto the original image with a specified transparency. The program should then display the modified image with the ... | ```python
import cv2
# Read the input image
image = cv2.imread("input_image.jpg")
# Perform palm line detection (not specified in the problem)
# Assume palm line detection is performed and the result is stored in the variable 'palm_lines'
# Save the detected palm lines as a new image
cv2.imwrite("palmlines.jpg", pal... | magicoder | python |
You are tasked with implementing a retry mechanism for asserting conditions in automated tests. Your goal is to create a method that will repeatedly execute a given assertion function until it either succeeds or reaches a maximum number of retries. This is useful in scenarios where the system under test may not be imme... | ```csharp
public static class AssertHelper
{
public static void RetryAssert(int retryInterval, int retryCount, string failureMessage, Func<bool> assertion)
{
var count = 0;
while (count < retryCount)
{
if (assertion())
{
return; // Assertion succee... | magicoder | csharp |
You are tasked with creating a class to simulate the behavior of a rocket engine. The class should have methods to update the engine's state over time and to save relevant data to a CSV file. The rocket engine has properties such as mass, propellant mass, and maximum g-forces experienced during operation.
Your task is... | ```python
class RocketEngine:
def __init__(self, engine_mass, propellant_mass, delta_mass):
self.engine_mass = engine_mass
self.propellant_mass = propellant_mass
self.delta_mass = delta_mass
self.gs = []
def step(self, dt):
self.engine_mass -= self.delta_mass * dt
... | magicoder | python |
You are tasked with creating a program to classify news headlines into different categories using a Gaussian Naive Bayes classifier. The given code snippet provides a starting point for the program. The program first converts the headlines to lowercase and then creates a bag-of-words representation of the headlines usi... | ```python
# Import necessary libraries
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report
# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(basictrain, labels, test_size=0.2, random_state=42)
# Train ... | magicoder | python |
You are tasked with creating a class that manages a list of error messages and provides a combined error text by concatenating all error messages with a new line delimiter. Your task is to implement a class in TypeScript that fulfills the given requirements.
You are provided with a partial code snippet as inspiration:... | ```typescript
import * as ko from 'knockout';
class ErrorMessage {
constructor(public Message: string) {}
}
class ErrorList {
public Errors: KnockoutObservableArray<ErrorMessage>;
public ErrorsText: KnockoutObservable<string>;
constructor() {
this.Errors = ko.observableArray<ErrorMessage>();
... | magicoder | typescript |
You are tasked with creating a script to automate the deployment of a Docker image to a container registry. The script should perform the following steps:
1. Authenticate with the Docker registry using the provided username and password.
2. Build a Docker image with the specified tag and version.
3. Push the built Doc... | ```bash
#!/bin/bash
# Input parameters
DOCKER_USERNAME="your_username"
DOCKER_PASSWORD="your_password"
IMAGE_NAME="your_image_name"
VERSION="your_version"
# Authenticate with the Docker registry
docker login -u $DOCKER_USERNAME -p $DOCKER_PASSWORD
# Build the Docker image with specified tag and version
docker build ... | magicoder | shell |
You are given a code snippet for a data structure called BCC (Biconnected Component) which is used to find biconnected components in a graph. The code snippet includes a template for the BCC structure and a method to add edges to the graph. Your task is to implement a method within the BCC structure to find all the bic... | ```cpp
template<int SZ> struct BCC {
int N;
vpi adj[SZ], ed;
vi disc, low, par, art;
vector<vector<int>> bcc;
stack<int> stk;
void addEdge(int u, int v) {
adj[u].pb({v,sz(ed)}),
adj[v].pb({u,sz(ed)});
ed.pb({u,v});
}
void dfs(int u, int p, int &time) {
... | magicoder | cpp |
You are tasked with creating a simple command-line utility that processes a given input string and performs a specific operation on it. Your program should take a single input string and apply a transformation to it based on a set of rules. The transformation involves counting the occurrences of each character in the i... | ```python
def transform_string(input_string):
char_count = {}
transformed_string = ""
for char in input_string:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
for char, count in char_count.items():
transformed_string += c... | magicoder | python |
You are tasked with creating a function that processes a request to update a tool kit in a workshop management system. The function should handle the mapping of the request to the model, attempt to update the model in the repository, and return an appropriate response based on the outcome.
You are given the following ... | ```csharp
public async Task<IActionResult> UpdateToolKit(VaerktoejskasseRequest vaerktoejskasseRequest)
{
try
{
var model = _mapper.Map<Vaerktoejskasse>(vaerktoejskasseRequest);
await _repository.Update(model);
return Ok();
}
catch
{
return BadRequest();
}
}
```
I... | magicoder | csharp |
You are tasked with creating a configuration file parser for a PHP application. The configuration file is in the form of an associative array and contains environment-specific settings for different services. Each service has its own set of configuration parameters, such as 'secret', 'hash', 'timeout', and 'base_uri'. ... | ```php
function parseConfig(array $config): array {
$flattenedConfig = [];
foreach ($config as $service => $parameters) {
foreach ($parameters as $param => $envVar) {
$envValue = getenv($envVar);
$flattenedConfig[$service . '_' . $param] = $envValue !== false ? $envValue : null;... | magicoder | php |
You are tasked with implementing a custom command-line utility that allows users to define and use their own aliases for frequently used commands. The utility should support the creation, listing, and execution of aliases.
Your task is to implement a class `AliasManager` in Python that provides the following functiona... | ```python
class AliasManager:
def __init__(self):
self.aliases = {}
def add_alias(self, alias, command):
self.aliases[alias] = command
def remove_alias(self, alias):
if alias in self.aliases:
del self.aliases[alias]
def list_aliases(self):
return list(self.... | magicoder | python |
You are tasked with implementing a plugin management system for a visualization toolkit. The system should be able to handle the event of a new plugin becoming available and perform the necessary actions. The code snippet provided is a callback function that is triggered when a new plugin becomes available. Your task i... | ```cpp
#include <iostream>
#include <vector>
#include <string>
class Plugin {
public:
std::string name;
// Other plugin attributes and methods
};
class PluginManager {
private:
std::vector<Plugin> availablePlugins;
public:
void registerPlugin(const Plugin& plugin) {
availablePlugins.push_back... | magicoder | cpp |
You are given a hexadecimal color code in the form of an integer. Your task is to write a function to convert this integer into its corresponding RGB (Red, Green, Blue) representation.
Write a function `hexToRGB` that takes an integer `hexColor` as input and returns a tuple of three integers representing the RGB value... | ```python
def hexToRGB(hexColor):
red = (hexColor >> 16) & 0xff
green = (hexColor >> 8) & 0xff
blue = hexColor & 0xff
return (red, green, blue)
# Test the function
print(hexToRGB(0xff676767)) # Output: (103, 103, 103)
``` | magicoder | python |
You are tasked with implementing a class for handling RSA private keys in a PHP application. Your goal is to create a `RsaPrivateKey` class that can handle RSA private keys and provide methods for key generation, encryption, and decryption.
Your task is to implement the `RsaPrivateKey` class with the following require... | ```php
<?php
namespace MiladRahimi\Jwt\Cryptography\Keys;
use MiladRahimi\Jwt\Exceptions\InvalidKeyException;
class RsaPrivateKey extends PrivateKey
{
private $privateKey;
public function __construct(string $privateKey)
{
if (!$this->isValidPrivateKey($privateKey)) {
throw new Invali... | magicoder | php |
You are tasked with implementing a simple version of a closure in Rust. A closure is a function that captures the environment in which it is defined, allowing it to access variables from its surrounding scope. In this problem, you will create a closure that takes a reference to a trait object and calls a method on it.
... | The error "borrowed data escapes outside of closure" occurs because the closure captures a reference to the trait object, but the reference may outlive the closure, leading to potential memory safety issues. To resolve this, we can use the `move` keyword to force the closure to take ownership of the referenced data, pr... | magicoder | rust |
You are tasked with implementing a custom range view in C++ that concatenates a given range with itself and then repeats each element a specified number of times. Your task is to create a class template `ConcatRepeatView` that takes two parameters: the input range `R` and the number of times each element should be repe... | ```cpp
#include <iostream>
#include <range/v3/all.hpp>
template <typename R, std::size_t N>
class ConcatRepeatView : public ranges::view_facade<ConcatRepeatView<R, N>> {
friend ranges::range_access;
R base_range;
using base_iterator_t = ranges::iterator_t<R>;
using base_sentinel_t = ranges::sentinel_... | magicoder | cpp |
You are tasked with implementing a serverless function that handles different types of requests based on the path provided. The function `lambda_handler` takes two arguments: `event`, a dictionary containing the request details, and `context`, the runtime information. The function processes the request and returns a re... | ```python
import json
def user_details(user_uid, body):
# Implementation not shown
pass
def place_budget(user_uid, body, entity):
# Implementation not shown
pass
def respond(err, res):
# Implementation not shown
pass
def lambda_handler(event, context):
path = event.get('path', '')
us... | magicoder | python |
You are tasked with implementing a function to determine whether two strings are anagrams of each other. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. For example, "listen" and "silent" are anagrams.
Write a functi... | ```python
def are_anagrams(s1, s2):
# Remove spaces and convert strings to lowercase
s1 = s1.replace(" ", "").lower()
s2 = s2.replace(" ", "").lower()
# Check if the sorted strings are equal
return sorted(s1) == sorted(s2)
```
The `are_anagrams` function first removes any spaces from the input str... | magicoder | python |
You are tasked with implementing a function that manages audio output device selection in a web application. The function needs to handle the process of changing the audio output device and updating the audio stream accordingly. The provided code snippet is part of the existing implementation and contains the logic for... | ```typescript
function changeAudioOutputDevice(newDevice: MediaDeviceInfo, audioElement: HTMLAudioElement): void {
const audioElementWithSinkId = audioElement as AudioElementWithSinkId;
const newSinkId = newDevice ? newDevice.deviceId : '';
const oldSinkId: string = audioElementWithSinkId.sinkId;
if (newSinkI... | magicoder | typescript |
You are tasked with implementing a Python function that takes a sentence as input and generates a dependency parse-based graph using the networkx library. The graph should represent the relationships between the words in the sentence based on their syntactic dependencies.
Your function should accept a single string pa... | ```python
import spacy
import networkx as nx
def generate_dependency_graph(sentence):
# Load the English tokenizer, tagger, parser, NER, and word vectors
nlp = spacy.load("en_core_web_sm")
# Process the input sentence using spaCy
doc = nlp(sentence)
# Create a directed graph using network... | magicoder | python |
You are tasked with implementing a JSON to object conversion utility for a Python application. The `JsonUtil` class provides a method `json2obj` that should convert a JSON string into a Python object. The `JsonUtilTestCase` class contains a unit test `test_json2obj` that aims to verify the functionality of the `json2ob... | ```python
import unittest
import json
from qqbot.core.util.json_util import JsonUtil
class JsonUtilTestCase(unittest.TestCase):
def test_json2obj(self):
class Score:
def __init__(self):
self.chinese = ""
self.math = ""
# Complete the implementation of ... | magicoder | python |
You are tasked with creating a Java program that can dynamically retrieve and list all the classes in a specified package. Your program should utilize reflection to achieve this functionality.
Write a Java class named `AllClassesInPackageController` that contains a method `listClassesInPackage` which takes a package ... | ```java
import java.util.ArrayList;
import java.util.List;
import java.lang.reflect.*;
public class AllClassesInPackageController {
public List<Class<?>> listClassesInPackage(String packageName) {
List<Class<?>> classes = new ArrayList<>();
try {
ClassLoader classLoader = Thread.curren... | magicoder | java |
You are tasked with implementing a function to calculate the sum of all prime numbers within a given range. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Your function should take two integers, `start` and `end`, as input and return the sum of all prime numbers... | ```python
def sumOfPrimes(start, end):
def isPrime(num):
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
prime_sum = 0
for num in range(start, end + 1):
if isPrime(num):
... | magicoder | python |
You are tasked with implementing a function to calculate the total number of atoms in a supercell based on a given unit cell and a supercell matrix. The supercell matrix is a 3x3 matrix that defines how many times the unit cell is repeated in each direction to form the supercell. The unit cell is represented by its lat... | ```python
import numpy as np
def count_atoms_in_supercell(unitcell_lattice, unitcell_atoms, supercell_matrix):
# Convert lattice vectors and atomic positions to numpy arrays for easier manipulation
unitcell_lattice = np.array(unitcell_lattice)
unitcell_atoms = np.array(unitcell_atoms)
# Calculate the ... | magicoder | python |
You are tasked with implementing a ping-pong messaging system using Java. The system involves sending ping messages and receiving pong responses over a network using JGroups library. Your goal is to complete the implementation of the `PingMessageAnswer` class, which is responsible for sending ping messages and processi... | ```java
import org.jgroups.JChannel;
public class PingMessageAnswer {
private int pingCount = 0;
private JChannel channel;
private GMSPingPonger pingPonger = new GMSPingPonger();
private Set<Integer> simulatedPongRespondersByPort;
public PingMessageAnswer(JChannel channel, Set<Integer> simulatedPo... | magicoder | java |
You are tasked with implementing a method for a structured name class that adds a type to the name. The method should return the modified structured name with the type inserted and the old type, if any. The structured name is represented as a nested list, and the type is represented as an object of the Type class.
You... | ```python
from typing import Tuple, Optional
class Type:
pass # Placeholder for the Type class
class StructuredName:
def __init__(self, se):
self.se = se
def is_derivation(self):
return isinstance(self.se, list)
def add_type(self, ty) -> Tuple["StructuredName", Optional[Type]]:
... | magicoder | python |
You are tasked with creating a Python program that manages a simple to-do list. The program should allow users to add tasks, mark tasks as completed, view all tasks, and delete tasks. The tasks should be stored in a text file, and the program should be able to read and write to this file to maintain the to-do list.
Yo... | ```python
import datetime
import os
# Function to add a task to the to-do list file
def add_task(task):
with open('todo_list.txt', 'a') as file:
file.write(f"- [ ] {task}\n")
# Function to mark a task as completed in the to-do list file
def mark_completed(index):
with open('todo_list.txt', 'r') as fil... | magicoder | python |
You are tasked with implementing a memory reset control module for a hardware design. The module is responsible for controlling the reset signals for different memory channels. The provided code snippet is a part of a Rust programming language implementation for this memory reset control module.
Your task is to comple... | ```rust
// Definition of the memory reset control module
struct MemoryResetControl;
impl MemoryResetControl {
// Structure for controlling memory reset for channel 2
struct MEM_WR_RST_CH2_W {
w: u8, // Assuming the control signal is represented by a single byte
}
impl MEM_WR_RST_CH2_W {
... | magicoder | rust |
You are tasked with implementing a server-sent events (SSE) endpoint for a timer application. The provided code snippet is a part of an asynchronous function that handles timer events. The function takes a request and response object as parameters and writes SSE messages to the response based on the current status of t... | ```typescript
timerEvents = async (_request: Request, response: Response) => {
response.writeHead(StatusCodes.OK, this.httpHeaders);
switch (this.status) {
case TimerStatus.STOPPED:
response.write(getSSEBody("stop", {}));
break;
case TimerStatus.RUNNING:
response.write(getSSEBody("init", ... | magicoder | typescript |
You are given a list of integers `nums` and a string `k`. If `k` is equal to 'rev', you need to reverse the list `nums`. If `k` is an integer, you need to perform a specific operation on the list `nums` based on the value of `k`.
The operation to be performed when `k` is an integer is as follows:
- If `k` is even, you... | ```python
from typing import List, Union
def perform_operation(nums: List[int], k: Union[str, int]) -> List[int]:
if isinstance(k, str) and k == 'rev':
return list(reversed(nums))
elif isinstance(k, int):
if k % 2 == 0:
del nums[k]
else:
nums[k] *= 2
return n... | magicoder | python |
You are tasked with implementing a simple command-line text editor that supports basic operations such as inserting, deleting, and displaying text. The editor should also provide the ability to undo the last operation performed.
You are given a partial implementation of the `Editor` struct and its associated methods i... | ```rust
struct Editor {
text: String,
undo_stack: Vec<Operation>,
}
enum Operation {
Insert(usize, String),
Delete(usize, usize, String),
}
impl Editor {
fn new() -> Editor {
Editor {
text: String::new(),
undo_stack: Vec::new(),
}
}
fn insert_text(&... | magicoder | rust |
You are tasked with creating a program that utilizes speech recognition to fetch images from the internet based on the user's verbal input. The program should prompt the user to speak, recognize the spoken input, and then use the recognized text to search for and download relevant images from the internet.
Your task i... | ```python
import speech_recognition as sr
from google_images_download import google_images_download
def fetch_images():
r = sr.Recognizer()
response = google_images_download.googleimagesdownload()
with sr.Microphone() as source:
print("Say something!")
audio = r.listen(source)
try:
... | magicoder | python |
You are given a dataset `data` containing metadata and experimental data. The metadata is a list of strings, and the experimental data is a list of numerical values. Your task is to write a function that calculates the weighted average of the variances of the experimental data grouped by the metadata. If a group contai... | ```python
import numpy as np
def weighted_variance_average(data):
groups = {}
for x, y in zip(data.metadata, data.exp):
if x not in groups:
groups[x] = []
groups[x].append(y)
variances, weights = [], []
for group in groups.values():
group_size = len(group)
... | magicoder | python |
You are tasked with creating a PHP unit test for a class that interacts with an external API. The class `CheckMot` is responsible for making requests to the `Djam90\CheckMot\Api` and processing the responses. Your goal is to write a unit test that ensures the `CheckMot` class functions correctly and handles the API res... | ```php
use Djam90\CheckMot\Api;
use PHPUnit\Framework\TestCase;
class CheckMotTest extends TestCase
{
public function testSuccessfulApiRequest()
{
// Create a mock for the Api class
$apiMock = $this->createMock(Api::class);
// Define the expected response from the API
$expected... | magicoder | php |
You are tasked with implementing a Python decorator that logs the execution time of a function and prints it to the console. The decorator should also handle the case where the function being decorated has arguments. You should ensure that the decorator works correctly for functions with any number of positional and ke... | ```python
import time
def log_execution_time(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
execution_time = (end_time - start_time) * 1000
print(f"Function '{func.__name__}' executed in {execution_time:.2f... | magicoder | python |
You are tasked with implementing a feature for an email client application that allows users to open selected emails in different operating systems. The application uses a graphical user interface (GUI) library, and the code snippet provided is a part of the user interface implementation. The snippet shows the addition... | To address the requirement of opening selected emails in different operating systems, a platform-independent solution can be implemented using the `open::that` crate in Rust. This crate provides a cross-platform way to open files or URLs using the default program associated with the file type or URL scheme.
First, add... | magicoder | toml |
You are tasked with implementing a function to calculate the true negative (TN) values for a multilabel classification problem. In multilabel classification, each instance can be assigned multiple labels. The true negative value represents the number of instances where all the predicted labels are not present in the tr... | ```python
def calculate_true_negatives(y_true, y_pred):
true_negatives = []
for label in range(len(y_true[0])):
tn_count = 0
for i in range(len(y_true)):
if all([y_true[i][label] == 0, y_pred[i][label] == 0]):
tn_count += 1
true_negatives.append(tn_count)
... | magicoder | python |
You are tasked with creating a Python function that generates a front matter for a markdown file used in a static site generator. The front matter should include the path, date, title, tags, and an excerpt. The function should take the path and title as input and return the formatted front matter string.
Write a Pytho... | ```python
from datetime import datetime
def gen_frontmatter(path, title):
current_date = datetime.now().strftime("%Y-%m-%d")
front_matter = f"""---
path: "/{path}"
date: "{current_date}"
title: "{title}"
tags: ['{title}']
excerpt: "Notes on {title}"
---
"""
return front_matter
```
The `gen_frontmatter` fu... | magicoder | python |
You are tasked with implementing a file system monitoring system that tracks changes to files and directories. Your goal is to create a class `FileSystemMonitor` with the following functionalities:
1. Add a file or directory to the monitoring system.
2. Remove a file or directory from the monitoring system.
3. Refresh... | ```python
import os
class FileSystemMonitor:
def __init__(self):
self.monitored_files = set()
self.monitored_directories = set()
def add_file_or_directory(self, path: str):
if os.path.isfile(path):
self.monitored_files.add(path)
elif os.path.isdir(path):
... | magicoder | python |
You are tasked with creating a Python class that simulates a simple shopping cart system. The class should allow users to add products, remove products, calculate the total cost of the items in the cart, and apply a discount to the total cost. The class should also have methods to display the list of products in the ca... | ```python
class ShoppingCart:
def __init__(self):
self.products = []
def add_product(self, product_name, price):
self.products.append((product_name, price))
def remove_product(self, product_name):
for product in self.products:
if product[0] == product_name:
... | magicoder | python |
You are tasked with creating a game using Python and Pygame. The game world consists of entities with positions, and the player's objective is to reach a specific position to win the game. The provided code snippet is a part of the game logic that checks if the player's position matches the win condition and triggers a... | ```python
import pygame
class Position:
def __init__(self, x, y):
self.x = x
self.y = y
class GameEvent:
WIN_CONDITION_MET = pygame.USEREVENT + 1
class World:
def get_player(self):
# Implementation of get_player method
pass
def get_entitys_component(self, entity, comp... | magicoder | python |
You are tasked with creating a custom tag helper in an ASP.NET Core web application. Tag helpers are a feature in ASP.NET Core that enables server-side code to participate in creating and rendering HTML elements in Razor files. In this problem, you will create a custom tag helper to generate a custom HTML tag for displ... | To create the custom tag helper, you need to define a class that inherits from `TagHelper` and override the `Process` method to generate the desired HTML output. Below is the implementation of the custom tag helper in C#:
```csharp
using Microsoft.AspNetCore.Razor.TagHelpers;
using SiteBuilder.Core.Models;
namespace ... | magicoder | csharp |
You are tasked with creating a custom form input component for a web application using PHP and Laravel's Blade templating engine. The provided code snippet is a part of a Laravel Blade template file and uses the `Form::normalTextarea` method to generate a textarea input for a leave reason field. Your goal is to impleme... | ```php
// Define the customTextarea directive in the AppServiceProvider.php boot method or a dedicated service provider
Blade::directive('customTextarea', function ($expression) {
list($name, $label, $errors) = explode(', ', $expression);
return <<<HTML
<div class="form-group">
<label for="$name">$... | magicoder | php |
You are tasked with implementing a Java method to calculate the arc sine (asin) using the Maclaurin series. The Maclaurin series is a Taylor series expansion around 0, and it can be used to approximate various mathematical functions. Your task is to complete the implementation of the `calculateAsin` method in the given... | ```java
import com.shengbojia.bigmath.BigRational;
public class AsinCalculator extends SeriesCalculator {
public BigRational calculateAsin(BigRational x) {
BigRational result = BigRational.ZERO;
BigRational term = x;
BigRational xSquared = x.multiply(x);
BigRational numerator = x;
... | magicoder | java |
You are tasked with implementing a custom event listener for a mapping framework. The mapping framework uses the Dozer library, which facilitates object-to-object mapping. The code snippet provided demonstrates the setup of the DozerBeanMapper and the addition of a custom event listener.
Your task is to create a custo... | ```java
import org.dozer.DozerEventListener;
import org.dozer.event.DozerEvent;
public class CustomEventListener implements DozerEventListener {
@Override
public void mappingStarted(DozerEvent event) {
System.out.println("Mapping started from " + event.getSourceObject().getClass().getName() +
... | magicoder | java |
You are tasked with analyzing performance data from a system using the `perf` tool and generating an "Off-CPU Time Flame Graph" to visualize the off-CPU time of various processes. The provided code snippet is a part of this process and involves several commands and pipelines. Your task is to understand the code snippet... | ```python
import subprocess
# Step 1: Read the input from the file perf.data.raw
perf_inject_cmd = "perf inject -v -s -i perf.data.raw -o perf.data"
subprocess.run(perf_inject_cmd, shell=True)
# Step 2: Process the data to extract relevant information
perf_script_cmd = "perf script -F comm,pid,tid,cpu,time,period,eve... | magicoder | python |
You are working on a project that involves processing satellite imagery data using Python. The given code snippet is part of a class that handles the processing of raster data using the GDAL library. The `km2` method within the class is responsible for processing specific blocks of raster data and performing certain op... | ```python
import numpy as np
def calculate_land_cover_area(x, y, ncols, nrows, maskblock, km2block, df, admin):
block = self.band.ReadAsArray(x, y, ncols, nrows)
unique_labels = np.unique(block)
area_dict = {}
for label in unique_labels:
if label not in [0, 255]: # Skip label 0 (no land cover... | magicoder | python |
You are tasked with implementing a class to manage HTTP status codes. The class should allow adding, removing, and retrieving HTTP status codes along with their corresponding messages. Additionally, the class should provide a method to retrieve all the status codes in a formatted string.
You need to implement the `Htt... | ```java
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class HttpStatusCodeManager {
private Map<Integer, String> statusCodes;
public HttpStatusCodeManager() {
statusCodes = new HashMap<>();
}
public void addStatusCode(int code, String message) {
... | magicoder | java |
You are tasked with creating a script to monitor the log file generated by a Maven test run and take specific actions based on the test results.
You have been provided with a code snippet that sets up the log file path and runs the Maven test, redirecting the output to the log file. After the test run, the script chec... | ```bash
#!/bin/bash
BASE_DIR=`pwd`
LOG_FILE=$BASE_DIR/test.log
EMAIL_SUBJECT="Maven Test Failure"
EMAIL_RECIPIENT="dev_team@example.com"
# Run Maven test and redirect output to log file
mvn test > $LOG_FILE 2>&1
ret=$?
if [ $ret != 0 ] ; then
# Maven test failed, send email notification with log file attached
ec... | magicoder | shell |
You are tasked with implementing a database utility class in C# that interacts with a SQL database. The class should provide methods to create a data adapter and retrieve a parameter for executing SQL commands. The provided code snippet is a part of the database utility class and contains the implementation of the `Get... | ```csharp
using System;
using System.Data;
using System.Data.Common;
public class DatabaseUtility
{
private DatabaseManager pManager;
public DatabaseUtility(DatabaseManager manager)
{
pManager = manager;
}
public DbDataAdapter GetDataAdapter(IDbCommand cmd)
{
DbDataAdapter ada... | magicoder | csharp |
You are tasked with implementing a configuration class for a TortugaScript application. The provided code snippet includes a schema definition for the configuration fields and a custom exception class. Your task is to complete the implementation of the `TortugaScriptConfig` class by incorporating the schema and handlin... | ```python
from marshmallow import Schema, fields
from config import Config, ConfigException
class TortugaScriptConfigSchema(Schema):
navops_cli = fields.String()
url = fields.String()
username = fields.String()
password = fields.String()
token = fields.String()
verify = fields.Boolean()
clas... | magicoder | python |
You are given a class `Timestamps` that contains a list of timestamps. Each timestamp is represented as a string in the format "YYYY-MM-DD HH:MM:SS". Your task is to implement a method `findTimeGaps` within the `Timestamps` class that identifies the time gaps between consecutive timestamps and returns them as a list of... | ```python
from typing import List
class Timestamps:
def __init__(self, timestamps: List[str]):
self.timestamps = timestamps
def findTimeGaps(self) -> List[str]:
time_gaps = []
for i in range(len(self.timestamps) - 1):
start_time = self.timestamps[i]
end_time = s... | magicoder | python |
You are tasked with implementing a function that extracts a value from a Google Cloud Datastore entity value protobuf message. The Google Cloud Datastore is a fully managed, schemaless database for storing non-relational data. The provided code snippet initializes a protobuf message representing a value in the Google C... | ```python
from google.cloud.datastore_v1.types import entity as entity_pb2
from google.cloud.datastore.helpers import _get_value_from_value_pb
from google.protobuf.timestamp_pb2 import Timestamp
from typing import Any
def _get_value_from_value_pb(value_pb) -> Any:
if value_pb.HasField('integer_value'):
ret... | magicoder | python |
You are tasked with creating a script that automates the build process for a software project. The script should determine the version of the software based on the current date and the short commit hash, and handle the presence of uncommitted changes in the repository. Additionally, the script should support building t... | ```bash
#!/bin/sh
# Remove the bin directory if it exists
rm -rf bin
# Determine the version of the software
VERSION=$(date +%Y.%m.%d.)$(git rev-parse --short HEAD)
# Check for uncommitted changes and modify the version if necessary
if [ -n "$(git status --porcelain --untracked-files=no)" ]; then
VERSION="$VERSION... | magicoder | shell |
You are tasked with implementing a simple dependency injection framework in Java. In this framework, you need to create a class `BeanFactory` that can manage the lifecycle of various beans and inject dependencies into them. The `BeanFactory` should support the following functionalities:
1. Registering beans with the fa... | ```java
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class BeanFactory {
private Map<Class<?>, Object> beans = new HashMap<>();
public void registerBean(Class<?> beanClass) {
try {
Object beanInstance = beanClass.getDeclaredConstructor().newInstanc... | magicoder | java |
You are tasked with creating a custom user control for a combat selection menu in a game development project. The user control should allow the player to select from a list of available combat options. The control should be implemented as a C# class that extends the UserControl class.
Your task is to implement the Use... | ```csharp
using System;
using System.Windows.Forms;
public partial class UserControlMenuSeleccionCombate : UserControl
{
// Define event for combat option selection
public event EventHandler<string> CombatOptionSelected;
// Constructor
public UserControlMenuSeleccionCombate()
{
InitializeC... | magicoder | csharp |
You are tasked with implementing a custom panic handler for a Rust application. The provided code snippet shows a part of the panic handler implementation for a testing framework. Your goal is to complete the implementation of the panic handler function and ensure that it properly handles panics during testing.
Your t... | ```rust
use core::panic::PanicInfo;
#[cfg(test)]
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
serial_println!("[failed]\n");
serial_println!("Error: {}\n", info);
exit_qemu(QemuExitCode::Failed);
loop {}
}
```
In the solution, the panic handler function `panic` is implemented as a part of a testi... | magicoder | rust |
You are tasked with implementing a file upload management system using asynchronous methods in a C# application. The provided code snippet outlines the interface for interacting with the file upload system. You need to create a class that implements the methods defined in the interface to manage file uploads to a cloud... | ```csharp
using System.Threading.Tasks;
public class FileUploadManager : IFileUploadManager
{
public async Task<UploadInfo> BeginUploadAsync(string bucketName, string objectKey, UploadOptions uploadOptions)
{
// Implementation for initiating the file upload process
}
public async Task<CommitUp... | magicoder | csharp |
You are tasked with implementing a simple Entity-Component-System (ECS) framework using C#. An ECS is a design pattern commonly used in game development to manage entities (game objects), their components (data), and systems (behavior).
Your task is to create a class called `ECSContainer<TState>` that represents the E... | ```csharp
using MicroResolver;
/// <summary>
/// Represents an Entity-Component-System (ECS) container using MicroResolver for dependency injection.
/// </summary>
/// <typeparam name="TState">Type of state parameter that gets passed to systems.</typeparam>
public class ECSContainer<TState>
{
private readonly Micr... | magicoder | csharp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.